此程序使用键在4个方向上移动Turtle。我想控制 龟也与屏幕边界发生碰撞。但是我很奇怪 问题!
例如,当我将Turtle移到右侧时,它可以正常工作,但是
当我将Turtle移到左侧时,它以图形方式变为OK,但是print
给我的坐标值,而不是减小X坐标值,增加一倍,然后开始减小!当然,这与我要创建的碰撞控制很混乱!
这很尴尬,我只是测试了我能想到的一切,但到目前为止还没有运气!
在Thonny 3.2.7中,我正在使用带有Turtle图形的Python 3.7.7。 我在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()
答案 0 :(得分:1)
我看到的主要问题是,您在class PrintTest:
def __init__(self, file, game):
self.f = file
self.game = game
def write(self, t):
if t != '\n':
self.f.write(t)
self.game.text, self.game.textRect = game.font.render(t, self.game.text_colors[2])
self.game.textRect.center = (300, 300)
def flush(self):
pass
命令之后检查冲突,而命令本身本身不会导致冲突,然后执行setheading()
或setx()
命令造成碰撞,但请勿检查!就像您检查下一个动作中上一个动作的碰撞一样。我看到的第二个问题是,您使用各种固定值来计算碰撞,而不是从屏幕的宽度和高度得出这些值:
sety()