dimanche 12 juin 2016

Unbeatable tic tac toe game Python 3


I'm new to stack overflow this seems like a very helpful community. I was wondering how I could make my tic tac toe game unbeatable, now it has some intelligence but if you play well you can beat it. The first move is always the center which is 5 and if the human goes there then it chooses randomly where to go then uses some guidance to see if it can win the game. This can be beaten with some strategy but I want to make it in such a way that either the human loses or its a tie, but the human can't win.

def get_computer_move(board, player):

it = play_defense(board, player)
if it:
    return it

#check colums for a win 
for i in range(1,10):
    if board[i] == " ":
        board [i] = player
        if is_winner(board, player):
            return i
        else:
            board[i] = " "

#if the center square is empty choose that
if board[5] == " ":
    return 5

while True:
    move = random.randint(1,9)
    # move is blank go and return otherwise try again
    if board[move] == " ":
        return move


def play_defense(board, player):

#columns
for i in [1,2,3]:
    if board[i] == player and board[i+3] == player and board[i+6] == " ":
        return i+6
    if board[i+3] == player and board[i+6] == player and board[i] == " ":
        return i
    if board[i] == player and board[i+6] == player and board[i+3] == " ":
        return i+3
#rows
for a in [1,4,7]:
    if board[a] == player and board[a+1] == player and board[a+2] == " ":
        return a+2
    if board[a+1] == player and board[a+2] == player and board[a] == " ":
        return a
    if board[a+2] == player and board[a] == player and board[a+1] == " ":
        return a+1

if board[1] == player and board[5] == player and board[9] == " ":
   return 9 
if board[5] == player and board[9] == player and board[1] == " ":
   return 1 
if board[9] == player and board[1] == player and board[5] == " ":
   return 5 

if board[3] == player and board[5] == player and board[7] == " ":
   return 7
if board[5] == player and board[7] == player and board[3] == " ":
   return 3
if board[7] == player and board[3] == player and board[5] == " ":
   return 5

Aucun commentaire:

Enregistrer un commentaire