Python中的岩石,纸张,剪刀(大于小于)

时间:2015-09-15 14:00:57

标签: python

有没有办法可以做一个大于和小于标志的石头剪刀游戏?

我知道有不同的方式来做RPS,但我想特别了解大于和小于。

这是我的代码:

"Rock" > "Scissors" and 'Rock' < 'Paper'
"Paper" > "Rock" and 'Scissors' < 'Rock' 
"Sissors" > "Paper" and 'Paper' < 'Scissors'
choose1 = input("Player One, Enter your answer ")
choose2 = input("Player Two, Enter your answer ")

if choose1 == "Paper":
    "Paper" > "Rock"
if choose1 == "Scissor":
    "Scissor" > "Rock"


if choose1 != "Rock" and choose1 != "Paper" and choose1 != "Scissors":
    print("Player one please chose Rock, Paper, or Scissors")

if choose2 != "Rock" and choose2 != "Paper" and choose2 != "Scissors":
    print("Player two please chose Rock, Paper, or Scissors")

if choose1 > choose2:
    print('Player1 ({}) beats ({})'.format (choose1, choose2))
else:
    print('Player2 ({}) beats ({})'.format (choose2, choose1))

游戏有效,然而,它看到摇滚乐打败了所有东西,纸张只打了剪刀,剪刀什么都没打。

如何修复此代码以使其正确执行?

3 个答案:

答案 0 :(得分:3)

如果你真的想使用<>,那么make class,简单的字符串将无法满足你的需求。

class Rock:
    def __gt__(self, other):
        return isinstance(other, Scissors)

class Paper:
    def __gt__(self, other):
        return isinstance(other, Rock)

class Scissors:
    def __gt__(self, other):
        return isinstance(other, Paper)


CHOICES = {
    "rock": Rock(),
    "paper": Paper(),
    "scissors": Scissors()
}

a = CHOICES["rock"]
b = CHOICES["scissors"]

print("player a wins:", a > b)

编辑:或者只有一个班级

可能更好
class RPS:
    table = {
        "rock": "scissors",
        "paper": "rock",
        "scissors": "paper"
    }

    def __init__(self, what):
        self.what = what
        self.winsover = self.table[what]

    def __eq__(self, other):
        return self.what == other.what

    def __gt__(self, other):
        return self.winsover == other.what


a = RPS("rock")
b = RPS("scissors")

print("player a wins:", a > b)

答案 1 :(得分:2)

创建一个选择词典,每个k / v对代表选择,以及该选项将在RPS游戏中“击败”的项目,然后你可以测试两个玩家的选择,如这样:

def rps():
    """
        choices defines the choice, and opposing choice which it will beat
    """
    choices = {'rock':'scissors', 'paper':'rock', 'scissors':'paper'}

    c1 = raw_input("Player One, Enter your answer ")
    c2 = raw_input("Player Two, Enter your answer ")

    if choices[c1] == c2:
        print 'player 1 wins, {} beats {}'.format(c1,c2)
    elif choices[c2] == c1:
        print 'player 2 wins, {} beats {}'.format(c2,c1)
    else:
        print 'both players choose {}'.format(c1)

答案 2 :(得分:1)

使用运算符lt和gt的纯粹“数学”形式,可以实现无需操作的操作。

#ask the choices and map to P=3,R=2,S=1, using a dictionary for instance
#any difference between options will work as long as simmetric 
#and the rest is adapted with the step different from one

result = abs(choose1 - choose2)
if not result:
    print "Tie"

if result == 1:
    #choose max
    if choose1 > choose2:
         print "Player 1 wins"
    else:
         print "Player 2 wins"
else: 
    #choose min:
    if choose1 < choose2:
         print "Player 1 wins"
    else:
         print "Player 2 wins"