program for tic tac toe in python

Solutions on MaxInterview for program for tic tac toe in python by the best coders in the world

showing results for - "program for tic tac toe in python"
Linus
04 Oct 2020
1#Tic Tac Toe game in python by techwithtim
2
3board = [' ' for x in range(10)]
4
5def insertLetter(letter, pos):
6    board[pos] = letter
7
8def spaceIsFree(pos):
9    return board[pos] == ' '
10
11def printBoard(board):
12    print('   |   |')
13    print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
14    print('   |   |')
15    print('-----------')
16    print('   |   |')
17    print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
18    print('   |   |')
19    print('-----------')
20    print('   |   |')
21    print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
22    print('   |   |')
23    
24def isWinner(bo, le):
25    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)
26
27def playerMove():
28    run = True
29    while run:
30        move = input('Please select a position to place an \'X\' (1-9): ')
31        try:
32            move = int(move)
33            if move > 0 and move < 10:
34                if spaceIsFree(move):
35                    run = False
36                    insertLetter('X', move)
37                else:
38                    print('Sorry, this space is occupied!')
39            else:
40                print('Please type a number within the range!')
41        except:
42            print('Please type a number!')
43            
44
45def compMove():
46    possibleMoves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0]
47    move = 0
48
49    for let in ['O', 'X']:
50        for i in possibleMoves:
51            boardCopy = board[:]
52            boardCopy[i] = let
53            if isWinner(boardCopy, let):
54                move = i
55                return move
56
57    cornersOpen = []
58    for i in possibleMoves:
59        if i in [1,3,7,9]:
60            cornersOpen.append(i)
61            
62    if len(cornersOpen) > 0:
63        move = selectRandom(cornersOpen)
64        return move
65
66    if 5 in possibleMoves:
67        move = 5
68        return move
69
70    edgesOpen = []
71    for i in possibleMoves:
72        if i in [2,4,6,8]:
73            edgesOpen.append(i)
74            
75    if len(edgesOpen) > 0:
76        move = selectRandom(edgesOpen)
77        
78    return move
79
80def selectRandom(li):
81    import random
82    ln = len(li)
83    r = random.randrange(0,ln)
84    return li[r]
85    
86
87def isBoardFull(board):
88    if board.count(' ') > 1:
89        return False
90    else:
91        return True
92
93def main():
94    print('Welcome to Tic Tac Toe!')
95    printBoard(board)
96
97    while not(isBoardFull(board)):
98        if not(isWinner(board, 'O')):
99            playerMove()
100            printBoard(board)
101        else:
102            print('Sorry, O\'s won this time!')
103            break
104
105        if not(isWinner(board, 'X')):
106            move = compMove()
107            if move == 0:
108                print('Tie Game!')
109            else:
110                insertLetter('O', move)
111                print('Computer placed an \'O\' in position', move , ':')
112                printBoard(board)
113        else:
114            print('X\'s won this time! Good Job!')
115            break
116
117    if isBoardFull(board):
118        print('Tie Game!')
119
120while True:
121    answer = input('Do you want to play again? (Y/N)')
122    if answer.lower() == 'y' or answer.lower == 'yes':
123        board = [' ' for x in range(10)]
124        print('-----------------------------------')
125        main()
126    else:
127        break
Willie
13 Jan 2020
1board = ['-', '-', '-',
2         '-', '-', '-',
3         '-', '-', '-']
4gameplay = [1, 0, 1, 0, 1, 0, 1, 0, 1]
5def display_board():
6    print(board[0] + '|' + board[1] + '|' + board[2])
7    print(board[3] + '|' + board[4] + '|' + board[5])
8    print(board[6] + '|' + board[7] + '|' + board[8])
9
10def win_check():
11    # Row Check
12    for col in range(7):
13        if board[col] is board[col+1] is board[col+2] == 'X':
14            print('You win')
15            return True
16        if board[col] is board[col+1] is board[col+2] == 'O':
17            print('You win')
18            return True
19
20    # Column Check
21    for row in range(3):
22        if board[row] is board[row+3] is board[row+6] == 'X':
23            print('You win')
24            return True
25        if board[row] is board[row+3] is board[row+6] == 'O':
26            print('You win')
27            return True
28
29    # Diagonal Check
30    dia = 0
31    if board[dia] is board[dia+4] is board[dia+8] == 'X':
32        print('You win')
33        display_board()
34        return True
35    elif board[dia] is board[dia+4] is board[dia+8] == 'O':
36        print('You win')
37        display_board()
38        return True
39    dia = 2
40    if board[dia] is board[dia+2] is board[dia+4] == 'X':
41        print('You win')
42        display_board()
43        return True
44    elif board[dia] is board[dia+2] is board[dia+4] == 'O':
45        print('You win')
46        display_board()
47        return True
48
49def play_game():
50    i = 0
51    if gameplay[i] == 1:
52        board[val] = 'X'
53        gameplay.pop(i)
54        res = win_check()
55        if res is True:
56            return True
57        else:
58            display_board()
59            inval()
60    else:
61        board[val] = 'O'
62        gameplay.pop(i)
63        res = win_check()
64        if res is True:
65            return True
66        else:
67            display_board()
68            inval()
69
70
71def inval():
72    global val
73    val = int(input('Choose the values from 0 to 8'))
74    try:
75        if val<=8 and val>=0:
76            for item in range(9):
77                if item == val:
78                    res = play_game()
79                    if res is True:
80                        break
81                    break
82        else:
83            print('Enter Valid Input!!!!')
84            inval()
85
86    except TypeError:
87        print('Enter Valid Input!!!!')
88        inval()
89
90
91
92display_board()
93inval()
Frida
02 May 2016
1import time
2import sys
3
4TITLES = "    A   B   C\n"
5INIT_BOARD = "| / | / | / |\n"
6A, B, C = 4, 8, 12
7# creates the game board
8board = [f"{x} {INIT_BOARD}" for x in range(3)]
9user_turn = ""
10taken = True
11winner = False
12turn_number = 0
13# keeps the score and determines what symbols will be used
14SYMBOLS = ["x", "o"]
15winner_save = [list(x * 3) for x in SYMBOLS]
16score = {symbol: 0 for symbol in SYMBOLS}
17
18# does all the logic to the game
19class logic:
20    def __init__(self, ctx, turn, win_template):
21        self.ctx = ctx
22        self.turn = turn
23        self.template = win_template
24
25    # check if 3 of the same symbols are in a line
26    def winner_check(self):
27        # initializes the list containing the rows. rows 0, 1, and 2 are created
28        win_check = [
29            [board[c][x] for x in range(4, len(board[c])) if x % 4 == 0]
30            for c in range(3)
31        ]
32        # adds the values for every possible row to the list
33        for x in range(3):
34            win_check.append([win_check[c][x] for c in range(3)])
35        win_check.append([win_check[x][x] for x in range(3)])
36        win_check.append([win_check[x][c] for x, c in zip(range(3)[::-1], range(3))])
37        # determines if someone has won
38        for x in win_check:
39            if x in self.template:
40                print(f"{self.turn} wins!")
41                keep = True
42                break
43            keep = False
44        return keep
45
46    # updates the spot value of the given input. ex: input = A1, spot A1 will be occupied by the player
47    def take_spot(self):
48        append_board = board[int(user[1])]
49        append_board = "".join(
50            [
51                append_board[x] if x != eval(user[0]) else self.turn
52                for x in range(len(append_board))
53            ]
54        )
55        return append_board
56
57    # checks to see if a spot on the board is already occupied
58    def spot_taken(self):
59        board_ctx = board[int(self.ctx[1])][eval(self.ctx[0])]
60        check_spot = True if board_ctx in ["o", "x"] else False
61        if check_spot == True:
62            print("spot already taken :/ try again")
63        return check_spot
64
65
66# takes the location input and checks if it exists
67def input_check():
68    slow_print("location- \n")
69    ctx = input().upper()
70    all_input = [x + str(c) for x in ["A", "B", "C"] for c in range(3)]
71    if ctx in all_input:
72        pass
73    else:
74        while ctx not in all_input:
75            slow_print("invalid location, try again\n")
76            slow_print("location- \n")
77            ctx = input().upper()
78    return list(ctx)
79
80
81# takes an input and prints it smoothly to the console
82def slow_print(inpt):
83    for x in inpt:
84        sys.stdout.write(x)
85        time.sleep(0.01)
86
87
88slow_print(TITLES + "".join(board))
89
90# determines what symbol will go first
91while True:
92    slow_print(f"{SYMBOLS[0]}'s or {SYMBOLS[1]}'s?- \n")
93    user_turn = input()
94    if user_turn in [SYMBOLS[0], SYMBOLS[1]]:
95        slow_print(f"{user_turn}'s first!\n")
96        break
97    else:
98        slow_print("incorrent input try again!")
99
100# brings all the functions and logic together
101while True:
102    outcome = "None"
103    while winner == False:
104        # keeps track of the amount of turns to determine if the outcome is a tie
105        turn_number += 1
106        if turn_number == 10:
107            slow_print("Tie!\n")
108            outcome = None
109            break
110        # takes spot input and brings the spot_taken logic together to determines==
111        # whether a spot is already occupied
112        while taken == True:
113            user = input_check()
114            init = logic(user, user_turn, winner_save)
115            taken = init.spot_taken()
116        ctx_board = init.take_spot()
117        board[int(user[1])] = ctx_board
118        slow_print(TITLES + "".join(board))
119        user_turn = SYMBOLS[0] if user_turn != SYMBOLS[0] else SYMBOLS[1]
120        taken = True
121        winner = init.winner_check()
122    # makes sure the point is given to the winner by inverting the current user_turn
123    if outcome == None:
124        pass
125    else:
126        score[SYMBOLS[0] if user_turn == SYMBOLS[1] else SYMBOLS[1]] += 1
127    slow_print(
128        f"Scores: {SYMBOLS[0]}-{score[SYMBOLS[0]]}, {SYMBOLS[1]}-{score[SYMBOLS[1]]}\n"
129    )
130    slow_print("Would you like to play another (Y/N)?- \n")
131    repeat = input().upper()
132    if repeat == "Y":
133        winner = False
134        board = [f"{x} {INIT_BOARD}" for x in range(3)]
135        turn_number = 0
136        continue
137    else:
138        break
139
queries leading to this page
python tic tac toe projecthow to program a tic tac toe game in python where computer never loseshow to make a tik tik toe game in pythonpython tic tac toe codepython tic tac toe ai codetic tac toe 2 players pythonhow to code a tic tac toe game with ai pythontic tac go game code in pythontic tac toe 2 player python codesimple tic tac toe game in pythontic tac toe ai in pythonpython team tic tac toetic tac toe api pythonpython how to display tic tac toetic tac toe program using a algorithm in pythonhow to make tic tac toe in python with aitic tac toe program in python using tkintertic tac toe output in python without codetic tac toe python that always win algorithm using aipython tic tac toe object orientedhow to create an interactive tic tac toe game in python with tynkertic tac toe python tkinterplayer pc tic tac toe python code for beginnersminimax tic tac toe size varable pythonhow to code tic tac toe game in pythn tkinertic tac toe ai python tkinter codetic toc tiae logic pythontic tac toe project in pythonimport tictactoetic tac toe python run gamehow to make a tic tac toe game using pythoncreating a tic tac toe game in pythoncoding a tic tac toe board game pythonpython tic tac toe interfacehow to make an ai tic tac toe using pythonpython computer player tic tac toetice tac toe python codeconsole based tic tac toe pythontic tac toe front end pythontic tac toe with ai pythontic tac toe with computer python codetic tac toe game in pythontictactoe pythontic tac toe game in python with source codesimple tic tac toe python codetic tac toe pytohnbasic python tic tac toetic tac toe tutorial pythontic tac toe code in pythoncreating tic tac toe in pythontic tac toe python source codelets create a python tic tac toe ai from scratchhow to test your tic toe toe game in python in vs codelearn python basic tic tac toetic tac toe game in python tutorialtic tac toe with pythontic tac toe code pythobntic tac toe python guitic tac toe pyrhon aiai tic tac toe pythonhow to automate tic tac toe online pythonminimax algorithm python tic tac toetic tac toe ml pythonpython tic tact toepython tic tac toe using tkintertic tac toe ai pythonultimate tic tac toe codingame pythonbasic tic tac toe pythoncode tic tac toe pythonpython tic tac toe game source codehow to display tic tac toe in pythontic tac toe simple code in python using tkinterpython tic tac toe aitic tac toe python favtutorhow to create simple tic tac toe game using pythontic tac toe program using a 2a algorithm in pythontic tac toe code pythontic tac toe minimax pythontic tac toe board in pythonpython code for tic tac toecreate tic tac toe in python program make tic tac toe in pythontac tic toe pythonhow we can make tic tac toe against computer in pythontice tac toe pythontic tat toe pythontic tac toe library used in pythontic tac toe python 2 playercustom tic tac toe pythontic tac toe ai in pythonhow to make ai for tic tac toe pythontic tac toe game with help of pythontext based python tic tac toe gametic tac toe game in python pseudocoden x n tic tac toe python codetic tac toe game code on pythntic tac to pythontic tac toe with classes pythoncreating tic tac toe using tkinter in pythonhow to code tic tac toe in pythonwhat all you need to know to build tic tac toe in pythontic tac toe python rulestic tac toe python machine learninghow to create tic tac toe in pythontic tac toe app in pythontic tac toe game using ai in pythontic tac toe python to copytic tac toe program in pythontic tac toe python ooppython tic tac toe tutorialtic tac toe in pythonhow to output the tic tac toe in pythontic tac toe pythonpython tic tac toe gamepython discord bot tic tac toetic tac toe with computer and person python codesimple games like tic tac toe pythonpython code for tic tac toe aitic tac toe source code in pythonhow to build tic tac toe pythontic tac toe pytohn computerpython tic tac toe downloadpython tic tac toe gameplaytic tac toe full game in python odepython tic tac toetic tac toe using pythonprogram for tic tac toe in pythongame playing 2c minmax on tictactoe python codewhat features can be added to tic tac toe code in pythonpython ai to play tic tac toetic tac toe python project reporttic tac toe ai pythoncoding ai for tic tac toe in pythonpython tic tac gametictactoe ai pythontic tac pythontic tac toe where does the computer play algorithm pythonmake tic tac toe in python with ai opponentai in python to play xopython algorithm to win tic tac toeimplementation of tic tac toe using game playing algorithm pythonpython tic tac toe code exampletic tac toe code python codesnailpython puzzle 3a tic tac toepython console tic tac toetic tac toe python freetic tac toe written in pythontic tac toe python winningtic tac toe project python full codetic tac toe phytontic tac toe pythom gfgtictac toe using pythonhow to create a tic tac toe game with ai pythontic tac toe game in python with source code programming python netpython ai to always win gametic tac toe python code for beginnerssimple tic tac toe using pythonpython check tic tac toe create a tic tac toe pythonhow to make a tic tac toe board in pythontic tac toe python project pdftic tac toe python refactoringtic tac toe board evaluation pythonmake tic tac toe pythontic tac toe logic pythonpython x o gamecode for tic tac toe game in pythonpython simple tic tac toeai python tik tac toepython tik tak toepythin tic tac toe gametic tac toe game in python tkinterpython tic tac toe logotic tac toe python code lazy programmerhow to make tic tac toe in pythontic tac toe game in pythonconsole based tic tac toe for ai 2b human pythontic tac toe game pythontic tac toe lib used in pythontic tac ote pythontic tac toe game using python normaltic tac toe python aiminimax tic tac toe pythonpython tutorial tic tacc toeai for tic tac toe pythontic tac toe using a 2a algorithm in pythonhow to make tic tac toe in python using randrannge 28 29tic tac toe python iahow to create a tic tac toe game in python in botalgorithm for understanding tic tac toe pythontic tac toe in tkinter in pythontic tac toe with computer pythonadvanced tic tac toe game python codetic tac toe python projecttic tac toe python tutorialalgorithm for tic tac toe games pythontik tok toe game using pythonpython tic tac toe boardtic tac toe with python the most advanced best codehow to build a tic tac toe aiin pythontic tac toe gameboard pythonai tic tac toe python boardcreate a tiktok game with pythontic tact oe pythontic tac toe python gamehow to build a tic tac toe game in python with guihow to make a tic tac toe ai in pythontic tac toe python full codetiv tac toe in pythontic tac toe python codetic tac toe game source code in python with imagepython tic tac toe project source codepython tic tac toe game codestic tac toe board design code pythonhow to make a self learning tic tac toe in pythontic tac toe problem in pythonpython tik tak toe utility functiontic tac toe python beginnerpython code tic tac toetic tac toe in python using machine learningtic tac toe game in python for beginnerstic tac toe in python source codepython how to make the tic tac toe boardcodingame ultimate tic tac toe pythonpython ai tic tac toesource code of tic tac toe game in pythonpython tic tac toe fuieldmin max algorithm tic tac toe pythontic tac toe cade pythonpython tic tac toe board codetictactoe python with aitic tac toe website codesimple tic tac toe game in pythonhow can i make a tic tac toe game in pythontic tac toe pythonpython tic tac toe programpython games tic tac toetic tac toe python program source codehow to make tic tac toe pythonhow to add a computer player in my tic tac toe with pythontic tac toe pythpndesign of the tic tac toe game using pythontic tac toe strategy pythontic tac toe python programtic tac toe miniterm pythonimplement tic tac toe python tkinteralgorithm for tic tac toe game in pythontic tac toe python using randomhow to make the ai randomly choose a position in tic tac toe pythongultimate tic tac toe pythontic tac toe game program in pythontic tac toe computer pythonnumerical tic tac toe python codewrite a program to implement tic tac toe game using pythontic tac toe in python tic tac toe code python artificial intelligencebest ai algorithm for tic tac toe pythonusaco team tic tac toe pythonunbeatable tic tac toe pythontictac toe pythontic tac toe bot pythonopython tic tac toetic tac toe ai pythonprinting tic tac toe pythontic tac toe gui pythontic tac toe python codetic tac toe app pythontic tac toe ai python codehow to make a tic tac toe game in pythontic tac board problem pythoncode for tic tac toe in pythonpython tic tac toe ai example codetic tac toe python 3ftic tac toe python runhow to program a tic tac toe board in pythontic tac winner problem pythontic tac toe app in python tkintertic tac toe board pythonhow to build a tic tac toe game in pythontic tac toe softuni pythonpygletmake tic tac toe pythontic tac toe python that always win algorithmtic tac toe python with aitic tak toe game code in pythonpython programs for tic tac toeonline tic tac toe pyttic tac toe algorithm pythonprogram for tic tac toe in python