0

我正在使用 python 构建一个命令行游戏。这个游戏的一个主要特点是让用户输入 1 或 2 作为整数值。任何其他字符都必须被拒绝。我使用try-except&if-else condition来执行此操作,如下所示。我想知道是否有更好的方法可以通过一行或其他方式完成此操作,而无需缩进一大堆代码。

if __name__ == '__main__':
# INITIALIZE THE TOTAL STICKS , DEPTH OF THE TREE AND THE STARTINGG PLAYER
i_stickTotal = 11 # TOTAL NO OF STICKS IN THIS GAME
i_depth = 5 # THE DEPTH OF THE GOAL TREEE THE COMPUTER WILL BUILD
i_curPlayer = 1 # THIS WILL BE +1 FOR THE HUMAN AND -1 FOR THE COMPUTER
print("""There are 11 sticks in total.\nYou can choose 1 or 2 sticks in each turn.\n\tGood Luck!!""")
# GAME LOOP
while i_stickTotal > 0:
    print("\n{} sticks remain. How many would you pick?".format(i_stickTotal))
    try:
        i_choice = int(input("\n1 or 2: "))
        if  i_choice - 1 == 0 or i_choice - 2 == 0:            
            i_stickTotal -= int(i_choice)
            if WinCheck(i_stickTotal, i_curPlayer):
                i_curPlayer *= -1
                node = Node(i_depth, i_curPlayer, i_stickTotal)
                bestChoice = -100
                i_bestValue = -i_curPlayer * maxsize

                #   Determine No of Sticks to Remove

                for i in range(len(node.children)):
                    n_child = node.children[i]
                    #print("heres what it look like ", n_child.i_depth, "and",i_depth)
                    i_val = MinMax(n_child, i_depth-1, i_curPlayer)
                    if abs(i_curPlayer * maxsize - i_val) <= abs(i_curPlayer*maxsize-i_bestValue):
                        i_bestValue = i_val
                        bestChoice = i
                        #print("Best value was changed @ ", i_depth, " by " , -i_curPlayer, " branch ", i, " to ", i_bestValue)



                bestChoice += 1
                print("Computer chooses: " + str(bestChoice) + "\tbased on value: " + str(i_bestValue))
                i_stickTotal -= bestChoice
                WinCheck(i_stickTotal, i_curPlayer)
                i_curPlayer *= -1
            else:
                print("You can take only a maximum of two sticks.")

    except:
        print("Invalid input.Only Numeric Values are accepted")
4

2 回答 2

0

编写一个循环调用的函数input,直到值满足您的约束。也许叫它get_user_input。然后在你的 main 函数中调用它而不是input. 对于附加值,将 lambda 作为谓词传递给该函数以测试用户输入值 - 这将get_user_input更加通用。

于 2020-06-07T12:04:00.530 回答
0

您可以创建一个函数来检查用户输入并使用以下代码。

while True:
    var = int(input('Enter value (1 or 2) - '))
    if var not in range(1, 3):
        print('Invalid entry, please try again...')
        continue
    else:
        break
于 2020-06-07T12:19:29.137 回答