2017-11-25 4 views
0

こんにちは私はチックタックつま先のゲームを作成しようとしている値["0", "1", "2", "3", "4", "5", "6", "7", "8"]フロントエンドから戻ってくると、これらの値はすべてフロントエンドに戻ってくるユーザーからのXまたはランダムな数式からの0を使用して計算されます。 初めて値を入力すると機能しますが、2回目に値を入力するとこのエラーが発生します。チックタックトーゲームタイプエラーなし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 

答えて

2

opponent_fun関数のelseブロックでは、再帰呼び出しの結果を返していません。これに変更すると修正されるはずです。

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: 
    return opponent_fun(board) 

関数は常に直接呼び出し側ではなく、最初の発信者までのすべての方法に値を返すので、これが起こっています。ですから、関数を再帰的に呼び出すたびに、あなたも関数を返す必要があります。