我正在尝试用Python制作“石头,剪刀”游戏,我想将一个变量设置为大于另一个变量。
类似:
paper > rock
scissors > paper
rock > scissors
我该怎么办..?
答案 0 :(得分:5)
是的,就像丹尼尔说的那样,使用__cmp__
的覆盖,您可以实现:
class Comparable(object):
def __init__(self, below_class, above_class):
self.above_class = above_class
self.below_class = below_class
def __cmp__(self, other):
if isinstance(other, self.below_class):
return 1
if isinstance(other, self.above_class):
return -1
return 0
class Paper(Comparable):
pass
class Rock(Comparable):
pass
class Scissors(Comparable):
pass
scissors = Scissors(Paper, Rock)
paper = Paper(Rock, Scissors)
rock = Rock(Scissors, Paper)
# True
print paper > rock
print scissors > paper
print rock > scissors
# False
print paper < rock
print scissors < paper
print rock < scissors
有关此工作方式的文档,请参见:https://docs.python.org/2.6/reference/datamodel.html#object.cmp
答案 1 :(得分:3)
这实际上是一个有趣的问题,因为它提出了一些有用的想法。
例如,如果剪刀石头布遵循mathematical inequality的定律,那将是一个微不足道的问题。假设paper > rock > scissors
在数学上是 是真的(即paper > scissors
,与游戏规则相反):
class fist(object):
def __init__(self, weapon):
WEAPON_VALUES = {'paper': 2, 'rock': 1, 'scissors': 0}
self.weapon_value = WEAPON_VALUES[weapon]
def __gt__(self, other):
return self.weapon_value > other.weapon_value
def __lt__(self, other):
return self.weapon_value < other.weapon_value
def __eq__(self, other):
return self.weapon_value == other.weapon_value
def __ne__(self, other):
return self.weapon_value != other.weapon_value
paper = fist('paper')
rock = fist('rock')
scissors = fist('scissors')
现在我们可以检查:
In [7]: paper > rock
Out[7]: True
In [8]: rock == rock
Out[8]: True
In [9]: paper < scissors
Out[9]: False
In [10]: scissors < rock
Out[10]: True
不幸的是,剪刀石头布具有循环逻辑,因此不平等的通常概念在这种情况下不起作用(因此paper < scissors
的结果为False
)。
您可以使用自定义可比对象as explained in another answer,但请记住,这当然会引起rock > scissors > paper == True
之类的自相矛盾。
答案 2 :(得分:2)
在您的情况下,我建议您创建一个函数来返回赢家。像
def winner(J1, J2):
if J1 == 'rock':
if J2 == 'paper':
return('J2')
if J2 == 'rock':
return('draw')
if J2 == 'paper':
return('J1')
...
那将使您看到谁获胜。
答案 3 :(得分:1)
您可以通过在对象上定义>
方法来覆盖__gt__
运算符的行为。有关更多信息,请参见documentation on the Python data model。
答案 4 :(得分:1)
对于不涉及重新定义运算符的简单解决方案:
首先定义游戏规则:
rules = ['paper>rock', 'rock>scissors', 'scissors>paper']
并使用如下函数根据规则检查数据:
def greater(opt1, opt2):
if opt1 == opt2:
return None # draw
return "{0}>{1}".format(opt1, opt2) in rules
>>> greater('paper','rock')
True
>>> greater('paper','scissors')
False
>>> greater('rock','paper')
False