当我运行该程序时,它卡住并且无法工作。该程序的要点是,当由键绑定(bind)控制的用户控制的 turtle 的 x 和 y 位置坐标与其他 turtle 的 x 和 y 位置坐标的距离小于 10 像素时,打印出一些内容。
import turtle
import random
wn = turtle.Screen()
wn.setup(width = 450, height = 450)
player = turtle.Turtle()
player2 = turtle.Turtle()
def up():
y = player.ycor()
y = y + 5
player.sety(y)
if y>=310:
player.sety(y-15)
def down():
y = player.ycor()
y = y - 5
player.sety(y)
if y<-310:
player.sety(y+15)
def left():
x = player.xcor()
x = x - 5
player.setx(x)
if x<=-625:
player.setx(x+15)
def right():
x = player.xcor()
x = x + 5
player.setx(x)
if x>=625:
player.setx(x-15)
player.penup()
player.setpos(0,0)
player.showturtle()
player.shape("square")
wn.bgcolor("green")
player2.shape("square")
player2.penup()
player2.setpos(300,300)
player2.showturtle()
turtle.listen()
turtle.onkeypress(up,"Up")
turtle.onkeypress(left,"Left")
turtle.onkeypress(right,"Right")
turtle.onkeypress(down, "Down")
def checkcollision(player,player2):
if abs(player.xcor() - player2.xcor()) < 10 and abs(player.ycor() - player2.ycor()) < 10:
player.write("collision")
while True:
checkcollision(player,player2)
最佳答案
我认为它卡住是因为代码中的循环:
while True:
checkcollision(player,player2)
它总是检查碰撞,将该代码移动到移动函数Up
、Down
、Left
、Right
等等,然后在移动后调用它。
关于python - 碰撞检测程序在 Turtle 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60609836/