我在修改已经编码的游戏“Catch”以使其成为乒乓球游戏时遇到了麻烦。对于上下文,在{8.13。项目:pong.py“底部的部分中see here。
球似乎随机曲折。为了获得更好的画面,球可以从一个桨叶上反弹,并且在其通向另一侧的路径中的任意点处(有时会稍微盘旋)并返回到它开始的一侧。我无法弄清楚为什么或如何解决它。我的代码的哪一部分是这样做的?
我在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()
答案 0 :(得分:0)
让我们看一下hit
函数。请记住,r
为10。
def hit(bx, by, r, px, py, h):
if py <= by <= (py + h) and bx >= px - r:
return True
else:
return False
这部分py <= by <= (py + h)
问“球的顶部边缘和顶部边缘之间是球的顶部+ 10px?”,这是非常严格的,因为我相信padel实际上是50px高。
这部分bx >= px - r
问道:“球是否在这个球拍左边缘的右边?”这听起来没问题,但它总是在最左边的桨的右侧,并为每个桨调用此功能。
点击功能通常会要求x1, y2, x2, y2, tx1, ty1, tx2, ty2
。基本上,每个对象的左上角和右下角。或者,x2,y2,tx2,ty2
可以替换为w,h,tw,th
(宽度和高度)。
如果您是Python新手,请先尝试在纸上写出来。绘制它,在纸上做一些例子,然后编写代码,看看这些例子是否有效。如果您仍有问题,但至少尝试过,请提出另一个问题。除此之外,您的代码看起来很好。