0

在为初学者阅读 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()

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

4

1 回答 1

0

用反弹法去除dy = -dy

于 2015-11-26T20:58:24.047 回答