【发布时间】:2020-08-17 23:01:29
【问题描述】:
该程序使用键在 4 个方向上移动海龟。我想控制 海龟也与屏幕边界发生碰撞。但我有一个非常奇怪的 问题!
例如,当我将 Turtle 移到右侧时,它可以正常工作,但是
当我将 Turtle 转到左侧时,图形上它变成了 OK,但是 print 给我的坐标值,而不是减少 X 坐标值,增加一次然后开始减少!当然,这会与我正在尝试创建的碰撞控制相混淆!
这很尴尬,我只是测试了我能想到的所有东西,但到目前为止没有运气!
我在 Thonny 3.2.7 中使用 Python 3.7.7 和 Turtle 图形。 我在 Repl.it 中测试过,结果是一样的!
代码如下:
import turtle
screen_width = 1000
screen_height = 800
s = turtle.Screen()
s.setup(screen_width, screen_height)
s.title("Python Turtle (Movimento)")
s.bgcolor("lime")
def turtleUp():
t1.setheading(90)
if not colisao(t1):
t1.sety(t1.ycor() + 10)
def turtleDown():
t1.setheading(270)
if not colisao(t1):
t1.sety(t1.ycor() - 10)
def turtleRight():
t1.setheading(0)
if not colisao(t1):
t1.setx(t1.xcor() + 10)
def turtleLeft():
t1.setheading(180)
if not colisao(t1):
t1.setx(t1.xcor() - 10)
def colisao(t):
print(t.xcor(), t.ycor())
if t.xcor() < -470 or t.xcor() > 460 or t.ycor() < -370 or t.ycor() > 360:
return True
else:
return False
t1 = turtle.Turtle()
t1.speed(0)
t1.shape("turtle")
t1.color("black")
t1.up()
t1.goto(0, 0)
s.onkeypress(turtleUp, "w")
s.onkeypress(turtleDown, "s")
s.onkeypress(turtleRight, "p")
s.onkeypress(turtleLeft, "o")
s.listen()
s.mainloop()
【问题讨论】:
标签: python python-3.x turtle-graphics python-turtle