如何实现字段并像国际象棋一样解决它们

时间:2017-12-02 19:57:16

标签: python algorithm field

我正在尝试实施一款名为Pah Tum的游戏。 (它与我的问题的工作方式无关。)我想在控制台中创建一个字段,如下所示:

  A  B  C  D
1 [] [] [] []
2 [] [] [] []
3 [] [] [] []
4 [] [] [] []

我已经想出了如何打印但是: 我想定义一个函数,我可以在其中处理特定字段并阻止它们,如下所示:B3

  A  B  C  D
1 [] [] [] []
2 [] [] [] []
3 [] [X][] []
4 [] [] [] []

不知怎的,我不知道如何在不使用数百行代码的情况下做到这一点,我会逐步打印出来。

1 个答案:

答案 0 :(得分:2)

您可以创建一个班级并使用__setitem__

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(4)
board[(2, 2)] = 'X'
print(board)

输出:

  a  b  c  d
a[] [] [] []
b[] [] [] []
c[] [] ['X'] []
d[] [] [] []