gpt4 book ai didi

python - 在pygame中创建一个随机门

转载 作者:行者123 更新时间:2023-12-01 05:00:20 25 4
gpt4 key购买 nike

我正在尝试在 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",
]

图像如下所示: enter image description here

我想在中心的矩形中创建一扇随机门。一个人被固定在中心的矩形内。所以他必须想方设法走出这扇随机门。

需要一些关于如何创建随机门的想法。欢迎任何建议。也欢迎更好的实现方法。

代码:

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)

最佳答案

我会将您的级别更改为表示可以变成随机门的墙壁的内容。我选择“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”:

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)

我喜欢这种方法的原因是,您可以创建多个完全不同的级别,并且仍然将其传递给函数,而无需任何额外的代码。它还使得在视觉上更容易选择可能的随机门位置,我认为这有助于游戏的制作。

关于python - 在pygame中创建一个随机门,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26367894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com