Python - 石头剪刀布游戏

标签 python random input user-input

所以,我用 python 制作这个游戏。问题是,剪刀、布和石头可以有不同的组合,比如石头和布、石头和剪刀等等。那么我该如何在不执行大量 elif 语句的情况下做到这一点。

import random
random_choice = ["Scissors", "Paper", "Rock"][random.randint(0, 2)]

player_input = raw_input("What's your choice (Scissors, Paper, or Rock)")
if player_input not in ["Scissors", "Paper", "Rock"]:
      print("Not valid choice")
      raw_input()
      exit()

if player_input == random_choice:
      print("You both choose %s" % random_choice)
elif player_input == "Rock" and random_choice == "Scissors":
      print("You picked Rock and the bot picked Scissors, you win!")
      raw_input()
#And so on making heaps of elif's for all the combinations there can be.

那么我们如何制作这个游戏,而不必执行这么多 elif 语句或键入更少的代码。当然必须有一个更好的编程顺序来处理这些类型的事情?

最佳答案

如果你想避免elif树,你可以使用一个集合来存储所有获胜组合:

import random

# random.choice is a convenient method
possible_choices = ["Scissors", "Paper", "Rock"]
random_choice = random.choice(possible_choices)

# set notation, valid since Python 2.7+ and 3.1+ (thanks Nick T)
winning = {("Scissors", "Paper"), ("Paper", "Rock"), ("Rock", "Scissors")}

player_input = raw_input("What's your choice (Scissors, Paper, or Rock)")
if player_input not in possible_choices:
      print("Not valid choice.")
      raw_input()

if player_input == random_choice:
      print("You both choose %s" % random_choice)
elif (player_input, random_choice) in winning:
      print("You picked %s and the bot picked %s, you win!" % (player_input, random_choice))
else:
      print("You picked %s and the bot picked %s, you lose!" % (player_input, random_choice))

raw_input()

关于Python - 石头剪刀布游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26272627/

相关文章:

c# - switch 语句可以有多个变量吗?

python - 自更新 1.8.8 起,开发服务器上出现 Google Cloud Storage Client Library 400 错误

random - 通过将三角形分成更小的部分来对三角形进行均匀采样?

linux - 使用输入和多个管道循环 Linux 命令

python - 输入不工作Python

python - 结果后端中的 Celery + rabbitmq

python - 分析和查找 flask 应用程序的瓶颈——当前响应时间为 30 秒

python - 如何解释这种随机的 python 行为?

c++ - 如何随机化这些数字?

c# - C# 中的浮点型/ double 型输入验证