井字棋python代码注释
时间: 2023-12-12 11:36:07 浏览: 120
Python实现简易井字棋
以下是井字棋Python代码的注释:
```python
# Tic-Tac-Toe 井字棋游戏
# 全局常量
X = "X"
O = "O"
EMPTY = " "
# 询问是否继续
def ask_yes_no(question):
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
# 询问玩家下棋位置
def ask_number(question, low, high):
response = None
while response not in range(low, high):
response = int(input(question))
return response
# 询问玩家选择棋子
def pieces():
go_first = ask_yes_no("你想先手吗?(y/n): ")
if go_first == "y":
print("\n你先手!")
human = X
computer = O
else:
print("\n我先手!")
computer = X
human = O
return computer, human
# 新建棋盘
def new_board():
board = []
for square in range(9):
board.append(EMPTY)
return board
# 显示棋盘
def display_board(board):
print("\n\t", board[0], "|", board[1], "|", board[2])
print("\t", "---------")
print("\t", board[3], "|", board[4], "|", board[5])
print("\t", "---------")
print("\t", board[6], "|", board[7], "|", board[8], "\n")
# 判断胜者
def winner(board):
WAYS_TO_WIN = ((0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6))
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
winner = board[row[0]]
return winner
if EMPTY not in board:
return "Tie"
return None
# 询问玩家下棋位置
def human_move(board, human):
legal = legal_moves(board)
move = None
while move not in legal:
move = ask_number("你的下棋位置(0-8):", 0, 9)
if move not in legal:
print("\n这个位置已经被占了,请重新选择。\n")
print("好的...")
return move
# 计算AI下棋位置
def computer_move(board, computer, human):
# 复制一份棋盘,以免影响原棋盘
board = board[:]
# AI下棋位置的优先级
BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)
print("我选择了位置", end=" ")
# 如果AI能赢,就下在那个位置
for move in legal_moves(board):
board[move] = computer
if winner(board) == computer:
print(move)
return move
# 撤销这个位置的选择
board[move] = EMPTY
# 如果玩家能赢,就下在那个位置
for move in legal_moves(board):
board[move] = human
if winner(board) == human:
print(move)
return move
# 撤销这个位置的选择
board[move] = EMPTY
# 如果都不能赢,就下在最优先的位置
for move in BEST_MOVES:
if move in legal_moves(board):
print(move)
return move
# 获取合法的下棋位置
def legal_moves(board):
moves = []
for square in range(9):
if board[square] == EMPTY:
moves.append(square)
return moves
# 主函数
def main():
computer, human = pieces()
board = new_board()
display_board(board)
while not winner(board):
if computer == X:
move = computer_move(board, computer, human)
board[move] = computer
else:
move = human_move(board, human)
board[move] = human
display_board(board)
the_winner = winner(board)
if the_winner == "Tie":
print("平局!")
else:
print("胜利者是:", the_winner, "!")
if the_winner == computer:
print("我赢了!")
else:
print("你赢了!")
# 运行主函数
main()
```
阅读全文