扫雷游戏板在

Minesweeper game board in

我必须创建一个为扫雷游戏创建游戏板的函数(我对编码也很陌生)。

我打算让董事会最初开始时每个 space 都被覆盖并且没有我的,由字符串 "C " 表示。

然后我需要将地雷分配给我的 2D 列表中的随机 space,将 "C " 的实例替换为 "C*"

# create board function
def createBoard (rows, cols, mines):

    board = []
    #set the range to the number of rows and columns provided +1
    #for every row, create a row and a column
    for r in range (0,rows+1):
        board.append([])
        for c in range (0,cols+1):
            board[r].append("C ")

    #set # of mines to 0

    num_mines=0

    while num_mines < mines :
        x = random.choice(board)
        y = random.choice(x)
        if y == "C ":
            x[y]= "C*"


            num_mines = num_mines+1

我的问题是我不知道如何实际替换字符串。

当您随机选择一个项目时,您最终会得到一个对它的引用。因为你得到一个字符串,所以你有一个对字符串的引用。当你想改变它时......你不能这样做,因为字符串是不可变的。不是获取对字符串的引用,而是获取其在 list 中的位置的引用。然后您可以替换该元素。

x = random.choice(board)
y = random.randint(0, len(x)-1)
if x[y] == "C ":
    x[y] = "C*"

不使用 random.choice,而是使用 random.randint 在两个参数之间选择一个随机整数(包括在内,因此我们必须从该子列表的长度中减去 1)。它用作该子列表的索引,以便我们可以更改相应的元素。

首先请注意,您的看板有一个额外的列和行。 (只需使用 range(rows)range(cols)

然后随机选择'coordinates':

    x = random.randrange(rows)
    y = random.randrange(cols)

然后顺其自然:

    if board[x][y] == "C ":
        board[x][y] = "C*"