出现此错误。我不知道它是什么。我是初学程序员。
ConnectFourBoard.py“,第58行,在show_board_dynamic中 print(self .__ board [i] [j],end =“”),IndexError:列表索引超出范围
我的代码:
class ConnectFourBoard:
def __init__(self, cols = 7, rows = 6, requiredToWin = 4):
global __board
self.__space = ''
self.__board = []
self.cols = cols
self.rows = rows
self.Win = requiredToWin
self.__board = [[''] * rows for i in range(cols)]
for i in range(cols):
row = ['']*cols
self.__board.append(row)
def MakeMove(self, row, col, element):
global __board
self.__board[row][col] = element
def CheckForWin(self):
return winner
def CheckHz():
for x in range (6):
for y in range (7):
row += board[x][y]
print("%s" %row)
row = ""
if "XXXX" in row:
print("Winner is X")
break;
def CheckVt():
for y in range(7):
for x in range(6):
column += board[y][x]
print("%s" %column)
column = ""
if "XXXX" in column:
print ("Winner is X")
break;
def FullBoard(self):
return True
def FreeSpace(self, row, col):
return True
def show_board_dynamic(self):
print()
print("-------")
for i in range(len(self.__board)):
for j in range(len(self.__board)):
print("|", end = "")
print(self.__board[i][j], end = ""),
print("|")
print("-------")
print()
答案 0 :(得分:0)
对于行和列,您有不同的数字,但对于这两个数字,您只需要len(self.__board)
进行迭代。
变化:
for i in range(len(self.__board)):
for j in range(len(self.__board)):
print("|", end = "")
print(self.__board[i][j], end = ""),
print("|")
print("-------")
为:
for col in self.__board:
for val in col:
print("|", end = "")
print(val, end = ""),
print("|")
print("-------")
答案 1 :(得分:0)
你应该
有很多方法可以解决在整个程序中没有同步行和列的错误。
for i in range(len(self.__board)):
for j in range(len(self.__board[0])):
此行应固定于此。