简体   繁体   中英

Python - Scissors, paper and rock game

So, I'm making this game in python. The thing is, in scissors, paper and rock there can be different combinations like .. Rock and paper, Rock and scissors, and so on. So how would I make this without doing heaps of elif statements.

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.

So how do we make this game without having to do so many elif statements or type less code. Surely there has to be a better programming sequence for dealing with these types of things?

If you want to avoid the elif tree, you may use a set to store all the winning combinations:

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()

How about doing a map of possible results:

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

(Note that keys must be tuples). And then do a lookup with like this:

player_wins = a_beats_b[(player_input, random_choice)]

You'll need to handle the case of the same choices (as you already do).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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