tic tac toe python machine learning code example

Example 1: how to code a tic tac toe game with ai python

#Tic Tac Toe game in python by techwithtim

board = [' ' for x in range(10)]

def insertLetter(letter, pos):
    board[pos] = letter

def spaceIsFree(pos):
    return board[pos] == ' '

def printBoard(board):
    print('   |   |')
    print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
    print('   |   |')
    
def isWinner(bo, le):
    return (bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or(bo[1] == le and bo[2] == le and bo[3] == le) or(bo[1] == le and bo[4] == le and bo[7] == le) or(bo[2] == le and bo[5] == le and bo[8] == le) or(bo[3] == le and bo[6] == le and bo[9] == le) or(bo[1] == le and bo[5] == le and bo[9] == le) or(bo[3] == le and bo[5] == le and bo[7] == le)

def playerMove():
    run = True
    while run:
        move = input('Please select a position to place an \'X\' (1-9): ')
        try:
            move = int(move)
            if move > 0 and move < 10:
                if spaceIsFree(move):
                    run = False
                    insertLetter('X', move)
                else:
                    print('Sorry, this space is occupied!')
            else:
                print('Please type a number within the range!')
        except:
            print('Please type a number!')
            

def compMove():
    possibleMoves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0]
    move = 0

    for let in ['O', 'X']:
        for i in possibleMoves:
            boardCopy = board[:]
            boardCopy[i] = let
            if isWinner(boardCopy, let):
                move = i
                return move

    cornersOpen = []
    for i in possibleMoves:
        if i in [1,3,7,9]:
            cornersOpen.append(i)
            
    if len(cornersOpen) > 0:
        move = selectRandom(cornersOpen)
        return move

    if 5 in possibleMoves:
        move = 5
        return move

    edgesOpen = []
    for i in possibleMoves:
        if i in [2,4,6,8]:
            edgesOpen.append(i)
            
    if len(edgesOpen) > 0:
        move = selectRandom(edgesOpen)
        
    return move

def selectRandom(li):
    import random
    ln = len(li)
    r = random.randrange(0,ln)
    return li[r]
    

def isBoardFull(board):
    if board.count(' ') > 1:
        return False
    else:
        return True

def main():
    print('Welcome to Tic Tac Toe!')
    printBoard(board)

    while not(isBoardFull(board)):
        if not(isWinner(board, 'O')):
            playerMove()
            printBoard(board)
        else:
            print('Sorry, O\'s won this time!')
            break

        if not(isWinner(board, 'X')):
            move = compMove()
            if move == 0:
                print('Tie Game!')
            else:
                insertLetter('O', move)
                print('Computer placed an \'O\' in position', move , ':')
                printBoard(board)
        else:
            print('X\'s won this time! Good Job!')
            break

    if isBoardFull(board):
        print('Tie Game!')

while True:
    answer = input('Do you want to play again? (Y/N)')
    if answer.lower() == 'y' or answer.lower == 'yes':
        board = [' ' for x in range(10)]
        print('-----------------------------------')
        main()
    else:
        break

Example 2: program for tic tac toe in python

board = ['-', '-', '-',
         '-', '-', '-',
         '-', '-', '-']
gameplay = [1, 0, 1, 0, 1, 0, 1, 0, 1]
def display_board():
    print(board[0] + '|' + board[1] + '|' + board[2])
    print(board[3] + '|' + board[4] + '|' + board[5])
    print(board[6] + '|' + board[7] + '|' + board[8])

def win_check():
    # Row Check
    for col in range(7):
        if board[col] is board[col+1] is board[col+2] == 'X':
            print('You win')
            return True
        if board[col] is board[col+1] is board[col+2] == 'O':
            print('You win')
            return True

    # Column Check
    for row in range(3):
        if board[row] is board[row+3] is board[row+6] == 'X':
            print('You win')
            return True
        if board[row] is board[row+3] is board[row+6] == 'O':
            print('You win')
            return True

    # Diagonal Check
    dia = 0
    if board[dia] is board[dia+4] is board[dia+8] == 'X':
        print('You win')
        display_board()
        return True
    elif board[dia] is board[dia+4] is board[dia+8] == 'O':
        print('You win')
        display_board()
        return True
    dia = 2
    if board[dia] is board[dia+2] is board[dia+4] == 'X':
        print('You win')
        display_board()
        return True
    elif board[dia] is board[dia+2] is board[dia+4] == 'O':
        print('You win')
        display_board()
        return True

def play_game():
    i = 0
    if gameplay[i] == 1:
        board[val] = 'X'
        gameplay.pop(i)
        res = win_check()
        if res is True:
            return True
        else:
            display_board()
            inval()
    else:
        board[val] = 'O'
        gameplay.pop(i)
        res = win_check()
        if res is True:
            return True
        else:
            display_board()
            inval()


def inval():
    global val
    val = int(input('Choose the values from 0 to 8'))
    try:
        if val<=8 and val>=0:
            for item in range(9):
                if item == val:
                    res = play_game()
                    if res is True:
                        break
                    break
        else:
            print('Enter Valid Input!!!!')
            inval()

    except TypeError:
        print('Enter Valid Input!!!!')
        inval()



display_board()
inval()