我是python的初学者,我正在尝试创建一个简单的游戏。我正在努力创建一个函数,该函数需要接受零参数并返回包含随机放置的炸药的网格。
一般要求,获得地雷的机会应该为百分之十。
到目前为止,这是我的代码,但我一直在努力寻找从这里出发的去向。我也不太了解发出地雷要求的可能性,因为我认为必须有10个不同的盒子?如果有人可以帮助将我推向正确的方向,我将非常感激。
def mines():
gridSize = 3
createGrid = [[' ' for i in range(gridSize)] for i in range(gridSize)]
return createGrid
print(initMines())
所有这些答案都非常有帮助,谢谢! :)
答案 0 :(得分:0)
使用随机库,您可以使用randint获得十分之一的机会,并通过if语句实现
import random
GRIDSIZE = 3
CHANCE = 10
def mines():
createGrid = [[("x" if random.randint(0, CHANCE) == 0 else " ") for i in range(GRIDSIZE)] for i in range(GRIDSIZE)]
return createGrid
print(mines())
输出示例
[['x', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
编辑:我根据您的问题为网格大小和机会添加了全局常数,但是如果您是我,则将其作为参数传递。
答案 1 :(得分:0)
要获得1/10
的地雷机会,您可以使用类似(记住import random
)的方法:
opts = "M........."
[[random.choice(opts) for c in range(gridSize)] for r in range(gridSize)]
它只是从字符串中选择一个字符,碰巧有10%的机会获得地雷。
在完整的程序中使用它,并使其更具可配置性:
import random
def mines(gsz, pct):
# Silently enforce int 0-100, create choices, then choose.
pct = max(0, min(100, int(pct)))
opts = "M" * pct + ' ' * (100 - pct)
return [[random.choice(opts) for i in range(gsz)] for i in range(gsz)]
# Test harness. First, create a grid.
sz = 10
grid = mines(sz, 20)
# Then dump it for confirmation.
for line in grid: print(line)
mineCount = sum([cell == 'M' for row in grid for cell in row])
print('\nActual percentage was', 100 * mineCount / sz / sz)
显示它的作用:
[' ', ' ', 'M', ' ', ' ', ' ', 'M', ' ', ' ', ' ']
['M', ' ', ' ', ' ', 'M', ' ', ' ', ' ', ' ', ' ']
['M', ' ', ' ', ' ', 'M', 'M', ' ', ' ', ' ', ' ']
[' ', 'M', 'M', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
['M', ' ', ' ', ' ', ' ', 'M', ' ', ' ', ' ', ' ']
['M', ' ', ' ', ' ', ' ', ' ', 'M', 'M', ' ', ' ']
[' ', ' ', 'M', ' ', 'M', ' ', 'M', ' ', ' ', 'M']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', 'M', ' ', ' ', ' ']
Actual percentage was 19.0
答案 2 :(得分:0)
我对Python并不是最熟悉的,如果事情不能正常工作,请对不起,但是从事物的外观来看,您正在寻找一个2d数组,然后用空字符串“”或基于概率的地雷“ x”。
根据第一个答案here,虽然您可能必须使两个“ i”不同(假设它们表示数组中的“坐标”),但在初始化数组时通常处于正确的轨道上我建议x和y)
createGrid = [[' ' for x in range(gridSize)] for y in range(gridSize)]
然后,您需要填充数组,而我建议您这样做的方法是使用嵌套的for循环,如下所示:
for i in range(gridSize)
for j in range(gridSize)
createGrid[i][j] = //code for mine/empty
这将循环遍历数组中的所有值,然后根据其是否应包含地雷或为空来更新它们。
要确定是否应该是我的,最好的选择是导入random module,并使用randint函数或random函数,然后使用if语句确定是否为地雷。不应该是我的。 (如果if语句位于for循环内,则导入将在代码中的任何其他内容之前发生)
例如
import random
if random.randint(0, 10) <= 1
createGrid[i][j] = "x"
希望是有帮助的!
答案 3 :(得分:0)
如果您想要保证地雷的数量,可以执行以下操作:
import random
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
size = int(input('Enter length of row: '))
# By default 1/size of cells will be mines.
mines = (size**2)//size
# There is probably a better way to get user input, but this will do.
try:
mines = int(input('Enter number of mines [default=%s]: ' % mines))
except:
mines = (size**2)//size
# Make an one dimensional list of size square.
field_1d = [' ']*(size**2)
# Stick the mines into the list.
for m in range(mines):
field_1d[m] = '*'
# Randomly place the mines.
random.shuffle(field_1d)
# Make a 2D list out of the 1D list.
field = [r for r in chunks(field_1d,size)]
# Display it.
for row in field:
print(row)
以下是输出:
$ ./minesweeper.py
Enter length of row: 3
Enter number of mines [default=3]: 1
[' ', ' ', ' ']
[' ', '*', ' ']
[' ', ' ', ' ']
$ ./minesweeper.py
Enter length of row: 10
Enter number of mines [default=10]:
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', '*', ' ', ' ', '*', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', '*', ' ', ' ']
[' ', '*', '*', ' ', ' ', ' ', ' ', ' ', ' ', '*']
[' ', ' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
抱歉,我无法抗拒。我继续写了一个完整的扫雷游戏:
import random
class Cell():
def __init__(self,i,j,field):
self.i = i
self.j = j
self.exposed = False
self.field = field
self.value = self.calc_value()
def display(self):
if self.exposed:
return self.value
return '_'
def expose(self):
self.exposed = True
def calc_value(self):
i = self.i
j = self.j
f = self.field
if self.field[i][j] == '*':
return '*'
v=0
try:
if f[i-1][j-1] == '*':
v += 1
except:
pass
try:
if f[i-1][j] == '*':
v += 1
except:
pass
try:
if f[i-1][j+1] == '*':
v += 1
except:
pass
try:
if f[i][j-1] == '*':
v += 1
except:
pass
try:
if f[i][j+1] == '*':
v += 1
except:
pass
try:
if f[i+1][j-1] == '*':
v += 1
except:
pass
try:
if f[i+1][j] == '*':
v += 1
except:
pass
try:
if f[i+1][j+1] == '*':
v += 1
except:
pass
return str(v)
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
size = int(input('Enter size of field: '))
# 1/10th of cells will be mines.
mines = (size**2)//size
try:
mines = int(input('Enter number of mines [default=%s]: ' % mines))
except:
mines = (size**2)//size
# Make an one dimensional list of size square.
field_1d = [' ']*(size**2)
# Stick the mines into the list.
for m in range(mines):
field_1d[m] = '*'
# Randomly place the mines.
random.shuffle(field_1d)
# Make a 2D list out of the 1D list.
field = [r for r in chunks(field_1d,size)]
# Display it.
for row in field:
print(row)
board_1d = []
for i in range(size):
for j in range(size):
print(i,j)
board_1d.append(Cell(i,j,field))
board = [r for r in chunks(board_1d,size)]
def display(board):
for i in range(size):
for j in range(size):
print(board[i][j].display(), end='|')
print("")
def win(board):
unexposed = 0
for i in range(size):
for j in range(size):
if board[i][j].exposed == False:
unexposed += 1
if unexposed == mines:
print('WINNER!!!!')
return True
return False
gameover = False
while not gameover:
display(board)
I = int(input('Enter I: '))
J = int(input('Enter J: '))
c = board[I][J]
c.expose()
if c.value == '*':
print("BOOM!")
gameover = True
gameover = win(board)
display(board)