我正在尝试在pygame中创建一个随机门。我有一个这样的墙结构:
level = [
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"W W",
"W W",
"W W",
"W WWWWWWWWW W",
" W W ",
"W W W W",
"W W W W",
"W W W W",
"W WWWWWWWWW W",
" ",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
]
图片如下所示:
我想在中心的矩形中创建一个随机门。一个人被固定在中心的矩形内。所以他必须试着走出随机门。
需要一些关于如何创建随机门的想法。任何建议都是受欢迎的。更好的实施方法也很受欢迎。
代码:
class Wall(object):
def __init__(self, pos):
walls.append(self)
self.rect = pygame.Rect(pos[0], pos[1], 16, 16)
level = [
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"W W",
"W W",
"W W",
"W WWWWWWWWW W",
" W W ",
"W W W W",
"W W W W",
"W W W W",
"W WWWWWWWWW W",
" ",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
]
x = y = 0
for row in level:
for col in row:
if col == "W":
Wall((x, y))
x += 16
y += 16
x = 0
for wall in walls:
pygame.draw.rect(screen, (255, 255, 255), wall.rect)
答案 0 :(得分:2)
我会将你的level
更改为可以成为随机门的墙壁。我选择了" R"表示有可能成为随机门的墙壁。
level = [
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"W W",
"W W",
"W W",
"W WRRRRRRRW W",
" R R ",
"W R R W",
"W R R W",
"W R R W",
"W WRRRRRRRW W",
" ",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
]
我还创建了一个名为RandomDoorCreator
的函数,该函数接受level
,并更改level
以包含一个随机的"门" - 它实际上只是用'替换随机位置。 '
import random
def RandomDoorCreator(level):
locationsfordoor = []
xpos = ypos = 0
for element in level:
ypos=0
for letter in element:
if letter == 'R':
locationsfordoor.append([xpos,ypos]) #If it's a possible door location, add it to the list of possibilities
ypos+=1
xpos+=1
doorlocation = random.choice(locationsfordoor) #Pick a random location from our list of locations
newrow = list(level[doorlocation[0]]) #Create a list of strings for the row that we want to replace
newrow[doorlocation[1]] = ' ' #Replace the correct value in the row with ' '
del(level[doorlocation[0]]) #Delete the old row from the level
level.insert(doorlocation[0],''.join(newrow)) #Add the new row to the level
之后,您必须编辑for
循环以考虑新的" R" s:
RandomDoorCreator(level) #Create a random door BEFORE we create walls
x = y = 0
for row in level:
for col in row:
if col == "W" or col == "R": #Only row changed -- we just want to account for our new R values
Wall((x, y))
x += 16
y += 16
x = 0
for wall in walls:
pygame.draw.rect(screen, (255, 255, 255), wall.rect)
我喜欢这种方法的原因是你可以创建完全不同的多个级别,并且仍然将它传递给函数而不需要任何额外的代码。它还使您可以在视觉上轻松选择可能的随机门位置,我认为这可以帮助制作游戏。