人生苦短 我用Python
项目案例
题目:
实现一个人机对战的恶小游戏–〉剪刀、石头、布
需求:
- 分析人物角色
- 玩家,玩家出拳:1==石头 2==剪刀 3==布
- 电脑,电脑角色出拳,random.randint(1,3)
- 程序处理
- 使用多重if判断玩家与电脑角色输赢情况
- 使用while无限循环实现多局对战
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import random
player_score=0 computer_score=0
print(''' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 欢迎试玩剪刀石头布 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''') player_name=input('请输入玩家姓名:') print('1.貂蝉 2.曹操 3.诸葛亮') choice=eval(input('请选择电脑角色:')) if choice==1: computer_name='貂蝉' elif choice==2: computer_name='曹操' elif choice==3: computer_name='诸葛亮' else: computer_name='佚名' print(player_name,'VS',computer_name) while True: player_fist=eval(input('------请出拳: 1.石头 2.剪刀 3.布------\n')) if player_fist==1: print(player_name,'出拳:石头') elif player_fist==2: print(player_name,'出拳:剪刀') elif player_fist==3: print(player_name,'出拳:布') else: print(player_name,'出拳:石头') player_fist==1 computer_fist=random.randint(1,3) if computer_fist==1: print(computer_name,'出拳:石头') elif computer_fist==2: print(computer_name,'出拳:剪刀') else: print(computer_name,'出拳:布') if player_fist==computer_fist: print('平局') elif (player_fist==1 and computer_fist==2) or (player_fist==2 and computer_fist==3) or (player_fist==3 and computer_fist==1): print(player_name,'获胜') player_score+=1 else: print(computer_name,'获胜') computer_score+=1 answer=input('再来一句吗?[y/n]') if answer!='y': break print('---------------') print('游戏结束') print(player_name,':',player_score) print(computer_name,':',computer_score) print('---------------') if player_score>computer_score: print(player_name,'大获全胜') elif player_score<computer_score: print(computer_name,'大获全胜') else: print('平局')
|