我正在通过实时电线使用 Pygame 制作 Pong 游戏,但我无法让碰撞检测正常工作



当我正在阅读初学者的Python编程书时,我正在玩一个乒乓球游戏,我不知道我在这个游戏的代码中缺少了什么。游戏中的一切都正常工作,除了当球与棋盘精灵重叠时,它没有检测到它,它直接到达窗口边缘,结束了游戏。

# single player pong
# the player must rebound the ball to avoid it going off screen.
from livewires import games, color
games.init(screen_width = 1152, screen_height = 768, fps = 60)
class board(games.Sprite):
    """The object used to bounce the ball."""
    image = games.load_image("paddle.png")
    def __init__(self):
        """initialize the board"""
        super(board, self).__init__(image = board.image,
                                   y = games.mouse.y,
                                   right = games.screen.width)
    def update(self): 
        """
        :return:move mouse to y position
        """
        self.y = games.mouse.y
        if self.top < 0:
            self.top = 0
        if self.bottom > games.screen.height:
            self.bottom = games.screen.height
        self.check_rebound()

    def check_rebound(self):
        """Check for ball rebound"""
        for ball in self.overlapping_sprites:
            ball.rebound()

class ball(games.Sprite):
    """ A bouncing pizza."""
    image = games.load_image("ball.png")
    def __init__(self):
        """initialize the ball"""
        super(ball, self).__init__(image = ball.image,
                                  x = games.screen.width/2,
                                  y = games.screen.height/2,
                                  dx = 1,
                                  dy = 1)
    def end_game(self):
        """ End the game. """
        end_message = games.Message(value = "Game Over",
                                    size = 90,
                                    color = color.red,
                                    x = games.screen.width/2,
                                    y = games.screen.height/2,
                                    lifetime = 5 * games.screen.fps,
                                    after_death = games.screen.quit)
        games.screen.add(end_message)
    def update(self):
        """ Reverse a velocity component if edge of screen is reached and end game if the right    wall is reached."""
        if  self.left < 0:
            self.dx = -self.dx
        if self.bottom > games.screen.height or self.top < 0:
            self.dy = -self.dy
        if self.right > games.screen.width:
            self.end_game()
            self.destroy()

    def rebound(self):
        "Ball rebounds from board."
        self.dx = -self.dx
        self.dy = -self.dy
def main():
    """ Play the game. """

    the_board = board()
    games.screen.add(the_board)
    the_ball = ball()
    games.screen.add(the_ball)
    games.screen.add(the_ball)
    games.mouse.is_visible = False
    games.screen.event_grab = True
    games.screen.mainloop()
# start it up!
main()

很抱歉,如果代码排序有点不稳定,我不得不将它的空间增加四倍才能在网站上工作。

在回弹方法中移除dy = -dy

相关内容

  • 没有找到相关文章

最新更新