我想创建扫雷,所以制作此代码
def mines(m,n):
matrix = [[ '*' for m in range(10)] for n in range(10)]
for sublist in matrix:
s = str(sublist)
s = s.replace('[', '|').replace(']', '|').replace(',', "")
print(s)
并创建一个网格10x10,看起来像:
| * | * | * | * | * | * | * | * | * | * |
| * | * | * | * | * | * | * | * | * | * |
| * | * | * | * | * | * | * | * | * | * |
| * | * | * | * | * | * | * | * | * | * |
| * | * | * | * | * | * | * | * | * | * |
| * | * | * | * | * | * | * | * | * | * |
| * | * | * | * | * | * | * | * | * | * |
| * | * | * | * | * | * | * | * | * | * |
| * | * | * | * | * | * | * | * | * | * |
| * | * | * | * | * | * | * | * | * | * |
现在我想要随机定位一个' O'我知道我必须随机使用,但不知道如何添加
答案 0 :(得分:4)
我会这样做,使用random.sample
来获取唯一的坐标:
positions = random.sample(range(100), amount_you_want)
for coord in positions:
matrix[coord%10][coord//10] = 'O'
当然,import random
位于顶部。
答案 1 :(得分:1)
我会稍微重构你的代码,因为我认为你错过了学习OOP的巨大机会。
class Tile(object):
"""Tile defines an individual square of the board. This is an ABC, don't
instantiate it yourself but use Mine and Empty"""
shape = "!"
def __init__(self):
self.flagged = False
def __str__(self):
return "?" if self.flagged else self.shape
class Mine(Tile):
shape = "O"
class Empty(Tile):
shape = "."
class MineSweeperBoard(object):
def __init__(self, size, num_mines):
self.max_x, self.max_y = size
self.num_mines = num_mines
self.field = [[Empty() for y in range(self.max_y)] for x in range(self.max_x)]
self.generateMines()
def generateMines(self):
from random import randrange
for _ in range(self.num_mines):
while True:
x, y = randrange(self.max_x), randrange(self.max_y)
if not isinstance(self.field[y][x], Mine):
self.field[y][x] = Mine()
break
def run(self):
"""Runs the game of minesweeper"""
# implement your runnable code!
答案 2 :(得分:0)
这行代码:
matrix[random.randrange(10)][random.randrange(10)] = 'O' # genrates the bomb***
只运行一次,因此只生成一枚炸弹。要在x
和y-1
之间生成随机数量的炸弹,请将其包裹在for
循环中:
for _ in range(x, y):
matrix[random.randrange(10)][random.randrange(10)] = 'O' # generates the bomb
如果您需要特定数量的炸弹,请注意这可以创建重叠炸弹(同一坐标不止一次) - 如果这是一个问题,您可以切换到while
循环,直到生成正确的数字