Python - 剪刀石头布游戏

2 投票
2 回答
929 浏览
提问于 2025-04-26 12:24

我正在用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语句,或者说写更少的代码呢?肯定有更好的编程方式来处理这些情况吧?

暂无标签

2 个回答

1

我们可以做一个可能结果的映射表:

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

(注意,键必须是元组)。然后可以这样查找:

player_wins = a_beats_b[(player_input, random_choice)]

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

2

如果你想避免使用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()

撰写回答