arrays - 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?
解决方案
使用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]])
推荐阅读
- python - python中的嵌套三角形与乌龟
- vue.js - Nuxt 没有在刷新/ssr 上添加 bodyAttr
- unit-testing - 从 UnitTest 跳过课程 - Visual Studio 2019
- linux - 有没有办法在 ansible 的条件过滤器中使用 if..else 逻辑?
- android - 在颤振中使用飞镖从值通知器中删除侦听器
- r - 使用数据表来屏蔽/过滤 R 中的另一个数据表
- javascript - 更改 Google 地图中的图标标记颜色
- java - 在使用 jsoup 解析时摆脱 html 属性及其值
- php - 用 PHP 切片图像 src 字符串
- angular - 为什么在尝试将引导模板集成到 Angular 应用程序中时出现此错误?