how to create tic tac toe in python 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: tic tac toe algorithm python

#algorithim for X player
#python 3.85


import random


def algoX(lisp):
  '''my bacic stupid idiotic dunder-headded ape-brained algorithim'''
  
  for i in range(len(lisp)):
    if lisp[i] == 1:
      lisp[i] = 'X'
    elif lisp[i] == 2:
      lisp[i] = 'O'
  
  def zeros(list):
    out = 0
    for i in range(len(list)):
      if list[i] == 0:
        out += 1
    return out
  
  def count(list, simb):
    out = 0
    for i in range(len(list)):
      if list[i] == simb:
        out += 1
    return out
  
  if count(lisp[0:3], 'X') == 2 and zeros(lisp[0:3]) == 1:
    lisp[0:3] = 'X','X','X'
  
  elif count(lisp[3:6], 'X') == 2 and zeros(lisp[3:6]) == 1:
    lisp[3:6] = 'X','X','X'
  
  elif count(lisp[6:9], 'X') == 2 and zeros(lisp[6:9]) == 1:
    lisp[6:9] = 'X','X','X'
    
  elif count([lisp[0],
              lisp[3],
              lisp[6]],'X') == 2 and zeros([lisp[0],lisp[3],lisp[6]]) == 1:
    for i in range(3):
      lisp[i*3] = 'X'
  
  elif count([lisp[1],
              lisp[4],
              lisp[7]],'X') == 2 and zeros([lisp[1],lisp[4],lisp[7]]) == 1:
    for i in range(3):
      lisp[(i*3)+1] = 'X'
  
  elif count([lisp[2],
              lisp[5],
              lisp[8]],'X') == 2 and zeros([lisp[2],lisp[5],lisp[8]]) == 1:
    for i in range(3):
      lisp[(i*3)+2] = 'X'
      
  elif count([lisp[0],
              lisp[4],
              lisp[8]],'X') == 2 and zeros([lisp[0],lisp[4],lisp[8]]) == 1:
    for i in range(3):
      lisp[(i*4)] = 'X'
  
  elif count([lisp[2],
              lisp[4],
              lisp[6]],'X') == 2 and zeros([lisp[2],lisp[4],lisp[6]]) == 1:
    
    lisp[2], lisp[4], lisp[6] = 'X','X','X'
  
  else:
    '''prevent loss'''
    if count(lisp[0:3], 'O') == 2 and zeros(lisp[0:3]) == 1:
      for i in range(3):
        if lisp[i] == 0:
          lisp[i] = 'X'
    
    elif count(lisp[3:6], 'O') == 2 and zeros(lisp[3:6]) == 1:
      for i in range(3,6):
        if lisp[i] == 0:
          lisp[i] = 'X'
    
    elif count(lisp[6:9], 'O') == 2 and zeros(lisp[6:9]) == 1:
      for i in range(6,9):
        if lisp[i] == 0:
          lisp[i] = 'X'
    
    elif count([lisp[0],
                lisp[3],
                lisp[6]],'O') == 2 and zeros([lisp[0],lisp[3],lisp[6]]) == 1:
      for i in range(3):
        if lisp[i*3] == 0:
          lisp[i*3] = 'X'
          
    elif count([lisp[1],
              lisp[4],
              lisp[7]],'X') == 2 and zeros([lisp[1],lisp[4],lisp[7]]) == 1:
      for i in range(3):
        if lisp[(i*3)+1] == 0:
          lisp[(i*3)+1] = 'X'
    
    elif count([lisp[2],
              lisp[5],
              lisp[8]],'X') == 2 and zeros([lisp[2],lisp[5],lisp[8]]) == 1:
      for i in range(3):
        if lisp[(i*3)+2] == 0:
          lisp[(i*3)+2] = 'X'
    
    elif count([lisp[0],
              lisp[4],
              lisp[8]],'X') == 2 and zeros([lisp[0],lisp[4],lisp[8]]) == 1:
      for i in range(3):
        if lisp[i*4] == 0:
          lisp[(i*4)] = 'X'
    
    elif count([lisp[2],
              lisp[4],
              lisp[6]],'X') == 2 and zeros([lisp[2],lisp[4],lisp[6]]) == 1:
      if lisp[2] == 0:
        lisp[2] = 'X'
        
      elif lisp[4] == 0:
        lisp[4] = 'X'
        
      elif lisp[6] == 0:
        lisp[6] = 'X'
    
    else:
      '''regular options'''
      if lisp[4] == 0:
        lisp[4] = 'X'
      else:
        while True:
          rand = random.randint(0,8)
          if lisp[rand] == 'X' or lisp[rand] == 'O':
            continue
          else:
            lisp[rand] = 'X'
            break
     
    
          
      
    
        
  return lisp