当吃豆人撞到墙的时候我遇到了麻烦。我输入了一个迷宫,用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"
字符串
1条答案
按热度按时间7dl7o3gd1#
如果你将屏幕更新移动到
for
循环下面,pacman将在撞墙后继续响应移动:字符串
然而,请注意,如果吃豆人抓住墙壁,它将无法自由移动,但它会“拖动”,导致您必须反复按方向键才能移动。更糟糕的是,吃豆人将能够进入墙壁。当然,所有这些都与您如何编写算法来检测,更重要的是,批准下一步行动直接相关。具体而言,标准
layer.distance(wall)<29
是指到墙壁的距离,而不管吃豆人移动的方向是沿着的。2这需要另一种方式来考虑它。