使用python制作经典井字游戏,判断是否输入错误,和游戏结束。
演示:
#-*- coding:utf-8 -*-
well = {
"top-L": " ","top-M": " ","top-R": " ",
"mid-L": " ", "mid-M": " ", "mid-R": " ",
"low-L": " ", "low-M": " ", "low-R": " "
}
def wellPritn():
print(f'{well["top-L"]} | {well["top-M"] } | {well["top-R"]}\n'
f'{well["mid-L"]} + {well["mid-M"] } + {well["mid-R"]}\n'
f'{well["low-L"]} | {well["low-M"] } | {well["low-R"]}\n')
#判断是否胜利
def gameOver(p1,p2,p3):
if p1 != ' ' and p2 !=' ' and p3 !=' ':
if p1 == p2 ==p3:
#代表结束
return True
#制定赢得规则返回胜利者名称
def winner(who):
result1 = gameOver(well['top-L'],well['top-M'],well["top-R"])
result2 = gameOver(well['mid-L'],well['mid-M'],well["mid-R"])
result3 = gameOver(well['low-L'],well['low-M'],well["low-R"])
result4 = gameOver(well['top-L'],well['mid-L'],well['low-L'])
result5 = gameOver(well['top-M'],well['mid-M'],well['low-M'])
result6 = gameOver(well['top-R'], well['mid-R'], well['low-R'])
result7 = gameOver(well['top-L'], well['mid-M'], well['low-R'])
result8 = gameOver(well['top-R'], well['mid-M'], well['low-L'])
if result1 or result2 or result3 or result4 or result5 or result6 or result7 or result8:
return f"{who} win !"
if __name__ =='__main__':
wellPritn()
print(list(well.keys()))
sign = 'o'
count = 0
while count < 9:
# 判断是否输入正确
try:
position = input(f"现在是 {sign} 输入要下的位置(ex: top-M ) :")
well[position]
except:
print(f"输入错误,请输入:{list(well.keys())}")
continue
# 'o' 先开始
if well[position] == ' ':
well[position] = sign
count += 1
else:
print(f"{position} 已经下过了: {well[position]}")
continue
wellPritn()
# 判断是否有赢家
if winner(sign):
print(winner(sign))
break
if sign == 'o':
sign = 'x'
else:
sign = 'o'
print("游戏结束,平局!")