当我尝试添加更多形状时,为什么我的乌龟停止移动?
我正在尝试绘制一个形状,然后使用箭头键在屏幕上移动该形状。我的目标是最终制作一款 2D 游戏,但我不知道如何绘制多个圆圈并使其全部移动。
到目前为止我粘贴了我的代码。画完圆圈后,我尝试画一条线,但似乎不喜欢那样。如果我取出那个 forward
语句,那么我可以再次移动圆圈。
import turtle
def Left():
move.left(1)
move.forward(1)
def Right():
move.right(1)
move.forward(1)
def Forwards():
move.forward(1)
def Backwards():
move.backward(1)
def moving_object(move):
move.fillcolor('orange')
move.begin_fill()
move.circle(20)
move.forward(10)
move.end_fill()
screen = turtle.Screen()
screen.setup(600,600)
screen.bgcolor('green')
screen.tracer(0)
move = turtle.Turtle()
move.color('orange')
move.speed(0)
move.width(2)
move.hideturtle()
move.penup()
move.goto(-250, 0)
move.pendown()
screen.listen()
screen.onkeypress(Left, "Left")
screen.onkeypress(Right, "Right")
screen.onkeypress(Forwards, "Up")
screen.onkeypress(Backwards, "Down")
while True :
move.clear()
moving_object(move)
screen.update()
I am trying to draw a shape and then move that shape around the screen with the arrow keys. My goal is to make a 2D game in the end, but I can't figure out how to draw more than a circle and get it all to move.
I pasted my code so far. After the circle is drawn I tried going for a line and it doesn't seem to like that. If I take out that forward
statement then I can move the circle around again.
import turtle
def Left():
move.left(1)
move.forward(1)
def Right():
move.right(1)
move.forward(1)
def Forwards():
move.forward(1)
def Backwards():
move.backward(1)
def moving_object(move):
move.fillcolor('orange')
move.begin_fill()
move.circle(20)
move.forward(10)
move.end_fill()
screen = turtle.Screen()
screen.setup(600,600)
screen.bgcolor('green')
screen.tracer(0)
move = turtle.Turtle()
move.color('orange')
move.speed(0)
move.width(2)
move.hideturtle()
move.penup()
move.goto(-250, 0)
move.pendown()
screen.listen()
screen.onkeypress(Left, "Left")
screen.onkeypress(Right, "Right")
screen.onkeypress(Forwards, "Up")
screen.onkeypress(Backwards, "Down")
while True :
move.clear()
moving_object(move)
screen.update()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的海龟代码的整个结构是不正确的。在像海龟这样的事件驱动世界中不应该有
while True:
。您的循环逻辑使moving_object()
内的任何向前运动无限重复,并将您的乌龟推出屏幕。让我们重建您的程序以展示类似坦克的运动,其中圆圈是坦克,线条是它的枪:
The whole structure of your turtle code is incorrect. There shouldn't be a
while True:
in an event-driven world like turtle. Your looping logic made any forward motion insidemoving_object()
repeat infinitely and push your turtle off the screen.Let's rebuild your program to exhibit tank-like movement where the circle is the tank and the line is its gun: