日期: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):
break
if theBoard['midL'] == theBoard['midM'] and theBoard['midM'] == theBoard['midR'] and theBoard['midM'] == str(whichSide):
break
if theBoard['lowL'] == theBoard['lowM'] and theBoard['lowM'] == theBoard['lowR'] and theBoard['lowM'] == str(whichSide):
break
if theBoard['topL'] == theBoard['midL'] and theBoard['midL'] == theBoard['lowL'] and theBoard['midL'] == str(whichSide):
break
if theBoard['topM'] == theBoard['midM'] and theBoard['midM'] == theBoard['lowM'] and theBoard['midM'] == str(whichSide):
break
if theBoard['topR'] == theBoard['midR'] and theBoard['midR'] == theBoard['lowR'] and theBoard['midR'] == str(whichSide):
break
if theBoard['topL'] == theBoard['midM'] and theBoard['midM'] == theBoard['lowR'] and theBoard['midM'] == str(whichSide):
break
if theBoard['topR'] == theBoard['midM'] and theBoard['midM'] == theBoard['lowL'] and theBoard['midM'] == str(whichSide):
break
else:
return
print(str(whichSide) + ' 赢得了游戏!')
return sys.exit()
printBoard(theBoard)
sideToPlay = 'X'
gameTimes = 0
boardLeft = ['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) # 将棋子位置从可选项中删除
break
theBoard[position] = sideToPlay
printBoard(theBoard)
# 判断此轮赛比是否有人获胜
whoWins(sideToPlay)
# 棋盘铺满仍无人获胜是,宣布平局
if gameTimes == 9:
print('游戏结束,平局!')
break
# 交换游戏双方
if sideToPlay == 'X':
sideToPlay = 'O'
else:
sideToPlay = 'X'