2017-10-31 20 views
0

私はコーディングの初心者ですが、現在はRPGを作っています。コードを実行すると、上記のエラーが表示されます。私にエラーを出す部分はprint("You are on " + floors[currentRoom] + ". You find " + floorsFeature[currentRoom])です。私の推測では、フロア、フロアフィーチャ、およびcurrentRoomsに何か問題があるはずです。私は初心者なので、エラーの意味が分かりません。誰か簡単に説明できますか?"リストのインデックスはタプルではなく整数またはスライスでなければなりません"エラー

print("You are finally a Pokemon trainer! Today, you have gotten your very first Pokemon, a Bulbasaur!") 
name = input("What will you name your Bulbasaur? ") 
print("Unfortunately, " + name + " doesn't seem to obey or like you...") 
print("You try to be friendly to " + name + ", but it just won't listen...") 
print("As " + name + " was busy ignoring you, something seems to catch its attention and it runs off!") 
print("You chase after " + name + ", but it's too fast! You see it running into an abandoned Pokeball Factory.") 
print("You must explore the abandoned Pokeball Factory and find " + name + " before something happens to it!") 
print() 
print("You may input 'help' to display the commands.") 
print() 

gamePlay = True 
floors = [['floor 1 room 1', 'floor 1 room 2', 'floor 1 room 3', 'floor 1 room 4'],['floor 2 room 1', 'floor 2 room 2', 'floor 2 room 3', 'floor 2 room 4', 'floor 2 room 5'],['floor 3 room 1,' 'floor 3 room 2', 'floor 3 room 3'],['floor 4 room 1', 'floor 4 room 2']] 
floorsFeature = [['nothing here.', 'nothing here.', 'stairs going up.', 'a Squirtle.'],['stairs going up and a pokeball.', 'a Charmander.', 'a FIRE!!!', 'stairs going down.', 'a pokeball.'],['stairs going down.', 'a door covered in vines.', '2 pokeballs!'],['your Bulbasaur!!!', 'an Eevee with a key tied around its neck.']] 
currentRoom = [0][1] 
pokemonGot = [] 
count = 0 
bagItems = [] 
countItems = 0 

while gamePlay == True: 
    print("You are on " + floors[currentRoom] + ". You find " + floorsFeature[currentRoom]) 
    move = input("What would you like to do? ") 
    while foo(move) == False: 
     move = input("There's a time and place for everything, but not now! What would you like to do? ") 
    if move.lower() == 'left': 
     if currentRoom > 0: 
      currentRoom = currentRoom - 1 
      print("Moved to " + floors[currentRoom] + ".") 
     else: 
      print("*Bumping noise* Looks like you can't go that way...") 
    elif move.lower() == 'right': 
     if currentRoom < len(floors) - 1: 
      currentRoom = currentRoom + 1 
      print("Moved to " + floors[currentRoom] + ".") 
     else: 
      print("*Bumping noise* Looks like you can't go that way...") 
    elif move.lower() == 'help': 
     print("Input 'right' to move right. Input 'left' to move left. Input 'pokemon' to see what Pokemon are on your team. Input 'bag' to see the items you are carrying. Input 'help' to see the commands again.") 
    elif move.lower() == 'pokemon': 
     if count == 0: 
      print("There are no Pokemon on your team.") 
     else: 
      print("The Pokemon on your team are: " + ", ".join(pokemonGot) + ".") 
    elif move.lower() == 'bag': 
     if countItems == 0: 
      print("There are no items in your bag.") 
     else: 
      print("The items in your bag are: " + ", ".join(bagItems) + ".") 
    print() 
+0

currentRoom = [0] [1] このコードは正しいですか?ちょうど2倍のチェック – elanor

+0

「フロア3の部屋1」、「フロア3の部屋2」、...でカンタが引用符から外れるはずです。 – Adirio

答えて

0

私はそれが別のエラー(範囲外のリストインデックスを)投げたとして、提供されたコードを使用してエラーを複製することができませんでした

私は、問題はここにある疑い

currentRoom = [0][1] 

何これcurrentRoomの値を存在しない[0]のインデックス1に設定しようとしていることを意味します。

[0]ここには1つの項目を含むリストがあります。 あなたはこのことについて混乱している場合は、のpython3を起動し、あなたのサンプルに基づいて、この

currentRoom = [0,2][1] 
print(currentRoom) 

を試してみてください、あなたはあなたの床リストのネストされたリストを使用しています。

階は[0]床1内など

階1フロア[0] =床2を、=、あなたはそれぞれのインデックスは、あなたの現在の部屋を決める別のリストを持っています。

代わりに2つの整数を使用して現在の位置を保持するのはどうですか?

currentRoom = 0 // room 1 
currentFloor = 0 //floor 1 
print (You are on floors[currentFloor][currentRoom], you find floorsFeature[currentFloor][currentRoom]) 
.... 
..... // user entered move left 
if currentRoom >0: 
     currentRoom -= 1 
     print (Moved to floors[currentFloor][currentRoom]) 
.... //user went up by one floor 
if .... 
     currentFloor += 1 
     print (Moved to floors[currentFloor][currentRoom]) 
0

あなたはcurrentRoom = [0][1]を定義することはできません。

>>> currentRoom = [0][1] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: list index out of range 

[0][1]は、整数、文字列または別のタイプではありません。あなたは、床と部屋の情報を維持するために、リストやタプルを使用することができます。

#To get floor 3, room 2 
currentRoom = [2,1] # Or you can use currentRoom = (2,1) 
print(floors[currentRoom[0]][currentRoom[1]]) # It refers print(floors[2][1]) 

出力:

floor 3 room 2 

あなたが行うとき、ヘッダにエラーが発生する可能性があります。

>>> currentRoom = (2,1) 
>>> print(floors[currentRoom]) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: list indices must be integers or slices, not tuple 

上記のソリューションを使用してください:

print(floors[currentRoom[0]][currentRoom[1]]) 
0私たちは、 foo()機能が何をするか分からない

は、すべての必要なコードを提供します

0

は部品で行くことができます。これは検証機能のようですが、コードのその部分が欠落しています。エラーを確認するために実行できるコードを常に提供してください。

foo()交換:

あなたは、単一の行でそれを行うことができますオプションの有効なセットに対して選択を確認するには:

1 in [1, 2, 3] # Output: True 
4 in {1, 2, 3} # Output: False 
4 not in {1, 2, 3} # Output: True 
"b" in ("a", "b", "c") # Output: True 
"abc" in ("a", "b", "c") # Output: False 
"a" in "abc" # Output: True 

あなたは(私は別の値を使用しましたintを見ることができるようにし、 str)と異なる容器(listsettuplestr、...)と私はさらに使用することができます。 not inを使用すると、期待どおりの逆の回答が得られます。あなたのケースでは、あなたが使用することができます

commands = {'help', 'pokemons', 'bag', 'left', 'right'} 
while move not in commands: 
    ... 

文字列の整形:

その中の変数の値が含まれるように、文字列をフォーマットするが、ほとんどのニシキヘビの方法はstr.format()を使用している複数の方法があります。あなたは、フォーマット文字列がhereをどのように機能するかについての文書を確認することができますが、最も簡単な例は次のようになります。

print("Unfortunately, {} doesn't seem to obey or like you...".format(name)) 

は、基本的には、{}で区切らplacehodlersを使用して、あなたがそこに配置したい引数を持つ.format()関数を呼び出します。 {}の中には、たとえば浮動小数点数の小数点以下の桁数を決定するなど、さまざまな文字列を追加して出力をフォーマットすることができます。

list sおよびtuple S:Pythonで

list sおよびtuple S両方のシーケンスコンテナです。主な違いは、listは変更可能であり、tupleは変更されていません。それらは0から始まる表記var[position]でアクセスされます。したがって、シーケンスの内容を変更するつもりがない場合は、リストの代わりにtupleを使用して、インタープリタに適用してより効率的にメモリを使用する必要があります。タプルには角カッコの代わりに括弧を使用します。

dict

dict sが状態を保持する素晴らしい方法です:

player = { 
      'floor': 1, 
      'room': 2, 
      'pokemons': [], 
      'bag': [], 
     } 

あなたは、配列の長さを格納する必要はありません:あなたは常に保ついくつかの言語で

配列内のアイテムの数が格納されます。 Pythonのコンテナは、len(container)を呼び出すことによって、実行時にそのサイズを判断できます。あなたはコードのいくつかの部分でそれを使用しましたが、必要でない変数はcountcountItemsのままです。

多次元リスト(通称マトリックス):(それは0で始まりとして)i+1番目のj+1番目の要素にアクセスするためにmatrix[i][j]

あなたは、次の表記法を使用し、マトリックスを扱ういくつかの問題を抱えているように見えますリスト。

ケースのフロアにあるリストの数を確認するには、len(matrix)を使用してください。n番目のリストの要素数を知るには、len(matrix[n-1])を使用します。

最終的なコード:

commands = {'help', 'pokemons', 'bag', 'left', 'right', 'exit'} 

gamePlay = True 
features = (
      ['nothing here.'     , 'nothing here.'       , 'stairs going up.', 'a Squirtle.'  ], 
      ['stairs going up and a pokeball.', 'a Charmander.'       , 'a FIRE!!!'  , 'stairs going down.', 'a pokeball.'], 
      ['stairs going down.'    , 'a door covered in vines.'     , '2 pokeballs!'], 
      ['your Bulbasaur!!!'    , 'an Eevee with a key tied around its neck.'], 
      ) 

player = { 
      'floor': 1, 
      'room': 2, 
      'pokemons': [], 
      'bag': [], 
     } 

def positionString(player): 
    return "floor {p[floor]} room {p[room]}".format(p=player) 

def featureString(player): 
    return features[player['floor']-1][player['room']-1] 

print("You are finally a Pokemon trainer! Today, you have gotten your very first Pokemon, a Bulbasaur!") 
name = input("What will you name your Bulbasaur? ") 
print("Unfortunately, {} doesn't seem to obey or like you...".format(name)) 
print("You try to be friendly to {}, but it just won't listen...".format(name)) 
print("As {} was busy ignoring you, something seems to catch its attention and it runs off!".format(name)) 
print("You chase after {}, but it's too fast! You see it running into an abandoned Pokeball Factory.".format(name)) 
print("You must explore the abandoned Pokeball Factory and find {} before something happens to it!".format(name)) 
print() 
print("You may input 'help' to display the commands.") 
print() 

while gamePlay == True: 
    print("You are on {}. You find {}".format(positionString(player), featureString(player))) 
    move = input("What would you like to do? ").lower() 
    while move not in commands: 
     move = input("There's a time and place for everything, but not now! What would you like to do? ").lower() 
    if move == 'left': 
     if player['room'] > 1: 
      player['room'] -= 1 
      print("Moved to {}.".format(positionString(player))) 
     else: 
      print("*Bumping noise* Looks like you can't go that way...") 
    elif move == 'right': 
     if player['room'] < len(features[player['floor']-1]): 
      player['room'] += 1 
      print("Moved to {}.".format(positionString(player))) 
     else: 
      print("*Bumping noise* Looks like you can't go that way...") 
    elif move == 'help': 
     print("Input 'right' to move right. Input 'left' to move left. Input 'pokemons' to see what Pokemon are on your team. Input 'bag' to see the items you are carrying. Input 'help' to see the commands again.") 
    elif move == 'pokemons': 
     if len(player['pokemons']) == 0: 
      print("There are no Pokemon on your team.") 
     else: 
      print("The Pokemon on your team are: {}.".format(", ".join(player['pokemons']))) 
    elif move == 'bag': 
     if len(player['bag']) == 0: 
      print("There are no items in your bag.") 
     else: 
      print("The items in your bag are: {}.".format(", ".join(player['bag']))) 
    elif move == 'exit': 
     gamePlay = False 
    print() 

あなたは私が複製する必要がないように部屋の名前と状態ベクトルから部屋の特徴を取得するための2つの関数を作った見ることができるようにどこでもコードのその部分。関数の1つでは、文字列自体が生成されているので、すべて同じスキーム(floor X room Y)を持っています。 'lobby'のような名前をつけない限り、マトリックスにそれらを保持することは意味がありません。私はあなたにその場合は関数を変更する作業を任せます、それは2番目のものと非常に似ているので簡単です。私はループから抜け出すための 'exit'コマンドも追加しました。

関連する問題