NumPy数组:扫雷-替换随机项目



我正试图制作一款"扫雷舰"游戏。我有一个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])

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

使用不带替换选项的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]])

最新更新