NumPy数组:扫雷-替换随机物品

时间:2018-08-01 23:10:58

标签: arrays numpy random minesweeper

我正在尝试制作“扫雷”游戏。我有一个0的8 x 8数组。我想用值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])

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

1 个答案:

答案 0 :(得分:0)

使用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]])