Python井字棋游戏代码
时间: 2024-02-17 20:56:57 浏览: 124
python实现井字棋游戏
以下是Python井字棋游戏代码:
```python
def winner(board):
# 判断所给棋子是否获胜
_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 r in _to_win:
if board[r[0]] == board[r[1]] == board[r[2]]:
return True
return False
def dis_board(board):
# 显示出棋盘
print("\t{0} | {1} | {2}".format(board[0], board[1], board[2]))
print("\t_ | _ | _")
print("\t{0} | {1} | {2}".format(board[3], board[4], board[5]))
print("\t_ | _ | _")
print("\t{0} | {1} | {2}".format(board[6], board[7], board[8]))
def tic_tac_toe():
# 初始化棋盘
board = list("012345678")
# 初始化玩家
player = "X"
# 初始化步数
step = 0
# 游戏开始
while True:
# 显示棋盘
dis_board(board)
# 玩家输入位置
move = input("Player {0}, please enter a move (0-8): ".format(player))
# 判断输入是否合法
if move not in board:
print("Invalid move, please try again.")
continue
# 更新棋盘
board[int(move)] = player
# 判断是否获胜
if winner(board):
dis_board(board)
print("Player {0} wins!".format(player))
break
# 判断是否平局
step += 1
if step == 9:
dis_board(board)
print("It's a tie!")
break
# 切换玩家
player = "O" if player == "X" else "X"
tic_tac_toe()
```
阅读全文