赞
踩
石头剪刀布的游戏规则:
1.玩家是输入,电脑是随机数
2.通过if语句进行判断
3.当输入字符串和浮点数时,报错。循环执行。
- import random
- class Game(object):
- def __init__(self, name, player, computer):
- self.name = name
- self.player = player
- self.computer = computer
-
- def Game(self):
- if (self.player == 1 and self.computer == 2) or (self.player == 2 and self.computer == 3) or (self.player == 3 and self.computer == 1):
- print(f"玩家{self.name}出{self.player},电脑出{self.computer}。玩家赢了。")
- elif self.player == self.computer:
- print(f"双方出的均是{self.player},平局。")
- elif (self.player == 3 and self.computer == 2) or (self.player == 1 and self.computer == 3) or (self.player == 2 and self.computer == 1):
- print(f"玩家“{self.name}”出{self.player},电脑出{self.computer}。玩家输了。")
- else:
- print("输入错误,只能输入1 2 3!")
-
- while True:
- try:
- name = input("请输入您的名字:")
- player1 = int(input("请输入对应的数字,1(石头)、2(剪刀)、3(布):"))
- computer1 = random.randint(1,3)
- PlayGame = Game(name, player1, computer1).Game()
- break
- except ValueError:
- print("输入错误,只能输入1 2 3!")
- print("-" *30)
- 运行结果:
-
- 请输入您的名字:王怕怕
- 请输入对应的数字,1(石头)、2(剪刀)、3(布):王怕怕
- 输入错误,只能输入1 2 3!
- ------------------------------
- 请输入您的名字:王怕怕
- 请输入对应的数字,1(石头)、2(剪刀)、3(布):2
- 双方出的均是2,平局。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。