井字棋python代码
时间: 2023-12-19 18:32:26 浏览: 146
基于python纯函数实现井字棋游戏
以下是一个简单的井字棋游戏的Python代码示例:
```python
# Tic-Tac-Toe 井字棋游戏
# 全局常量
X = "X"
O = "O"
EMPTY = " "
# 初始化游戏棋盘
board = [EMPTY] * 9
# 打印游戏棋盘
def print_board(board):
print("--")
for i in range(3):
print("|", board[i*3], "|", board[i*3+1], "|", board[i*3+2], "|")
print("--")
# 询问是否继续
def ask_yes_no(question):
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
# 主游戏循环
def main():
print("Welcome to Tic-Tac-Toe!")
print_board(board)
while True:
# 玩家X下棋
move = int(input("Player X, enter your move (0-8): "))
board[move] = X
print_board(board)
# 判断是否获胜
if (board[0] == board[1] == board[2] == X) or \
(board[3] == board[4] == board[5] == X) or \
(board[6] == board[7] == board[8] == X) or \
(board[0] == board[3] == board[6] == X) or \
(board[1] == board[4] == board[7] == X) or \
(board[2] == board[5] == board[8] == X) or \
(board[0] == board[4] == board[8] == X) or \
(board[2] == board[4] == board[6] == X):
print("Player X wins!")
break
# 判断是否平局
if EMPTY not in board:
print("It's a tie!")
break
# 玩家O下棋
move = int(input("Player O, enter your move (0-8): "))
board[move] = O
print_board(board)
# 判断是否获胜
if (board[0] == board[1] == board[2] == O) or \
(board[3] == board[4] == board[5] == O) or \
(board[6] == board[7] == board[8] == O) or \
(board[0] == board[3] == board[6] == O) or \
(board[1] == board[4] == board[7] == O) or \
(board[2] == board[5] == board[8] == O) or \
(board[0] == board[4] == board[8] == O) or \
(board[2] == board[4] == board[6] == O):
print("Player O wins!")
break
# 运行游戏
main()
```
阅读全文