Python 3命令行Minesweeper游戏,代码错误

时间:2018-11-18 20:50:16

标签: python-3.x minesweeper

大家好,我正在用python 3做一个简单的命令行版本的minesweeper游戏,我在代码上遇到了一些麻烦。

想法是用二维数组构建一个扫雷游戏,以表示炸弹随机放置的9x9网格。

这是我到目前为止所做的:

import random

#Function to create the 9x9 grid
def initialize():
    grid=9
    matrix=[[' ' for i in range(grid)] for i in range(grid)]
    return matrix

#Function to print the grid
def printMat( matrix ):
    print('     0   1    2    3    4    5    6    7    8')
    for i in range( 9 ):
        print(i,end=' ')
        for j in range( 9 ):
            print('[',matrix[i][j],']',sep = " ",end=' ')
        print('\n')

#Function to place the bombs
def place_bomb(bomb):
    bombs = 10
    while bombs != 0:
        bomb[random.randint(0,8)][random.randint(0,8)] = "*"
        bombs-=1
    return bomb

#Function to calculate the surrounding bombs 
def surrounding(grid, lin, col):
    size = len(grid)
    surrounding = []

    for i in range(-1, 2):
        for j in range(-1, 2):
            if i == 0 and j == 0:
                continue
            elif -1 < (lin + i) < size and -1 < (col + j) < size:
                surrounding+=lin + i, col + j
    return surrounding



#Function to verify if the player found a bomb and show the updated grid
#Not finished yet
def step(grid, lin, col):
    if grid[lin][col] == '* ':
        print("bomb")
        #return bomb=bomb-1

#Function to verify if the player found all the bombs
#If all the booms were found then return True else return False
#Not finished yet

def status():
   pass



def game():
    game_active=True
    grid=initialize()
    printMat(grid)
    while game_active==True:
        lin = int(input('Choose a line :'))
        col = int(input('Choose a column:'))
        c=place_bomb(grid)
        printMat(c)
        f=surrounding(c,lin,col)
        printMat(f)

game()

它从printMat函数返回错误:

Traceback (most recent call last):
   line 52, in <module>
    game()
   line 50, in game
    printMat(f)
   line 13, in printMat
    print('[',matrix[i][j],']',sep = " ",end=' ')
TypeError: 'int' object is not subscriptable

我该如何解决? 任何帮助或技巧来制作游戏将不胜感激

2 个答案:

答案 0 :(得分:0)

看看surrounding函数中发生了什么(我简化了一点):

>>> surrounding=[]
>>> surrounding += 2, 4
>>> surrounding
[2, 4]

因此,将元组添加到列表中不会将元组添加到列表中,而是会使用元组的元素扩展列表。这意味着该函数实际上返回一个平面列表,而不是列表列表(又称矩阵列表),因此,在调用printMat时,matrix[i]将是一个单独的 integer ,当然不能用matrix[i][j]进行索引。

您应该追加元组而不是添加元组:

surrounding.append((lin + i, col + j)) # not surrounding+=lin + i, col + j

答案 1 :(得分:0)

surrounding将返回一个列表(一维对象)。将其存储在f中,然后在其上调用一个函数,该函数除外矩阵(实际上是列表列表)。

因此,您将不能两次对该对象下标。这就是为什么您得到错误。

如果要使用相同的功能进行输出,则可以简单地将[f]而不是f传递给打印机功能。

相关问题