gpt4 book ai didi

python - 在 Python turtle 游戏中检测碰撞

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

我正在尝试制作一个红 turtle 追逐蓝 turtle 的 Python 游戏。当红 turtle 捕获蓝 turtle 时,我想让它在屏幕上说“碰撞”,但它不起作用。当它发生碰撞时,什么也没有发生,它给我一个错误“Turtle”对象不可调用。

from turtle import Turtle, Screen

playGround = Screen()

playGround.screensize(250, 250)
playGround.title("Turtle Keys")

run = Turtle("turtle")
run.speed("fastest")
run.color("blue")
run.penup()
run.setposition(250, 250)

follow = Turtle("turtle")
follow.speed("fastest")
follow.color("red")
follow.penup()
follow.setposition(-250, -250)

def k1():
run.forward(45)

def k2():
run.left(45)

def k3():
run.right(45)

def k4():
run.backward(45)

def quitThis():
playGround.bye()

def follow_runner():
follow.setheading(follow.towards(run))
follow.forward(8)
playGround.ontimer(follow_runner, 10)

playGround.onkey(k1, "Up") # the up arrow key
playGround.onkey(k2, "Left") # the left arrow key
playGround.onkey(k3, "Right") # you get it!
playGround.onkey(k4, "Down")

playGround.listen()

follow_runner()

def is_collided_with(self, run):
return self.rect.colliderect(run.rect)

runner = run(10, 10, 'my_run')
follower = follow(20, 10)
if follow.is_collided_with(run):
print 'collision!'

playGround.mainloop()

最佳答案

这段代码似乎比实际编程更像是一厢情愿:

def is_collided_with(self, run):
return self.rect.colliderect(run.rect)

runner = run(10, 10, 'my_run')
follower = follow(20, 10)
if follow.is_collided_with(run):
print 'collision!'

turtle 没有.rect() 方法。您不能使用此 def 语句简单地将 is_collided_with() 方法添加到现有类。没有 run()follow() 函数。此碰撞测试只会在每次运动后需要时执行一次。让我们尽我们所能挽救一切并使这项工作成功:

from turtle import Turtle, Screen

playGround = Screen()

playGround.screensize(250, 250)
playGround.title("Turtle Keys")

run = Turtle("turtle")
run.color("blue")
run.penup()
run.setposition(250, 250)

follow = Turtle("turtle")
follow.color("red")
follow.penup()
follow.setposition(-250, -250)

def k1():
run.forward(45)

def k2():
run.left(45)

def k3():
run.right(45)

def k4():
run.backward(45)

def quitThis():
playGround.bye()

def is_collided_with(a, b):
return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10

def follow_runner():
follow.setheading(follow.towards(run))
follow.forward(min(follow.distance(run), 8))

if is_collided_with(follow, run):
print('Collision!')
quitThis()
else:
playGround.ontimer(follow_runner, 10)

playGround.onkey(k1, "Up") # the up arrow key
playGround.onkey(k2, "Left") # the left arrow key
playGround.onkey(k3, "Right") # you get it!
playGround.onkey(k4, "Down")

playGround.listen()

follow_runner()

playGround.mainloop()

我根据 turtle 光标的大小使用 10 作为碰撞半径,您可以根据需要进行调整。这段代码简单地结束了游戏,并带有一条消息,当发生碰撞时,您可能想要做一些更复杂的事情。您可以考虑将碰撞逻辑设为自己的函数,以便在每次击键后使用,以防奔跑者不小心撞到跟随者!

关于python - 在 Python turtle 游戏中检测碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43461566/

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