我正在使用乌龟图形构建一个简单的python游戏,这是一辆在轨道上行驶的汽车。我已经建造了轨道和汽车,并且我知道如何使汽车向不同的方向旋转,但是我不知道如何使汽车朝着其所面对的特定方向移动。有人有什么想法吗?这是我到目前为止的内容:
import turtle
#Screen
wn = turtle.Screen()
wn.title('Car')
wn.bgcolor('black')
wn.setup(width=1200, height=1200)
wn.tracer(0)
#Track
track = turtle.Turtle()
track.color('white')
track.speed(0)
track.penup()
track.goto(-550, 0)
track.pendown()
track.goto(-550, 300)
track.goto(-100,370)
track.goto(100, 210)
track.goto(300, 380)
track.goto(580, 100)
track.goto(570, -300)
track.goto(300, -370)
track.goto(0, -250)
track.goto(-300, -200)
track.goto(-570, -250)
track.goto(-550, 0)
track.hideturtle()
#Track 2
track2 = turtle.Turtle()
track2.color('white')
track2.speed(0)
track2.penup()
track2.goto(-450, 0)
track2.pendown()
track2.goto(-450, 230)
track2.goto(-150, 250)
track2.goto(100, 100)
track2.goto(300, 200)
track2.goto(460, 100)
track2.goto(450, -220)
track2.goto(300, -250)
track2.goto(0, -130)
track2.goto(-300, -100)
track2.goto(-450, 0)
track2.hideturtle()
#Start line
line = turtle.Turtle()
line.color('white')
line.speed(0)
line.penup()
line.goto(-550, 0)
line.pendown()
line.goto(-450,0)
line.hideturtle()
#Car
car = turtle.Turtle()
car.color('red')
car.speed(0)
car.penup()
car.shape('square')
car.shapesize(stretch_wid=1, stretch_len=2)
car.goto(-500, 0)
car.setheading(90)
#Move car
def turn_right():
car.right(20)
def turn_left():
car.left(20)
#Key Bindings
wn.listen()
wn.onkey(turn_right, 'd')
wn.onkey(turn_left, 'a')
while True:
wn.update()
turtle.mainloop()
答案 0 :(得分:0)
简单的答案是更改它:
while True:
wn.update()
改为:
while True:
car.forward(1)
wn.update()
,您会发现您的汽车向前移动,并要求您驾驶它以保持在赛道上。更复杂的答案是,while True:
在像乌龟这样的事件驱动环境中没有业务,而您需要的是计时器事件:
from turtle import Screen, Turtle, mainloop
# Move car
def turn_right():
car.right(20)
def turn_left():
car.left(20)
def move():
car.forward(1)
screen.update()
screen.ontimer(move, 25)
# Screen
screen = Screen()
screen.title('Car')
screen.bgcolor('black')
screen.setup(width=1200, height=1200)
screen.tracer(0)
# Track
track = Turtle()
track.hideturtle()
track.color('white')
track.penup()
track.goto(-550, 0)
track.pendown()
track.goto(-550, 300)
track.goto(-100, 370)
track.goto(100, 210)
track.goto(300, 380)
track.goto(580, 100)
track.goto(570, -300)
track.goto(300, -370)
track.goto(0, -250)
track.goto(-300, -200)
track.goto(-570, -250)
track.goto(-550, 0)
track.penup()
track.goto(-450, 0)
track.pendown()
track.goto(-450, 230)
track.goto(-150, 250)
track.goto(100, 100)
track.goto(300, 200)
track.goto(460, 100)
track.goto(450, -220)
track.goto(300, -250)
track.goto(0, -130)
track.goto(-300, -100)
track.goto(-450, 0)
# Start line
line = Turtle()
line.hideturtle()
line.color('white')
line.penup()
line.setx(-550)
line.pendown()
line.setx(-450)
# Car
car = Turtle()
car.shape('square')
car.shapesize(stretch_wid=1, stretch_len=2)
car.color('red')
car.setheading(90)
car.penup()
car.setx(-500)
# Key Bindings
screen.onkey(turn_right, 'd')
screen.onkey(turn_left, 'a')
screen.listen()
move()
mainloop()