2016-06-24 14 views
0

シンプルな戦艦ゲームを作成する際にこの問題が発生します。ここに私のコードです:Python:TypeError: 'str'オブジェクトがアイテム割り当てをサポートしていません

board = [] 
row = ['O'] * 5 #<<<<determine the board size here 
joined_O = ' '.join(row) 


for i in range(5): #<<<<determine the board size here 
    board.append(joined_O) 
    print(joined_O) 

from random import randint #<<<< this code is to determine where the ship is. It is placed randomly. 
ship_row = randint(1,len(board)) 
ship_col = randint(1,len(board)) 

print(ship_row,', ',ship_col,'\n') 

print('Shoot missile to the ship') 
missile_row = int(input('row : ')) 
missile_col = int(input('column: ')) 

#I really don't know where you're supposed to put the int() thingy so i put it everywhere 
if int(missile_row) == int(ship_row) and int(missile_col) == int(ship_col): 
    print("Congratulation! You've hit the ship.") 
    break 
elif int(missile_row) >= len(board) or int(missile_col) >= len(board): 
    print('Sorry! Area is out of range.') 
    break 
else: 
    print('Missile missed the target') 
    board[int(missile_row)][int(missile_col)] = 'X' 
    print(board) 

私は再割り当てしようとした「Oのところでヒットミサイル 'X' が、その後、それは言う

TypeError: 'str' object does not support item assignment.

答えて

1

ルックで:

board = [] 
row = ['O'] * 5 #<<<<determine the board size here 
joined_O = ' '.join(row) 
  • ボードがリストです。
  • 行がリストです。
  • joined_Oは、rowの要素を連結した文字列です。

AND:

for i in range(5): #<<<<determine the board size here 
    board.append(joined_O) 
    print(joined_O) 

ボードは、ボードリストに文字列を変更しようとしているので、そう

board[int(missile_row)][int(missile_col)] = 'X' 

が有効なコマンドではありません、今、文字列

のリストです2Dリスト内の要素の代わりに使用します。 Pythonでは、文字列は不変なので、文字をインプレースで変更することはできません。

要するに、ボードはコード内の2Dリストではなく、文字列のリストです。

+0

ありがとうございます。私はそれらを結合することが文字列にそれらを作ることを知らなかった。なぜ私はOをXと置き換えることができないのか、今理解しています。 – Inas

2
for i in range(5): #<<<<determine the board size here 
    board.append(joined_O) 

これは正しく表示されません。文字列ではなく、boardにリストを追加する必要があります。私はあなたが以前に次のようなものを持っていたと推測しています:

for i in range(5): 
    board.append(row) 

少なくとも正しいタイプでしょうか。しかし、あなたが船を見逃すたびに5つのXesが1つではなく現れる奇妙なバグがあります。これは、各行が同じ行であるためです。 1つに変更を加えると、そのすべてに変更が加えられます。これを避けるには、スライシングトリックを使用するたびに行のコピーを作成します。

for i in range(5): #<<<<determine the board size here 
    board.append(row[:]) 

これで、Xesが正しく割り当てられるはずです。しかしelseブロックのprint(board)は少し醜いでしょう。あなたは括弧や引用符を使わずに、素早く結合することができます。

else: 
    print('Missile missed the target') 
    board[int(missile_row)][int(missile_col)] = 'X' 
    print("\n".join(" ".join(row) for row in board)) 

これでかなり良い出力が得られました。

Shoot missile to the ship 
row : 1 
column: 1 
Missile missed the target 
O O O O O 
O X O O O 
O O O O O 
O O O O O 
O O O O O 
+0

兄弟、あなたはコード内のすべてのバグを修正し、Pythonを学ぶ機会を失っただけです。 – Wajahat

+0

おそらく...プログラミングについての素晴らしい点は、今後もバグや学習の機会が増えているということです:-) – Kevin

+0

@Wajahat彼は良い教訓の瞬間をここでやっていますが、少なくともコードを打ち破ってプログラム全体をコピーして貼り付けます。 – Delioth

関連する問題