1

私は、ユーザーに2つの洞窟のうちの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-exceptwhile

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

また、入力が実際に1またはであるかどうかを確認することもできます2

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 に答える