Beispiel #1
0
    def __init__(self):
        pygame.init()  # Initialize pygame
        self.height = 800
        self.width = 860
        self.screen = pygame.display.set_mode(
            (self.width, self.height))  # Create screen object.
        self.clock = pygame.time.Clock()  # Create game clock.
        self.board = Board.Board()  # Create game board
        self.screen = pygame.display.set_mode(
            (self.width, self.height))  # Create screen object.
        pygame.display.set_caption('Pacman')
        self.clock = pygame.time.Clock()  # Create game clock.
        self.board = Board.Board()  # Reset board.

        self.pacman = Sprites.PacMan('PacMan')
        self.blinky = Sprites.Ghost('Blinky')
        self.inky = Sprites.Ghost('Inky')
        self.pinky = Sprites.Ghost('Pinky')
        self.clyde = Sprites.Ghost('Clyde')
        self.sprites = [
            self.pacman, self.blinky, self.inky, self.pinky, self.clyde
        ]
        #self.ghosts = [self.blinky, self.inky, self.pinky, self.clyde]

        #self.max_levels
        self.game_over = True
Beispiel #2
0
    def __init__(self, level_file):
        self.filename = level_file
        fh = open(self.filename)

        self.level_sprites = pygame.sprite.RenderUpdates()
        self.character_sprites = pygame.sprite.RenderUpdates()

        row = 0
        col = 0

        for i in fh.readlines():
            row = 0
            i.rstrip()
            if i[0] == '#':
                continue

            for j in i:
                if j == ' ':
                    pass
                elif j == 'R':
                    self.level_sprites.add(
                        Sprites.AnimateImageBox('data/graphics/red-brick.png',
                                                [row, col]))
                elif j == 'r':
                    self.level_sprites.add(
                        Sprites.AnimateImageBox(
                            'data/graphics/red-brick-animate.png', [row, col]))
                elif j == 'B':
                    self.character_sprites.add(
                        Sprites.Character("data/graphics/bad-guy.png",
                                          [row, col], 2, True))
                row = row + 32
            col = col + 32
Beispiel #3
0
    def __init__(self):

        pg.init()
        '''Animation Parameters'''
        self.years_per_tick = 0.0001
        self.pixels_per_AU = 800. / 3.
        '''Initialize display surface'''
        self.screen_size = (800, 800)
        self.screen = pg.display.set_mode(
            (int(self.screen_size[0]), int(self.screen_size[1])))
        self.background = pg.Surface(self.screen_size)
        self.background.fill(BLACK)

        self.model = Model.SolarModel()
        '''Build Sprites'''
        self.sun = Sprites.PlanetSprite(self.pixels_per_AU, self.screen_size,
                                        'sun.png', self.model.sun)
        self.earth = Sprites.PlanetSprite(self.pixels_per_AU, self.screen_size,
                                          'googleearth.png', self.model.earth)
        self.sgroup = pg.sprite.RenderUpdates([self.sun, self.earth])
        '''Set up the timer'''
        self.ticks = pg.time.get_ticks()

        self.screen.blit(self.background, (0, 0))
        self.sgroup.clear(self.screen, self.background)
        dirty = self.sgroup.draw(self.screen)
        pg.display.update(dirty)
Beispiel #4
0
 def __init__(self):
     super().__init__()
     # initalise sprites
     self.sprites = pygame.sprite.Group()
     self.left_paddle = Sprites.Paddle(LEFT_PADDLE_X, STARTING_PADDLE_Y)
     self.sprites.add(self.left_paddle)
     self.right_paddle = Sprites.Paddle(RIGHT_PADDLE_X, STARTING_PADDLE_Y)
     self.sprites.add(self.right_paddle)
     self.paddles = [self.left_paddle, self.right_paddle]
     self.ball = Sprites.Ball(STARTING_BALL_X, STARTING_BALL_Y, self.paddles)
     self.sprites.add(self.ball)
     self.next_state = None
Beispiel #5
0
    def advance(self):
        '''Advance the simulation one frame'''
            
        '''Calculate the time step'''
        ticks = pg.time.get_ticks()
        elapsed_time = (ticks - self.ticks)*self.years_per_tick

        '''Advance the simulation'''
        self.model.advance(time=elapsed_time)
        
        '''Update the display'''
        self.screen.blit(self.background,(0,0))
        self.all.update()
        
        '''Test for Warhead-Defense Collisions'''
        impacts = pg.sprite.groupcollide(self.warheadgrp,self.defensegrp,True,True)
        for impact in impacts:
            exp = Sprites.ExplosionSprite(self.pixels_per_AU,
                                                self.screen_size,impact)
            self.all.add(exp)                                    
        
        '''Test for Warhead-Asteroid Collisions'''
        boom = pg.sprite.groupcollide(self.asteroidgrp,self.warheadgrp,True,True)
        for b in boom:
            exp = Sprites.ExplosionSprite(self.pixels_per_AU,
                                                self.screen_size,b)
            self.all.add(exp)
            del self.model.sim.body[3]
            
        '''Test for Defense-Asteroid Collisions'''
        whap = pg.sprite.groupcollide(self.asteroidgrp,self.warheadgrp,True,True)
        for w in whap:
            self.model.sim.body
            exp = Sprites.ExplosionSprite(self.pixels_per_AU,
                                                self.screen_size,w)
            self.all.add(exp)
            del self.model.sim.body[3] 
              
        '''Test for Warhead-Earth Collision and End Game if Earth is Destroyed'''
        collisions = pg.sprite.spritecollide(self.earth,self.warheadgrp,True)
        if len(collisions) > 0:
            self.end_game = True
            exp = Sprites.ExplosionSprite(self.pixels_per_AU,
                                                self.screen_size,self.earth)
            self.earth.kill()
            self.all.add(exp)
                
        '''Draw'''    
        dirty = self.all.draw(self.screen)
        pg.display.update(dirty)
Beispiel #6
0
    def update(self):
        time = pg.time.get_ticks()

        if time - self.creationTimer > 1000:
            pass

            if len(self.evil_sprites) < 10:
                i = Player.PacManEvil(random.randrange(0, 30),
                                      random.randrange(0, 30), self,
                                      random.choice(COLORS))

                self.evil_sprites.add(i)
                self.all_sprites.add(i)
                print("Creado")

                self.creationTimer = time
        if time - self.creationTimer > 10:
            if len(self.coin_sprites) < 10:
                i = Coin.Coin(random.randrange(0, 30), random.randrange(0, 30),
                              self, YELLOW)
                self.coin_sprites.add(i)
                self.all_sprites.add(i)
                print("COINER")
                self.creationTimer = time

        for i in self.evil_sprites:
            i.mov()
            i.update()
        self.player.update()
Beispiel #7
0
 def make_roid(self):
     '''generates random asteroid'''
     if len(self.asteroidgrp) == 0:
         self.asteroid = Sprites.AsteroidSprite(self.pixels_per_AU,self.screen_size)
         self.asteroidgrp.add(self.asteroid)
         self.all.add(self.asteroid)
         self.model.sim.body.append(self.asteroid.body)
Beispiel #8
0
 def defense_cannon(self):
     '''fires the defense cannon if warhead is incoming'''
     if len(self.warheadgrp) == 1:
         defense = Sprites.DefenseSprite(self.pixels_per_AU,self.screen_size,
                                         self.earth,self.warhead)
         self.defensegrp.add(defense)
         self.all.add(defense)
Beispiel #9
0
def main():

    #initializing game objects
    sprite_obj = Sprites.Sprites()
    player_obj = Players.Player()
    asteroids_obj = Players.Asteroids()

    event_handler_obj = AsteroidsGame.Event_Handler(player_obj)
    draw_handler_obj = AsteroidsGame.Draw_Handler(sprite_obj, player_obj,
                                                  asteroids_obj)

    state = 'blank screen'

    while event_handler_obj['running']:

        for event in pygame.event.get():
            '''
            instead of having a huge number of if-branches to assess the events, maybe
            we can pass the event to an event handler which returns a dictionary/hash table
            that describes the state of the game/player (i.e. {game_state: True, player_health: 100, etc...})
            '''
            event_handler_obj.action(event, draw_handler_obj)

        draw_handler_obj['']

        pygame.display.flip()

    pygame.quit()
Beispiel #10
0
def PlayerAnimate(cont):

    obj = cont.owner

    mv = obj.getVelocity()

    if abs(mv.x) > 0.1:
        obj['anim'] = 'walk'
        sprfps = 6
    else:
        obj['anim'] = 'stand'
        sprfps = 12

    if mv.x > 0.1:
        obj['facing'] = 1
    elif mv.x < -0.1:
        obj['facing'] = -1

    e = obj['sprite'].worldOrientation.to_euler()

    if obj['facing'] == 1:
        e.z = 0
    elif obj['facing'] == -1:
        e.z = math.pi

    obj['sprite'].worldOrientation = e

    anim = obj['animdict'][obj['anim']]

    obj['sprite']['spranim'] = anim
    obj['sprite']['sprfps'] = sprfps

    Sprites.SpriteMesh(obj['sprite'])
Beispiel #11
0
    def __create_sprites(self):
        """创建精灵组"""
        # 背景组
        bg1 = sp.BGSprite()
        bg2 = sp.BGSprite(True)
        self.back_group = pygame.sprite.Group(bg1, bg2)
        # 敌机组
        enemy = sp.EnemySprite()
        self.enemy_group = pygame.sprite.Group(enemy)
        # 英雄组
        self.hero = sp.HeroSprite()
        self.hero_group = pygame.sprite.Group(self.hero)
        # 补给组
        self.bomb = sp.BombSprite()
        self.bomb_group = pygame.sprite.Group(self.bomb)

        self.destroy_group = pygame.sprite.Group()
Beispiel #12
0
 def PrintRealmToSurface(self):
     AllSpriteRect = Sprites.SpriteGroupRect(self.gameSprites)
     OutSurface = pygame.surface.Surface(AllSpriteRect.size)
     OutSurface.fill(Settings.FloorColor)
     self.teleportAllSprites(-AllSpriteRect.left, -AllSpriteRect.top)
     for sprite in self.gameSprites:
         sprite.draw(OutSurface)
     self.teleportAllSprites(AllSpriteRect.left, AllSpriteRect.top)
     return OutSurface
Beispiel #13
0
    def __event_handler(self):
        """事件监听"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("退出游戏...")
                pygame.quit()
                exit()
            if event.type == CREATE_ENEMY_EVENT:
                # 创建敌机,并且添加到敌机组
                self.enemy_group.add(sp.EnemySprite())
                # 测试敌机精灵数量
                # enemy_count = len(self.enemy_group.sprites())
                # print("敌机精灵数量 %d" % enemy_count)
            if event.type == CREATE_STRONG_ENEMY_EVENT:
                # 创建敌机,并且添加到敌机组
                self.enemy_group.add(sp.StrongEnemySprite())
            if event.type == CREATE_BOSS_EVENT:
                # 创建敌机,并且添加到敌机组
                self.enemy_group.add(sp.BossSprite())
            if event.type == CREATE_BOMB_EVENT:
                # 创建bomb,并且添加到bomb组
                self.bomb_group.add(sp.BombSprite())
            if event.type == HERO_FIRE_EVENT:
                # 英雄发射子弹
                self.hero.fire()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                print("gaga, bombs left : %d" % self.hero.has_bombs)
                if self.hero.has_bombs > 0:
                    self.hero.has_bombs -= 1
                    enemies = pygame.sprite.groupcollide(self.enemy_group, self.enemy_group, False, True )
                    for enemy in enemies:
                        enemy.life -= 1
                        if enemy.life <= 0:
                            enemy.add(self.destroy_group)
                            enemy.remove(self.enemy_group)

        # 通过 pygame.key 获取用户按键
        keys_pressed = pygame.key.get_pressed()
        hdir = keys_pressed[pygame.K_d] - keys_pressed[pygame.K_a]
        vdir = keys_pressed[pygame.K_s] - keys_pressed[pygame.K_w]
        # 根据移动方向设置英雄的速度
        self.hero.h_speed = hdir * 5
        self.hero.v_speed = vdir * 5
Beispiel #14
0
 def __init__(self):
     super().__init__()
     self.allSprites = pygame.sprite.Group(
         sp.ButtonSprite(390,
                         450,
                         50,
                         50,
                         "QUIT",
                         pygame.Color('steelblue1'),
                         BLACK,
                         text="yes"),
         sp.ButtonSprite(460,
                         450,
                         50,
                         50,
                         "BACK",
                         pygame.Color('steelblue1'),
                         BLACK,
                         text="no"))
Beispiel #15
0
 def __init__(self):
     super().__init__()
     self.allSprites = pygame.sprite.Group(
         sp.ButtonSprite(50,
                         50,
                         100,
                         50,
                         "MAINMENU",
                         pygame.Color('steelblue1'),
                         BLACK,
                         text="Back"))
Beispiel #16
0
    def __init__(self):
           
        pg.init()

        '''Animation Parameters'''
        self.years_per_tick = 0.0001
        self.pixels_per_AU = 1000./12.
        
        '''Initialize display surface'''
        self.screen_size = (1000,1000)
        self.screen = pg.display.set_mode((int(self.screen_size[0]),
                                           int(self.screen_size[1])))
        self.background = pg.image.load('spacebackground.png').convert_alpha()
        
        self.model = Model.SolarModel()
        
        '''Build Sprites'''
        self.sun = Sprites.PlanetSprite(self.pixels_per_AU,self.screen_size,
                                        'sun.png',self.model.sun)
        self.earth = Sprites.PlanetSprite(self.pixels_per_AU,self.screen_size,
                                          'earth.png',self.model.earth)
        self.rigel5 = Sprites.PlanetSprite(self.pixels_per_AU,self.screen_size,
                                           'rigel5.png',self.model.rigel5)
        self.all = pg.sprite.RenderUpdates([self.sun,self.earth,self.rigel5])                                   
        self.warheadgrp = pg.sprite.RenderUpdates([])
        self.defensegrp = pg.sprite.RenderUpdates([])
        self.asteroidgrp = pg.sprite.RenderUpdates([])
                                           
        '''Set up the timer'''        
        self.ticks = pg.time.get_ticks()
        
        self.screen.blit(self.background,(0,0))
        self.all.clear(self.screen,self.background)
        planets = self.all.draw(self.screen)
        pg.display.update()

        '''Set up Key Flags'''
        self.ra = False
        self.la = False
        self.ua = False 
        self.da = False                   
Beispiel #17
0
    def __init__(self, pos, unit="None", level=1, nature=[], abilsToUse=[]):
        self.pos = pos
        self.teamOn = "None"

        self.sprite = Sprites.Sprite("Spikey", 1)
        self.state = 0

        self.ID = GLOBALS["ID"]
        GLOBALS["ID"] += 1

        self.level = level

        self.target = None
        self.abilities = []
        self.abilToUse = None
        self.casting = False

        self.stats = {
            "OFF": [5, 100],
            "DEF": [5, 100],
            "CON": [5, 100],
            "STA": [5, 100],
            "SPE": [5, 100]
        }
        self.statBuffs = {"OFF": 0, "DEF": 0, "CON": 0, "STA": 0, "SPE": 0}
        self.health = [50, 50, 0]
        self.energy = [50, 50, 0]
        self.speed = 3
        self.size = 15

        self.nature = nature
        self.abilsToUse = abilsToUse

        self.buffs = []

        self.obeying = False

        self.currGoal = "None"

        self.angFacing = 0

        self.damageTaken = [0, None]
        self.enragedAt = None
        self.movedThisFrame = False

        self.enraged = False
        self.cooldown = False
        self.stunned = False

        self.safeTime = 0

        self.unitName = unit
        self.loadStats(unit)
Beispiel #18
0
def main():
    sprite = Sprites()
    sprite.createAnimation("animation", 7, "ninja/flip_0")
    #sprite.createAnimation("animation2", 5, "ninja/die_0")
    sprite.setDelay(50)
    while True:
        screen.fill((0, 0, 0))
        sprite.playAnimation("animation", 0, 0, screen)
        #sprite.playAnimation("animation2", 140, 140, screen)
        msElapsed = clock.tick(30)  #PCMR
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
Beispiel #19
0
 def __init__(self):
     super().__init__()
     self.allSprites = pygame.sprite.Group(
         sp.TextboxSprite(360, 90, 180, 420, GRAY_GREEN),
         sp.TextboxSprite(370, 100, 160, 50, LIGHT_GREEN2,
                          text="Main Menu"),
         sp.ButtonSprite(400,
                         300,
                         100,
                         50,
                         "GAME",
                         LIGHT_GREEN,
                         DARK_BLUE,
                         textColor=DARK_BLUE2,
                         text="Play"),
         sp.ButtonSprite(400,
                         400,
                         100,
                         50,
                         "CONFIRM",
                         LIGHT_GREEN,
                         DARK_BLUE,
                         textColor=DARK_BLUE2,
                         text="Quit"))
Beispiel #20
0
 def Draw(self, outputName="output"):
     from PIL import Image
     import Sprites
     
     image_width = self.colCount * Sprites.CellSize
     image_height = self.rowCount * Sprites.CellSize
     
     image = Image.new('RGBA', (image_width, image_height), 'black')
     
     for row in range(self.rowCount):
         for col in range(self.colCount):
             offset = ((col * Sprites.CellSize), (image_height - ((row+1) * Sprites.CellSize)))
             
             sprite = Sprites.SelectSprite(self[col, row])
             image.paste(sprite, offset)
     
     image.save(outputName + ".png")
Beispiel #21
0
    def run(self):
        #Loop del juego
        self.playing = True

        while self.playing:
            #Mantains the speed
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()
            for i in self.evil_sprites:
                if self.player.updateX() == i.updateX(
                ) and self.player.updateY() == i.updateY():
                    print("Choque")
                    pg.quit()
            for i in self.coin_sprites:
                if self.player.updateX() == i.updateX(
                ) and self.player.updateY() == i.updateY():
                    print("Coin up")
                    i.kill()
                    self.coins += 1
                    q = Coin.Coin(random.randrange(0, 30),
                                  random.randrange(0, 30), self, YELLOW)
                    self.coin_sprites.add(q)
                    self.all_sprites.add(q)
                    print("COINER")
                    print(self.coins)
            if self.coins == 20:
                i = Coin.Coin(random.randrange(0, 30), random.randrange(0, 30),
                              self, PURPLE)
                self.pill_sprites.add(i)
                self.all_sprites.add(i)
                self.coins = 0
                q = Player.Chaser(random.randrange(0, 30),
                                  random.randrange(0, 30), self,
                                  random.choice(COLORS))
                self.evil_sprites.add(q)
                self.all_sprites.add(q)

            for i in self.pill_sprites:
                if self.player.updateX() == i.updateX(
                ) and self.player.updateY() == i.updateY():
                    print("Pill up")
                    i.kill()

        pg.quit()
Beispiel #22
0
    def new(self):
        #Inicia el juego

        self.creationTimer = 0

        self.player = Player.PacMan(0, 0)

        self.all_sprites = pg.sprite.Group()

        self.evil_sprites = pg.sprite.Group()

        #My shit
        self.coin_sprites = pg.sprite.Group()
        #End of my shit

        self.pill_sprites = pg.sprite.Group()

        self.all_sprites.add(self.player)

        self.run()
Beispiel #23
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((1024, 768))
    pygame.display.set_caption('Teh Platformz')
    pygame.mouse.set_visible(1)
    background = pygame.Surface([1024, 768])
    background.fill(THECOLORS["black"])
    screen.blit(background, [0,0])

    the_level = Level.Level("data/levels/level1.dat")
    (level, characters) = the_level.get_sprites()
    the_hero = Sprites.Character("data/graphics/hero-small.png", [40,40])
    characters.add(the_hero)

    done = False
    # Main loop
    while not done:

        # Check for input
        for e in pygame.event.get():
            if e.type == QUIT:
                done = True
                break
            elif e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    done = True
                    break

        level.update(pygame.time.get_ticks())
        #characters.update(pygame.time.get_ticks())

        rectlist = level.draw(screen)
        rectlist.extend(characters.draw(screen))
        pygame.display.update(rectlist)

        pygame.time.delay(10)
        level.clear(screen, background)
        characters.clear(screen, background)

    print "Done"
    return
Beispiel #24
0
def CreationRes():
	print("Creation de la classe Ressources")
	#On creait ici les variables
	res.fenetre = pygame.display.set_mode((res.ResolutionX, res.ResolutionY))
	res.continuer_jeu = 1 #Variable qui indique si le jeu est en cours
    
	#On charge la partie reseau
	Reseau.Reseau()
	#On charge les sprites avant tout
	Sprites.ChargerSpritePersonnage()
    #Creation des autres classes
	res.niveau = class_niveau.Niveau("n3") #Doit etre avant character car c'est ici qu'on calcul les resolution du personnage
	res.character = class_perso.Perso()
	res.interface = class_interface.Interface()
	#Creation des moteurs graphique et physique 
	res.moteurphysique = class_moteurphysique.MoteurPhysique()
	res.moteurgraphique = class_moteurgraphique.MoteurGraphique()
	res.moteuranimation = class_moteuranimation.MoteurAnimation()
	res.moteurscrolling = class_moteurscrolling.MoteurScrolling()
	
    #Images
	res.fond = pygame.image.load("images/fond.jpg").convert()
Beispiel #25
0
    def loadStats(self, unit):
        if unit in UNITSTATS:
            #Set default values of stats
            for k in self.stats:
                if k in UNITSTATS[unit]:
                    self.stats[k] = [0, int(UNITSTATS[unit][k])]
                else:
                    print "ERROR when loading stats.  UNITSTATS[" + unit + "] does not contain '" + k + "'"

            #Add Nature Bonuses
            if self.nature:
                if self.nature[0] in self.stats:
                    self.stats[self.nature[0]][1] *= 1.1
                if self.nature[1] in self.stats:
                    self.stats[self.nature[1]][1] *= 0.9
            #Set picture/evolution state
            if "PIC" in UNITSTATS[unit] and "STATE" in UNITSTATS[unit]:
                self.sprite = Sprites.Sprite(UNITSTATS[unit]["PIC"],
                                             int(UNITSTATS[unit]["STATE"]))
                self.state = UNITSTATS[unit]["STATE"]
            else:
                print "ERROR when loading stats.  UNITSTATS[" + unit + "] does not contain PIC or STATS"
            #Set size
            if "SIZE" in UNITSTATS[unit]:
                self.size = int(UNITSTATS[unit]["SIZE"]) / 2
            else:
                print "ERROR when loading stats.  UNITSTATS[" + unit + "] does not contain SIZE"
            #Calculate current values of stats
            calcStatsAtLevel(self.level, self.stats, self.health, self.energy)
            self.speed = calcSpeed(self.getStat("SPE"), self.level)

        else:
            print "ERROR: ", unit, "not in Unit stats"

        self.abilities = Abilities.calcAbilList(self.level, self,
                                                self.abilsToUse)
Beispiel #26
0
def ChargerSpritePersonnage():
    print "Chargement des sprites du personnage"

    #Calcul de la resolution du blitage des personnages
    CalculerResolution()
    #Creation du tableau de personnage
    CreerPersonnageSprite()
    #On ne charge que l'image 0 pour le moment
    for i in range(0, 4):
        for u in range(0, 3):
            Sprites.personnage[i].append(
                pygame.image.load(
                    Sprites.StringPersonnage(NumeroPersonnage, i, u)))
            Sprites.personnage[i][u] = pygame.transform.scale(
                Sprites.personnage[i][u],
                (Sprites.ResSpritePersoX, Sprites.ResSpritePersoY))
            Sprites.personnage[i][u].convert()
    print "Fin de chargement des sprites du personnage"

    #On charge le sprite de la balle
    Sprites.balle = pygame.image.load("images//balle.png")
    Sprites.balle = pygame.transform.scale(
        Sprites.balle, (Sprites.ResSpriteBalleX, Sprites.ResSpriteBalleY))
    Sprites.balle.convert()
Beispiel #27
0
def main(genomes, config):
    global generation
    generation += 1
    nets = []
    pigs = []
    ge = []
    game = Game()
    clock_tick = 60

    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        pig = Sprites.Pig(game)
        pigs.append(pig)
        game.pig_sprites.add(pig)
        g.fitness = 0
        ge.append(g)

    game.add_pipe()
    # Main loop
    while game.running:
        alive_list = []
        for pig in game.pig_sprites:
            alive_list.append(pig.alive)
        if not any(alive_list):
            game.paused = True

        if len(pigs) == 0:
            break
            game.running = False

        # Creates new pipes
        if game.pipe_sprites.sprites(
        )[-1].rect.left <= game.DISPLAY_WIDTH - game.PIPE_FREQUENCY:
            game.add_pipe()

        # Removes offscreen pipes
        for sprite in game.pipe_sprites:
            if sprite.rect.right <= 0:
                game.pipe_sprites.remove(sprite)

        # Checks for button presses and acts upon that action
        for event in pygame.event.get():
            # Ends game if exit is pressed
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()

            if event.type == pygame.KEYDOWN:
                if clock_tick == 180:
                    clock_tick = 60
                else:
                    clock_tick = 180

        # Updates sprites
        if not game.paused:
            game.pipe_sprites.update()
            game.pig_sprites.update()

        for pipe in game.pipe_sprites:
            if not pipe.passed and pipe.follow_pipe != None:
                current_pipe = pipe
                for x, pig in enumerate(pigs):

                    ge[x].fitness += 0.1 + pig.adjust_fitness()

                    outputs = nets[x].activate(
                        (pipe.rect.bottom - pig.rect.top,
                         pipe.follow_pipe.rect.top - pig.rect.bottom))

                    if outputs[0] > 0:
                        pig.jump()
                break

        for x, pig in enumerate(pigs):
            if pig.collided():
                pigs.pop(x)
                nets.pop(x)
                ge.pop(x)
                game.pig_sprites.remove(pig)

        # Draws display
        game.gameDisplay.fill((255, 255, 255))
        game.gameDisplay.blit(game.background_img, (0, 0))

        game.pipe_sprites.draw(game.gameDisplay)
        game.pig_sprites.draw(game.gameDisplay)

        textsurface = game.font.render("Score: " + str(game.score), False,
                                       (255, 255, 255))
        game.gameDisplay.blit(
            textsurface,
            (int(game.DISPLAY_WIDTH - textsurface.get_width() - 20),
             int(game.DISPLAY_HEIGHT * 0.05)))

        textsurface = game.font.render("Generation: " + str(generation), False,
                                       (255, 255, 255))
        game.gameDisplay.blit(
            textsurface,
            (int(game.DISPLAY_WIDTH - textsurface.get_width() - 20),
             int(game.DISPLAY_HEIGHT * 0.1)))

        if clock_tick == 60:
            textsurface = game.font.render("Press button to speed up", False,
                                           (255, 255, 255))
            game.gameDisplay.blit(
                textsurface,
                (int(game.DISPLAY_WIDTH // 2 - textsurface.get_width() // 2),
                 int(game.DISPLAY_HEIGHT * 0.95)))

        pygame.display.update()
        game.clock.tick(clock_tick)
Beispiel #28
0
 def add_pipe(self):
     pipe_y_pos = int(random.random() * self.DISPLAY_HEIGHT * 0.5 + 250)
     pipe = Sprites.Pipe(pipe_y_pos, self)
     self.pipe_sprites.add(pipe)
     self.pipe_sprites.add(
         Sprites.Pipe(pipe_y_pos - self.PIPE_GAP, self, pipe))
Beispiel #29
0
 def restart(self):
     self.pipe_sprites.empty()
     self.pig_sprites.empty()
     self.pig_sprites.add(Sprites.Pig(self))
     self.paused = False
     self.add_pipe()
Beispiel #30
0
EditRightClickMode = "SelectSprites"
PlayMouseModes = ["TeleportSelectedAllies", "CenterAtMouse", "SelectAllies"]
PlayLeftClickMode = "TeleportSelectedAllies"
PlayMiddleClickMode = "CenterAtMouse"
PlayRightClickMode = "SelectAllies"
selectRect = pygame.Rect(0, 0, 0, 0)
showSelectRect = False

# Sprites Groups
hudSprites = pygame.sprite.Group()
selectedSprites = pygame.sprite.Group()
selectedAllies = pygame.sprite.Group()
clickable = pygame.sprite.Group()

# # hudSprites
PD = sp.AnimatedSprite("Port1", 1468, 862)
hudSprites.add(PD)


def recenterAt(x, y):
    cr.teleportAllSprites(SCREEN_WIDTH // 2 - x, SCREEN_HEIGHT // 2 - y)


def OutputRealmToPNG():
    rs = cr.PrintRealmToSurface()
    pygame.image.save(rs, 'Realm' + cr.name + '.png')


# Game Loop
isRunning = True
gameModes = ['Edit', 'Play', 'Settings']