首页 > 解决方案 > NumPy Array: Minesweeper - 替换随机项

问题描述

我正在尝试制作“扫雷”游戏。我有一个 8 x 8 的 0 数组。我想用值 1 替换数组中的 8 个随机 0(代表“地雷”)。我不知道从哪里开始。这是我的代码:

import numpy as np
import sys
import random

a = np.array([(0, 0, 0, 0, 0, 0, 0, 0),
             (0, 0, 0, 0, 0, 0, 0, 0),
             (0, 0, 0, 0, 0, 0, 0, 0),
             (0, 0, 0, 0, 0, 0, 0, 0),
             (0, 0, 0, 0, 0, 0, 0, 0),
             (0, 0, 0, 0, 0, 0, 0, 0),
             (0, 0, 0, 0, 0, 0, 0, 0),
             (0, 0, 0, 0, 0, 0, 0, 0)])

for random.item in a:
    item.replace(1)
    print(a)

row = int(input("row "))
column = int(input("column "))

print(a[row - 1, column - 1])

如何用 1 替换数组中的 8 个随机 0?

标签: arraysnumpyrandomminesweeper

解决方案


使用np.random.choice无替换选项 -

In [3]: a # input array of all zeros
Out[3]: 
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]])

# Generate unique flattened indices and on a flattened view of
# input array assign those as 1s
In [8]: a.flat[np.random.choice(a.size,8,replace=False)] = 1

# Verify results
In [9]: a
Out[9]: 
array([[0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0],
       [0, 1, 1, 0, 1, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]])

推荐阅读