如何让我的海龟停止移动,并结束事件



我正在制作一个"游戏";乌龟必须呆在方格里,如果它移出去,游戏结束。我在while循环中使用了break命令,在评估提供的教学视频中,它有效,但我也不能理解。如果你感到困惑,我想让乌龟在走出方块时无法移动。我能做什么?下面是代码

import turtle
import random
turt = turtle.Turtle()
turt.speed("100")
tart = turtle.Turtle()
screen = turtle.Screen()
def up():
turt.setheading(90)
turt.forward(10)
def down():
turt.setheading(270)
turt.forward(10)
def left():
turt.setheading(180)
turt.forward(10)
def right():
turt.setheading(0)
turt.forward(10)

screen.onkey(up, "w")
screen.onkey(down, "s")
screen.onkey(left, "a")
screen.onkey(right, "d")
screen.listen()
tart.speed("100101001010000010101010000010010100")
tart.shape("square")
tart.penup()
tart.goto(-250,250)
tart.pendown()
for i in range(4):
tart.forward(400)
tart.right(90)
tart.forward(100)
tart.penup()
tart.goto(-2000000000,200000000000000000000)


while True:

r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
turt.color(r,g,b)

if turt.ycor() > 250 or turt.xcor() > -250:
break

elif turt.xcor() > 250 or turt.ycor() < -250:
break

#----------------------------------
tart.speed("100101001010000010101010000010010100")
tart.shape("square")
tart.penup()
tart.goto(-400,300)
tart.pendown()

您的程序有许多错误和不一致之处。让我们把它拆开再重新组装成一个合适的海龟程序。(不需要也不需要while True:)

from turtle import Pen, Turtle, Screen
def up():
turtle.setheading(90)
if turtle.ycor() < 240:
turtle.forward(10)
def down():
turtle.setheading(270)
if -240 < turtle.ycor():
turtle.forward(10)
def left():
turtle.setheading(180)
if -240 < turtle.xcor():
turtle.forward(10)
def right():
turtle.setheading(0)
if turtle.xcor() < 240:
turtle.forward(10)
turtle = Turtle()
turtle.speed('fastest')
pen = Pen()
pen.hideturtle()
pen.speed('fastest')
pen.penup()
pen.goto(-250, 250)
pen.pendown()
for _ in range(4):
pen.forward(500)
pen.right(90)
screen = Screen()
screen.onkey(up, 'w')
screen.onkey(down, 's')
screen.onkey(left, 'a')
screen.onkey(right, 'd')
screen.listen()
screen.mainloop()

为了简单起见,我删除了你可疑的海龟颜色逻辑,因为它与你的问题无关。

最新更新