gpt4 book ai didi

python - 检查 Tic Tac Toe 中的平局 [Python]

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:38 25 4
gpt4 key购买 nike

我有一个 Python 程序,可以在两个人类玩家之间玩井字游戏。如果玩家 A 或玩家 B 获胜,则会宣布获胜并且程序终止。但是,如果程序以平局结束,它将继续请求用户输入。

我不知道如何检查平局。它必须在 while 循环内还是需要它自己的单独函数?

import sys

## Define and create tic tac toe gameboard
board = range(0,9)

def show_board():
print board[0], '|', board[1], '|', board[2]
print '---------'
print board[3], '|', board[4], '|', board[5]
print '---------'
print board[6], '|', board[7], '|', board[8]

# Function used to check for winner
def line(char, box1, box2, box3):
if board[box1] == char and board[box2] == char and board[box3] == char:
return True

# Function used to automate process for checking every possible way to win
def all(char):
# Horizontal check
if line(char, 0, 1, 2):
return True
if line(char, 3, 4, 5):
return True
if line(char, 6, 7, 8):
return True
# Vertical check
if line(char, 0, 3, 6):
return True
if line(char, 1, 4, 7):
return True
if line(char, 2, 5, 8):
return True
# Diagnol check
if line(char, 0, 4, 8):
return True
if line(char, 2, 4, 6):
return True

show_board()

# Initial while loop will ask for player A input and show the board as well
# check conditions to see whether or not player A wins. If player A wins,
# the program will terminate so it does not ask for player B input after.
while True:
player_a = int(raw_input('Player A, please select a spot that is not taken \
(0-8): '))
# Checks for empty spot and places an 'X' if it exists, otherwise
# asks again.
if board[player_a] != 'X' and board[player_a] != 'O':
board[player_a] = 'X'
show_board()
# Check to see if Player A wins.
if all('X') == True:
print "Player A wins."
sys.exit()
break;

# While loop to ask for player B input and display the board as well as check
# the conditions as to whether or not player B wins. If player B wins, the
# program will terminate so it does not ask for player A input after.
while True:
player_b = int(raw_input('Player B, please select a spot that is \
not taken (0-8): '))
# Checks for empty spot and places an 'O' if it exists, otherwise
# asks again.
if board[player_b] != 'O' and board[player_b] != 'X':
board[player_b] = 'O'
# Check to see if Player B wins.
if all('O') == True:
show_board()
print "Player B wins."
sys.exit()
break;

break;

show_board()

最佳答案

无需详细查看代码,我可以告诉您,平局会在 9 回合后发生,并且只有当玩家 A 和 B 都没有在最后回合中获胜时才会发生。对于您的简单程序,我要做的是创建一个名为 ELAPSED_TURNS 或类似名称的全局变量,每次玩家输入角色时该变量都会递增,然后在检查两个玩家的获胜条件以及是否没有获胜后,检查 ELAPSED_TURNS。如果等于9,那么比赛一定是平局。

关于python - 检查 Tic Tac Toe 中的平局 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31757011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com