Python-检查二维数组中的多个项目

标签 python arrays

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

让我给你一些背景知识:

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

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

grid = []

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

因为我的游戏基于网格设计,这使我能够分隔各个行。

for i in range(8):
    grid.append([])

这使得主“网格”列表中有 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

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

GetValue() 函数仅返回 Y 和 X 坐标的网格项的值。

visitedChests 是另一个网格,它需要与 chestLocations 完全相同,但每个“子网格”中都有一个额外的项目来保存用户降落在箱子上的次数。

我的问题是我无法解决如何检测随机生成的 posY 和 posX 整数是否已存在于 chestLocations 列表中。

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

感谢您阅读顺便说一句;)

最佳答案

使用标准库:

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)

关于Python-检查二维数组中的多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35188820/

相关文章:

python - 将 readlines() 与索引一起使用或即时解析行?

python - 使用 Itertools 从多个列表中创建元素组合列表

java - 在控制台显示一定数量的元素后添加一行

javascript - 为什么拼接方法只删除 React 中的第一个数组索引?

python - SQLAlchemy 和 SQLite 中的非常长整数

python - Azure 上带有 Windows Docker 容器的 Django Web 应用程序 : Invalid HTTP_HOST header: '10.40.0.7:30015' . 您可能需要将 '10.40.0.7' 添加到 ALLOWED_HOSTS

python - Flask-Login 中使用的 "is_authenticated"方法有什么意义?

arrays - 如何使用函数初始化数组?

c++ - 扫描数字数组并计算范围 (0 - 24)(25 - 49) 等之间的数字的算法

C : Array of bytes which stores unsigned ints using 3 bytes