現時点では、Python のオンライン コースを受講していますが、約 1/3 しか進んでおらず、これまでに学んだことを使って何かを作ってみることにしました。ただし、現在エラーが発生しています。家でテキストベースのアドベンチャーゲームを作成しています。各部屋は独立した機能です。元:
def hallway():
hallway_direction = raw_input('blahblah')
if hallway_direction == 'n':
living_room()
入るのにトーチが必要な部屋が1つありますが。部屋の値を保持するために辞書を使用しました。これが私が持っているものです。
global rooms
rooms = {}
rooms['first_room'] = {'note' : False}
rooms['old_door'] = {'boots' : False}
rooms['first_again'] = {'torch' : False}
rooms['first_again'] = {'seen' : False}
別の部屋ではたいまつをtrueに設定しますが、私が抱えている問題は、あなたがたいまつを持っていない場合、あなたをホールに戻すために必要だということです
def fancy_door():
raw_input('You open the door, the inside is pitch black. You need a source of light before you can enter.')
if rooms['first_again']['torch']:
raw_input('You light the torch and step inside, the room is bare, only a table with a ring in the center.')
choice5_r = raw_input('Do you take the ring? Y/N ("back" to leave)')
choice5_r = choice5_r.lower()
if choice5_r == 'y':
raw_input('Some text here')
darkness()
elif choice5_r == 'n':
raw_input('You leave the ring as it is.')
fancy_door()
elif choice5_r == 'back':
hall()
else:
raw_input('Not a valid option')
fancy_door()
else:
hall()
ただし、これを実行すると、次のエラーが発生します。
Traceback (most recent call last):
File "<stdin>", line 247, in <module>
File "<stdin>", line 23, in first_room
File "<stdin>", line 57, in hall
File "<stdin>", line 136, in fancy_door
KeyError: 'torch'
247 行目で、この時点まで機能する first_room() を呼び出します。23 は、この時点まで機能する hall() を呼び出します。57 は、機能するはずの fancy_door() を呼び出します。これは、他のドア関数と同じように見え、正常に機能します。136 行目は、"if rooms['first_again']['torch']:" の上の行です。
問題がここにない場合は、コード全体をここまたはペーストビンに投稿できますが、それは 230 行の長さだったからではありません。
誰かが私を助けてくれたら、とても助かります。
また、悪いコードを許してください。おそらく適切な規則に従っていないことはわかっていますが、私が言ったように、私はPythonとプログラミング全般に不慣れです。これは私が今までに書いた最初のものです。前もって感謝します!