我在修改已经编码的游戏“Catch”以使其成为乒乓球游戏的练习时遇到了麻烦。有关上下文,请参阅底部标题为“8.13. Project: pong.py”的部分。
球似乎随机曲折。为了获得更好的画面,球可能会从一个桨上反弹,并且在其到达另一侧的路径中的任意点处,将(有时悬停一点)并返回到它开始的一侧。我不知道为什么或如何解决它。我的代码的哪一部分使它这样做?
我在 play_round 函数中重新排列了 while 循环的元素,以为我可能误解了执行流程,但没有任何改进。问题是程序和帧速率不兼容吗?
我是编程新手,不幸的是已经花了好几个小时试图解决这个问题,所以我想我会来这里寻求帮助。
from gasp import *
COMPUTER_WINS = 1
PLAYER_WINS = 0
QUIT = -1
def hit(bx, by, r, px, py, h):
if py <= by <= (py + h) and bx >= px - r:
return True
else:
return False
def play_round():
bx = 400
by = 300
ball = Circle((bx, by), 10, filled=True)
r = 10
dx = random_between(-4, 4)
dy = random_between(-5, 5)
px = 780
py = random_between(30, 270)
paddle = Box((px, py), 20, 50)
h = 30
px2 = 20
py2 = random_between(30, 270)
paddle2 = Box((px2, py2), 20, 50)
h2 = 30
while True:
if by >= 590 or by <= 10:
dy *= -1
bx += dx
by += dy
if bx >= 810:
remove_from_screen(ball)
remove_from_screen(paddle)
remove_from_screen(paddle2)
return COMPUTER_WINS
move_to(ball, (bx, by))
if key_pressed('k') and py <= 570:
py += 5
elif key_pressed('j') and py > 0:
py -= 5
if hit(bx, by, r, px, py, h):
dx *= -1
if key_pressed('escape'):
return QUIT
move_to(paddle, (px, py))
if key_pressed('a') and py2 <= 570:
py2 += 5
elif key_pressed('s') and py2 > 0:
py2 -= 5
move_to(paddle2, (px2, py2))
if hit(bx, by, r, px2, py2, h2):
dx *= -1
if bx <= -10:
remove_from_screen(ball)
remove_from_screen(paddle)
remove_from_screen(paddle2)
return PLAYER_WINS
update_when('next_tick')
def play_game():
player_score = 0
comp_score = 0
while True:
pmsg = Text("Player: %d Points" % player_score, (10, 570), size=24)
cmsg = Text("Computer: %d Points" % comp_score, (640, 570), size=24)
sleep(3)
remove_from_screen(pmsg)
remove_from_screen(cmsg)
result = play_round()
if result == PLAYER_WINS:
player_score += 1
elif result == COMPUTER_WINS:
comp_score += 1
else:
return QUIT
if player_score == 5:
return PLAYER_WINS
elif comp_score == 5:
return COMPUTER_WINS
begin_graphics(800, 600, title="Catch", background=color.YELLOW)
set_speed(120)
result = play_game()
if result == PLAYER_WINS:
Text("Player Wins!", (340, 290), size=32)
elif result == COMPUTER_WINS:
Text("Computer Wins!", (340, 290), size=32)
sleep(4)
end_graphics()