在我为初学者阅读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()
如果代码的排序有点不合时道歉,我不得不将其空间翻两倍才能在网站上运行。
答案 0 :(得分:0)
在回弹法中删除dy = -dy
。