我正在尝试制作一个随机游戏,其中哪个角色先到达终点就获胜。我基本上已经编写了完整的代码,但我需要最后的帮助来确定谁先冲过终点线。那么我该怎么做呢?我的代码是:
from turtle import Turtle
from random import randint
t = Turtle()
t.speed(0)
t.up()
t.goto(-200,0)
t.down()
t.forward(900)
t.up()
t.goto(-200,100)
t.down()
t.forward(900)
t.up()
t.goto(-200,200)
t.down()
t.forward(1000)
t.up()
t.goto(-200,-100)
t.down()
t.forward(900)
t.up()
t.goto(-200,-200)
t.down()
t.forward(1000)
t.up()
t.goto(-200,200)
t.down()
t.right(90)
t.forward(400)
t.left(90)
t.up()
t.goto(-100, -200)
t.left(90)
t.down()
t.forward(400)
t.up()
t.goto(800,-200)
t.down()
t.forward(400)
t.up()
t.goto(700,-200)
t.down()
t.forward(400)
d = Turtle()
d.speed(5)
d.color('red')
d.shape('arrow')
d.up()
d.goto(-155,150)
d.right(360)
c = Turtle()
c.speed(5)
c.color('blue')
c.shape('turtle')
c.up()
c.goto(-155,50)
c.right(360)
b = Turtle()
b.speed(5)
b.color('yellow')
b.shape('arrow')
b.up()
b.goto(-155,-50)
b.right(360)
a = Turtle()
a.speed(5)
a.color('green')
a.shape('turtle')
a.up()
a.goto(-155,-150)
a.right(360)
for i in range(350):
a.forward(randint(1,6))
b.forward(randint(1,6))
d.forward(randint(1,6))
c.forward(randint(1,6))
任何使代码更小的建议也将不胜感激。我正在尝试使用 while
循环,以便在越过终点线后立即停止游戏。
最佳答案
我们可以测试 turtle 的 .xcor()
值是否大于终点线的 x 坐标,以查看是否有人赢得了比赛。我在下面相应地重新设计了您的代码,并进行了一些代码压缩(但没有我能做的那么多,只是为了让事情变得简单):
from turtle import Screen, Turtle
from random import randint
START_LINE = -300
FINISH_LINE = 300
screen = Screen()
screen.setup(1000, 600)
t = Turtle(visible=False)
t.speed('fastest')
# Race Lanes
for y in range(-200, 300, 100):
t.up()
t.goto(START_LINE - 100, y)
t.down()
t.forward((FINISH_LINE + 90) - (START_LINE - 100))
# Starting and Finishing Gates
for x in [START_LINE - 100, FINISH_LINE - 10]:
t.up()
t.goto(x, 200)
t.right(90)
t.down()
t.forward(400)
t.left(90)
t.forward(100)
t.left(90)
t.forward(400)
t.right(90)
d = Turtle('arrow')
d.color('red')
d.speed(5)
d.up()
d.goto(START_LINE - 50, 150)
d.right(360)
c = Turtle('turtle')
c.color('blue')
c.speed(5)
c.up()
c.goto(START_LINE - 50, 50)
c.right(360)
b = Turtle('arrow')
b.color('yellow')
b.speed(5)
b.up()
b.goto(START_LINE - 50, -50)
b.right(360)
a = Turtle('turtle')
a.color('green')
a.speed(5)
a.up()
a.goto(START_LINE - 50, -150)
a.right(360)
while a.xcor() < FINISH_LINE and b.xcor() < FINISH_LINE and c.xcor() < FINISH_LINE and d.xcor() < FINISH_LINE:
a.forward(randint(1, 6))
b.forward(randint(1, 6))
c.forward(randint(1, 6))
d.forward(randint(1, 6))
# The race is over
screen.mainloop()
最好用变量定义关键位置,这样您就不必计算代码中每个步骤的数字 - 您可以根据需要进行计算和调整。
关于python - 在Python turtle 中使用while循环控制游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54103580/