海龟事件和屏幕坐标



该程序使用键在 4 个方向上移动一只海龟。我想控制 也与屏幕边界碰撞。但是我有一个很奇怪的 问题!

例如,当我将移动到右侧时,它可以正常工作,但是 当我将 Turtle 转到左侧时,图形上它变得正常,但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()

我看到的主要问题是您在setheading()命令之后检查冲突,该命令本身不会导致冲突,然后执行可能导致冲突的setx()sety()命令,但不要检查它! 就好像你在下一步时检查上一步的碰撞一样。 我看到的第二个问题是您使用各种固定值来计算碰撞,而不是从屏幕宽度和高度得出这些值:

from turtle import Screen, Turtle
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 800
CURSOR_SIZE = 20
def turtleUp():
turtle.setheading(90)
turtle.sety(turtle.ycor() + 10)
if colisao(turtle):
# turtle.undo()
turtle.sety(turtle.ycor() - 10)
def turtleDown():
turtle.setheading(270)
turtle.sety(turtle.ycor() - 10)
if colisao(turtle):
# turtle.undo()
turtle.sety(turtle.ycor() + 10)
def turtleRight():
turtle.setheading(0)
turtle.setx(turtle.xcor() + 10)
if colisao(turtle):
# turtle.undo()
turtle.setx(turtle.xcor() - 10)
def turtleLeft():
turtle.setheading(180)
turtle.setx(turtle.xcor() - 10)
if colisao(turtle):
# turtle.undo()
turtle.setx(turtle.xcor() + 10)
def colisao(t):
return not(CURSOR_SIZE - SCREEN_WIDTH/2 < t.xcor() < SCREEN_WIDTH/2 - CURSOR_SIZE and 
CURSOR_SIZE - SCREEN_HEIGHT/2 < t.ycor() < SCREEN_HEIGHT/2 - CURSOR_SIZE)
screen = Screen()
screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT)
screen.title("Python Turtle (Movimento)")
screen.bgcolor('lime')
turtle = Turtle()
turtle.shape('turtle')
turtle.speed('fastest')
turtle.penup()
screen.onkeypress(turtleUp, 'w')
screen.onkeypress(turtleDown, 's')
screen.onkeypress(turtleRight, 'p')
screen.onkeypress(turtleLeft, 'o')
screen.listen()
screen.mainloop()

最新更新