Python乌龟比赛游戏.结束游戏功能似乎不起作用



我遇到了一个如何结束我的龟蟒游戏的问题。如果我把乌龟放在代码开头的起点/终点,代码似乎会起作用,但当乌龟到达游戏终点时,它不会注册。据我所知,我认为我对端函数的数学计算是正确的。我是新来的,很感激你的帮助。不过我目前处于离线状态。

代码:

import time
import turtle
from turtle import *

wn = turtle.Screen()

name=textinput("Question", "what is your name")
#display
pencolor("white")
penup()
goto(0,170)
write("hello " +name,align='center',font=('Comic Sans', 20))
#wn = turtle.screen() if the code doesn't work
#diffrent turtles here

t1 = turtle.Turtle()
t2 = turtle.Turtle()
t3 = turtle.Turtle()
#starting psoition
turtle.penup()
t1.penup()
turtle.goto(-1, -230)
t1.goto(-1, -170)
#starting line postion

def f():
fd(10)

def b():
bk(10)

def l():
left(10)

def r():
right(10)

#testing
def fo():
t1.fd(10)

def ba():
t1.bk(10)

def le():
t1.left(10)

def ri():
t1.right(10)

#turtle coordinates
first=turtle.ycor()
second=turtle.xcor()
third=t1.ycor()
fourth=t1.xcor()

#when to end the game
if (turtle.ycor()>= (-160)) and (turtle.ycor()<= (-240)):
if (turtle.xcor()>= (0)) and (turtle.xcor()<= (11)):    
print("Finally working")
#replaced with write who the winner is later

if (t1.ycor()>= (-160)) and (t1.ycor()<= (-240)):
if (t1.xcor()>= (0)) and (t1.xcor()<= (11)):    
print("Finally")
# onkey creates the key board = turtle.onkey("function, key")  You have to keep pressing keys for it to move
turtle.onkey(f, "w")
turtle.onkey(b, "s")
turtle.onkey(l, "a")
turtle.onkey(r, "d")

wn.onkey(fo, "Up")
wn.onkey(ba, "Down")
wn.onkey(le, "Left")
wn.onkey(ri, "Right")
listen()

#WINDOW SETUP
window = Screen()    
window.setup(800, 800)
window.title("Turtle game")
turtle.bgcolor("forestgreen")
t3.color("black")
t3.speed(0) 
t3.penup()
t3.setpos(-140, 250)
t3.write("THE TURTLE RACE", font=("Comic Sans", 30, "bold"))
t3.penup()
#turtle ask name
#add images here
#turtle controls
# def creates a function. : means opperation f means move turtle foward. fd push turtle forward
# onkey creates the key board = turtle.onkey("function, key")  You have to keep pressing keys for it to move

t2.speed(0)
t2.color("grey")
t2.pensize(100)
t2.penup()
t2.goto(-200, -200)
t2.left(90)
t2.pendown()
t2.forward(300)
t2.right(90)
t2.forward(500)
t2.right(90)
t2.forward(300)
t2.right(90)
t2.forward(500)

turtle.penup()

首先,你的数学不太正确-坐标永远不可能既是<=-240和>=-160.它应该是t.ycor() >= -240 and t.ycor() <= -160,或者更简单地说,-240 <= t.ycor() <= -160

其次,当代码第一次运行时,只检查一次当前条件。相反,你需要让程序定期检查它。您可以通过添加一个通用的onkeypress事件处理程序来实现这一点,该事件处理程序在每次按下任何键时都会进行检查。

def check_status():
for player, t in enumerate([turtle, t1]):
if  0 <= t.xcor() <= 11 and -240 <= t.ycor() <= -160:
print(f"Player {player} is at the endpoint")
...
wn.onkeypress(check_status)
listen()

最新更新