Python: 如何获取我们game-field中单元格的内容?

Python: How to retrieve the content of a cell in our game-field?

我和我的搭档,我们需要在 python 中创建一个游戏。我们完全是初学者,如果我们问的问题对 Python-Pro 来说可能听起来很轻率,我们深表歉意。

这是我们创建一个范围为 7x7 的字段的代码:

import string 

class board:
   def __init__(self, width):
      self.w = width
      self.board = [[[] for i in range(width)] for b in range(width)]

   def __setitem__(self, coords, val):
      self.board[coords[0]][coords[-1]] = [val]

   def __repr__(self):
      return ' '+'  '.join(list(string.ascii_lowercase[:self.w]))+"\n"+'\n'.join(string.ascii_lowercase[a]+' '.join(str(i) for i in b) for a, b in enumerate(self.board))  

board = board(7)   
board[(3, 3)] = 'X'

直到现在,它仍然有效(不完美,但足以继续使用)。

我现在有几个问题。如果你不介意,你可以只回答其中一个。我们将不胜感激。

  1. 列和行的标题都是字母(a-g),如何将它们转换成数字?

  2. 获取特定'cell'的内容需要做什么?例如。如果 3,3 中的单元格包含内容 'X',我如何只获取 'X'?

非常感谢你们!

要获取该项目,您必须为您的情况定义 __getitem__ 方法:

class board:
    def __init__(self, width):
        self.w = width
        self.board = [[[] for i in range(width)] for b in range(width)]

    def __setitem__(self, coords, val):
        self.board[coords[0]][coords[-1]] = [val]

    def __getitem__(self, item):
        row, col = item
        return self.board[row][col]

    def __repr__(self):
        return ' ' + '  '.join(list(map(str, range(self.w)))) + "\n" + '\n'.join(str(a) + ' '.join(str(i) for i in b) for a, b in enumerate(self.board))


board = board(7)
board[(3, 3)] = 'X'

print(board[(3, 3)])
# ['X']

print('{board!r}'.format(board=board)

你得到的板看起来像:

 0  1  2  3  4  5  6
0[] [] [] [] [] [] []
1[] [] [] [] [] [] []
2[] [] [] [] [] [] []
3[] [] [] ['X'] [] [] []
4[] [] [] [] [] [] []
5[] [] [] [] [] [] []
6[] [] [] [] [] [] []

顺便说一句,为什么要将值定义为 __setitem__ 中的列表?我还更改了 __repr__ 的代码,使其代表数字而不是字母。实际上你应该使用 __str__ 方法而不是 __repr__ 来做到这一点。

首先,使用函数ord():

ord('a') # => 97
ord('g') # => 103
ord("letter of column/row") - ord('a') # will return index of column/row
ord('g') - ord('a') # this will return 6