2016-01-21 61 views
-1

我正在製作一個Tic Tac Toe遊戲,並且無法將播放器/計算機的標誌分配給2D列表。在更改2D列表中的項目時出現Python錯誤

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' object does not support item assignment

我如何更改代碼,使其更改的項目我表示程序寫在它的「X」或「O」?

回答

0

就像錯誤說,「海峽」對象不支持項目assignement,那是你不能做的:

ga = "---" 
ga[0] = "X" 

但是你可以通過改變使用您的示例列表:

start_arr.append('-' * 3) 

start_arr.append(["-"] * 3) 
相關問題