连接4个游戏纯粹为循环和列表分配



我正在构建一个Connect 4游戏,但任务要求我们使用游戏板的for循环和保持玩家移动的列表来构建它。我用for循环构建了如下的游戏板;

def drawBoard (field):
for column in range(7):
for row in range(15):
if row % 2 == 0:
if row != 14:
print("|", end="")
else:
print("|")
else:
print(field[column][row], end="")

然后是包含我作为Board构建的列表项的Board;

Board = [["0", " ", " ", " ", " ", " ", "X"],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", "0", "X", "X", " ", "X"],
[" ", " ", "X", "0", "0", " ", " "],
["0", " ", "X", "0", "0", " ", "0"]]
drawBoard(Board)

当我试图使用函数绘制董事会时,我的问题就出现了,例如

| | |a|Traceback (most recent call last):
File "C:UsersAdam StevePycharmProjectsmoshcoursepythontest2.py", line 34, in <module>
drawBoard(Board)
File "C:UsersAdam StevePycharmProjectsmoshcoursepythontest2.py", line 31, in drawBoard
print(field[column][row], end="")
IndexError: list index out of range

如何将列表中的项目显示到我使用该功能绘制的Board中??预期输出为,
|0||||X|
||

正如它出现在Board列表中,但现在使用该函数绘制。

正如kuro的评论中所述,您的board没有那么多条目,对于columnrange(7)有7个条目,但您只有6个,对于rowrange(15)有15个条目,而您只有7个,因此引发IndexError。同样,你最好把rowcolumn换成它们的真正含义。

我交换rowcolumn变量并执行一些小的更改(请参阅代码中的注释(:

def drawBoard(field):
# range(6) for 6 rows
for row in range(6):
for column in range(15):
if column % 2 == 0:
if column != 14:
print("|", end="")
else:
print("|")
else:
# divide the column value by 2, so all odd values can correctly match to 0-7
print(field[row][column//2], end="")

但我建议在这种情况下直接获取值,而不是通过索引:

def draw_board(field):
for row in field:
for column in row:
# print | before each column value
print("|" + column, end="")
# print | after reading all column values
print("|")

两个代码的输出相同:

|0| | | | | |X|
| | | | | | | |
| | | | | | | |
| | |0|X|X| |X|
| | |X|0|0| | |
|0| |X|0|0| |0|

最新更新