繁体   English   中英

Python-剪刀,纸和摇滚游戏

[英]Python - Scissors, paper and rock game

所以,我正在用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()

如何绘制可能的结果图:

a_beats_b = {('Scissors', 'Paper'): True,
             ('Scissors', 'Rock'):  False,
             ...

(请注意,键必须是元组)。 然后使用以下命令进行查找:

player_wins = a_beats_b[(player_input, random_choice)]

您需要处理相同选择的情况(就像您已经做的那样)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM