我在Pygame做了一个程序,你走进了一个迷宫。迷宫是一个2D阵列,其中包含任何一个
没错:墙就在那里
或
错:墙不在那里
它工作正常。但是当我走到8号位置时,我现在可以走右边 - 通过一堵墙。它只发生在 y 位置。当我检查right
变量时,它是False。
import pygame
from pygame.locals import *
from pygame import gfxdraw
white = (255, 255, 255)
width, height = 220, 220
screen = pygame.display.set_mode((width, height))
psurf = pygame.Surface((20, 20))
psurf.fill((0, 0, 0))
wallsurf = pygame.Surface((20, 20))
wallsurf.fill((255, 0, 0))
t = True
f = False
walls = [[f, t, f, f, f, f, f, f, f, f, f],
[f, t, f, f, f, f, f, f, f, f, f],
[f, t, f, f, t, t, t, t, t, f, f],
[f, t, f, f, t, f, f, f, t, f, f],
[f, t, f, f, t, f, f, f, t, f, f],
[f, t, f, f, t, f, f, f, t, f, t],
[f, t, f, f, t, f, f, f, t, f, t],
[f, t, f, f, t, f, f, f, t, f, t],
[f, t, f, f, t, f, f, f, f, f, t],
[f, t, t, f, t, t, t, t, t, t, t],
[f, f, f, f, f, f, f, f, f, t, t]]
px = 0
py = 0
move_ticker = 0
right = True
left = True
delay = 500
maze = pygame.Surface((220, 220))
maze.fill(white)
placex = 0
placey = 0
for row in walls:
placex = 0
for wall in row:
if wall == True:
maze.blit(wallsurf, (placex * 20, placey * 20))
placex += 1
placey += 1
while True:
pygame.event.get()
screen.fill(white)
screen.blit(maze, (0, 0))
screen.blit(psurf, (px, py))
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if left:
if move_ticker == 0:
move_ticker = delay
px -= 20
if px < -1:
px = 0
if keys[K_RIGHT]:
if right:
if move_ticker == 0:
move_ticker = delay
px += 20
if px > 200:
px = 200
if keys[K_DOWN]:
if down:
if move_ticker == 0:
move_ticker = delay
py += 20
if py >= 200:
py = 200
if keys[K_UP]:
if up:
if move_ticker == 0:
move_ticker = delay
py -= 20
if py < 0:
py = 0
if move_ticker > 0:
move_ticker -= 1
truex = int(px / 20)
truey = int(py / 20)
right = True
left = True
up = True
down = True
try:
if walls[truey-1][truex]:
up = False
if walls[truey+1][truex]:
down = False
if walls[truey][truex-1]:
left = False
if walls[truey][truex+1]:
right = False
except IndexError:
pass
pygame.display.flip()
答案 0 :(得分:3)
问题是您有一个try语句而不是4.当您到达最低行walls[truey+1][truex]
时将返回索引错误。 Right仍设置为True
,因此永远不会更新为False。一个快速(和丑陋)的修复是:
try:
if walls[truey-1][truex]:
up = False
except IndexError:
up = False
try:
if walls[truey+1][truex]:
down = False
except IndexError:
down = False
try:
if walls[truey][truex-1]:
left = False
except IndexError:
left = False
try:
if walls[truey][truex+1]:
right = False
except IndexError:
right = False
我认为更漂亮的方法是使用函数,函数是一段代码,您可以多次重复使用,因此您不必反复重写相同的内容。
def can_move(pos_x, pos_y, dx, dy, walls):
move = True
try:
if walls[pos_y + dy][pos_x + dx]:
move = False
except IndexError:
move = False
return move
您可以缩短为:
def can_move(pos_x, pos_y, dx, dy, walls):
try:
move = not(walls[pos_y + dy][pos_x + dx])
except IndexError:
move = False
return move
使用此功能可以定义您的动作:
right = can_move(truex, truey, 1, 0, walls)
left = can_move(truex, truey, -1, 0, walls)
up = can_move(truex, truey, 0, -1, walls)
down = can_move(truex, truey, 0, 1, walls)