python井字棋人机交互
时间: 2023-11-17 16:03:51 浏览: 76
python实现井字棋游戏
以下是Pyth井字棋人机交互的实现方法:\n\```pyth\impor random\n\# 初始化棋盘\boar = [' '] * 9\n\# 画出棋盘\f draw_boar(boar):\ pri(boar[] + '|' + boar[1] + '|' + boar[2])\ pri('-+-+-')\ pri(boar[3] + '|' + boar[4] + '|' + boar[5])\ pri('-+-+-')\ pri(boar[6] + '|' + boar[7] + '|' + boar[8])\n\# 判断胜负\f check_wi(boar, player):\ if (boar[] == player boar[1] == player boar[2] == player) or \\\ (boar[3] == player boar[4] == player boar[5] == player) or \\\ (boar[6] == player boar[7] == player boar[8] == player) or \\\ (boar[] == player boar[3] == player boar[6] == player) or \\\ (boar[1] == player boar[4] == player boar[7] == player) or \\\ (boar[2] == player boar[5] == player boar[8] == player) or \\\ (boar[] == player boar[4] == player boar[8] == player) or \\\ (boar[2] == player boar[4] == player boar[6] == player):\ retur Tru\ els\ retur Fals\n\# 人机对战\f hum_vs_computer():\ # 随机决定谁先手\ if random.randi(, 1) == \ tur = 'mputer'\ els\ tur = 'hum'\n\ # 游戏开始\ whi Tru\ if tur == 'hum':\ # 人类玩家落子\ mov = inpu(\请输入你的落子位置(1-9) \")\ mov = i(mov) - 1\ if boar[mov] == ' '\ boar[mov] = 'X'\ tur = 'mputer'\ els\ pri(\该位置已经有棋子,请重新输入!\")\ continu\ els\ # 电脑玩家落子\ mov = random.randi(, 8)\ if boar[mov] == ' '\ boar[mov] = 'O'\ tur = 'hum'\ els\ continu\n\ # 画出当前棋盘\ draw_boar(boar)\n\ # 判断胜负\ if check_wi(boar, 'X'):\ pri(\恭喜你,你赢了!\")\ break\ elif check_wi(boar, 'O'):\ pri(\很遗憾,你输了!\")\ break\ elif ' ' i boar\ pri(\平局!\")\ break\n\# 主程序\whi Tru\ pri(\请选择游戏模式:\")\ pri(\1. 人机对战\")\ pri(\2. 退出游戏\")\ m = inpu(\请输入模式编号(1-2) \")\ if m == '1':\ boar = [' '] * 9\ hum_vs_computer()\ elif m == '2':\ break\ els\ pri(\输入有误,请重新输入!\")\n\```\n\
阅读全文