Python中的石头、布、剪刀(带大于和小于)

2024-10-03 02:45:48 发布

您现在位置: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))

这个游戏起作用了,然而,它认为石头打败了一切,纸打败了剪刀,剪刀却什么也没打。在

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


Tags: and代码游戏inputifpaperplayerprint
3条回答

创建一个选项字典,每个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)

一个纯粹的“数学”形式使用的运算符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"

如果您真的想使用<>,make classes,simple string将不符合您的需要。在

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)

编辑:或者最好只使用一个类

^{pr2}$

相关问题 更多 >