##! usr/bin/env python## -*- coding:utf-8 -*-#小游戏:石头、剪刀、布
importrandom#函数定义#打印目录
defprintDict(myDict):print('-'*40)for i,j inmyDict.items():print('{} : {}'.format(i,j))print('-'*40)#机器出拳:输入游戏目录,返回机器出拳结果
defcomputerPunch(gameDict):
myPunch= random.randint(1,3)returngameDict[myPunch]#玩家出拳:输入游戏目录,返回玩家出拳结果
defplayerPunch(gameDict):
printDict(gameDict)whileTrue:
myPunch= input('请出拳:\n>>>\t')try:
temp=int(myPunch)if int(temp) ingameDict.keys():returngameDict[temp]break
except:print('输入错误。')#出拳比较,返回‘平局’或者 '0':第一个玩家赢,'1'第二个玩家赢
defshowWinner(player1,player2,player1_Punch,player2_Punch):if player1_Punch ==player2_Punch:print('{}:{},\t{}:{}。\n>>>\t本局\'打平\'。'.format(player1, player1_Punch, player2, player2_Punch))elif (player1_Punch == '石头' and player2_Punch == '剪刀') or (player1_Punch == '剪刀' and player2_Punch == '布') or (player1_Punch == '布' and player2_Punch == '石头'):print('{}:{},\t{}:{}。\n>>>\t本局\'{}\'胜!!!'.format(player1, player1_Punch, player2, player2_Punch, player1))else:print('{}:{},\t{}:{}。\n>>>\t本局\'{}\'胜!!!'.format(player1, player1_Punch, player2, player2_Punch, player2))#---------------------------------------------------------------------------------
whileTrue:#开始游戏
gameDict = {1: '石头', 2: '剪刀', 3: '布'}#游戏说明
print('石头、剪刀、布'.center(40,'-'))print('单人游戏:1'.center(40))print('双人游戏:2'.center(40))print('-'*48)#--------------------------------------------------------------------------------#请选择是单人游戏还是双人游戏
gameChoice = input('请输入序号,选择游戏方式:\t')#-------------------------------------------------------------------------------
if gameChoice == '1': #单人游戏
print('人机对战开始:')whileTrue:#机器出拳
punch_computer =computerPunch(gameDict)#玩家出拳
punch_player =playerPunch(gameDict)#显示本局游戏结果
showWinner('电脑','玩家',punch_computer,punch_player)#继续游戏或退出
goOn = input('\n继续游戏:1,\t退出游戏:其它。\n>>>\t选择:\t')if goOn == '1':continue
else:print('人机对战游戏已退出。'.center(40,'-'))break
#---------------------------------------------------------------------------
elif gameChoice == '2': #双人游戏
print('双人大战开始:')whileTrue:#玩家1出拳
punch_player1 =playerPunch(gameDict)#玩家2出拳
punch_player2 =playerPunch(gameDict)#显示本局游戏结果
showWinner('玩家1','玩家2',punch_player1,punch_player2)#继续游戏或退出
goOn = input('\n继续游戏:1,\t退出游戏:其它。\n>>>\t选择:\t')if goOn == '1':continue
else:print('双人大战游戏已退出。'.center(40, '-'))break
#---------------------------------------------------------------------------
else: #输入有误,请重新选择
print('输入错误。\n')continue
#-------------------------------------------------------------------------------#游戏结束,退出
goOn = input('\n确认退出\'石头、剪刀、布\'游戏:1,\t\t继续\'石头、剪刀、布\'游戏:其它。\n>>>\t选择:\t')if goOn == '1':print('\'石头、剪刀、布\'游戏已经退出'.center(40, '-'))break
else:print('\'石头、剪刀、布\'游戏继续'.center(40, '-'))continue