使用while循环来控制Python turtle中的游戏

时间:2019-01-09 05:11:29

标签: python loops turtle-graphics

我正在尝试制作一个随机游戏,其中哪个角色先赢。我基本上已经完成了全部代码,但是最后需要帮助,以确定谁首先越过终点。那我该怎么办呢?我的代码是:

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循环,以便一旦越过终点线就可以停止游戏。

1 个答案:

答案 0 :(得分:0)

我们可以测试乌龟的.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()

最好用变量定义关键位置,这样您就不必在代码的每个步骤中计算出数字,而可以根据需要进行计算和调整。

enter image description here