我试着让一只乌龟停下来,直到它改变了方向。在
from turtle import *
import turtle
import time
user_speed = 46
border_pen = Turtle()
shouldMove = True
#alreadyStoppedDown = False
#alreadyStoppedUp = False
prev_heading = heading()
#Set up border
def setup(turt):
turt.ht()
turt.pu()
turt.speed(0)
turt.goto(-250,250)
turt.pd()
turt.begin_fill()
for x in range(4):
turt.fd(500)
turt.rt(90)
turt.color('black')
turt.end_fill()
#Set up user
def user():
pu()
shape('square')
shapesize(2)
color('orange')
speed(0)
goto(-230,230)
speed(1)
#Keybind functions
def down():
global prev_heading
prev_heading = heading()
speed(0)
setheading(-90)
speed(1)
def up():
global prev_heading
prev_heading = heading()
speed(0)
setheading(90)
speed(1)
def left():
global prev_heading
prev_heading = heading()
speed(0)
setheading(180)
speed(1)
def right():
global prev_heading
prev_heading = heading()
speed(0)
setheading(0)
speed(1)
#Border restriction
def restrict():
global shouldMove
if ycor() <= -230:
shouldMove = False
global prev_heading
prev_heading = heading()
def main():
global shouldMove
while True:
#Debugging
print(shouldMove)
print(heading(),prev_heading,ycor())
if shouldMove:
fd(user_speed)
restrict()
else:
if heading() != prev_heading:
shouldMove = True
else:
continue
setup(border_pen)
user()
onkey(up,'w')
onkey(down,'s')
onkey(left,'a')
onkey(right,'d')
listen()
main()
我只设置了边界底部的限制。在
我能让乌龟停止移动,但当它停止移动时,它不会改变它的方向。我试着按wasd
来改变它的方向,但它一直呆在那里直到窗口崩溃。我试着想出多种解决办法,但我做不到。这里的主要问题是当海龟的ycor()小于或等于-230时,它会停止,但不会改变它的航向。在
当我更改main()使其在ycor()小于或等于-230时,它将向右移动一次,因为ycor()仍然是-230,它将停止移动。在
^{pr2}$我这样做是为了好玩,我看了一个使用处理的蛇游戏的编码训练,我试图用Python中的turtle模块重新创建它。是的,我是初学者。我想尝试使用turtle模块重新制作snake游戏,尽管我可以使用其他模块,如PyGame,因为我不熟悉PyGame。这个问题有什么解决办法吗?或者我不能用海龟模块来做这个吗?在
我在代码中看到的主要问题是
while True:
,它在事件驱动的世界中没有一席之地。(因为它可以阻止事件!)我们将改用ontimer()
事件。下一个问题是控制结构太复杂了。我们将放弃它的大部分,只保留布尔值shouldMove
作为控制。最后,将函数接口与turtle的面向对象接口混合在一起。我们将把import
改为只允许面向对象的接口:这应该像你描述的那样。乌龟会一直沿着直线移动,直到你按下方向键或者它停在边界处。在
相关问题 更多 >
编程相关推荐