日期:2022年5月13日
介绍:1、这是一个简单的井字棋游戏;
2、玩家通过输入字符控制下棋的位置;
3、游戏具备判断输赢的功能;
4、游戏具备判断输入正确性的功能;
################################################################ 日期:2022年5月13日# 介绍:1、这是一个简单的井字棋游戏;# 2、玩家通过输入字符控制下棋的位置;# 3、游戏具备判断输赢的功能;# 4、游戏具备判断输入正确性的功能;###############################################################import sys# 创建一个字典,用来存储棋盘位置theBoard = {'topL': ' ', 'topM': ' ', 'topR': ' ','midL': ' ', 'midM': ' ', 'midR': ' ','lowL': ' ', 'lowM': ' ', 'lowR': ' '}def printBoard(board): # 生成一个空白的棋盘的函数print('=================')print(' ' + board['topL'] + ' | ' + board['topM'] + ' | ' + board['topR'] + ' ')print('-----+-----+-----')print(' ' + board['midL'] + ' | ' + board['midM'] + ' | ' + board['midR'] + ' ')print('-----+-----+-----')print(' ' + board['lowL'] + ' | ' + board['lowM'] + ' | ' + board['lowR'] + ' ')print('=================')def whoWins(whichSide): # 判断哪一方赢得了游戏的函数while True:if theBoard['topL'] == theBoard['topM'] and theBoard['topM'] == theBoard['topR'] and theBoard['topM'] == str(whichSide):breakif theBoard['midL'] == theBoard['midM'] and theBoard['midM'] == theBoard['midR'] and theBoard['midM'] == str(whichSide):breakif theBoard['lowL'] == theBoard['lowM'] and theBoard['lowM'] == theBoard['lowR'] and theBoard['lowM'] == str(whichSide):breakif theBoard['topL'] == theBoard['midL'] and theBoard['midL'] == theBoard['lowL'] and theBoard['midL'] == str(whichSide):breakif theBoard['topM'] == theBoard['midM'] and theBoard['midM'] == theBoard['lowM'] and theBoard['midM'] == str(whichSide):breakif theBoard['topR'] == theBoard['midR'] and theBoard['midR'] == theBoard['lowR'] and theBoard['midR'] == str(whichSide):breakif theBoard['topL'] == theBoard['midM'] and theBoard['midM'] == theBoard['lowR'] and theBoard['midM'] == str(whichSide):breakif theBoard['topR'] == theBoard['midM'] and theBoard['midM'] == theBoard['lowL'] and theBoard['midM'] == str(whichSide):breakelse:returnprint(str(whichSide) + ' 赢得了游戏!')return sys.exit()printBoard(theBoard)sideToPlay = 'X'gameTimes = 0boardLeft = ['topL', 'topM', 'topR', 'midL', 'midM', 'midR', 'lowL', 'lowM', 'lowR']while True:gameTimes += 1# 在屏幕上打印出游戏方print('现在轮到 ' + sideToPlay + ' 下棋')# 提示剩余的棋盘空格print('请输入以下步骤之一: ', end='')for i in range(len(boardLeft)):print(boardLeft[i], end=', ')print()# 判输入的步骤是否可选while True:position = input() # 输入棋子位置if position not in boardLeft:print('请输入正确的步骤!')else:boardLeft.remove(position) # 将棋子位置从可选项中删除breaktheBoard[position] = sideToPlayprintBoard(theBoard)# 判断此轮赛比是否有人获胜whoWins(sideToPlay)# 棋盘铺满仍无人获胜是,宣布平局if gameTimes == 9:print('游戏结束,平局!')break# 交换游戏双方if sideToPlay == 'X':sideToPlay = 'O'else:sideToPlay = 'X'
