0
direction = input("enter a direction: ")
if direction != "quit" and direction != "go north" and direction != "go south" and direction != "go east" and direction != "go west" and direction != "go up" and direction != "go down" and direction != "look":
    print ("please enter in the following format, go (north,east,south,west,up,down)")

elif direction == "quit":
    print ("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh) ... the game should then end.")

elif direction == "look":
    print ("You see nothing but endless void stretching off in all directions ...")

else:
    print ("You wander of in the direction of " + direction)

Pythonでこれを行う方法を知る必要があります。たとえば、ユーザー入力の最初の2文字をスキャンする必要があります

i = user_input
#user inputs go ayisgfdygasdf

ユーザー入力をスキャンし、最初の 2 文字が go かどうかを確認し、go である場合は 2 番目の単語 (この場合は「ayisgfdygasdf」) を認識せず、「申し訳ありませんが、できません」と出力できるようにする必要があります。それ"

4

4 に答える 4

1

彼はまた、以下を使用することもできます:

    directions.split()

ただし、場合によっては、try/except を使用する必要があります。

分割とメソッドの詳細については、次を使用してみてください。

    dir(directions)

オブジェクトの方向が持つメソッドを確認するには

また:

    help(directions.split) 

特定のメソッドに関するヘルプを表示するには (この場合、オブジェクト方向のメソッド分割)

于 2013-04-01T23:14:18.027 に答える
0

入力の個々の文字にインデックスを付けることができます。

if direction[:2] == "go":
    print "Sorry, I can't do that."

ただし、可能性のある各入力に if-else 分岐を割り当てようとするのは、一般的には悪い選択です...非常に迅速に維持することが難しくなります。

この場合のよりクリーンなアプローチは、次のように有効な入力で辞書を定義することです。

input_response = {"quit":"OK ... but", "go north": "You wander off north", \
                  "go south": "You wander off south"} # etc

次に、コードを次のように書き直すことができます。

try:
    print input_response[direction]
except KeyError:
    if direction[:2] == "go":
        print "Sorry, I can't do that."
    else:
        print ("please enter in the following format...")
于 2013-04-01T23:27:37.520 に答える