Beispiel #1
0
def run_game():
    pygame.init()
    settings = game_settings.Settings()
    screen = pygame.display.set_mode(settings.resolution)
    snake = Snake(screen, settings)
    pygame.display.set_caption("Snake")
    my_tail = []
    x, y = gf.generate_randoms()
    food = GroupSingle(Food(snake, screen, x, y))
    tails = OrderedUpdates()
    gf.initialise_snake(snake, screen, my_tail, tails, settings)
    button = Play_button(screen, settings, "Play")
    end_game_screen = EndGameScreen(screen, settings, "Game Over")
    score = Score(screen, settings)
    clock = pygame.time.Clock()
    gametime = GTime(clock)

    while True:
        screen.fill(settings.bg_color)
        score.draw_me()
        gf.check_events(snake, food, screen, my_tail, tails, settings, button,
                        gf, end_game_screen, score, gametime)
        if settings.game_active == False:
            if gf.lose_condition_met(snake, settings, tails,
                                     gametime) == False:
                button.draw_me()
        if settings.game_active == True:
            snake.update()
            tails.update()
            snake.draw_me()
            food.update()
            clock.tick(10)
            gametime.update()
            print(gametime.time)
        pygame.display.flip()
Beispiel #2
0
class Game:

    def __init__(self, title='Checkers', log_level=log.INFO, show_fps=False):
        log.basicConfig(level=log_level)
        self.show_fps = show_fps
        self.window_title = title
        self.game = Board(BOARD_DIM)
        # Initialize Game Groups
        self.brown_spaces = RenderUpdates()
        self.pieces = RenderUpdates()
        self.piece_selected = GroupSingle()
        self.space_selected = GroupSingle()
        self.current_piece_position = ORIGIN
        self.screen = None
        self.fps_clock = None
        self.font = None
        self.font_rect = None
        self.background = None
        self.background_rect = None
        self.fps_text = None
        self.fps_rect = None
        self.winner_text = None
        self.winner_rect = None

    def _board_setup(self, **kwargs):
        """ initialize board state """
        brown_spaces = kwargs.get('brown_spaces')
        for col, row in self.game.usable_positions():
            loc = TILE_WIDTH * col + (BORDER_WIDTH / 2), TILE_WIDTH * row + (BORDER_WIDTH / 2)
            brown_spaces.add(SquareSprite(loc, "brown", row, col))

    def _screen_init(self):
        """ Initialise screen """
        pygame.init()
        self.screen = pygame.display.set_mode(SCREEN_RES)
        pygame.display.set_caption(self.window_title)
        return self.screen

    def _get_background(self):
        result = pygame.Surface(self.screen.get_size())
        (bg_img, bg_rect) = ImageLoader.load_img('marble-board.jpg')
        result.blit(bg_img, bg_rect)
        return result.convert(), bg_rect

    def _get_fps_text(self):
        fps_text = self.font.render("%4.1f fps" % self.fps_clock.get_fps(), True, WHITE)
        rect = fps_text.get_rect()
        rect.right, rect.bottom = self.background_rect.right, self.background_rect.bottom
        return fps_text, rect

    def _draw_fps(self):
        if self.show_fps:
            self.fps_text, self.fps_rect = self._get_fps_text()
            self.screen.blit(self.fps_text, self.fps_rect)

    def _clear_fps(self):
        if self.show_fps:
            self.screen.blit(self.background, self.fps_rect, area=self.fps_rect)

    def _clear_items(self):
        self._clear_winner()
        self._clear_fps()
        self.piece_selected.clear(self.screen, self.background)
        self.pieces.clear(self.screen, self.background)

    def _draw_winner(self):
        winner = self.game.winner()
        if winner:
            self.winner_text = self.font.render("%s wins!" % winner.title(), True, WHITE)
            winner_rect = self.winner_text.get_rect()
            winner_rect.centerx = self.background.get_rect().centerx
            winner_rect.top = 100
            self.winner_rect = winner_rect
            self.screen.blit(self.winner_text, winner_rect)

    def _clear_winner(self):
        winner = self.game.winner()
        if winner:
            self.screen.blit(self.background, self.winner_rect, area=self.winner_rect)

    def _quit(self):
        log.debug('quitting')
        sys.exit()

    def _select_piece(self, event):
        # select the piece by seeing if the piece collides with cursor
        self.piece_selected.add(piece for piece in self.pieces if piece.rect.collidepoint(event.pos))
        # Capture piece's original position (at center) to determine move on drop
        if len(self.piece_selected) > 0:
            # Assumed: starting a move
            pygame.event.set_grab(True)
            self.pieces.remove(self.piece_selected)
            self.current_piece_position = (self.piece_selected.sprite.rect.centerx,
                                           self.piece_selected.sprite.rect.centery)
            log.debug('grabbing input, picked up piece at %s', self.current_piece_position)

    def _drag_piece(self):
        #  Until button is let go, move the piece with the mouse position
        self.piece_selected.update(pygame.mouse.get_pos())
        log.debug('updated piece to %s', pygame.mouse.get_pos())

    def _drop_piece(self, event):
        if pygame.event.get_grab():
            pygame.event.set_grab(False)
            log.debug('releasing input')

            # center the piece on the valid space; if it is not touching a space, return it to its original position
            self.space_selected.add(space for space in self.brown_spaces
                                    if space.rect.collidepoint(event.pos))

            if self.piece_selected and self.space_selected:
                log.debug('dropped a piece')
                piece, space = self.piece_selected.sprite, self.space_selected.sprite
                try:
                    captured = self.game.move(piece.location, (space.col, space.row))
                    if captured:
                        self.pieces.remove(captured)
                except InvalidMoveException as ce:
                    log.debug(ce)
                log.debug("%s", str(self.game))

            self.piece_selected.sprite.update_from_board()

            # Add piece back to stationary set
            self.pieces.add(self.piece_selected)

            # clean up for the next selected piece
            self.piece_selected.empty()
            self.space_selected.empty()

    def _draw_items(self):
        self.pieces.draw(self.screen)
        self.piece_selected.draw(self.screen)
        self._draw_winner()
        self._draw_fps()


    def run(self):

        log.debug('starting game')

        log.debug('initializing screen')
        self.screen = self._screen_init()

        log.debug('getting font')
        self.font = pygame.font.Font(None, 36)

        log.debug('loading background')
        self.background, self.background_rect= self._get_background()

        log.debug('building initial game board')
        self._board_setup(brown_spaces=self.brown_spaces)

        log.debug('initializing game pieces')
        for player, x, y in self.game.start_positions():
            new_piece = PieceSprite(player)
            self.game.add_piece(new_piece, (x, y))
            new_piece.update_from_board()
            self.pieces.add(new_piece)

        log.debug('drawing initial content to screen')
        self.screen.blit(self.background, ORIGIN)
        pygame.display.flip()

        self.piece_selected = GroupSingle()
        self.space_selected = GroupSingle()
        self.current_piece_position = ORIGIN

        self.fps_clock = Clock()

        self._draw_fps()

        # Event loop
        while True:

            self._clear_items()

            for event in pygame.event.get():

                if event.type == QUIT:
                    self._quit()

                if event.type == MOUSEBUTTONDOWN:     # select a piece
                    log.debug('mouse pressed')
                    self._select_piece(event)

                if event.type == MOUSEBUTTONUP:     # let go of a piece
                    log.debug('mouse released')
                    self._drop_piece(event)

                if pygame.event.get_grab():          # drag selected piece around
                    log.debug('dragging')
                    self._drag_piece()

            self._draw_items()

            self.fps_clock.tick(60)  # Waits to maintain 60 fps

            # TODO: Use display.update instead
            pygame.display.flip()
Beispiel #3
0
class Game(Application):
    def __init__(self):
        Application.__init__(self)

        self.screenRect = self.screen.get_rect()
        
        self.minDt = 200
        self.enemyGroup = Group()
        self.enemyGroup.add(BasicEnemy(100,100,0,1,self.screenRect,80))

        self.bulletGroup = Group()

        self.player = Player(self.screenRect)
        self.playerGroup = GroupSingle(self.player)
        self.playerWeaponType = 1
        self.playerFired = False
        self.playerMoveX = 0
        self.playerMoveY = 0
        self.playerMoveFlag = False

    def handle_event(self,event):
        if event.type == MOUSEBUTTONUP and event.button == 1:
             self.playerFired = True
        if event.type == KEYDOWN:
            ## need to put in KEYUP to turn off the thing...
            if event.key == K_DOWN:
                self.playerMoveY = 1
                self.playerMoveFlag = True
            if event.key == K_UP:
                self.playerMoveY = -1
                self.playerMoveFlag = True
            if event.key == K_LEFT:
                self.playerMoveX = -1
                self.playerMoveFlag = True
            if event.key == K_RIGHT:
                self.playerMoveX = 1
                self.playerMoveFlag = True
            if event.key == K_SPACE:
                self.playerFired = True
        
        if event.type == KEYUP:
            if event.key == K_DOWN:
                self.playerMoveY = 0
                self.playerMoveFlag = True
            if event.key == K_UP:
                self.playerMoveY = 0
                self.playerMoveFlag = True
            if event.key == K_LEFT:
                self.playerMoveX = 0
                self.playerMoveFlag = True
            if event.key == K_RIGHT:
                self.playerMoveX = 0
                self.playerMoveFlag = True

    def update(self, screen):
        dt = min(self.minDt, self.clock.get_time())
        self.enemyGroup.update(dt)

        if self.playerFired:
            self.bulletGroup.add(self.player.shoot(self.playerWeaponType))
            self.playerFired = False

        ## need to validate holding down the key... 
        if self.playerMoveFlag:
            self.player.setDirection(self.playerMoveX, self.playerMoveY)
            self.playerMoveFlag = False
            
        self.bulletGroup.update(dt)
        self.playerGroup.update(dt)

        pygame.sprite.groupcollide(self.enemyGroup, self.bulletGroup, True, True)
            
    def draw(self,screen):
        screen.fill((0,0,0))
        self.playerGroup.draw(screen)
        self.enemyGroup.draw(screen)
        self.bulletGroup.draw(screen)
Beispiel #4
0
	screenSurface.fill(pi_globals.BLACK)

	position = Vector2(0, 0)
	pressedKeys = pygame.key.get_pressed()

	if pressedKeys[pygame.K_w] or pressedKeys[pygame.K_UP]:
		position.y -= 1

	if pressedKeys[pygame.K_s] or pressedKeys[pygame.K_DOWN]:
		position.y += 1

	# Hard Coded Speed
	player.position += position * 10;

	playerGroup.update()

	playerGroup.draw(screenSurface)

	# Update screen with what has been drawn
	display.flip()

	# Game loop clock tick and delta time calculation
	pi_globals.deltaTime = clock.tick_busy_loop(pi_globals.FRAMERATE) / 1000.0  # Close the window and quit.
	
pygame.quit()

######## Refrence Player ########

# Player class with hard coded sprite
# class Player(pygame.sprite.Sprite):
Beispiel #5
0
def main():
    # initialze pygame
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE)
    bounds = screen.get_rect()

    # initialize the game
    player = Player(bounds.center, bounds)
    player_grp = GroupSingle(player)
    enemies = Group()
    spawn_counter = 0
    fast_spawn_counter = 0
    score = 0

    font = pygame.font.Font(None, 40)

    # game loop
    done = False
    clock = pygame.time.Clock()
    while not done:
        # input
        for event in pygame.event.get():
            if event.type == QUIT:
                done = True
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                done = True
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                player.shoot()
            elif event.type == KEYDOWN and event.key == K_SPACE and not player.alive():
                player = Player(bounds.center, bounds)
                player_grp.add(player)
                score = 0
                for enemy in enemies:
                    enemy.kill()
                # same as enemies.empty()

        # update
        player_grp.update()
        player.bullets.update()
        enemies.update()

        # spawn enemies
        spawn_counter += 1
        if spawn_counter >= 10:
            n = randrange(4)
            for i in range(n):
                x = randrange(bounds.width - Enemy.width) 
                enemy = Enemy((x, 0), bounds)
                enemies.add(enemy)
            spawn_counter = 0

        # fast spawn 
        fast_spawn_counter += 1
        if fast_spawn_counter >= 45:
            x = randrange(bounds.width - FastEnemy.width)
            enemy = FastEnemy((x, 0), bounds)
            enemies.add(enemy)
            fast_spawn_counter = 0

        # collisions
        groupcollide(player_grp, enemies, True, False)

        for enemy in groupcollide(enemies, player.bullets, True, True):
            if player.alive():
                score += 1

        # draw
        screen.fill(BG_COLOR)
        player_grp.draw(screen)
        player.bullets.draw(screen)
        enemies.draw(screen)

        score_text = font.render("Score: %08d"%score, False, (255, 255, 255))
        screen.blit(score_text, (5, 5))

        if not player.alive():
            gameover = font.render("Press Space to Respawn", False, (255, 255, 255))
            rect = gameover.get_rect()
            rect.center = screen.get_rect().center
            screen.blit(gameover, rect)

        pygame.display.flip()

        clock.tick(30)
Beispiel #6
0
        vida_foguete += -1
        if vida_foguete == 0:
            perdeu = True

    superficie.blit(fundo, (0, 0))

    fonte_abates = fonte.render(f'Abates: {abates}', True, (129, 101, 239))
    superficie.blit(fonte_abates, (20, 70))

    fonte_vida = fonte.render(f'Vidas: {vida_foguete}', True, (129, 101, 239))
    superficie.blit(fonte_vida, (20, 550))

    grupo_foguete.draw(superficie)
    grupo_cometas.draw(superficie)
    grupo_balas.draw(superficie)

    grupo_foguete.update()
    grupo_cometas.update()
    grupo_balas.update()

    if perdeu:
        game_over = fonte_perdeu.render('Game Over', True, (129, 101, 239))
        superficie.blit(game_over, (200, 200))
        display.update()
        pygame.mixer.music.stop()
        som_bala.stop()
        pygame.time.delay(1000)

    display.update()
    round += 1
Beispiel #7
0
class Game:
    def __init__(self, title='Checkers', log_level=log.INFO, show_fps=False):
        log.basicConfig(level=log_level)
        self.show_fps = show_fps
        self.window_title = title
        self.game = Board(BOARD_DIM)
        # Initialize Game Groups
        self.brown_spaces = RenderUpdates()
        self.pieces = RenderUpdates()
        self.piece_selected = GroupSingle()
        self.space_selected = GroupSingle()
        self.current_piece_position = ORIGIN
        self.screen = None
        self.fps_clock = None
        self.font = None
        self.font_rect = None
        self.background = None
        self.background_rect = None
        self.fps_text = None
        self.fps_rect = None
        self.winner_text = None
        self.winner_rect = None

    def _board_setup(self, **kwargs):
        """ initialize board state """
        brown_spaces = kwargs.get('brown_spaces')
        for col, row in self.game.usable_positions():
            loc = TILE_WIDTH * col + (BORDER_WIDTH /
                                      2), TILE_WIDTH * row + (BORDER_WIDTH / 2)
            brown_spaces.add(SquareSprite(loc, "brown", row, col))

    def _screen_init(self):
        """ Initialise screen """
        pygame.init()
        self.screen = pygame.display.set_mode(SCREEN_RES)
        pygame.display.set_caption(self.window_title)
        return self.screen

    def _get_background(self):
        result = pygame.Surface(self.screen.get_size())
        (bg_img, bg_rect) = ImageLoader.load_img('marble-board.jpg')
        result.blit(bg_img, bg_rect)
        return result.convert(), bg_rect

    def _get_fps_text(self):
        fps_text = self.font.render("%4.1f fps" % self.fps_clock.get_fps(),
                                    True, WHITE)
        rect = fps_text.get_rect()
        rect.right, rect.bottom = self.background_rect.right, self.background_rect.bottom
        return fps_text, rect

    def _draw_fps(self):
        if self.show_fps:
            self.fps_text, self.fps_rect = self._get_fps_text()
            self.screen.blit(self.fps_text, self.fps_rect)

    def _clear_fps(self):
        if self.show_fps:
            self.screen.blit(self.background,
                             self.fps_rect,
                             area=self.fps_rect)

    def _clear_items(self):
        self._clear_winner()
        self._clear_fps()
        self.piece_selected.clear(self.screen, self.background)
        self.pieces.clear(self.screen, self.background)

    def _draw_winner(self):
        winner = self.game.winner()
        if winner:
            self.winner_text = self.font.render("%s wins!" % winner.title(),
                                                True, WHITE)
            winner_rect = self.winner_text.get_rect()
            winner_rect.centerx = self.background.get_rect().centerx
            winner_rect.top = 100
            self.winner_rect = winner_rect
            self.screen.blit(self.winner_text, winner_rect)

    def _clear_winner(self):
        winner = self.game.winner()
        if winner:
            self.screen.blit(self.background,
                             self.winner_rect,
                             area=self.winner_rect)

    def _quit(self):
        log.debug('quitting')
        sys.exit()

    def _select_piece(self, event):
        # select the piece by seeing if the piece collides with cursor
        self.piece_selected.add(piece for piece in self.pieces
                                if piece.rect.collidepoint(event.pos))
        # Capture piece's original position (at center) to determine move on drop
        if len(self.piece_selected) > 0:
            # Assumed: starting a move
            pygame.event.set_grab(True)
            self.pieces.remove(self.piece_selected)
            self.current_piece_position = (
                self.piece_selected.sprite.rect.centerx,
                self.piece_selected.sprite.rect.centery)
            log.debug('grabbing input, picked up piece at %s',
                      self.current_piece_position)

    def _drag_piece(self):
        #  Until button is let go, move the piece with the mouse position
        self.piece_selected.update(pygame.mouse.get_pos())
        log.debug('updated piece to %s', pygame.mouse.get_pos())

    def _drop_piece(self, event):
        if pygame.event.get_grab():
            pygame.event.set_grab(False)
            log.debug('releasing input')

            # center the piece on the valid space; if it is not touching a space, return it to its original position
            self.space_selected.add(space for space in self.brown_spaces
                                    if space.rect.collidepoint(event.pos))

            if self.piece_selected and self.space_selected:
                log.debug('dropped a piece')
                piece, space = self.piece_selected.sprite, self.space_selected.sprite
                try:
                    captured = self.game.move(piece.location,
                                              (space.col, space.row))
                    if captured:
                        self.pieces.remove(captured)
                except InvalidMoveException as ce:
                    log.debug(ce)
                log.debug("%s", str(self.game))

            self.piece_selected.sprite.update_from_board()

            # Add piece back to stationary set
            self.pieces.add(self.piece_selected)

            # clean up for the next selected piece
            self.piece_selected.empty()
            self.space_selected.empty()

    def _draw_items(self):
        self.pieces.draw(self.screen)
        self.piece_selected.draw(self.screen)
        self._draw_winner()
        self._draw_fps()

    def run(self):

        log.debug('starting game')

        log.debug('initializing screen')
        self.screen = self._screen_init()

        log.debug('getting font')
        self.font = pygame.font.Font(None, 36)

        log.debug('loading background')
        self.background, self.background_rect = self._get_background()

        log.debug('building initial game board')
        self._board_setup(brown_spaces=self.brown_spaces)

        log.debug('initializing game pieces')
        for player, x, y in self.game.start_positions():
            new_piece = PieceSprite(player)
            self.game.add_piece(new_piece, (x, y))
            new_piece.update_from_board()
            self.pieces.add(new_piece)

        log.debug('drawing initial content to screen')
        self.screen.blit(self.background, ORIGIN)
        pygame.display.flip()

        self.piece_selected = GroupSingle()
        self.space_selected = GroupSingle()
        self.current_piece_position = ORIGIN

        self.fps_clock = Clock()

        self._draw_fps()

        # Event loop
        while True:

            self._clear_items()

            for event in pygame.event.get():

                if event.type == QUIT:
                    self._quit()

                if event.type == MOUSEBUTTONDOWN:  # select a piece
                    log.debug('mouse pressed')
                    self._select_piece(event)

                if event.type == MOUSEBUTTONUP:  # let go of a piece
                    log.debug('mouse released')
                    self._drop_piece(event)

                if pygame.event.get_grab():  # drag selected piece around
                    log.debug('dragging')
                    self._drag_piece()

            self._draw_items()

            self.fps_clock.tick(60)  # Waits to maintain 60 fps

            # TODO: Use display.update instead
            pygame.display.flip()
Beispiel #8
0
def main():
    #initialize pygame
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE)
    bounds = screen.get_rect()

    #initialize game
    Player = Player(bounds.center, bounds) #sets starting position fir player
    player_grp = GroupSingle(player)
    enemies = Group()
    spawn_counter = 0 
    fast_spawn_counter = 0
    score = 0
    font = pygame.font.Font(None, 40)
    

    #game loop
    done = False
    clock = pygame.time.Clock()
    
    while not done:
        #input
        for event in pygame.event.get():
            if event.type == QUIT:
                done = True
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                done = True

            elif event.type == MOUSEBUTTONDOWN and event.button == 1: #1=left mouse button
                player.shoot()
            elif event.type == KEYDOWN and event.key == K_SPACE and not player.alive(): #if player dies, hit space and game restarts
                player = Player(bounds.center,bounds)
                player_grp.add(player)
                for enemy in enemies:
                    enemy.kill() #same as enemies.empty()

        #update
        player_grp.update()     
        player.bullets.update()
        enemies.update()

        #spawn enemies
        spawn_counter+=1
        if spawn_counter >= 10:
            n = randrange(4)
            for i in range(n):
                x = randrange(bounds.width - Enemy.width)
                enemy = Enemy((x,0),bounds)
                enemies.add(enemy)
            spawn_counter = 0 #reset counter afer
            #spawn fast enemy
        fast_spawn_counter += 1
        if fast_spawn_counter >= 45:
            x = randrange(bounds.width - FastEnemy.width)
            enemy = FastEnemy((x,0),bounds)
            enemies.add(enemy)
            fast_spawn_counter = 0

        #collisions - see pygame documentation 
        groupcollide(player_grp, enemies, True, False) #if enemies hit player, player dies
        
        #if bullets hit enemies, enemy dies
        #score keeper
        for enemy in groupcollide(enemies, player.bullets, True, True):
            if player.alive():
                score+=1

        #draw
        screen.fill(BG_COLOR)
        player_grp.draw(screen)
        player.bullets.draw(screen)
        enemies.draw(screen)

        score_text = font.render("Score: %08d"%score, False, (255,255,255))
        screen.blit(score_text, (5,5))
        pygame.display.flip()

        clock.tick(30)
Beispiel #9
0
class Game(StatusHandler):

    def __init__(self, title='Checkers', log_drag=False, show_fps=False, ip='127.0.0.1', port=5000, spectate=False):
        self.game_running = True
        self.player = None
        self.log_drag = log_drag
        self.show_fps = show_fps
        self.window_title = title
        self.game = NetBoard(handler=self, ip=ip, port=port, spectate=spectate)
        # Initialize Game Groups
        self.board_spaces = set()
        self.pieces = RenderUpdates()
        self.piece_selected = GroupSingle()
        self.bg_text = RenderUpdates()
        self.fg_text = RenderUpdates()
        self.current_piece_position = ORIGIN
        self.screen = None
        self.fps_clock = None
        self.font = None
        self.background = None
        self.background_rect = None
        self.fps_text = None
        self.winner_text = None
        self.turn_text = None
        self.player_text = None
        self.game_id_text = None

    def handle_game_id(self, game_id):
        self.game_id_text.text = "Game: %s" % game_id

    def handle_list(self, game_list, list_type):

        if list_type == SPECTATE and game_list:
            game_id = game_list[0]
            self.game.client.spectate(game_id)
            self.player_text.text = 'You are a spectator'
        elif not list_type and game_list:
            game_id = game_list[0]
            self.game.client.join(game_id)
        elif not list_type and not game_list:
            self.game.client.new_game()

    def handle_board(self, board):
        for piece in board:
            new_piece = PieceSprite(piece.player)
            new_piece.king = piece.king
            self.game.add_piece(new_piece, piece.location)
            new_piece.update_from_board()
            self.pieces.add(new_piece)

    def handle_turn(self, player):
        self.game.turn = player

    def handle_you_are(self, player):
        self.player = player

    def handle_moved(self, src, dst):
        moved_pieces = [p for p in self.pieces if p.location == src]
        Board.move(self.game, src, dst)
        if moved_pieces:
            moved_pieces[0].update_from_board()
            Sounds.play('slap.ogg')
            log.debug("board after drop:\n%s", str(self.game))

    def handle_captured(self, loc):
        captured_pieces = [p for p in self.pieces if p.location == loc]
        if captured_pieces:
            self.pieces.remove(captured_pieces[0])

    def _board_space_setup(self):
        """ initialize board state """
        for col, row in self.game.usable_positions():
            self.board_spaces.add(Square(row, col))

    def _screen_init(self):
        """ Initialise screen """
        self.screen = pygame.display.set_mode(SCREEN_RES)
        pygame.display.set_caption(self.window_title)
        return self.screen

    def _get_background(self):
        result = pygame.Surface(self.screen.get_size())
        (bg_img, bg_rect) = Images.load('marble-board.jpg')
        result.blit(bg_img, bg_rect)
        return result.convert(), bg_rect

    def _clear_items(self):
        self.fg_text.clear(self.screen, self.background)
        self.piece_selected.clear(self.screen, self.background)
        self.pieces.clear(self.screen, self.background)
        self.bg_text.clear(self.screen, self.background)

    def _quit(self):
        log.debug('quitting')
        self.game.client.quit()
        self.game_running = False

    def _select_piece(self, event):
        # select the piece by seeing if the piece collides with cursor
        self.piece_selected.add(piece for piece in self.pieces
                                if piece.rect.collidepoint(event.pos)
                                and piece.player == self.player
                                and piece.player == self.game.turn)
        # Capture piece's original position (at center) to determine move on drop
        if len(self.piece_selected) > 0:
            # Assumed: starting a move
            pygame.event.set_grab(True)
            self.pieces.remove(self.piece_selected)
            self.current_piece_position = (self.piece_selected.sprite.rect.centerx,
                                           self.piece_selected.sprite.rect.centery)
            log.debug('grabbing input, picked up piece at %s', self.current_piece_position)
            Sounds.play('slide.ogg')

    def _drag_piece(self):
        #  Until button is let go, move the piece with the mouse position
        if self.log_drag:
            log.debug('dragging')
        rect = self.piece_selected.sprite.rect
        rect.centerx, rect.centery = pygame.mouse.get_pos()
        if self.log_drag:
            log.debug('updated piece to %s', pygame.mouse.get_pos())

    def _reset_selected_piece(self):
        self.piece_selected.sprite.update_from_board()
        Sounds.play('slap.ogg')
        log.debug("board after drop:\n%s", str(self.game))

    def _drop_piece(self, event):
        if pygame.event.get_grab():
            pygame.event.set_grab(False)
            log.debug('releasing input')

            # center the piece on the valid space; if it is not touching a space, return it to its original position
            space_selected = [space for space in self.board_spaces if space.collidepoint(event.pos)]

            if self.piece_selected and space_selected:
                log.debug('dropped a piece')
                piece, space = self.piece_selected.sprite, space_selected[0]
                try:
                    self.game.move(piece.location, (space.col, space.row))
                except InvalidMoveException as ce:
                    log.debug(ce)
                    self._reset_selected_piece()
            else:
                log.debug('dropped on unplayable game space')
                self._reset_selected_piece()

            # Add piece back to stationary set
            self.pieces.add(self.piece_selected)

            # clean up for the next selected piece
            self.piece_selected.empty()

    def _draw_items(self):
        self.bg_text.draw(self.screen)
        self.pieces.draw(self.screen)
        self.piece_selected.draw(self.screen)
        self.fg_text.draw(self.screen)

    def _update(self):
        self.game.update()

        self.fps_text.text = "%4.1f fps" % self.fps_clock.get_fps()

        if self.player:
            self.player_text.text = "Your pieces are %s" % self.player

        if self.game.turn not in players:
            self.turn_text.text = "Waiting for player"
        else:
            if self.player == self.game.turn:
                self.turn_text.text = "Your turn"
            else:
                self.turn_text.text = "%s's turn" % self.game.turn.title()

        if self.game.winner():
            self.turn_text.text = ''
            self.winner_text.text = "%s wins!" % self.game.winner().title()
        else:
            self.winner_text.text = ''

        if not self.piece_selected and self.player == self.game.turn:
            highlight_player = self.game.turn
        else:
            highlight_player = None
        self.pieces.update(highlight_player)
        self.piece_selected.update(self.game.turn)
        self.bg_text.update()
        self.fg_text.update()

    def run(self):

        log.debug('pre-initializing sound')
        mixer.pre_init(buffer=32)

        log.debug('starting game')
        pygame.init()

        log.debug('initializing screen')
        self.screen = self._screen_init()

        log.debug('getting font')
        self.font = pygame.font.Font(None, 36)

        log.debug('loading background')
        self.background, self.background_rect = self._get_background()

        log.debug('setting up drop locations')
        self._board_space_setup()

        log.debug('building text')
        bg_rect = self.background_rect

        class FPSText(Text):
            def update(self, *args):
                Text.update(self, *args)
                self.rect.right, self.rect.bottom = bg_rect.right, bg_rect.bottom

        self.fps_text = FPSText('', self.font, WHITE)
        if self.show_fps:
            self.fg_text.add(self.fps_text)

        class TurnText(Text):
            def update(self, *args):
                Text.update(self, *args)
                self.rect.centerx, self.rect.centery = bg_rect.centerx, bg_rect.centery

        self.turn_text = TurnText('', self.font, WHITE)
        self.bg_text.add(self.turn_text)

        class WinnerText(Text):
            def update(self, *args):
                Text.update(self, *args)
                self.rect.centerx, self.rect.centery = bg_rect.centerx, bg_rect.centery

        self.winner_text = WinnerText('', self.font, WHITE)
        self.fg_text.add(self.winner_text)

        class PlayerText(Text):
            def update(self, *args):
                Text.update(self, *args)
                self.rect.centerx, self.rect.bottom = bg_rect.centerx, bg_rect.bottom

        self.player_text = PlayerText('', pygame.font.Font(None, 24), WHITE)
        self.bg_text.add(self.player_text)

        class GameIdText(Text):
            def update(self, *args):
                Text.update(self, *args)
                self.rect.centerx, self.rect.top = bg_rect.centerx, bg_rect.top + (0.25 * self.font.get_height())

        self.game_id_text = GameIdText('', pygame.font.Font(None, 20), WHITE)
        self.bg_text.add(self.game_id_text)

        log.debug('drawing initial content to screen')
        self.screen.blit(self.background, ORIGIN)
        pygame.display.flip()

        self.piece_selected = GroupSingle()
        self.current_piece_position = ORIGIN

        self.fps_clock = Clock()

        # Event loop
        while self.game_running:

            self._clear_items()

            for event in pygame.event.get():

                if event.type == QUIT:
                    self._quit()

                if event.type == MOUSEBUTTONDOWN:     # select a piece
                    log.debug('mouse pressed')
                    self._select_piece(event)

                if event.type == MOUSEBUTTONUP:     # let go of a piece
                    log.debug('mouse released')
                    self._drop_piece(event)

                if pygame.event.get_grab():          # drag selected piece around
                    self._drag_piece()

            self._update()

            self._draw_items()

            self.fps_clock.tick(60)  # Waits to maintain 60 fps

            # TODO: Use display.update instead
            pygame.display.flip()

        log.debug('finishing game loop')
Beispiel #10
0
class Player(Animated_Sprite):

    """Player class that the user will control.

    :param sheet: The image used for the sprite sheet of player.
    :param start_pos: Starting position for the Player.
    :param name: String of the player name.
    :param speed: Speed at which the player can move. Both horizontal and vertical.
    """

    def __init__(self, sheet, start_pos, speed=4, power=30):
        super(Player, self).__init__(sheet)
        self.strips = {
            'idle': self.sheet.load_strip(0, 6),
            'magic': self.sheet.load_strip(3, 4),
            'walking_r': self.sheet.load_strip(1, 6),
            'walking_l': self.sheet.load_strip(2, 6)
        }
        self.curr_strip = self.strips['idle']
        self.curr_anim = cycle(self.curr_strip)
        self.image = self.curr_anim.next().copy()
        self.mask = mask.from_surface(self.image)
        self.rect = self.image.get_rect(midbottom=start_pos)
        self.speed = speed
        self.vel = Vector2(0, 0)
        self.health = self.image.get_width()
        self.projectile = None
        self.power = power
        self.current_weapon = 'Arc Shot'

    def apply_damage(self, damage):
        """Has a player take damage.

        :param damage: How much damage to take.
        """
        self.health -= damage
        if self.health <= 0:
            self.kill()

    def adjust_height(self, ground, xoffset):
        """Adjusts the height of the player to climb slopes.

        :param ground: The surface the player is comparing to check if they are on a solid or not.
        :param xoffset: How many pixels the player wants to move left or right.
        """
        for i in range(1, self.speed + 1):
            if not self.collide_ground(ground, (xoffset, -i)):
                self.vel.y -= i
                break
        else:
            self.vel.x = 0

    def check_movement(self, ground, keys):
        """Perform actions based on what keys are pressed.

        :param keys: The keys that are currently being pressed.
        :param ground: The surface the player is walking on.
        """
        if keys[K_a]:
            self.transition('walking_l', ground, -self.speed)
        elif keys[K_d]:
            self.transition('walking_r', ground, self.speed)
        else:
            self.change_anim('idle')
        if keys[K_SPACE]:
            if not self.collide_ground(ground, (0, -self.speed)):
                self.vel.y -= self.speed
        if keys[K_1]:
            self.current_weapon = 'Arc Shot'
        elif keys[K_2]:
            self.current_weapon = 'Beam Shot'
        if keys[K_w] and self.power < 30:
            self.power += 1
        elif keys[K_s] and self.power > 10:
            self.power -= 1

    def collide_ground(self, ground, offset):
        """Returns the point of collision between player and ground with the given offset.

        :param ground: Reference to ground.
        :param offset: Tuple that offsets the player's mask.
        """
        return ground.mask.overlap(self.mask,
                                   (self.rect.left - ground.rect.left + offset[0],
                                    self.rect.top - ground.rect.top + offset[1]))

    def calc_angle(self, pos):
        """Helper function to calculate angle of trajectory for projectile.

        :param pos: Position of mouse.
        """
        (temp_x, temp_y) = self.rect.midtop
        return atan2(temp_y - pos[1], temp_x - pos[0])

    def change_anim(self, anim_name):
        """Changes the current animation to something different, for example,  from idle to moving left or moving right to idle.

        :param anim_name: The name of the animation to be set.
        """
        if self.curr_strip is not self.strips[anim_name]:
            self.curr_strip = self.strips[anim_name]
            self.curr_anim = cycle(self.curr_strip)

    def draw_health(self):
        """Draws the health bar.
        """
        self.image.fill((255, 0, 0) if self.health < self.image.get_width() else (0, 255, 0),
                        ((self.image.get_rect().topleft), (self.health, 4)))

    def fire(self, mouse_pos, collidables):
        """Fires A Projectile

        :param mouse_pos: The mouse position used to calculate the angle to fire the projectile.
        :param collidables: A list of objects a projectile can collide with.
        """
        if not self.projectile:
            if self.current_weapon == 'Arc Shot':
                self.projectile = GroupSingle(Explosive(cycle(self.strips['magic']),
                                                        self.rect.midtop,
                                                        self.calc_angle(
                                                            mouse_pos),
                                                        collidables,
                                                        self.power,
                                                        8,
                                                        3))
            else:
                self.projectile = GroupSingle(Beam_Shot(cycle(self.strips['magic']),
                                                        self.rect.midtop,
                                                        self.calc_angle(
                                                            mouse_pos),
                                                        collidables,
                                                        self.power,
                                                        6,
                                                        2))

    def transition(self, new_anim, ground, dx):
        """Helper function for updating animation and movement in check_movement.

        :param new_anim: New animation to set.
        :param ground: The surface the player is walking on.
        :param dx: Amount that the player will move on the next frame.
        """
        self.change_anim(new_anim)
        self.vel.x += dx
        if self.collide_ground(ground, (dx, 0)):
            self.adjust_height(ground, dx)

    def update(self, world):
        """Update the Player

        :param world: The world the player inhabits.
        """
        super(Player, self).update()
        self.draw_health()
        if self.projectile:
            self.projectile.update(world)
            self.projectile.draw(world.image)
        if not self.collide_ground(world.ground, (0, world.gravity)):
            self.vel.y += world.gravity
        self.rect.move_ip(self.vel)
        self.vel = Vector2(0, 0)
        self.rect.clamp_ip(world.rect)
def main():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)
    bounds = screen.get_rect()
    pygame.display.set_caption("Super Alien Assault!")

    # Load the sound mixer:
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    # This is supposed to help stop sound lag

    # Create the player
    player = Player(bounds.center, bounds)
    player_grp = GroupSingle(player)

    # Create an enemy
    enemies = pygame.sprite.Group()

    # Create all the levels
    lindex = random.randrange(3, 9)

    level_list = []
    level_list.append(levels.Level_01(player))
    level_list.append(levels.Level_02(player))
    level_list.append(levels.Level_03(player))
    for i in range(lindex):
        level_list.append(levels.Level_01(player))
        level_list.append(levels.Level_02(player))
        level_list.append(levels.Level_03(player))

    # Initialize variables
    score = 0
    spawn_counter = 0
    tween_diff = 1

    # Select the font to use
    font = pygame.font.SysFont("calibri", 48)

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    # List of each block
    block_list = pygame.sprite.Group()

    # Set current level for player and inital x,y position
    player.level = current_level
    player.rect.x = 340
    player.rect.y = 200

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # Play "Hot Nights" by Beardmont / Three Chain Links
    # Available under Creative Commons attribution license from:
    # https://soundcloud.com/beardmont
    pygame.mixer.music.load('HotNights.ogg')
    pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
    pygame.mixer.music.play()

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            elif event.type == pygame.constants.USEREVENT:
                # This event is triggered when the song stops playing.
                #
                # Next, play "Happiest Days" by Beardmont / Three Chain Links
                # Available under Creative Commons attribution license from:
                # https://soundcloud.com/beardmont
                pygame.mixer.music.load('HappiestDays.ogg')
                pygame.mixer.music.play()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True
                if event.key == pygame.K_q:
                    done = True
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()
                if event.key == pygame.K_SPACE:
                    player.shoot()
                if event.key == pygame.K_r and not player.alive():
                    main()

            elif event.type == pygame.KEYUP:

                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        # Update items in the level
        current_level.update()
        player_grp.update()
        player.bullets.update()
        player.bulletcasings.update()
        enemies.update()

        # Messing around with easing the enemy spawn counter
        # They should gradually trickle in at first and then build
        # to a flood of enemies then recede kind of like a tide
        spawn_counter += (101 - spawn_counter) * .1
        if spawn_counter >= 100:
            n = random.randrange(3)
            for i in range(n):
                x = random.randint(900, 1000)
                y = random.randint(100, 520)
                enemy = Enemy((x, y))
                enemies.add(enemy)
            spawn_counter = 0

        # Collision between player and enemies results in player death
        groupcollide(player_grp, enemies, True, False)

        # Add 1 point to score for every enemy the player kills
        for enemy in groupcollide(enemies, player.bullets, True, True):
            if player.alive():
                score += 1

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.x >= 310:
            diff = player.rect.x - 310
            # add some tweening/easing for momentum
            tween_diff += (diff - tween_diff) * .1
            player.rect.x = 310
            current_level.shift_world(int(-tween_diff))
            # also adjust enemies and bulletcasings by the world shift
            for enemy in enemies:
                enemy.rect.x += (int(-tween_diff))
            for bulletcasing in player.bulletcasings:
                bulletcasing.rect.x += (int(-tween_diff))

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.x <= 290:
            diff = 290 - player.rect.x
            # add some tweening/easing for momentum
            tween_diff += (diff - tween_diff) * .1
            player.rect.x = 290
            current_level.shift_world(int(tween_diff))
            # also adjust enemies and bulletcasings by the world shift
            for enemy in enemies:
                enemy.rect.x += (int(tween_diff))
            for bulletcasing in player.bulletcasings:
                bulletcasing.rect.x += (int(tween_diff))

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list) - 1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        player_grp.draw(screen)
        player.bullets.draw(screen)
        player.bulletcasings.draw(screen)
        enemies.draw(screen)

        # Blit the current score
        score_text = font.render("Score: %08d" % score, True, constants.PEACH)
        screen.blit(score_text, (5, 5))

        # If player dies, blit the respawn menu
        if not player.alive():
            gameover = font.render("Press R to Respawn or ESC to Quit", True,
                                   constants.PEACH)
            rect = gameover.get_rect()
            rect.center = screen.get_rect().center
            screen.blit(gameover, rect)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Beispiel #12
0
def main():
    # initialze pygame
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE)
    bounds = screen.get_rect()

    # initialize the game
    player = Player(bounds.center, bounds)
    player_grp = GroupSingle(player)
    enemies = Group()
    spawn_counter = 0
    fast_spawn_counter = 0
    score = 0

    font = pygame.font.Font(None, 40)

    # game loop
    done = False
    clock = pygame.time.Clock()
    while not done:
        # input
        for event in pygame.event.get():
            if event.type == QUIT:
                done = True
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                done = True
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                player.shoot()
            elif event.type == KEYDOWN and event.key == K_SPACE and not player.alive(
            ):
                player = Player(bounds.center, bounds)
                player_grp.add(player)
                score = 0
                for enemy in enemies:
                    enemy.kill()
                # same as enemies.empty()

        # update
        player_grp.update()
        player.bullets.update()
        enemies.update()

        # spawn enemies
        spawn_counter += 1
        if spawn_counter >= 10:
            n = randrange(4)
            for i in range(n):
                x = randrange(bounds.width - Enemy.width)
                enemy = Enemy((x, 0), bounds)
                enemies.add(enemy)
            spawn_counter = 0

        # fast spawn
        fast_spawn_counter += 1
        if fast_spawn_counter >= 45:
            x = randrange(bounds.width - FastEnemy.width)
            enemy = FastEnemy((x, 0), bounds)
            enemies.add(enemy)
            fast_spawn_counter = 0

        # collisions
        groupcollide(player_grp, enemies, True, False)

        for enemy in groupcollide(enemies, player.bullets, True, True):
            if player.alive():
                score += 1

        # draw
        screen.fill(BG_COLOR)
        player_grp.draw(screen)
        player.bullets.draw(screen)
        enemies.draw(screen)

        score_text = font.render("Score: %08d" % score, False, (255, 255, 255))
        screen.blit(score_text, (5, 5))

        if not player.alive():
            gameover = font.render("Press Space to Respawn", False,
                                   (255, 255, 255))
            rect = gameover.get_rect()
            rect.center = screen.get_rect().center
            screen.blit(gameover, rect)

        pygame.display.flip()

        clock.tick(30)
Beispiel #13
0
class Game:
    def __init__(self):
        self._settings = GameSettings()
        self.score_count = 0
        self.can_pipe_move = True
        self.is_game_over = False

        pygame.init()
        self.clock = pygame.time.Clock()
        self.game_display = display.set_mode(
            (self._settings.window_width, self._settings.window_height))

        self.asset_factory = AssetFactory()
        self._pipe_group = Group()
        self._pipe_gaps = Group()
        self._pipe_generator = PipeGenerator(self.asset_factory,
                                             self._settings)

        max_mum_pipes = int(
            self._settings.window_width /
            (self._settings.pipe_width + self._settings.pipe_distance))
        self._max_num_pipe_parts = max_mum_pipes * PipeGenerator.NUM_PIPE_PARTS
        self.__initialize_pipes__()

        self.flappy_bird_img = self.asset_factory.create_flappy_bird_image(
            BIRD_SIZE)
        self.flappy_bird = FlappyBird(BIRD_START_POS, self.flappy_bird_img)
        self.flappy_bird_group = GroupSingle(self.flappy_bird)

        self.bg_img = self.asset_factory.create_bg(
            self._settings.window_width, self._settings.window_height)

    def __initialize_pipes__(self):
        first_pipe_index = int(
            self._settings.pipe_start_pos /
            (self._settings.pipe_width + self._settings.pipe_distance))

        for i in range(first_pipe_index, self._max_num_pipe_parts):
            pipe_x = i * (self._settings.pipe_width +
                          self._settings.pipe_distance)
            result = self._pipe_generator.create_pipe(pipe_x)
            self._pipe_group.add([result.top_pipe, result.bottom_pipe])
            self._pipe_gaps.add(result.pipe_gap)

    def __update_pipes__(self):
        # Create more pipes if there's space
        # Each pipe actually has two parts, top and bottom
        num_sprites_to_add = self._max_num_pipe_parts - \
            len(self._pipe_group.sprites())
        if num_sprites_to_add > 0:
            for _ in range(0, num_sprites_to_add):
                self.__create_pipe_from_end__()

    def __create_pipe_from_end__(self):
        last_pipe = self._pipe_group.sprites()[-1]
        new_pipe_x = last_pipe.rect.x + \
            self._settings.pipe_width + self._settings.pipe_distance
        result = self._pipe_generator.create_pipe(new_pipe_x)
        self._pipe_group.add([result.top_pipe, result.bottom_pipe])
        self._pipe_gaps.add(result.pipe_gap)

    def start(self):
        while True:
            # Clear display
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    raise SystemExit
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
                    self.flappy_bird.do_flap()

            if self.is_bird_dead():
                self.handle_game_over()
            elif self.has_bird_passed_pipe():
                self.increase_score()

            pygame.Surface.blit(self.game_display, self.bg_img, [0, 0])
            self.update_sprites()
            self.draw_sprites()
            pygame.display.flip()
            self.clock.tick(60)

    def handle_game_over(self):
        if not self.is_game_over:
            self.is_game_over = True

            self.flappy_bird.fall_to_y_pos(self._settings.window_height)
            self.can_pipe_move = False
            print("Game over. Final score was: " + str(self.score_count))

    def increase_score(self):
        if self.is_game_over:
            return

        self.score_count = self.score_count + 1
        print("Score is: " + str(self.score_count))

    def is_bird_dead(self):
        # Game ends when bird collides with pipe
        collided_sprite = sprite.spritecollideany(self.flappy_bird,
                                                  self._pipe_group)
        if collided_sprite is not None:
            return True

        # Bird stops moving when hitting near bottom of screen
        bird_death_pos_y = self._settings.window_height - 20
        if self.flappy_bird.rect.bottom >= bird_death_pos_y:
            return True

        return False

    def has_bird_passed_pipe(self):
        # Score increments when bird goes through pipe gap
        collided_gaps = sprite.spritecollide(self.flappy_bird, self._pipe_gaps,
                                             False)
        for collided_gap in collided_gaps:
            if collided_gap.is_collided_for_first_time():
                self.increase_score()

    def update_sprites(self):
        self.flappy_bird_group.update()
        self.__update_pipes__()
        if self.can_pipe_move:
            self._pipe_group.update(MAP_MOVE_SPEED)
            self._pipe_gaps.update(MAP_MOVE_SPEED)

    def draw_sprites(self):
        self.flappy_bird_group.draw(self.game_display)
        self._pipe_group.draw(self.game_display)
        self._pipe_gaps.draw(self.game_display)
Beispiel #14
0
        if evento.type == KEYUP:
            if evento.key == K_SPACE:
                dunofausto.tacar_torradas()

    if groupcollide(grupo_torradas, grupo_inimigos, True, True):
        mortes += 1

    # Espaço do display
    superficie.blit(fundo, (0, 0))

    fonte_mortes = fonte.render(f'Mortes: {mortes}', True, (255, 255, 255))

    superficie.blit(fonte_mortes, (20, 70))

    grupo_duno.draw(superficie)
    grupo_inimigos.draw(superficie)
    grupo_torradas.draw(superficie)

    grupo_duno.update()
    grupo_inimigos.update()
    grupo_torradas.update()

    if perdeu:
        deu_ruim = fonte_perdeu.render('Voce perdeu', True, (255, 255, 255))
        superficie.blit(deu_ruim, (200, 200))
        display.update()
        pygame.time.delay(10000)

    round += 1
    display.update()
Beispiel #15
0
def main():
    #initialize pygame
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE)
    bounds = screen.get_rect()
    spawntime = 60
    spawnticker = 0
    fast_spawn_counter = 0
    score = 0
    #initialize the game
    player = Player(bounds.center, bounds) #creates a new player object, passes variables to it.
    player_grp = GroupSingle(player)
    enemies = Group() #emtpy sprite group
    
    font = pygame.font.Font(None, 40)
    #game loop
    done = False
    clock = pygame.time.Clock()
    while not done: 
        #input
        for event in pygame.event.get():
            if event.type == QUIT:
                done = True
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                done = True
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                player.shoot()
            elif event.type == KEYDOWN and event.key == K_SPACE and not player.alive():
                player = Player(bounds.center, bounds) # respawns player
                player_grp.add(player)
                score = 0
                for enemy in enemies:
                    enemy.kill()
                # can also do   enemies.empty()
            
                
        
        
        #update
        player_grp.update() #only if the player is in the player_grp sprite group.  See destroyed area
        player.bullets.update() #update everything in the Bullets list
        enemies.update()
        
        
        #collisions
        groupcollide(player_grp, enemies, True, False) #first group, second group, then which gets killed
        
        for enemy in groupcollide(enemies, player.bullets, True, True):
            if player.alive():
                score +=1 #counts how many are intersecting
        
        #spawn
        spawnticker += 1
        if spawnticker >= spawntime:
            #print "spawned!"
            enemies.add(Enemy((randrange(0,400),randrange(0,200)),bounds))
            spawnticker = 0
        fast_spawn_counter += 1
        if fast_spawn_counter >= 45:
            #print "spawned!"
            x = randrange (0, 480)
            enemy = FastEnemy((x,0), bounds)
            enemies.add(enemy)
            fast_spawn_counter = 0
        
        
        
        #draw
        
        screen.fill(BG_COLOR) # fill then draw
        player.bullets.draw(screen) #bullets is the list of all bullets
        player_grp.draw(screen)
        enemies.draw(screen)
        score_text = font.render("Score: %08d" %score, False, (255,255,255))
        screen.blit(score_text, (5,5))
        pygame.display.flip()
        clock.tick(30)
def main():
    """ Main Program """
    pygame.init()
 
    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)
    bounds = screen.get_rect()
    pygame.display.set_caption("Super Alien Assault!")
 
    # Load the sound mixer:
    pygame.mixer.pre_init(44100, -16, 2, 2048) 
    # This is supposed to help stop sound lag
 
    # Create the player
    player = Player(bounds.center, bounds)
    player_grp = GroupSingle(player)

    # Create an enemy
    enemies = pygame.sprite.Group()
 
    # Create all the levels
    lindex = random.randrange(3,9)

    level_list = []
    level_list.append(levels.Level_01(player))
    level_list.append(levels.Level_02(player))
    level_list.append(levels.Level_03(player))
    for i in range(lindex):
        level_list.append(levels.Level_01(player))
        level_list.append(levels.Level_02(player))
        level_list.append(levels.Level_03(player))

    # Initialize variables
    score = 0
    spawn_counter = 0
    tween_diff = 1

    # Select the font to use
    font = pygame.font.SysFont("calibri",48)
 
    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    # List of each block
    block_list = pygame.sprite.Group()

    # Set current level for player and inital x,y position
    player.level = current_level
    player.rect.x = 340
    player.rect.y = 200
 
    # Loop until the user clicks the close button.
    done = False
 
    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # Play "Hot Nights" by Beardmont / Three Chain Links
    # Available under Creative Commons attribution license from:
    # https://soundcloud.com/beardmont
    pygame.mixer.music.load('HotNights.ogg')
    pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
    pygame.mixer.music.play()

 
    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            elif event.type == pygame.constants.USEREVENT:
            # This event is triggered when the song stops playing.
            #
            # Next, play "Happiest Days" by Beardmont / Three Chain Links
            # Available under Creative Commons attribution license from:
            # https://soundcloud.com/beardmont
                pygame.mixer.music.load('HappiestDays.ogg')
                pygame.mixer.music.play()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True
                if event.key == pygame.K_q:
                    done = True
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()
                if event.key == pygame.K_SPACE:
                    player.shoot()
                if event.key == pygame.K_r and not player.alive():
                    main()
 
            elif event.type == pygame.KEYUP:

                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()
 
        # Update items in the level
        current_level.update()
        player_grp.update()
        player.bullets.update()
        player.bulletcasings.update()
        enemies.update()

        # Messing around with easing the enemy spawn counter
        # They should gradually trickle in at first and then build
        # to a flood of enemies then recede kind of like a tide
        spawn_counter += (101 - spawn_counter)*.1
        if spawn_counter >= 100:
            n = random.randrange(3)
            for i in range(n):
                x = random.randint(900, 1000)
                y = random.randint(100, 520)
                enemy = Enemy((x, y))
                enemies.add(enemy)
            spawn_counter = 0

        # Collision between player and enemies results in player death
        groupcollide(player_grp, enemies, True, False)

        # Add 1 point to score for every enemy the player kills
        for enemy in groupcollide(enemies, player.bullets, True, True):
            if player.alive():
                score += 1

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.x >= 310:
            diff = player.rect.x - 310
            # add some tweening/easing for momentum
            tween_diff += (diff - tween_diff)*.1
            player.rect.x = 310
            current_level.shift_world(int(-tween_diff))
            # also adjust enemies and bulletcasings by the world shift
            for enemy in enemies:
                enemy.rect.x += (int(-tween_diff))
            for bulletcasing in player.bulletcasings:
                bulletcasing.rect.x += (int(-tween_diff))


        # If the player gets near the left side, shift the world right (+x)
        if player.rect.x <= 290:
            diff = 290 - player.rect.x
            # add some tweening/easing for momentum
            tween_diff += (diff - tween_diff)*.1
            player.rect.x = 290
            current_level.shift_world(int(tween_diff))
            # also adjust enemies and bulletcasings by the world shift
            for enemy in enemies:
                enemy.rect.x += (int(tween_diff))
            for bulletcasing in player.bulletcasings:
                bulletcasing.rect.x += (int(tween_diff))

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list)-1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level
 
        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        player_grp.draw(screen)
        player.bullets.draw(screen)
        player.bulletcasings.draw(screen)
        enemies.draw(screen)

        # Blit the current score
        score_text = font.render("Score: %08d"%score, True, constants.PEACH)
        screen.blit(score_text, (5,5))

        # If player dies, blit the respawn menu
        if not player.alive():
            gameover = font.render("Press R to Respawn or ESC to Quit", True, constants.PEACH)
            rect = gameover.get_rect()
            rect.center = screen.get_rect().center
            screen.blit(gameover, rect)
 
        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
 
        # Limit to 60 frames per second
        clock.tick(60)
 
        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
 
    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Beispiel #17
0
    screenSurface.fill(pi_globals.BLACK)

    position = Vector2(0, 0)
    pressedKeys = pygame.key.get_pressed()

    if pressedKeys[pygame.K_w] or pressedKeys[pygame.K_UP]:
        position.y -= 1

    if pressedKeys[pygame.K_s] or pressedKeys[pygame.K_DOWN]:
        position.y += 1

    # Hard Coded Speed
    player.position += position * 10

    playerGroup.update()

    playerGroup.draw(screenSurface)

    # Update screen with what has been drawn
    display.flip()

    # Game loop clock tick and delta time calculation
    pi_globals.deltaTime = clock.tick_busy_loop(
        pi_globals.FRAMERATE) / 1000.0  # Close the window and quit.

pygame.quit()

######## Refrence Player ########

# Player class with hard coded sprite