我正在嘗試構建 4 排游戲,所以當我嘗試讓玩家有相同的選擇時,它會出現此錯誤
串列索引超出范圍
這是在此處輸入影像描述的示例
似乎是獲勝條件的問題,但我不明白為什么會發生這種情況,當輸入正確時它會給出正確的答案,比如讓一個玩家獲勝,但是當他們有相同的選擇時,它就會中斷。
代碼是
Width = 4
Height = 4
game_board = []
for x in range(Width): game_board.append(list(['a'] * Height))
def make_move(board, borad_row, board_col, piece):
board[borad_row][board_col] = piece
# check if the slot is empty
def is_slot_empty(board, board_col):
return board[Width - 1][board_col] == 'a'
# get the next available
def next_available_slot(board, board_col):
for i in range(Width):
if board[i][board_col] == 'a':
return i
# method for winning conditions
def winning(board, piece):
# check horizontally
for i in range(Height):
for j in range(Width):
if board[j][i] == piece and board[j][i 1] == piece and board[j][i 2] == piece and board[j][
i 3] == piece:
return True
# check vertically
for i in range(Height):
for j in range(Width):
if board[j][i] == piece and board[j 1][i] == piece and board[j 2][i] == piece and board[j 3][
i] == piece:
return True
# positive diagonal
for i in range(Height):
for j in range(Width):
if board[j][i] == piece and board[j 1][i 1] == piece and board[j 2][i 2] == piece and board[j 3][
i 3] == piece:
return True
# negative diagonal
for i in range(Height):
for j in range(Width):
if board[j][i] == piece and board[j - 1][i 1] == piece and board[j - 2][i 2] == piece and board[j - 3][
i 3] == piece:
return True
game_end = False
turn_1 = 0
while not game_end:
if turn_1 == 0:
user_input = int(input("player_1:"))
if is_slot_empty(game_board, user_input):
user_input_row = next_available_slot(game_board, user_input)
make_move(game_board, user_input_row, user_input, 'X')
if winning(game_board, 'X'):
print("player 1 wins")
game_end = True
else:
user_input: int = int(input("player_2:"))
if is_slot_empty(game_board, user_input):
user_input_row = next_available_slot(game_board, user_input)
make_move(game_board, user_input_row, user_input, 'Z')
if winning(game_board, 'Z'):
print("player_2 wins")
game_end = True
for row in reversed(game_board):
print(row)
# alternating between 2 users
turn_1 = 1
turn_1 = turn_1 % 2
uj5u.com熱心網友回復:
要修復winning(),請嘗試以下操作:
def winning(board, piece):
# check horizontally
for i in range(Height):
if all(board[j][i] == piece for j in range(Width)):
return True
# check vertically
for j in range(Width):
if all(board[j][i] == piece for i in range(Height)):
return True
# positive diagonal
if all(board[i][i] == piece for i in range(Width)):
return True
# negative diagonal
if all(board[i][-(i 1)] == piece for i in range(Width)):
return True
這僅設計用于處理 和 具有相等值的電路Height板Width。
uj5u.com熱心網友回復:
當您進行檢查時,請確保僅檢查板內的索引。
例如,對于水平檢查,左端(i)和右端(i 3)都需要在0..Width-1范圍內。因此,您應該限制i索引的值,使其i 3仍小于Width:
...
# check horizontally
for i in range(Width - 3):
for j in range(Height):
if board[j][i] == piece and board[j][i 1] == piece and board[j][i 2] == piece and board[j][i 3] == piece:
return True
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/432184.html
標籤:Python python-3.x
