有没有一种方法可以用大于号和小于号来做剪刀石头布游戏?
我知道执行 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))
游戏运行正常,但是,它认为石头打败一切,布只打剪刀,剪刀打不败任何东西。
如何修复此代码以使其正确执行?
请您参考如下方法:
如果你真的想用<和 > ,制作类,简单的字符串将不符合您的需求。
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)
