尝试为rps游戏进行输入验证

时间:2018-04-18 22:34:48

标签: python-3.x input

我正在使用python 3.6进行rps游戏,似乎无法弄清楚如何为我的双人游戏功能模块进行输入验证。每当我运行程序并选择两个玩家游戏并输入一个小于1或大于4的数字时,它只是询问我是否想再玩一次。

   def twoPlayerGame():
        player1 = False
        player2 = 0
        player1Win = 0
        player2Win = 0
        tie_ = 0

        #prompting for weapon choice
        while player1 == False:
            weaponMenu()
            player1 = int(input("Player 1, please make a selection.\t"))
            player2 = int(input("Player 2, please make a selection.\t"))

            while player1 or player2 not in range(1,4):
                print ("Invalid data entered, try again.")
                weaponMenu()
                player1 = int(input("Player 1, please make a selection.\t"))
                player2 = int(input("Player 2, please make a selection.\t"))

            #redirects to main
            while player1 == 4 or player2 == 4:
                main()

            if player1 == player2:
                print("It's a tie!\n")
                tie_ = tie_ + 1
            elif player1 == 1:
                if player2 == 2:
                    print("Paper covers rock! Player 2 won!\n")
                    player2Win = player2Win + 1
                else:
                    print("Rock smashes scissors! Player 1 won!\n")
                    player1Win = player1Win + 1
            elif player1 == 2:
                if player2 == 3:
                    print("Scissors cuts paper! Player 2 won!\n")
                    player2Win = player2Win + 1
                else:
                    print("Paper covers rock! Player 1 won!\n")
                    player1Win = player1Win + 1
            elif player1 == 3:
                if player2 == 1:
                    print("Rock smashes scissors! Player 2 won!\n")
                    player2Win = player2Win + 1
                else:
                    print("Scissors cuts paper! Player 2 won!\n")
                    p1ayer2Win = player2Win + 1


            #ask user if they want to play again
            again = input("Play again? Enter yes or no.\n")
            again = again.lower()
            #display scores
            print("Ties:\t", tie_)
            print("Player 1 wins:\t", player1Win)
            print("Player 2 wins:\t", player2Win)

            #if yes, player still playing
            #if no, redirect to main
            if again=="yes":
                player1 = False
            else:
                player1 = True
                main()

1 个答案:

答案 0 :(得分:0)

问题在于这一行:

 while player1 or player2 not in range(1,4):

无论你在or的每一方放置什么,通常应该是真值或假值。将player1置于左侧,虽然Python解释器可以接受,但这里不正确,因为您要做的是检查它是否在范围内。在右侧,player2 not in range(1,4)是实际的真/假值,所以没关系。

所以将左边的东西改为player1 not in range(1,4),功能正常:

while player1 not in range(1,4) or player2 not in range(1,4):