我正在制作Tic Tac Toe游戏,不能将玩家/电脑的标志分配到2d列表。
array = []
player_choice = 0
computer_choice = 0
player_move_col = 0
player_move_row = 0
def starting_array(start_arr):
for arrays in range(0, 3):
start_arr.append('-' * 3)
def print_array(printed_arr):
print printed_arr[0][0], printed_arr[0][1], printed_arr[0][2]
print printed_arr[1][0], printed_arr[1][1], printed_arr[1][2]
print printed_arr[2][0], printed_arr[2][1], printed_arr[2][2]
def player_sign():
choice = raw_input("Do you want to be X or O?: ").lower()
while choice != 'x' and choice != 'o':
print "Error!\nWrong input!"
choice = raw_input("Do you want to be X or O?: ").lower()
if choice == 'x':
print "X is yours!"
return 2
elif choice == 'o':
print "You've chosen O!"
return 1
else:
print "Error!\n Wrong input!"
return None, None
def player_move(pl_array, choice, x, y): # needs played array, player's sign and our col and row
while True:
try:
x = int(raw_input("Which place do you choose?: ")) - 1
y = int(raw_input("What is the row? ")) - 1
except ValueError or 0 > x > 2 or 0 > y > 2:
print("Sorry, I didn't understand that.")
# The loop in that case starts over
continue
else:
break
if choice == 2:
pl_array[x][y] = 'X'
elif choice == 1:
pl_array[x][y] = "O"
else:
print "Choice didn't work"
return pl_array, x, y
starting_array(array)
print_array(array)
# print player_choice, computer_choice - debugging
player_move(array, player_sign(), player_move_col, player_move_row)
print_array(array)
它给了我一个错误:
pl_array[x][y] = "O"
TypeError:'str'对象不支持项目分配
如何更改代码以使其更改项目我显示程序中写入“X”或“O”?
答案 0 :(得分:0)
就像错误所说的那样,' str'对象不支持项目分配,即你不能这样做:
ga = "---"
ga[0] = "X"
但您可以通过更改以下内容来使用示例中的列表:
start_arr.append('-' * 3)
到
start_arr.append(["-"] * 3)