Python-turtle:来自数学库:dist() 导致循环到 exit/freeze

Python-turtle: From math library: dist() causing loop to exit/freeze

我正在尝试使用 Python(使用乌龟)制作游戏 游戏的目的是射击对方

问题来自碰撞代码。我正在使用 dist() 检查与子弹的碰撞,但这似乎导致循环到 exit/freeze(我真的不知道是哪个)。

我试过使用距离公式而不是函数,但这并没有改变任何东西

这是我的代码:

        bullet.forward(10)
        distancetop1 = dist(player1.pos(),bullet.pos())
        if self != player1 and distancetop1 < 2:
            bullet.clear()
            print("orange won!")
            exit()
        distancetop2 = dist(player1.pos(),bullet.pos())
        if self != player2 and distancetop2 < 2:
            bullet.clear()
            print("blue won!")
            exit()

如果需要,我的完整代码是here

使用 turtle 时,不要将密钥检查放在循环中。设置一次然后调用 listen。使用mainloop保持游戏运行.

试试这个代码:

import turtle,random, math

sc = turtle.Screen()
sc.bgcolor("#000")

player1 = turtle.Turtle()
player1.color("#00f")
player1.speed(0)
player1.up()
player1.goto(-256,0)

player2 = turtle.Turtle()
player2.color("#ffa500")
player2.speed(0)
player2.up()
player2.goto(256,0)
player2.seth(180)

bullet1 = turtle.Turtle()
bullet1.color("#fff")
bullet1.speed(0)
bullet1.ht()
bullet1.up()
bullet1.active = False 

def dist(c1,c2):
   return math.sqrt((c1[0]-c2[0])**2 + (c1[1]-c2[1])**2)

def shoot(self):
    bullet = bullet1.clone()
    bullet.active = True
    bullet.goto(self.xcor(),self.ycor())
    bullet.down()
    bullet.seth(self.heading())
    while (bullet.xcor() < 600 and bullet.xcor() > -600) and (bullet.ycor() < 256 and bullet.ycor() > -256):
        bullet.forward(10)
        distancetop1 = dist(player1.pos(),bullet.pos())
        if self != player1 and distancetop1 < 5:
            bullet.clear()
            print("orange won!")
            exit()
        distancetop2 = dist(player2.pos(),bullet.pos())
        if self != player2 and distancetop2 < 5:
            bullet.clear()
            print("blue won!")
            exit()
    bullet.clear()
def p1right():
    player1.seth(0)
    player1.forward(4)
def p1left():
    player1.seth(180)
    player1.forward(4)
def p1up():
    player1.seth(90)
    player1.forward(4)
def p1down():
    player1.seth(270)
    player1.forward(4)
def p1shoot():
    shoot(player1)

def p2right():
    player2.seth(0)
    player2.forward(4)
def p2left():
    player2.seth(180)
    player2.forward(4)
def p2up():
    player2.seth(90)
    player2.forward(4)
def p2down():
    player2.seth(270)
    player2.forward(4)
def p2shoot():
    shoot(player2)

#while True:
sc.onkey(p1right,"D")
sc.onkey(p1left,"A")
sc.onkey(p1up,"W")
sc.onkey(p1down,"S")
sc.onkey(p1shoot,"space")

sc.onkey(p2right,"Right")
sc.onkey(p2left,"Left")
sc.onkey(p2up,"Up")
sc.onkey(p2down,"Down")
sc.onkey(p2shoot,"Return")
sc.listen()
sc.mainloop()