人机压指游戏Pthon代码
python代码实现人机压指游戏游戏规则:拇指赢食指,食指赢中指,中指赢无名指,无名指赢小指,小指赢拇指,不相邻手指平局。
游戏要求:计算机随机选择手指,用户键盘输入并控制游戏结束,赢一局得分+1,平局得分+0,输一局得分-1,统计输赢
欢迎大家进一步优化代码,谢谢!
# python代码实现人机压指游戏
# 游戏规则:拇指赢食指,食指赢中指,中指赢无名指,无名指赢小指,小指赢拇指,不相邻手指平局。
# 游戏要求:计算机随机选择手指,用户键盘输入并控制游戏结束,赢一局得分+1,平局得分+0,输一局得分-1,统计输赢
import random
def play_game():
# 定义一个字典,用来存储指针的名称
options = {1: "拇指", 2: "食指", 3: "中指", 4: "无名指", 5: "小指"}
# 定义一个字典,用来存储分数
scores = {"胜": 1, "平": 0, "负": -1}
# 定义用户分数
user_score = 0
# 定义电脑分数
computer_score = 0
# 定义计数器
count = 0
# 定义平局计数器
count_0 = 0
while True:
# 电脑随机出指针
computer_choice = random.randint(1, 5)
print(f"计算机出了{options}", computer_choice)# 人为作弊
# 用户出指针
user_choice = int(input("请选择手指(拇指:1,食指:2,中指:3,无名指:4,小指:5):"))
user_finger = options
computer_finger = options
# 判断用户和电脑出的指针是否满足条件
if (user_choice == 1 and computer_choice == 2) or \
(user_choice == 2 and computer_choice == 3) or \
(user_choice == 3 and computer_choice == 4) or \
(user_choice == 4 and computer_choice == 5) or \
(user_choice == 5 and computer_choice == 1):
# 满足条件,用户获胜
result = "胜"
user_score += 1
elif computer_choice - user_choice == -1 or computer_choice - user_choice == 4:
# 满足条件,电脑获胜
result = "负"
computer_score += 1
else:
# 不满足条件,平局
result = "平局"
user_score += 0
computer_score += 0
count_0 += 1
count += 1
print("你选择了:%s,计算机选择了:%s,结果:%s" % (user_finger, computer_finger, result))
# 判断是否继续游戏
continue_game = input("是否继续游戏?(Y/N)").upper()
if continue_game != "Y":
break
print("游戏结束")
print(f"总共玩了{count}局:")
print(f'平局次数:{count_0}')
print("你的得分:%d,计算机得分:%d" % (user_score, computer_score))
if user_score > computer_score:
print("恭喜:你赢了!!!")
elif user_score < computer_score:
print("抱歉:你输了!!!")
else:
print("平局!")
play_game()
欢迎大家指正
页:
[1]