更好地写石头剪刀(python)

时间:2018-04-03 12:59:00

标签: python python-3.x

嘿伙计我是 python 的新手,我已经制作了这个简单的石头剪刀游戏,但我想知道是否有更好的方法来编程这个没有超长的if if语句。

import random
options = ["scissors", "paper", "rock"]
i = random.randint(0, (len(options) - 1))
playedHand = input("PLay rock, paper or scissors please: ")
computerPlayedHand = options[i]

if playedHand == "rock" and computerPlayedHand == "scissors":
    print("the computer had scissors, you win")
elif playedHand == "rock" and computerPlayedHand == "paper":
    print("the computer had paper, you lose")
elif playedHand == "rock" and computerPlayedHand == "rock":
    print("the computer also had rock, its a tie")
elif playedHand == "paper" and computerPlayedHand == "rock":
    print("the computer had rock, you win")
elif playedHand == "paper" and computerPlayedHand == "scissors":
    print("the computer had scissors, you lose")
elif playedHand == "paper" and computerPlayedHand == "paper":
    print("the computer also had paper, its a tie")
elif playedHand == "scissors" and computerPlayedHand == "paper":
    print("the computer had paper, you win")
elif playedHand == "scissors" and computerPlayedHand == "scissors":
    print("the computer also had scissors, its a tie")
elif playedHand == "scissors" and computerPlayedHand == "rock":
    print("the computer had rock, you lose")
else:
    print("please only state rock, paper or scissors")

4 个答案:

答案 0 :(得分:1)

以下是我在一起尝试重用代码的方法。

关键部分是注意到options列表可以被视为一个选项总是胜过下一个选项的循环。您可以通过查找索引然后使用modulo使索引循环来检查这一点。

import random

options = ["scissors", "paper", "rock"]  # everything loses to the previous thing
comp_index = random.randint(0, (len(options) - 1))
playedHand = input("Play rock, paper or scissors please: ")
computerPlayedHand = options[comp_index]

try:
    player_index = options.index(playedHand)
except ValueError:
    print("please only state rock, paper or scissors")
else:
    if player_index == comp_index:
        res = "the computer also had {}, its a tie"
    # the key part
    elif (player_index - comp_index) % 3 == 1:
        res = "the computer had {}, you lose"
    else:
        res = "the computer had {}, you win"
    print(res.format(computerPlayedHand))

答案 1 :(得分:1)

使用字典来表示可以显着缩短代码的手拍。但是既然我们在那里,那就让我们用面向对象的解决方案做到更加简洁。

import random

class Hand:

    _ordering = {
        'rock': 'scissor',
        'scissor': 'paper',
        'paper': 'rock'
    }

    def __init__(self, kind):
        if kind in self._ordering:
            self.kind = kind
        else:
            raise ValueError(
                "It's rock, paper, scissor... Not rock, {}, scissor.".format(kind)
            )

    @classmethod
    def random_hand(cls):
        return cls(random.choice(list(cls._ordering)))

    def beats(self, other):
        return self._ordering[self.kind] == other.kind

playedHand = Hand(input("Play rock, paper or scissors please: "))

computerPlayedHand = Hand.random_hand()

if playedHand.beats(computerPlayedHand):
    print('You won! The computer had {}.'.format(computerPlayedHand.kind))
elif computerPlayedHand.beats(playedHand):
    print('You lost... The computer had {}.'.format(computerPlayedHand.kind))
else:
    print("It's a tie.")

答案 2 :(得分:0)

你不需要使用任何" if"除典型错误管理之外的语句。请看以下示例:

import random

def play():
    table = [[2, 0, 1],
             [1, 2, 0],
             [0, 1, 2]]

    options = ["Rock", "Paper", "Scissors"]
    results = ["Defeat", "Win", "Tie"]
    conv    = {"R": 0 , "P": 1, "S": 2}

    while True:
        i = random.randint(0, (len(options) - 1))
        p = input("Play rock, Paper or Scissors please (R, P, S): ")
        if p not in conv.keys():
            print("Unavailable option. Left the Game.")
            return
        print("Computer played %s. You have a %s"%(options[i], results[table[conv[p]][i]]))

play()

如果您有这样的表:

#          Rock Paper Scissor
# Rock       2    0      1
# Paper      1    2      0
# Scissor    0    1      2

...您可以让用户在行中播放,而计算机则在列中播放。结果将直接通过表中的数字索引。因此,在示例中玩游戏将如下所示:

enter image description here

答案 3 :(得分:0)

这是另一个可能的版本:

import random

try:
    options = [('rock', 'scissors'), ('paper', 'rock'), ('scissors', 'paper')]
    human_choice = int(input("Play rock(0), paper(1) or scissors(2) please: "))
    human_hand = options[human_choice]
    computer_hand = options[random.randint(0, (len(options) - 1))]
    text = "the computer {} {}, {}"

    if human_hand[0] == computer_hand[0]:
        print(text.format("also had", computer_hand[0], "it's a tie"))
    elif human_hand[1] == computer_hand[0]:
        print(text.format("had", computer_hand[0], "you win"))
    else:
        print(text.format("had", computer_hand[0], "you lose"))
except Exception as e:
    print("please only state rock, paper or scissors")