python人机猜拳游戏代码,适合初学者增加兴趣
【开发该软件的操作系统】:windows10
【软件开发环境/开发工具】:PyCharm 2020.3.3 X64
【解释器版本】:Python 3.9.7
【编程语言】:Python
【开发目的】: 供初学者参考学习
【开发者】:20届牛马毕业生_迪焱
import random #导入random随机函数
# 定义全局参数
count_pj = 0 #平局局数
count_playerwin = 0 #玩家胜利局数
count_comwin = 0 #电脑胜利局数
def Game(): #游戏内容
try:
player = eval(input('请输入您要出的手势(⽯头(1)/剪⼑(2)/布(3)):')) #玩家选择要出的数字
computer = random.randint(1, 3) #随机数获取电脑输出的数字
dic1 = {1: "石头", 2: "剪刀", 3: "布"} #将玩家与电脑获得的数字进行转化
if player == computer: #平局条件
print("玩家手势({}) vs ({})电脑手势".format(dic1[player], dic1[computer]))
print("平局了")
global count_pj #引用全局参数,记录平局次数
count_pj += 1
elif (player == 1 and computer == 2) or \
(player == 2 and computer == 3) or \
(player == 3 and computer == 1): #玩家胜利条件
print("玩家手势({}) vs ({})电脑手势".format(dic1[player], dic1[computer]))
print("玩家胜利")
global count_playerwin #引用全局参数,记录玩家胜利次数
count_playerwin += 1
else: #电脑胜利条件
print("玩家手势({}) vs ({})电脑手势".format(dic1[player], dic1[computer]))
print("电脑胜利了")
global count_comwin #引用全局参数,记录电脑胜利次数
count_comwin += 1
print("-" * 60) #每局游戏结束时分隔线
except: #异常处理重新运行函数 Game()
print("错误,请重新输入") #输入数据异常提醒
Game()
i = 1 #定义全局参数,判断游戏是否进行
count = 0 #记录游戏进行总局数
def game_times(): #游戏进行局数
num = eval(input("是否进行猜拳游戏[是(1),否(0)]:"))
if num == 0: #游戏进行条件
global count
count += 1
print("第{}局游戏".format(count).center(61, '-'))
elif num == 1: #游戏结束条件
print("游戏结束".center(50, '-'))
global i
i = 0
else: #输入数据异常,重新运行game_times函数
print("输入错误,请重新输入!!!")
game_times()
while i >= 1: #while循环,满足条件游戏可以无限进行
game_times() #调用game_times函数,显示游戏进行局数
if i == 0: #判断游戏是否进行
break #跳出while循环,结束游戏
else: #游戏继续进行条件
Game() #调用Game()函数,进行游戏
print("一共进行了{}局游戏。".format(count)) #打印游戏进行总局数
print("其中平局{}局,玩家赢{}局,电脑赢{}局。".format(count_pj, count_playerwin, count_comwin)) #打印平局,玩家胜利,电脑胜利局数
print("玩家的胜率为{:.2%}".format(count_playerwin / (count_pj + count_comwin + count_playerwin))) #打印玩家胜率