示例#1
0
def run_game():
    pygame.init()
    pygame.font.init()
    """This sets the score color and establishes the font of the score text"""
    score_color = (255, 255, 0)
    my_font = pygame.font.SysFont('Comic Sans MS', 30)
    """This sets the screen settings and also makes objects from the two class files that represent the ball and the 
    bar. """
    screen_width = 1200
    screen_height = 800
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("Pong Game")
    clock = pygame.time.Clock()
    bar = Bar()
    ball = Ball(screen_width, bar)
    score = 0
    """This is the main loop that makes sure that the game runs and updates many of the ongoing things we need the 
    player to see such as the position of the ball. """
    while True:
        clock.tick(30)  # set fps
        screen.fill(
            (0, 0, 0)
        )  # we need this so that the screen is reset and does not overlap with the pervious frames.

        score = gf.update_score(ball, bar, score)  # this updates the score
        text_displayed = "Score: " + str(
            score)  # this is what needs to show on the screen
        text_surface = my_font.render(
            text_displayed, False, score_color
        )  # this establishes the score test and also what the color of it should be
        screen.blit(text_surface, (screen_width - 200, screen_height -
                                   50))  # this sets the score onto the screen

        ball.draw_ball(screen)  # this draws the ball onto the screen
        bar.draw_bar(screen)  # draws the ball onto the screen
        gf.check_events(bar)  # checks user input such as pressing right key
        bar.update_bar(
            screen_width)  # updates the bar's position based on the user input
        ball.update_ball(
            screen_width)  # updates the ball's position every frame

        ball.check_for_collision(
            bar
        )  # sees if the ball is colliding with anything and makes changes to its velocity respectively

        pygame.display.update()
示例#2
0
class BouncingBall:
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        # Clock set-up for framerate
        self.clock = pygame.time.Clock()
        self.settings = Settings()
        self.stats = GameStats(self)
        self.screen = pygame.display.set_mode((self.settings.screen_width,
            self.settings.screen_height))
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Bouncing Ball")
        self.bar = Bar(self)
        self.ball = Ball(self)
        self.timebar = TimeBar(self)
        self.play_button = Button(self, 'Play')

    def run_game(self):
        """Main game loop."""
        while True:
            self._check_events()
            if self.stats.game_active:
                self._ball_checks()
                self.ball.update()
                self.bar.update() # implements movement depending on movement flag
                self.timebar.update(self)
                self._time_check(self.start)
            self._update_screen()

    def _check_events(self):
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            # Pressing arrow keys for movement:
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            # Releasing arrow keys:
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_keydown_events(self, event):
        """Checks keydown events."""
        if event.key == pygame.K_RIGHT:
            self.bar.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.bar.moving_left = True
        elif event.key == pygame.K_ESCAPE:
            sys.exit()

    def _check_play_button(self, mouse_pos):
        """Restart game when Play button is clicked."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked:
            self._click_play()

    def _click_play(self):
        pygame.mouse.set_visible(False)
        self.stats.reset_stats()
        self.settings.initialize_settings()
        self.bar.center_bar()
        self.ball._init_old_pos()
        self.stats.game_active = True
        self.start = perf_counter()

    def _check_keyup_events(self, event):
        """Checks keyup events."""
        if event.key == pygame.K_RIGHT:
            self.bar.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.bar.moving_left = False

    def _ball_checks(self):
        self._check_ball_bar_collision()
        self._check_ball_lost()

    def _check_ball_bar_collision(self):
        if pygame.sprite.collide_rect(self.ball, self.bar):
            print('Bounce!')
            self.ball.bounce = True

    def _check_ball_lost(self):
        """Reset game if ball drops below bottom edge"""
        if self.ball.rect.top >= self.settings.screen_height:
            self._restart_game()

    def _time_check(self, start):
        """Increase game difficulty if session duration has elapsed."""
        if perf_counter() - start >= self.settings.session_duration:
            self.start = perf_counter()
            self.settings.increase_game_difficulty()

    def _restart_game(self):
        """Take action if ball is lost"""
        if self.stats.ball_left > 0:
            self.ball._init_old_pos()
            self.stats.ball_left -= 1
            sleep(0.5)
        else:
            pygame.mouse.set_visible(True)
            self.stats.game_active = False

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.settings.bg_color)
        self.bar.draw_bar()
        self.timebar.draw_timebar()
        self.ball.draw_ball()
        if not self.stats.game_active:
            self.play_button.draw_button()
        pygame.display.flip()
        self.clock.tick(150)