python人机对战井字棋
时间: 2024-01-04 20:20:47 浏览: 91
函数:Tic-Tac-Toe游戏-人机对战井字棋.rar_happygrl_python程序_tic tac toe_井字棋py
5星 · 资源好评率100%
以下是一个简单的Python人机对战井字棋的示例:
```python
import random
# 初始化棋盘
board = [' '] * 9
# 打印棋盘
def print_board():
print(board[0] + '|' + board[1] + '|' + board[2])
print('-')
print(board[3] + '|' + board[4] + '|' + board[5])
print('-')
print(board[6] + '|' + board[7] + '|' + board[8])
# 判断是否有玩家获胜
def check_win(player):
win_conditions = [
[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 condition in win_conditions:
if board[condition[0]] == board[condition[1]] == board[condition[2]] == player:
return True
return False
# 判断是否平局
def check_draw():
return ' ' not in board
# 玩家落子
def player_move():
while True:
move = input("请输入你的落子位置(1-9):")
if move.isdigit() and 1 <= int(move) <= 9 and board[int(move) - 1] == ' ':
board[int(move) - 1] = 'X'
break
else:
print("无效的落子位置,请重新输入!")
# 电脑落子
def computer_move():
available_moves = [i for i in range(9) if board[i] == ' ']
move = random.choice(available_moves)
board[move] = 'O'
# 游戏主循环
def game_loop():
print("欢迎来到人机对战井字棋游戏!")
print_board()
while True:
player_move()
print_board()
if check_win('X'):
print("恭喜你,你赢了!")
break
if check_draw():
print("平局!")
break
computer_move()
print_board()
if check_win('O'):
print("很遗憾,你输了!")
break
if check_draw():
print("平局!")
break
# 开始游戏
game_loop()
```
阅读全文