我在Pygame里做了一个程序,你在迷宫里行走。迷宫是一个二维数组,包含
真的:墙在那里
或
错误:墙不在那里
很好用。但当我走到第8;9号位置时,我现在可以直接穿过一堵墙了。它只发生在这个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()
问题是你有一个try语句而不是4个。当到达最低行时
walls[truey+1][truex]
将返回一个索引错误。Right仍然设置为True
,因此从不更新为False。一个快速的解决方法是:我认为一个更漂亮的方法是使用一个函数,一个函数是一段代码,你可以重复使用多次,这样你就不必一遍又一遍地重写同样的东西。你知道吗
您可以将其缩短为:
使用此功能,您可以定义您的移动:
相关问题 更多 >
编程相关推荐