python实现猜拳小游戏

简单版

import random
player = int(input('请猜拳: 0剪刀,1石头,2布'))
computer = random.randint(0,2)
print('计算机出拳',computer)
if (player == 0 and computer==2) or (player==1 and computer==0) or (player==2 and computer==1):
    print('你赢了!')
elif player==computer:
    print('平局!')
else:
    print('你输了!')

改进版

import random
player = input('请出拳:石头,剪刀,布\n')
computer=random.choice(['石头','剪刀','布'])
print('你出拳:',player,'计算机出拳:',computer)
if player==computer:
    print('平局!')
elif player == '石头':
    if computer == '剪刀':
        print('你赢了!')
    else:
        print('你输了!')
elif player == '剪刀':
    if computer == '布':
        print('你赢了!')
    else:
        print('你输了!')
else:
    if computer == '石头':
        print('你赢了!')
    else:
        print('你输了!')

精简版

import random
all_choice = ['石头','剪刀','布']
you_win = [['石头','剪刀'],['剪刀','布'],['布','石头']]
prompt='''
(0)石头
(1)剪刀
(2)布
请出拳(0/1/2):
'''
computer = random.choice(all_choice)
ind  =int(input(prompt))
player = all_choice[ind]
print('您出拳: %s,计算机出拳:%s'% (player,computer))
if player == computer:
    print('平局!')
elif [player,computer] in you_win:
    print('你赢了!')
else:
    print('你输了!')

三局两胜制版

三局两胜制,直到分出胜负,平局局数增加

import random
# 三局两胜制,平局局数增加
all_choice = ['石头','剪刀','布']
you_win = [['石头','剪刀'],['剪刀','布'],['布','石头']]
prompt='''
(0)石头
(1)剪刀
(2)布
请出拳(0/1/2):
'''
i=1      #第几局
avg = 0  #平局次数
cwin = 0 #计算机胜利的次数
pwin = 0 #玩家胜利的次数
while cwin <2 and pwin <2:
    computer = random.choice(all_choice)
    player = input(prompt)
    print('您出拳: %s,计算机出拳:%s'% (player,computer))
    if computer == player:
        print('第%s局,平局'%i)
        avg +=1
    elif [player,computer] in you_win:
        print('第%s局,你赢了!'%i)
        pwin+=1
    else:
        print('第%s局,计算机赢了'%i)
        cwin+=1
    i+=1
print('计算机赢了%s局,你赢了%s局'%(cwin,pwin))
if pwin > cwin:
    print('最终结果:你赢了!')
else:
    print('最终结果: 你输了!')

你可能感兴趣的:(python实现猜拳小游戏)