Python检查2d数组中的多个项目

2024-09-29 23:26:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我环顾四周,但找不到任何人问我想做什么:

我来给你介绍一下背景:

我正在用python制作一个游戏,玩家在网格中移动,搜索宝箱,我尝试在8x8网格中随机生成10个宝箱位置。在

我的网格是通过执行以下操作创建的:

grid = []

然后我用“子网格”填充网格

因为我的游戏是基于一个网格设计的,这使得我可以分开单独的行。在

^{pr2}$

这使我在主“网格”列表中有8个空列表。在

接下来我要做的是随机生成胸部位置,并将它们映射到另一个名为“chestLocations”的列表中,该列表还使用10个子网格(每个单独的胸部位置对应一个)。这样我就可以创建Y和X变量,它们是相对于网格列表的。在

这是我的GenerateChestLocations()函数:

def GenerateChestLocations():
global chestY
global chestX
counter = 10

chestY = []
chestX = []

while counter > 0:

    posY = random.randint(0,7)
    posX = random.randint(1,8)

    value = GetValue(posY,posX)

    if value == gridChar:
        pass
    elif value == playerChar:
        continue

    chestY.append(posY)
    chestX.append(posX)
    counter -= 1

for a in range(len(chestY)):
    chestLocations[a].append(chestY[a])
    visitedChests[a].append(chestY[a])
for i in range(len(chestX)):
    chestLocations[i].append(chestX[i])
    visitedChests[i].append(chestX[i])

for subItem in range(len(visitedChests)):
    visitedChests[subItem].append(0)

return

(顺便说一句,这里使用的变量是在程序开始时定义的,如下所示:)

函数的作用是:返回Y和X坐标的网格项的值。在

visitedChests是另一个网格,它需要与chestLocations完全相同,但是每个“subgrid”中都有一个额外的项来保存用户在胸部着陆的次数。在

我的问题是我不知道如何检测随机生成的posY和posX整数是否已经存在于chestLocations列表中。在

如何创建检测,以便如果它已经找到具有相同坐标的项,它将只“继续”再次运行整个while循环?在

感谢您阅读btw;)


Tags: in网格列表forvaluecounterrangeappend
2条回答

尝试:

index = 0
while posX in chestX[index:]:
    position = chestX[index:].index(posX)
    if posY == chestY[index + position]:
        #Can't be used.  (maybe say used = True)
        break
    index += position + 1

使用stdlib:

import random
from itertools import product

num_bandits = 5
num_chests = 10

all_locns = list(product(range(0,8), range(1,9)))
chest_locns = random.sample(all_locns, num_chests)

unused_locns = [loc for loc in all_locns if loc not in chest_locns]
bandit_locns = random.sample(unused_locns, num_bandits)

相关问题 更多 >

    热门问题