0
嗨我試圖創建一個tic tac腳趾遊戲與board
值["0", "1", "2", "3", "4", "5", "6", "7", "8"]
來自前端並返回到後端,然後所有這些值返回到前端來自用戶的X或來自隨機數學的0。 我第一次輸入一個值,它的工作原理,但第二次輸入一個值,我得到這個錯誤。Tic tac toe遊戲類型錯誤無python
if board[cell1] == char and board[cell2] == char and board[cell3] == char:
TypeError: 'NoneType' object is not subscriptable
錯誤聽起來像板列表消失,但當我在我的代碼上打印板時,它表明該板在那裏。
def tic(request):
if request.method == 'POST':
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
input_str = body['value']
input = int(input_str)
board = body['x']
print(board) # Here I see the board is always there
if board[input] != 'x' and board[input] != 'o':
board[input] = 'x'
if check_match(board,'x') == True:
winner = 'x'
return JsonResponse({'input': input, 'board': board, 'winner': winner})
board = opponent_fun(board)
if check_match(board,'o') == True:
winner = 'o'
return JsonResponse({'input': input, 'board': board, 'winner': winner})
else:
winner = 0
return JsonResponse({'input': input, 'board': board, 'winner': winner})
else:
return JsonResponse({'taken' : 'place already taken'})
def opponent_fun(board):
random.seed()
opponent = random.randint(0, 8)
if board[opponent] != 'o' and board[opponent] != 'x':
board[opponent] = 'o'
return board
else:
opponent_fun(board)
def check(board, char, cell1, cell2, cell3):
if board[cell1] == char and board[cell2] == char and board[cell3] == char:
return True
def check_match(board,char):
if check(board,char, 0,1,2):
return True
if check(board,char, 3,4,5):
return True
if check(board,char, 6,7,8):
return True
if check(board,char, 2,4,6):
return True
if check(board,char, 0,4,8):
return True
if check(board,char, 1,4,7):
return True
if check(board,char, 2,5,8):
return True
if check(board,char, 6,7,8):
return True