此测试代码的目标是使玩家随W,A,S,D一起移动,并使用ENTER键开始或停止建造墙。如果有人能告诉我为什么他有时只撞墙,我将不胜感激。也可以随意批评我的代码!预先感谢。
import turtle
grid_size = 10
t1 = turtle.Pen()
t1.width(grid_size)
t1.up()
walls = [[0,0]]
walls.clear()
def toggle_building():
if t1.isdown():
t1.up()
else:
t1.down()
def lay_brick():
if t1.isdown() and t1.pos() not in walls:
walls.append(t1.pos())
print("Brick layed.")
def print_pos():
print(t1.pos())
def move_up():
t1.setheading(90)
if t1.pos() + [0, grid_size] not in walls:
t1.forward(grid_size)
lay_brick()
else:
print("wall")
print_pos()
def move_left():
t1.setheading(180)
if t1.pos() - [grid_size, 0] not in walls:
t1.forward(grid_size)
lay_brick()
else:
print("wall")
print_pos()
def move_down():
t1.setheading(270)
if t1.pos() - [0, grid_size] not in walls:
t1.forward(grid_size)
lay_brick()
else:
print("wall")
print_pos()
def move_right():
t1.setheading(0)
if t1.pos() + [grid_size, 0] not in walls:
t1.forward(grid_size)
lay_brick()
else:
print("wall")
print_pos()
turtle.onkeypress(move_up, "w")
turtle.onkeypress(move_left, "a")
turtle.onkeypress(move_down, "s")
turtle.onkeypress(move_right, "d")
turtle.onkeypress(toggle_building, "Return")
turtle.listen()
答案 0 :(得分:0)
正如您对问题的评论所指出的那样,乌龟徘徊在浮点平面上,即使您认为它已返回到与以前完全相同的位置,但该位置始终会添加一点浮点噪声。将职位转换为int
进行比较肯定有帮助,但可能还不够。
下面是我尝试通过更改坐标系本身来使其健壮,因此看来我们移动的是1而不是10。它还尝试减少需要进行浮点到整数转换的位数:< / p>
from turtle import Screen, Turtle
GRID_SIZE = 10
def toggle_building():
if turtle.isdown():
turtle.penup()
else:
turtle.pendown()
def lay_brick(position):
if turtle.isdown():
walls.add(position)
def move_up():
turtle.setheading(90)
position = int(turtle.xcor()), int(turtle.ycor()) + 1
if position not in walls:
turtle.goto(position)
lay_brick(position)
def move_left():
turtle.setheading(180)
position = int(turtle.xcor()) - 1, int(turtle.ycor())
if position not in walls:
turtle.goto(position)
lay_brick(position)
def move_down():
turtle.setheading(270)
position = int(turtle.xcor()), int(turtle.ycor()) - 1
if position not in walls:
turtle.goto(position)
lay_brick(position)
def move_right():
turtle.setheading(0)
position = int(turtle.xcor()) + 1, int(turtle.ycor())
if position not in walls:
turtle.goto(position)
lay_brick(position)
screen = Screen()
WIDTH, HEIGHT = (screen.window_width() / 2) // GRID_SIZE, (screen.window_height() / 2) // GRID_SIZE
screen.setworldcoordinates(-WIDTH, -HEIGHT, WIDTH, HEIGHT)
turtle = Turtle()
turtle.width(GRID_SIZE)
turtle.fillcolor('red')
turtle.penup()
walls = set()
screen.onkeypress(move_up, "w")
screen.onkeypress(move_left, "a")
screen.onkeypress(move_down, "s")
screen.onkeypress(move_right, "d")
screen.onkeypress(toggle_building, "Return")
screen.listen()
screen.mainloop()
它也使用set
来容纳墙壁。由于顺序无关紧要,因此可以使测试更快。