コード例 #1
0
    def __init__(self):
        self.middle_rects = self.create_middle_rects(5, 15)

        # Initialize entities
        self.player = Player(20, 20, 100, PLAYER_COLOR)
        self.enemy = Enemy(SCREEN_WIDTH - 20 - 20, 20, 100, ENEMY_COLOR)
        self.ball = Ball(12, 600)

        # Initialize fonts
        self.score_font = pygame.font.Font("8bit.ttf", SCORE_SIZE)
        self.player_score_label = self.score_font.render(
            str(self.player.score), True, SCORE_COLOR)
        self.enemy_score_label = self.score_font.render(
            str(self.enemy.score), True, SCORE_COLOR)
コード例 #2
0
def test_moving_ball():
    ball = Ball(surface)
    for i in range(0, 10):
        oldDirection = ball.get_current_position()
        ball.update_ball()
        pygame.display.flip()
        assert ball.get_current_position() != oldDirection
コード例 #3
0
ファイル: states.py プロジェクト: danrodlor/pypong
    def __init__(self, screen, resource_loader):
        super().__init__()
        self.screen = screen
        self.screen_rect = self.screen.get_rect()

        self.player = Paddle(config.BRICK_SIZE, 3 * config.BRICK_SIZE,
                             2 * config.BRICK_SIZE, self.screen_rect.centery,
                             config.PLAYER_SPEED, self.screen,
                             InputController())
        self.ball = Ball(
            config.BRICK_SIZE,
            self.screen_rect.centerx,
            self.screen_rect.centery,
            2,
            self.screen,
            bounce_sound=resource_loader.get_sound('ball_bounce_2'),
            hit_sound=resource_loader.get_sound('ball_hit'))
        self.enemy = Paddle(config.BRICK_SIZE, 3 * config.BRICK_SIZE,
                            config.SCREEN_WIDTH - 2 * config.BRICK_SIZE,
                            self.screen_rect.centery, config.ENEMY_SPEED,
                            self.screen, AIController(self))
        self.entities = [self.ball, self.player, self.enemy]
        self.paddles = [self.player, self.enemy]

        self.player_score = 0
        self.enemy_score = 0
        self.player_score_textbox = SimpleTextBox(self.screen_rect.centerx -
                                                  40,
                                                  36,
                                                  self.screen,
                                                  text=str(self.player_score))
        self.enemy_score_textbox = SimpleTextBox(self.screen_rect.centerx + 40,
                                                 36,
                                                 self.screen,
                                                 text=str(self.enemy_score))
        self.widgets = [self.player_score_textbox, self.enemy_score_textbox]
        self.score_point_sound = resource_loader.get_sound('score_point')

        self._init_static_elements()
コード例 #4
0
    def __init__(self, surface, username, numberOfPlayers, soundsOn):
        # Initialize variables
        self.__clock = pygame.time.Clock()
        self.__surface = surface
        self.__isRunning = True
        self.__username = username
        self.__numberOfPlayers = numberOfPlayers
        self.__soundsOn = soundsOn

        # Initialize the game entities
        self.__ball = Ball(self.__surface)
        self.__score = self.__ball.get_score()
        self.__playfield = Playfield(self.__surface, self.__username,
                                     self.__score)
        self.__surface = self.__playfield.get_surface()
        self.__snake = Snake(self.__surface, self.__isRunning)
        self.__food = Food(self.__surface)

        # Check if multiplayer or not
        if self.__numberOfPlayers == 0:
            self.__paddle = Paddle(self.__surface)
        else:
            self.__paddle = Paddle(self.__surface, True)
コード例 #5
0
def test_ball_creation():
    ball = Ball(surface)
    assert ball.get_current_position() == (400, 400)
    assert ball.get_score() == 0
コード例 #6
0
class Game:
    def __init__(self, surface, username, numberOfPlayers, soundsOn):
        # Initialize variables
        self.__clock = pygame.time.Clock()
        self.__surface = surface
        self.__isRunning = True
        self.__username = username
        self.__numberOfPlayers = numberOfPlayers
        self.__soundsOn = soundsOn

        # Initialize the game entities
        self.__ball = Ball(self.__surface)
        self.__score = self.__ball.get_score()
        self.__playfield = Playfield(self.__surface, self.__username,
                                     self.__score)
        self.__surface = self.__playfield.get_surface()
        self.__snake = Snake(self.__surface, self.__isRunning)
        self.__food = Food(self.__surface)

        # Check if multiplayer or not
        if self.__numberOfPlayers == 0:
            self.__paddle = Paddle(self.__surface)
        else:
            self.__paddle = Paddle(self.__surface, True)

    def start_game(self):

        while self.__isRunning:
            # Check if game is being closed manually
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.__isRunning = False

            # Check if game is done
            if self.__snake.game_over():
                self.__isRunning = False
                mixer.music.stop()
                self.__play_gameover_sound()
                Tk().wm_withdraw()  # Pop-up screen using tkinter library
                messagebox.showinfo(
                    'GAME OVER - You a dead snake bruv',
                    'I admit that I touched myself/walls :\'(')

            # Check if snake eats the food
            elif self.__snake.get_head().colliderect(self.__food.show_food()):
                self.__snake.set_length()
                self.__play_touch_sound()
                self.__food.update_food()

            # Check if the paddle touches the ball
            elif self.__paddle.get_paddle().colliderect(
                    self.__ball.get_ball()):
                self.__ball.bounce()
                self.__play_touch_sound()

            # Check if one of the segments of the snake touches the ball
            for segment in self.__snake.get_snake():
                if segment.colliderect(self.__ball.get_ball()):
                    self.__ball.bounce()
                    self.__play_touch_sound()

            # Continously update the game with the new values/info
            self.__update_game()

    def __update_game(self):
        self.__surface.fill((0, 0, 0))
        self.__score = self.__ball.get_score()
        Playfield(self.__surface, self.__username, self.__score)
        self.__snake.update_snake()
        self.__food.look_for_food()
        self.__paddle.update_paddle()
        self.__ball.update_ball()
        pygame.display.flip()
        self.__clock.tick(60)

    # Check if sounds are activated or not and then play them accordingly
    def __play_touch_sound(self):
        if self.__soundsOn:
            touch = mixer.Sound("assets/touch_sound.wav")
            mixer.Sound.play(touch)

    def __play_gameover_sound(self):
        if self.__soundsOn:
            gameover = mixer.Sound("assets/game_over_sound.wav")
            mixer.Sound.play(gameover)

    # Code for testing the Game class
    def get_username(self):
        return self.__username

    def get_numberOfPlayers(self):
        return self.__numberOfPlayers
コード例 #7
0
ファイル: states.py プロジェクト: danrodlor/pypong
class GameRunningState(State):

    MAXIMUM_SCORE = 11

    def __init__(self, screen, resource_loader):
        super().__init__()
        self.screen = screen
        self.screen_rect = self.screen.get_rect()

        self.player = Paddle(config.BRICK_SIZE, 3 * config.BRICK_SIZE,
                             2 * config.BRICK_SIZE, self.screen_rect.centery,
                             config.PLAYER_SPEED, self.screen,
                             InputController())
        self.ball = Ball(
            config.BRICK_SIZE,
            self.screen_rect.centerx,
            self.screen_rect.centery,
            2,
            self.screen,
            bounce_sound=resource_loader.get_sound('ball_bounce_2'),
            hit_sound=resource_loader.get_sound('ball_hit'))
        self.enemy = Paddle(config.BRICK_SIZE, 3 * config.BRICK_SIZE,
                            config.SCREEN_WIDTH - 2 * config.BRICK_SIZE,
                            self.screen_rect.centery, config.ENEMY_SPEED,
                            self.screen, AIController(self))
        self.entities = [self.ball, self.player, self.enemy]
        self.paddles = [self.player, self.enemy]

        self.player_score = 0
        self.enemy_score = 0
        self.player_score_textbox = SimpleTextBox(self.screen_rect.centerx -
                                                  40,
                                                  36,
                                                  self.screen,
                                                  text=str(self.player_score))
        self.enemy_score_textbox = SimpleTextBox(self.screen_rect.centerx + 40,
                                                 36,
                                                 self.screen,
                                                 text=str(self.enemy_score))
        self.widgets = [self.player_score_textbox, self.enemy_score_textbox]
        self.score_point_sound = resource_loader.get_sound('score_point')

        self._init_static_elements()

    def _game_reset(self):
        for entity in self.entities:
            entity.reset()

        self.player_score = 0
        self.enemy_score = 0
        self.player_score_textbox.modify(newtext=str(self.player_score))
        self.enemy_score_textbox.modify(newtext=str(self.enemy_score))

        config.PAUSED_GAME_IMG_STRING = None

    def _update_game_data(self):
        self.SHARED_DATA['GAME_DATA'].update({
            'player_x':
            self.player.x,
            'player_y':
            self.player.y,
            'player_score':
            self.player_score,
            'enemy_x':
            self.enemy.x,
            'enemy_y':
            self.enemy.y,
            'enemy_score':
            self.enemy_score,
            'ball_fx':
            self.ball.fx,
            'ball_fy':
            self.ball.fy,
            'ball_xspeed':
            self.ball.xspeed,
            'ball_yspeed':
            self.ball.yspeed,
            'ball_speed_coeff':
            self.ball.speed_coeff,
        })

    def _load_game_data(self):
        self.player.x = self.SHARED_DATA['GAME_DATA']['player_x']
        self.player.y = self.SHARED_DATA['GAME_DATA']['player_y']
        self.player_score = self.SHARED_DATA['GAME_DATA']['player_score']
        self.enemy.x = self.SHARED_DATA['GAME_DATA']['enemy_x']
        self.enemy.y = self.SHARED_DATA['GAME_DATA']['enemy_y']
        self.enemy_score = self.SHARED_DATA['GAME_DATA']['enemy_score']
        self.ball.fx = self.SHARED_DATA['GAME_DATA']['ball_fx']
        self.ball.fy = self.SHARED_DATA['GAME_DATA']['ball_fy']
        self.ball.xspeed = self.SHARED_DATA['GAME_DATA']['ball_xspeed']
        self.ball.yspeed = self.SHARED_DATA['GAME_DATA']['ball_yspeed']
        self.ball.speed_coeff = self.SHARED_DATA['GAME_DATA'][
            'ball_speed_coeff']

        self.player_score_textbox.modify(newtext=str(self.player_score))
        self.enemy_score_textbox.modify(newtext=str(self.enemy_score))

        self.SHARED_DATA['GAME_CONTROL']['data_loaded'] = False

    def _init_static_elements(self):
        self.middle_line = pygame.Surface([5, config.SCREEN_HEIGHT])
        self.middle_line.fill(pygame.Color('white'))

    def _draw_static_elements(self):
        self.screen.blit(self.middle_line, (self.screen_rect.centerx, 0))

    def _get_screenshot(self):
        screenshot_img_string = pygame.image.tostring(self.screen, 'RGB')
        config.PAUSED_GAME_IMG_STRING = screenshot_img_string

    def _check_collisions(self):
        for entity in pygame.sprite.spritecollide(self.ball,
                                                  self.paddles,
                                                  dokill=False):
            self.ball.process_collision(entity)

    def _execute_game_logic(self):
        if self.ball.rect.left < self.player.rect.left:
            self.enemy_score += 1
            self.enemy_score_textbox.modify(newtext=str(self.enemy_score))
            self.score_point_sound.play()
            self.ball.reset()
        elif self.ball.rect.right > self.enemy.rect.right:
            self.player_score += 1
            self.player_score_textbox.modify(newtext=str(self.player_score))
            self.score_point_sound.play()
            self.ball.reset()

        if self.enemy_score >= self.MAXIMUM_SCORE:
            self.next_state = 'GAME_LOSE_SCREEN_STATE'
            self.is_done = True
            self._game_reset()
        elif self.player_score >= self.MAXIMUM_SCORE:
            self.next_state = 'GAME_WIN_SCREEN_STATE'
            self.is_done = True
            self._game_reset()

        self._check_collisions()

    def get_event(self, event):
        if event.type == pygame.QUIT:
            self.is_quit = True
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_p:
            self.next_state = 'PAUSE_MENU_STATE'
            self._get_screenshot()
            self.is_done = True
        else:
            self.player.controller.handle_event(event)

    def update(self):
        if self.SHARED_DATA['GAME_CONTROL']['data_loaded']:
            self._load_game_data()

        self._execute_game_logic()

        self.enemy.controller.update()

        for entity in self.entities:
            entity.update()

        for widget in self.widgets:
            widget.update()

        self._update_game_data()

    def draw(self):
        self.screen.fill(pygame.Color('black'))
        self._draw_static_elements()

        for entity in self.entities:
            entity.draw()

        for widget in self.widgets:
            widget.draw()
コード例 #8
0
class PingPong:
    def __init__(self):
        self.middle_rects = self.create_middle_rects(5, 15)

        # Initialize entities
        self.player = Player(20, 20, 100, PLAYER_COLOR)
        self.enemy = Enemy(SCREEN_WIDTH - 20 - 20, 20, 100, ENEMY_COLOR)
        self.ball = Ball(12, 600)

        # Initialize fonts
        self.score_font = pygame.font.Font("8bit.ttf", SCORE_SIZE)
        self.player_score_label = self.score_font.render(
            str(self.player.score), True, SCORE_COLOR)
        self.enemy_score_label = self.score_font.render(
            str(self.enemy.score), True, SCORE_COLOR)

    def update(self, delta):
        # Update entities
        self.player.update(delta)
        self.enemy.update(delta)
        self.ball.update(delta)

        # Check if the ball collides with one of both paddles
        ball_collides_player = (self.ball.rect.colliderect(self.player.rect)
                                and self.ball.velocity.x < 0)
        ball_collides_enemy = (self.ball.rect.colliderect(self.enemy.rect)
                               and self.ball.velocity.x > 0)

        if ball_collides_player:
            self.ball.rect.x = self.player.rect.topright[0]

            # Clamp the value between 0 and player's height
            hit_relative_y = max(
                0,
                min(self.ball.rect.topleft[1] - self.player.rect.topright[1],
                    self.player.rect.height))

            self.ball.change_angle(hit_relative_y, self.player.rect.height)
            self.enemy.calculate_next_position(self.ball)
        elif ball_collides_enemy:
            self.ball.rect.x = self.enemy.rect.x - self.ball.radius * 2

            self.ball.velocity.x *= -1
            self.ball.predicted_y = -1

        # Increase score and update the label
        if self.ball.rect.topleft[0] <= 0:
            self.player.score += 1
            self.player_score_label = self.score_font.render(
                str(self.player.score), True, SCORE_COLOR)

            self.ball.reset()
        elif self.ball.rect.topright[0] >= SCREEN_WIDTH:
            self.enemy.score += 1
            self.enemy_score_label = self.score_font.render(
                str(self.enemy.score), True, SCORE_COLOR)

    def render(self, screen):
        # Render scores
        self.render_scores(screen)
        self.render_middle_rects(screen)

        # Render entities
        self.player.render(screen)
        self.enemy.render(screen)
        self.ball.render(screen)

    """ Returns an array of the rects that appear in the middle of the screen """

    def create_middle_rects(self, width, number):
        rects = []
        height = SCREEN_HEIGHT / number / 2

        for i in range(number):
            y = i * height * 2 + height / 2
            rect = pygame.Rect((SCREEN_WIDTH - width) / 2, y, width, height)
            rects.append(rect)

        return rects

    def render_middle_rects(self, screen):
        for rect in self.middle_rects:
            pygame.draw.rect(screen, MIDDLE_RECTS_COLOR, rect)

    def render_scores(self, screen):
        screen.blit(self.player_score_label, PLAYER_SCORE_POSITION)
        screen.blit(self.enemy_score_label, ENEMY_SCORE_POSITION)