tic tac toe 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

0
0

                                    # Python Program for simple Tic Tac Toe

board = [&quot;-&quot;, &quot;-&quot;, &quot;-&quot;,
         &quot;-&quot;, &quot;-&quot;, &quot;-&quot;,
         &quot;-&quot;, &quot;-&quot;, &quot;-&quot;]

game_still_going = True

winner = None

current_player = &quot;X&quot;

def play_game():

    display_board()

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

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

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


    valid = False
    while not valid:
        while position not in [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;]:
            position = input(&quot;Choose a position from 1-9: &quot;)
        position = int(position) - 1
        if board[position] == &quot;-&quot;:
            valid = True
        else:
            print(&quot;You can't go there. Go again.&quot;)
    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] != &quot;-&quot;
    row_2 = board[3] == board[4] == board[5] != &quot;-&quot;
    row_3 = board[6] == board[7] == board[8] != &quot;-&quot;
    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] != &quot;-&quot;
    column_2 = board[1] == board[4] == board[7] != &quot;-&quot;
    column_3 = board[2] == board[5] == board[8] != &quot;-&quot;
    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] != &quot;-&quot;
    diagonal_2 = board[2] == board[4] == board[6] != &quot;-&quot;
    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 &quot;-&quot; not in board:
        game_still_going = False
        return True
    else:
        return False

def flip_player():
    global current_player
    if current_player == &quot;X&quot;:
        current_player = &quot;O&quot;
    elif current_player == &quot;O&quot;:
        current_player = &quot;X&quot;
play_game()

0
0
3.75
8
Bill Reason 115 points

                                    class Grid:

    def __init__(self):
        self.__grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        self.__score = 0
        self.turn = 1

    def check_location(self, x_index, y_index):
        if self.__grid[int(x_index) - 1][int(y_index) - 1] == 1 or\
           self.__grid[int(x_index) - 1][int(y_index) - 1] == 2:
            return False
        else:
            return True

    def display(self):
        lineVal: int = 0
        print(&quot;0 1 2 3&quot;)
        for i in self.__grid:
            lineVal += 1
            print(str(lineVal), end=&quot; &quot;)
            for k in i:
                print(str(k), end=&quot; &quot;)

            print()

    def place_counter(self, x_index, y_index):
        if self.turn == 1:
            self.__grid[int(x_index) - 1][int(y_index) - 1] = 1
            self.turn = -1
        else:
            self.__grid[int(x_index) - 1][int(y_index) - 1] = 2
            self.turn = 1

    def reset_grid(self):
        for i in range(len(self.__grid)):
            for k in range((len(self.__grid[i]))):
                self.__grid[i][k] = 0

    def victory_check(self):
        for l in range(1, 2):

            for i in range(len(self.__grid)):
                if self.__grid[i][0] == l and self.__grid[i][1] == l and self.__grid[i][2] == l:
                    return True
                if self.__grid[0][i] == l and self.__grid[1][i] == l and self.__grid[2][i] == l:
                    return True
                if self.__grid[0][0] == l and self.__grid[1][1] == l and self.__grid[2][2] == l:
                    return True
                if self.__grid[0][2] == l and self.__grid[1][1] == l and self.__grid[2][0] == l:
                    return True


def collect_place():
    return input(&quot;Please enter a location: &quot;)


placingGrid = Grid()
while True:
    placingGrid.display()
    x_pos = collect_place()
    y_pos = collect_place()
    if placingGrid.check_location(x_pos, y_pos):
        placingGrid.place_counter(x_pos, y_pos)
    else:
        print(&quot;Invalid location&quot;)

    if placingGrid.victory_check():
        print(&quot;Well done&quot;)
        placingGrid.reset_grid()

3.75 (8 Votes)
0
4
5

                                    def tic_tac_toe():
    board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    end = False
    win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))

    def draw():
        print(board[0], board[1], board[2])
        print(board[3], board[4], board[5])
        print(board[6], board[7], board[8])
        print()

    def p1():
        n = choose_number()
        if board[n] == &quot;X&quot; or board[n] == &quot;O&quot;:
            print(&quot;\nYou can't go there. Try again&quot;)
            p1()
        else:

             board[n] = &quot;X&quot;
           
    def p2():
        n = choose_number()
        if board[n] == &quot;X&quot; or board[n] == &quot;O&quot;:
            print(&quot;\nYou can't go there. Try again&quot;)
            p2()
        else:
            board[n] = &quot;O&quot;

    def choose_number():
        while True:
            while True:
                a = input()
                try:
                    a  = int(a)
                    a -= 1
                    if a in range(0, 9):
                        return a
                    else:
                        print(&quot;\nThat's not on the board. Try again&quot;)
                        continue
                except ValueError:
                   print(&quot;\nThat's not a number. Try again&quot;)
                   continue

    def check_board():
        count = 0
        for a in win_commbinations:
            if board[a[0]] == board[a[1]] == board[a[2]] == &quot;X&quot;:
                print(&quot;Player 1 Wins!\n&quot;)
                print(&quot;Congratulations!\n&quot;)
                return True

            if board[a[0]] == board[a[1]] == board[a[2]] == &quot;O&quot;:
                print(&quot;Player 2 Wins!\n&quot;)
                print(&quot;Congratulations!\n&quot;)
                return True
        for a in range(9):
            if board[a] == &quot;X&quot; or board[a] == &quot;O&quot;:
                count += 1
            if count == 9:
                print(&quot;The game ends in a Tie\n&quot;)
                return True

    while not end:
        draw()
        end = check_board()
        if end == True:
            break
        print(&quot;Player 1 choose where to place a cross&quot;)
        p1()
        print()
        draw()
        end = check_board()
        if end == True:
            break
        print(&quot;Player 2 choose where to place a nought&quot;)
        p2()
        print()

    if input(&quot;Play again (y/n)\n&quot;) == &quot;y&quot;:
        print()
        tic_tac_toe()

tic_tac_toe()

4 (5 Votes)
0
3.67
6

                                    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&lt;=8 and val&gt;=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()

3.67 (6 Votes)
0
3.33
3

                                    def slant_check(matrix,P1,P2):
    empty_lst1 = []
    empty_lst2= []
    lst1 = []
    lst2 = []
    x = len(matrix)
    v = len(matrix) - 1
    t = 0 
    g = 0
    n = True
    while n:
        for i in range(x):
            if matrix[i][i] == P1 or matrix[t][i] == P1:
                empty_lst1.append(matrix[i][i])
            if matrix[i][i] == P2 or matrix[t][i] == P2:
                empty_lst2.append(matrix[i][i])
        while v &gt;= g:
            if matrix[g][v] == P1:
                lst1.append(matrix[g][v]) 
            if matrix[g][v] == P2:
                lst2.append(matrix[g][v])
            t -= 1
            v -= 1
            g += 1
        if len(empty_lst1) == x:
            return True
        if len(empty_lst2) == x:
            return True
        if len(lst1) == x:
            return True
        if len(lst2) == x:
            return True
        return False
def vertical_check(lst,P1,P2):
    for i in range(len(lst) - 2):
        for j in range(len(lst)):
            if lst[i][j] == P1 and lst[i + 1][j] == P1 and lst[i + 2][j] == P1:
                return True
            if lst[i][j] == P2 and lst[i + 1][j] == P2 and lst[i + 2][j] == P2:
                return True
            
    return False
def horizontal_check(lst,P1,P2):
    for i in range(len(lst)):
        for j in range(len(lst) - 2):
            if lst[i][j]== P1 and lst[i][j + 1]== P1 and lst[i][j + 2]== P1 :
                return True
            if lst[i][j]== P2 and lst[i][j + 1]== P2 and lst[i][j + 2]== P2 :
                return True
    return False
def find_grid2(place,lst):
    for i in range(len(lst)):
        for j in range(len(lst[i])):
            if place == lst[i][j]:
                return lst.index(lst[i])

def find_grid1(place,lst):
    for i in range(len(lst)):
        for j in range(len(lst[i])):
            if place == lst[i][j]:
                return lst[i].index(place)
            
def print_lst(lst):
    for i in range(len(lst)):
        for j in range(len(lst[i]) - 2):
            print(lst[i][j],'|', lst[i][j + 1],'|', lst[i][j + 2])
            print('----------')
def tic_tac_toe():
    lst = [[1,2,3],
           [4,5,6],
           [7,8,9]]
    P1 = 0
    P2 = 0
    counter_loop = 0
    _ = 0 
    new_lst = [1,2]
    while True:
        P1 = input('Player1 select &quot;x&quot; or &quot;o&quot; ? (Type in x or o):\n').lower()
        if P1 == 'x':
            print('Player2 is now &quot;o&quot;!\n')
            P2 = 'o'
            break
        if P1 == 'o':
            print('Player2 is now &quot;x&quot;!\n')
            P2 = 'x'
            break
        else:
            print('Try Again\n')
    print_lst(lst)
    while _ &lt; len(lst): 
        for i in range(len(lst[_])):
            if counter_loop == 9:
                print(&quot;Tie!&quot;)
                break
            place_grid1 = input('Where would Player 1 like to place? : ')
            if int(place_grid1) &gt;= 10 or int(place_grid1) &lt;= 0:
                print('Try Again')
                place_grid1 = input('Where would Player 1 like to place? : ')
                break
            place_grid = int(place_grid1)
            counter_loop += 1
            inner_index1 = find_grid1(place_grid,lst)
            outer_index1 = find_grid2(place_grid,lst)
            lst[outer_index1][inner_index1] = P1
            print_lst(lst)
            if horizontal_check(lst,P1,P2) == True:
                print(&quot;Player 1 wins!!&quot;)
                counter_loop = 9 
                break
            if vertical_check(lst,P1,P2) == True:
                print(&quot;Player 1 wins!!&quot;)
                counter_loop = 9 
                break
            if slant_check(lst,P1,P2) == True:
                print(&quot;Player 1 wins!!&quot;)
                counter_loop = 9 
                break
            if counter_loop == 9:
                print(&quot;Tie!&quot;)
                break
            place_grid2 = input('Where would Player 2 like to place? : ')
            if int(place_grid2) &gt;= 10 or int(place_grid2) &lt;=0:
                print('Try Again')
                place_grid2 = input('Where would Player 2 like to place? : ')
                break
            place_gridy = int(place_grid2)
            counter_loop += 1
            inner_index2 = find_grid1(place_gridy,lst)
            outer_index2 = find_grid2(place_gridy,lst)
            lst[outer_index2][inner_index2] = P2
            print_lst(lst)
            if horizontal_check(lst,P1,P2) == True:
                print(&quot;Player 2 wins!!&quot;)
                counter_loop = 9 
                break
            if vertical_check(lst,P1,P2) == True:
                print(&quot;Player 2 wins!!&quot;)
                counter_loop = 9 
                break
            if slant_check(lst,P1,P2) == True:
                print(&quot;Player 2 wins!!&quot;)
                counter_loop = 9 
                break
            if counter_loop == 9:
                print(&quot;Tie!&quot;)
                break        
        if counter_loop == 9:
            break
        
        _ += 1

    
tic_tac_toe()

3.33 (3 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
coding ai for tic tac toe in python tic tac toe python free Tic -Tac- Toe in Python. tic tac toe game in python for beginners pythin tic tac toe game how to create simple tic tac toe game using python tic tac toe bot python tic tac-toe program in python using tkinter python tic tac toe project tic tac to python how to make tic tac toe python python tic tac toe gameplay write a program to implement tic-tac-toe game using python tic tac toe game in python how can i make a tic tac toe game in python tic tac toe python 2 player tic tac toe source code in python tic tac ote python tic tac toe python ia ai python tik tac toe make tic tac toe in python tic tac toe python project tic tac toe 2 player python code tic tac toe phyton Simple Tic-Tac-Toe Game in Python python tic tac toe object oriented tic tac toe code python python Puzzle: Tic-Tac-Toe python console tic tac toe tic tac toe with python the most advanced best code How to code tic tac toe game in pythn tkiner how to make a tic tac toe in python tic tac toe pyhton tic tac toe Gui design python python3 tic tac toe tic tac toe python terminal what all you need to know to build tic tac toe in python tic tac toe game source code in python python game code Tic-Tac-Toe how to add a computer player in my tic tac toe with python tic tac toe python program 3d Tic-Tac Toe Python ai for tic tac toe python python check tic tac toe tic tac toe pytohn ti tac toe python tic tac toe board in python python tic tac toe tic tac toe board layout python tic tac toe in python tic tac toe python winning tic tac toe python source code How to create an interactive tic tac toe game in python tic-tac-toe python tic tac toe python with gui how to code tic tac toe in python python tic tac toe board python program for tic tac toe game tic tac toe python code for beginners tic tac toe game ai python tic tac toe python ai minimax tic tac toe python ai tic tac toe python tic toc tiae logic python tictactoe python tic tac toe ai python tic tac game in python tic tac toe python code tic-tac-toe game in python tic tak toe python code tic_tac_toe.py code make a python tic tac toe code tic tac toe python min max algorithm tic tac toe python game playing, minmax on tictactoe python code tic-tac-toe python code how to make a tik tac toe easy game in python make tic tac toe in python with ai opponent python tic tac toe game tic tac toe program in python tic tac toe with computer python code how to program a tik tak toe on python how to make tic tac toe with python Tic-tac-toe in python tic tac toe gam in pyhton is it ahrd to code how to make tic tack toe with python python x o game python tic tac toe board code create xo python code for tic tac toe in python code for tic tac toe game in python tic tac toe pythpj how to make tic tac toe game in python python tic toe game python simple tic tac toe game python tic tac toe program How to make a tic tac toe game using python tic tac toe python with ai tic tac toe cade python tic tac toe project python full code tic tac toe python Tic-Tac-Toe Python ? how to display tic tac toe in python python tic tac toe code how we can make Tic Tac Toe against computer in Python how to make tic tac toe in python tic tac toe game python
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source