27.4 C
HomepythonTic-Tac-Toe Game Using Python

Tic-Tac-Toe Game Using Python

Tic-Tac-Toe Game Using Python

Tic-Tac-Toe is normally played with two people. One player is X and the other player is O. Players take turns placing their X or O. If a player gets three of their marks on the board in a row, column, or diagonal, they win. When the board fills up with neither player winning, the game ends in a draw.

Sample Run of Tic-Tac-Toe

Here’s what the user sees when they run the Tic-Tac-Toe program. The text the player enters is in bold.
if you wanna play online

Designing the Program

The figure shows a flowchart of the Tic-Tac-Toe program. The program starts by asking the player to choose their letter, X or O. Who takes the first turn is randomly chosen. Then the player and computer take turns making moves.
Flowchart for Tic-Tac-Toe
Flowchart for Tic-Tac-Toe
The boxes on the left side of the flowchart show what happens during the player’s turn, and the ones on the right side show what happens during the computer’s turn. After the player or computer makes a move, the program checks whether they won or caused a tie, and then the game switches turn. After the game is over, the program asks the player if they want to play again.

Representing the Board as Data

First, you want to understand a way to represent the board as knowledge in a very variable. On paper, the tit-tat-toe board is drawn as a combine of horizontal lines and a combination of vertical lines, with an X, O, or empty area in every one of the 9 areas.
     In the program, the tit-tat-toe board is described as an inventory of strings Each string represents one in all the 9 areas on the board. The strings square measure either ‘X’ for the X player, ‘O’ for the O player, or one area ‘ ‘ for a blank area.

      Remember that we’re parturition out our board sort of a range pad on a keyboard. therefore if a listing with 9 strings was hold on a variable named board, then board[0] would be the top-left area on the board, board[1] would be the top-middle area, board[2] would be the top-right area, and so on.  The player can enter variety from 1 to 9 to inform the sport that area they require to move on.

Importing the random Module

The first few lines are made up of comments and an import line random module so that you can call randint() function later in:

# Tic-Tac-Toe

import random


Printing the Board on the Screen

In the next part of the code, we define a function to draw the board:

def drawBoard(board):
    """This function prints out the board that it was passed.
       "board" is a list of 9 strings representing the board .
    print(board[0] + '|' + board[1] + '|' + board[2] + 'tt1 2 3')
    print(board[3] + '|' + board[4] + '|' + board[5] + 'tt4 5 6')
    print(board[6] + '|' + board[7] + '|' + board[8] + 'tt7 8 9')
The drawBoard() function prints the game board represented by the board parameter. Remember that the board is represented as a list of 9 strings, where the string at index 0 is the mark on space 0 on the Tic-Tac-Toe board, and so on.  Many of the game’s functions work by passing a list of 9 strings as the board. Be sure to get the spacing right in the strings; otherwise, the board will look funny when printed on the screen.
The system takes each string and places it on the board by number. so for the first time three strings the top line of the board, the next three strings are in the middle, and the last three strings are at the bottom.


Letting the Player Choose X or O

Next, we will define a function to assign an X or O to the player

def inputPlayerLetter():
    """ Lets the player type which letter they want to be.
        Returns a list with the player's letter as the first item and the computer's letter as the second.
    letter = ''
    while not (letter == 'X' or letter == 'O'):

        print('Do you want to be X or O?')
        letter = input().upper()
The inputPlayerLetter() function asks if the player wants to be X or O. The shape of the loop while containing parentheses, i.e. the expression within parentheses is checked first.
If the letter has the value ‘X’ or ‘O’, then the loop condition is false as well let the execution of the process continue to pass the block in time. If the situation of course, the system will continue to ask the player to select a letter until then the player enters an X or O.
The following activity returns a list of two items:

# The first element in the list is the player's letter; the second is the computer's letter.
        if letter == 'X':
            return ['X', 'O']
            return ['O', 'X']

Deciding Who Goes First

Next we create a function that uses the randint () to select that player or the computer is playing first

def whoGoesFirst():
    """ Randomly choose which player goes first."""
    if random.randint(0, 1) == 0:
        return 'computer'
        return 'player'
The whoGoesFirst() function makes that decided to whether computer or player goes first. when call to random.randint (0, 1). There is a 50% chance returns 0 and then 50% chance returns 1. If the returns 0, the whoGoesFirst() function returns the ‘computer’.Otherwise, the function returns the ‘player’ string.this function will use the return value to determine who will do the first Game flow.

Placing a Mark on the Board

makeMove() function

def makeMove(board, letter, move):
    board[move] = letter
Parameters board, letter, and move. The variable board is a list with 9 strings representing the state of the board. A different character is player letter(either ‘X’ or ‘O’). The dynamic movement is local to board where that player wants to go (which is a whole number from 1 to 9).
this code appears to convert one of the objects in list of boards than the number in the letter. Because this code works,however, the board parameter will be forgotten when the function returns.So shouldn’t even the change on board be forgotten? Actually, this is not the case, because the list is special when you pass them such as arguments to functions. You are actually passing the reference to the list, no the list itself.

Checking Whether the Player Won

def isWinner(bo, le):
    """given a board and player's letter,this function returns True if that player has won
       We use "bo" instead of "board" and "le" instead of "letter" so we don't have to type as much.
    return (
            (bo[0] == le and bo[1] == le and bo[2] == le) or
            (bo[3] == le and bo[4] == le and bo[5] == le) or
            (bo[6] == le and bo[7] == le and bo[8] == le) or
            (bo[0] == le and bo[3] == le and bo[6] == 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[0] == le and bo[4] == le and bo[8] == le) or
            (bo[2] == le and bo[4] == le and bo[6] == le)

Bo names and le words are shortcuts boards and letters of the alphabet. These short words mean you have less to type in this activity. There are eight ways to win in Tic-Tac-Toe: you can have a line across the top, middle, or bottom lines; you can have a line at the bottom left, middle columns, or right; or you can have a line across the two diagonals. Each status line checks for three given spaces The line is the same as the given character. You combine each line using or operator to explore eight different methods to win. This means that only one of the eight ways must be Truth in order for us to know say the player who owns the book says this is the winner.

Duplicating the Board Data

getBoardCopy() function allows you to easily make a copy of a given 9-string list that represents a Tic-Tac-Toe board in the game.

def getBoardCopy(board):
    """Make a copy of the board list and return it."""
    boardCopy = []
    for i in board:
    return boardCopy

it will sometimes need to make modifications to a temporary copy of the board without changing the actual board. In those cases, we call this function to make a copy of the board’s list.

Currently, the list stored on boardCopy is just an empty list. for loop will measure over the parameter of the board, appending a copy of the string values on a real board on a duplicate board. After GetBoardCopy () function picks up a copy of the board itself, returns a reference to this new board in boardCopy, not the first board.

Checking Whether a Space on the Board Is Free

isSpaceFree() function returns whether that move is available or not
def isSpaceFree(board, move):
    """ Return True if the passed move is free on the passed board."""
    return board[move] == ' '

Letting the Player Enter a Move

getPlayerMove() function asks the player to enter the number for they want to move on

def getPlayerMove(board):
    """ Let the player enter their move."""
    move = ' '
    while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
        print('What is your next move? (1-9)')
        move = input()
        return int(move) - 1
The for loop makes sure the execution it does not continue until the player has entered the value between 1 and 9 it also looks at whether the space has not yet been taken, if you are given a Tic-Tac-Toe the board is passed to the function for the board parameter. Two lines of code inside the loop while simply asking the player to enter a number from 1 to 9. The phrase on the left checks if the player’s movements are correct equals’ 1 ‘,’ 2 ‘,’ 3 ‘, and so on up to ‘9’ by listing these strings (in the form of a split ()) and I’m looking to move on to this list. In this case expression, ‘1 2 3 4 5 6 7 8 9’.split () checks in [‘ 1 ‘,’ 2 ‘,’ 3 ‘,’ 4 ‘,’ 5 ‘, ‘6’, ‘7’, ‘8’, ‘9’], but the first one is easier to type.
The expression on the right shows whether the player is moving it free space is added to the board by calling SpaceFree(). Remember that isSpaceFree() returns True when the pass is found on board. Note that isSpaceFree() expects an integer for move, so the int() function returns an integer form of move. the Not operators can be heard on both sides to make the situation a reality when one of these requirements is not met. This causes the loop to ask the player repeatedly multiplies by number until they enter the correct move.

Choosing a Move from a List of Moves

chooseRandomMoveFromList() function

def chooseRandomMoveFromList(board, movesList):
    """Returns a valid move from the passed list on the passed board.
       Returns None if there is no valid move.
    possibleMoves = []
    for i in movesList:
        if isSpaceFree(board, i):

    if len(possibleMoves) != 0:
        return random.choice(possibleMoves)
        return None
Remember that the board parameter is a string of strings representing the file Tic-Tac-Toe Board. The second parameter, movesList, list of integers of available spaces to choose from. For example, if movesList is 0, 2, 6, 8], that means select RandomMoveFromList() should return a single value of corner spaces. However, first select RandomMoveFromList () first to determine if space is valid to make progress. Possible Moves list starts as an empty list. for loop it iterates over movesList. Departure causing SpaceFree() return Reality added to possibleMoves via append(). At this point, the possible Moves list has all the moves that were in movesList are also free spaces. The system then checks whether list is empty
If the list isn’t empty, then there is at least one possible submission made on board. But this list could be empty. For example, if movesList was [0, 2, 6, 8] but the board representing the board parameter had it all the corner spaces already occupied, the existing Moves list will be []. In that case, len (possibleMoves) checks at 0, and the function returns the value None.

Creating the Computer’s Move


def getComputerMove(board, computerLetter):
    """Given a board and the computer's letter, determine where to move and return that move."""
    if computerLetter == 'X':
        playerLetter = 'O'
        playerLetter = 'X'

The first issue is the Tic-Tac-Toe board parameter of the board. The the second argument is the computer-generated letter– either ‘X’ or ‘O’ in computerLetter parameter. The first few lines simply provide another publication A flexible playerLetter with a name. In this way, the same code can be used either computer X or O.
Remember how the Tic-Tac-Toe AI algorithm works:
1. See if any computer-generated movement will win the game. If there, take that step. Otherwise, go to step 2.
2. See if there is any move that the player can make that will create a computer losing a game. If there is, the computer should go there to block actor. Otherwise, go to step 3.
3. See if there are any corners (spaces 0, 2, 6, or 8) for free. If not space is free, go to step 4.
4. Check that the facility is free. If so, move there. If not, go to step 5.
5. Move to either side (space 1, 3, 5, or 7). No more steps
because side spaces are the only spaces left when the performance is the best reached this point. The function will return the total value from 1 to 9 representing the computer movement. Let’s go through the process of each of these steps code

Checking Whether the Computer Can Win in One Move

Before anything else, if the computer could win the next move, it should take that winning step immediately

     playerLetter = 'X'
    # Here is the algorithm for our Tic-Tac-Toe :
    # First, check if we can win in the next move.
    for i in range(0, 9):
        boardCopy = getBoardCopy(board)
        if isSpaceFree(boardCopy, i):
            makeMove(boardCopy, computerLetter, i)
            if isWinner(boardCopy, computerLetter):
                return i
     The first loop that starts to move over all possible moves from 1 to 9. The code inside the loop simulates what would have happened if the computer made that move.
     The first line in the loop makes a copy of the list of boards. This so the movement made inside the loop does not correct the actual Tic-Tac-Toe board stored on board variables. GetBoardCopy() returns the same but a different list of boards list.
      checks that space is free and, if so, simulates performance submission to a copy of the board. If this movement leads to a computer winning, the function returns the moving value of the movement. If none of the spaces results in winning,, the loop ends, and program execution continues.

Checking Whether the Player Can Win in One Move

Next, the code will simulate the  player moving

# Check if the player could win on their next move and block them.
    for i in range(0, 9):
        boardCopy = getBoardCopy(board)
        if isSpaceFree(boardCopy, i):
            makeMove(boardCopy, playerLetter, i)
            if isWinner(boardCopy, playerLetter):
                return i
The code is similar to the loop except the player’s letter is put on the board copy. If the isWinner() function shows that the player would win with a move, then the computer will return that same move to block this from happening. If the human player cannot win in one more move, the for loop finishes, and the execution continues.


Checking the Corner, Center, and Side Spaces (in That Order)

If the computer can’t make a winning move and doesn’t need to block the player’s move, it will move to a corner, center, or side space, depending on the spaces available. The computer first tries to move to one of the corner spaces

 # Try to take one of the corners, if they are free.
    move = chooseRandomMoveFromList(board, [0, 2, 6, 8])
    if move != None:
        return move
when call to the chooseRandomMoveFromList() function with the list [0, 2, 6, 8] ensures that the function returns the integer for one of the corner spaces: 0, 2, 6, or 8. If all the corner spaces are taken, the chooseRandomMoveFromList() function returns None, and the execution moves

  # Try to take the center, if it is free.
    if isSpaceFree(board, 4):
        return 4
If none of the corners is available, so moves on the center space if it is free. If the center space isn’t free, the execution moves on to next line.

 # Move on one of the sides.
    return chooseRandomMoveFromList(board, [1, 3, 5, 7])
This code also makes the call chooseRandomMoveFromList(), without you refer to the list of side spaces: [1, 3, 5, 7]. This operation will not return None because side spaces are the only spaces that can be left.

Check the Board Is Full


def isBoardFull(board):
    """ Return True if every space on the board has been taken. Otherwise, return False."""
    for i in range(0, 9):
        if isSpaceFree(board, i):
            return False
    return True
This function returns True if the 9-string list is in a board argument pass ‘X’ or ‘O’ in all directions. The for loop allows us to check for 0 to 8 index in the list of boards. As as soon as it gets free space on board (i.e., when isSpaceFree(board, i) Return True), the function isBoardFull () will return False.

The Main Game Loop

print('Welcome to Tic-Tac-Toe!')
while True:
    # Reset the board.
    theBoard = [' '] * 10
    playerLetter, computerLetter = inputPlayerLetter()
    turn = whoGoesFirst()
    print('The ' + turn + ' will go first.')
    gameIsPlaying = True
    while gameIsPlaying:
        if turn == 'player':
            # Player's turn
            move = getPlayerMove(theBoard)
            makeMove(theBoard, playerLetter, move)

            if isWinner(theBoard, playerLetter):
                print('Hooray! You have won the game!')
                gameIsPlaying = False
                if isBoardFull(theBoard):
                    print('The game is a tie!')

                    turn = 'computer'
            # Computer's turn
            move = getComputerMove(theBoard, computerLetter)
            makeMove(theBoard, computerLetter, move)
            if isWinner(theBoard, computerLetter):
                print('The computer has beaten you! You lose.')
                gameIsPlaying = False
                if isBoardFull(theBoard):
                    print('The game is a tie!')
                    turn = 'player'
    print('Do you want to play again? (yes or no)')
    if not input().lower().startswith('y'):



  1. whoah this blog is magnificent i like reading your articles.
    Keep up the great work! You know, lots of persons are
    searching around for this info, you can aid them greatly.

  2. Unquestionably believe that which you said. Your favorite justification appeared to be on the internet the easiest thing to be aware of.
    I say to you, I certainly get irked while people think about worries that they plainly
    don’t know about. You managed to hit the nail upon the top as well as defined out the whole
    thing without having side-effects , people could take
    a signal. Will likely be back to get more. Thanks

  3. Hello are using WordPress for your blog platform?
    I’m new to the blog world but I’m trying to get started and set up
    my own. Do you require any coding knowledge to make your own blog?
    Any help would be greatly appreciated!

  4. I have been surfing online more than 2 hours today,
    yet I never found any interesting article like yours.
    It is pretty worth enough for me. In my view, if all site owners and bloggers made good content
    as you did, the internet will be much more useful than ever before.

  5. The other day, while I was at work, my sister stole my apple ipad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My iPad is
    now destroyed and she has 83 views. I know this is totally off topic but I had to share
    it with someone!

  6. Most of whatever you state happens to be supprisingly precise and that makes me wonder why I had not looked at this in this light before. Your article really did turn the light on for me personally as far as this subject goes. However there is actually just one issue I am not necessarily too cozy with and whilst I try to reconcile that with the actual central idea of your position, allow me see exactly what all the rest of the visitors have to say.Nicely done.


Please enter your comment!
Please enter your name here

- Advertisment -spot_img

Subscribe to our newsletter

To be updated with all the latest news, offers and special announcements.

Most Popular