当吃豆人与墙壁相撞时,我遇到了麻烦。我输入了一个迷宫,并使用 for 循环绘制了迷宫,吃豆人运动也一切正常,但当它撞到墙上时,我希望它停止。
我怎样才能让它停止,然后等待用户输入使用按键切换方向?我尝试的是使用一个变量来表示它停止了,并且它会停止,但它不会响应我输入的任何键以使其再次移动
maze = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XP XXXXXXXE XX",
"X XXXXXXX XXXXXX XXXXX",
"X XX XXXXXX XXXXX",
"X XX XXX EXX",
"XXXXXX XX XXX XX",
"XXXXXX XX XXXXXX XXXXX",
"XXXXXX XX XXXX XXXXX",
"X XXX XXXX XXXXX",
"X XXX XXXXXXXXXXXXXXXXX",
"X XXXXXXXXXXXXXXX",
"X XXXXXXXX",
"XXXXXXXXXXXX XXXXX X",
"XXXXXXXXXXXXXXX XXXXX X",
"XXX XXXXXXXXXX X",
"XXXE X",
"XXX XXXXXXXXXXXXX",
"XXXXXXXXXX XXXXXXXXXXXXX",
"XXXXXXXXXX X",
"XX XXXXX X",
"XX XXXXXXXXXXXXX XXXXX",
"XX YXXXXXXXXXXX XXXXX",
"XX XXXX X",
"XXXXE X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]
def move():
if player.direction=="right":
player.setx(player.xcor()+7)
if player.direction=="left":
player.setx(player.xcor()-7)
if player.direction=="up":
player.sety(player.ycor()+7)
if player.direction=="down":
player.sety(player.ycor()-7)
def right():
player.direction="right"
def left():
player.direction="left"
def up():
player.direction="up"
def down():
player.direction="down"
def exit():
turtle.bye()
screen=turtle.Screen()
screen.bgcolor("black")
screen.setup(900,900)
screen.tracer(n=0)
walllist=[]
x=-365
y=360
for r in maze:
for h in r:
if h=="X":
wall=turtle.Turtle()
wall.color("blue")
wall.shapesize(1.43,1.43,1)
wall.shape("square")
wall.penup()
wall.goto(x,y)
walllist.append(wall)
if h=="P":
player=turtle.Turtle()
player.speed(0)
player.color("yellow")
player.shape("circle")
player.penup()
player.direction="stop"
player.goto(x,y)
x+=30
x=-365
y-=30
screen.listen()
screen.onkey(right,"Right")
screen.onkey(up,"Up")
screen.onkey(down,"Down")
screen.onkey(left,"Left")
screen.onkey(exit,"Escape")
while True:
move()
screen.update()
for wall in walllist:
if player.distance(wall)<29:
player.direction="stop"
如果您将屏幕更新移动到
for
循环下方,吃豆人将在撞墙后继续响应移动:但请注意,如果吃豆人抓住墙壁,它就不会自由移动,而是会“拖动”,导致您必须反复按方向键才能移动。更糟糕的是,吃豆人将能够进入墙壁。当然,所有这些都与您如何编写算法来检测以及更重要的是批准下一步行动直接相关。具体来说,该标准
layer.distance(wall)<29
参考到墙壁的距离,而不管吃豆人移动的方向如何。这需要换一种方式来思考。