gpt4 book ai didi

python - 检测球何时击中乒乓 Racket ?

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:05 24 4
gpt4 key购买 nike

我一直在阅读这个 tutorial .我在一个章节中,您可以在其中构建乒乓球游戏。但是,我在尝试制作一个可以检测球何时击中 Racket 的功能时遇到了问题?

它说我应该这样做:

Make a boolean function hit(bx, by, r, px, py, h) that returns True when the vertical coordinate of the ball (by) is between the bottom and top of the paddle, and the horizontal location of the ball (bx) is less than or equal to the radius (r) away from the front of the paddle.

到目前为止我已经试过了:

def hit(bx, by, r, px, py, h):
if by > py and by <= h:
if bx <= r:
return True
else:
return False

...

# If this returns True then change the direction of the ball (dx).
if hit(ball_x, ball_y, radius, paddle_x, paddle_y, height):
dx *= -1

我无法将引用的段落翻译成代码。我做错了什么?

注意:此函数的预期输出为:

hit(760, 100, 10, 780, 100, 100)
False

hit(770, 100, 10, 780, 100, 100)
True

hit(770, 200, 10, 780, 100, 100)
True

hit(770, 210, 10, 780, 100, 100)
False

最佳答案

您没有考虑元素的实际位置 - 您所拥有的坐标是指球和 Racket 上的特定点。您的代码所做的是检查球是否在 Racket 上方并且半径大于从 y 原点到 Racket 的距离,然后检查它是否比从 x 原点到 Racket 的距离更宽。

假设 (px, py) 是 Racket 的左上角,您可以尝试这样的操作:

def hit(bx, by, r, px, py, h):
if by >= py and by <= py + h:
print "Y satisfied."
if bx <= px + r:
print "HIT"
return True
print "X not satisfied."
print "not hit."
return False

请记住,这并不能说明球是圆形的(或您想到的任何其他形状)。

编辑:如果你在让它工作时遇到问题,你可以尝试加入一些打印语句来让你知道参数的值是什么以及返回值是什么。这应该让您对实际发生的事情有一些了解。

再次编辑:意识到函数有可能没有返回值。此外,此代码并未通过所有测试用例 - 它会将第一个测试用例计为命中。

关于python - 检测球何时击中乒乓 Racket ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3984541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com