Answers for "tic-tac-toe python code"

5

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
Posted by: Guest on June-12-2020
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()
Posted by: Guest on May-17-2020
1

how to make tic tac toe in python

# Python Program for simple Tic Tac Toe

board = ["-", "-", "-",
         "-", "-", "-",
         "-", "-", "-"]

game_still_going = True

winner = None

current_player = "X"

def play_game():

    display_board()

    while game_still_going:
        handle_turn(current_player)
        check_if_game_over()
        flip_player()
    if winner == "X" or winner == "O":
        print(winner + " won.")
    elif winner is None:
        print("Tie.")

def display_board():
    print("n")
    print(board[0] + " | " + board[1] + " | " + board[2] + "     1 | 2 | 3")
    print(board[3] + " | " + board[4] + " | " + board[5] + "     4 | 5 | 6")
    print(board[6] + " | " + board[7] + " | " + board[8] + "     7 | 8 | 9")
    print("n")

def handle_turn(player):
    print(player + "'s turn.")
    position = input("Choose a position from 1-9: ")


    valid = False
    while not valid:
        while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
            position = input("Choose a position from 1-9: ")
        position = int(position) - 1
        if board[position] == "-":
            valid = True
        else:
            print("You can't go there. Go again.")
    board[position] = player
    display_board()

def check_if_game_over():
    check_for_winner()
    check_for_tie()

def check_for_winner():
    global winner
    row_winner = check_rows()
    column_winner = check_columns()
    diagonal_winner = check_diagonals()
    if row_winner:
        winner = row_winner
    elif column_winner:
        winner = column_winner
    elif diagonal_winner:
        winner = diagonal_winner
    else:
        winner = None

def check_rows():
    global game_still_going
    row_1 = board[0] == board[1] == board[2] != "-"
    row_2 = board[3] == board[4] == board[5] != "-"
    row_3 = board[6] == board[7] == board[8] != "-"
    if row_1 or row_2 or row_3:
        game_still_going = False
    if row_1:
        return board[0]
    elif row_2:
        return board[3]
    elif row_3:
        return board[6]
    else:
        return None

def check_columns():
    global game_still_going
    column_1 = board[0] == board[3] == board[6] != "-"
    column_2 = board[1] == board[4] == board[7] != "-"
    column_3 = board[2] == board[5] == board[8] != "-"
    if column_1 or column_2 or column_3:
        game_still_going = False
    if column_1:
        return board[0]
    elif column_2:
        return board[1]
    elif column_3:
        return board[2]
    else:
        return None

def check_diagonals():
    global game_still_going
    diagonal_1 = board[0] == board[4] == board[8] != "-"
    diagonal_2 = board[2] == board[4] == board[6] != "-"
    if diagonal_1 or diagonal_2:
        game_still_going = False
    if diagonal_1:
        return board[0]
    elif diagonal_2:
        return board[2]
    else:
        return None

def check_for_tie():
    global game_still_going
    if "-" not in board:
        game_still_going = False
        return True
    else:
        return False

def flip_player():
    global current_player
    if current_player == "X":
        current_player = "O"
    elif current_player == "O":
        current_player = "X"
play_game()
Posted by: Guest on May-29-2020
0

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
Posted by: Guest on October-19-2020

Python Answers by Framework

Browse Popular Code Answers by Language