問題描述
為什麼我選擇第一個位置後立即收到勝利信息 (Why do i get the victory message right after choosing the first position)
我正在嘗試使用 python 在終端中製作井字遊戲,但我無法弄清楚為什麼在選擇第一個位置後我會收到勝利消息,其他人可以看到為什麼嗎?我做了一個 for 循環來檢查我是否在行或列中獲勝,並製作了 2 個 if 語句來檢查我是否在對角線上獲勝
import random
board = [[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']]
def checkwin(board):
for row in board:
if len(set(row)) == 1:
return True
elif board[0][0] == board[1][1] == board[2][2]:
return True
elif board[2][0] == board[1][1] == board[0][2]:
return True
else:
return False
def check_space_taken(board, number):
if not choose_position(board, number) == ' ':
return True
else:
return False
def choose_position(board, number):
if number <= 3:
board[0][number‑1] = 'X'
elif number <= 6:
board[1][number‑4] = 'X'
elif number <= 9:
board[2][number‑7] = 'X'
return board, number
def computer_position(board, computer_number):
computer_number = random.randint(0,9)
if computer_number <= 3:
board[0][computer_number‑1] = 'O'
elif computer_number <= 6:
board[1][computer_number‑4] = 'O'
elif computer_number <= 9:
board[2][computer_number‑7] = 'O'
return board, computer_number
Game_over = False
while not Game_over:
print(board)
player_input = int(input('move to: '))
changed_board = choose_position(board, player_input)
for line in changed_board:
print(line)
if checkwin(board):
print('\n‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑Congrats you won‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑\n')
Game_over = True
</code></pre>
參考解法
方法 1:
In principle, your logic isn't incorrect, but you need to account for empty spaces. You also forgot to check columns:
def checkwin(board):
for i in range(3):
if board[i][0] != " " and board[i][0] == board[i][1] == board[i][2]:
return True # found a winning row
if board[0][i] != " " and board[0][i] == board[1][i] == board[2][i]:
return True # found a winning column
# winning diagonals?
if board[1][1] != " " and board[0][0] == board[1][1] == board[2][2]:
return True
if board[1][1] != " " and board[2][0] == board[1][1] == board[0][2]:
return True
return False
(by user14900864、L3viathan)
參考文件