1

我正在开发一个程序,要求用户选择两个洞穴之一进入​​。用户可以选择洞穴 1 或洞穴 2。该数字与答案(由 random.randint (1,2) 生成)进行比较。如果用户的选择等于答案,则他获胜;否则,他就输了。问题是程序永远不会分支到获胜条件。无论用户做出什么选择,他总是输。我试过调试,但我看不到caveAnswer 和caveChoice 之间的变量比较值。

def gameCore (name):
    print ('You stand before the entrances of two caves.')
    print ('Choose a cave, either cave 1 or cave 2.')
    print ( )


    caveAnswer = random.randint (1,2)
    caveChoice = input ('Enter either 1 or 2. ')


    if caveAnswer == caveChoice:  [# I suspect the problem occurs at this comparison]
        print ('You enter the black mouth of the cave and...')
        time.sleep (1)
        print ( )
        print ('You find a hill of shining gold coins!')
        playAgain (name)

    else:
        print ('You enter the black mouth of the cave and...')
        time.sleep(1)
        print ( ) 
        print ('A wave of yellow-orange fire envelopes you. You\'re toast.')
        playAgain (name)

谢谢您的帮助。

4

4 回答 4

3
caveChoice = int(input ('Enter either 1 or 2. '))

您还应该这样做,以便如果它不是 int 时它会再试一次。

于 2013-01-12T00:25:56.093 回答
3

您应该将输入转换为 int:

caveChoice = int(input('Enter either 1 or 2. '))

但是,如果您不希望程序在输入 时崩溃'foo',那么您需要一个try-except块,它本身位于一个while循环中,因此您可以再试一次。

while True:
    try:
        caveChoice = int(input('Enter either 1 or 2. '))
        break
    except ValueError:
        print('Try again.')

此外,您可能想检查输入是否实际上是12

while True:
    try:
        caveChoice = int(input('Enter either 1 or 2. '))
        if caveChoice not in (1, 2):
            raise ValueError
        break
    except ValueError:
        print('Invalid input. Try again.')
于 2013-01-12T00:36:07.433 回答
0

我试过你的程序蚂蚁它肯定有效。要对其进行测试,只需caveAnswer在输入之前打印出来即可caveChoice。如果您有错误,则不在此功能中。

import random,time
def gameCore (name):
    print ('You stand before the entrances of two caves.')
    print ('Choose a cave, either cave 1 or cave 2.')
    print ( )


    caveAnswer = random.randint (1,2)
    print caveAnswer
    caveChoice = input ('Enter either 1 or 2. ')

    if caveAnswer == caveChoice:  
        print 'You enter the black mouth of the cave and - answer=%d - your answer=%d' % (caveAnswer, caveChoice)
        time.sleep (1)
        print ( )
        print 'You find a hill of shining gold coins!'
        # playAgain (name) 

    else:  
        print ('You enter the black mouth of the cave and - answer=%d - your answer=%d')% (caveAnswer, caveChoice)
        time.sleep(1)
        print ( ) 
        print ('A wave of yellow-orange fire envelopes you. You\'re toast.')
        # playAgain (name)

gameCore('Test')
于 2013-01-12T00:36:25.737 回答
-1

尝试转换为 int。

CaveChoice = input ('输入 1 或 2。')

于 2013-01-12T00:29:55.883 回答