Tic Tac Toe Python Game

Codecademy course: Computer Science Career Path - Portfolio Project #1


In this project I set out to utilize many of the skills that I learned in the first module of the Computer Science Career Path course from Codecademy. Most of this was a refresher from the programming courses I took for my undergraduate degree, but seeing as that was 10 years ago and I have never used Python...this was a great opportunity to utilize the basics to make something cool!

This short article is broken up into four main parts - what the program does, what the code looks like, what I learned, and ideas to expand the program.

Let's get started!

The What

This program is a simple Tic Tac Toe game played via the Terminal. It's a two player game and it begins by giving the players brief instructions. Each player takes turns choosing a play spot on the board until one player wins or it's a draw.

Article content
Tic Tac Toe game being played

The How

This game was coded using Python using a variety of data types and functions. I implemented basic input validation to ensure the user only enters the allowed characters, and if they don't, the game presents the user with a friendly message (and more importantly, doesn't crash!).

Below is the game's code.

Here is the game's repo on GitHub as well: https://github.com/dougjhall/tic-tac-toe

#set up a blank board
board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]

#main function that guides game flow
def ready():
    printInstructions()
    printInstructionBoard()
    #add some space after instructions
    print("\n<<<<------------------------->>>>")
    game()

#print the game instructions
def printInstructions():
    print("")
    print("")
    print("Welcome to tic tac toe!")
    print("The board is arranged 1-9, left to right as shown below.")
    print("Make your first move by simply typing the number for the position you would like to choose.")
    print("Then player two goes next.")
    print("\n<<<<------------------------->>>>\n")

#print the board along with an outline of the board with the 1-9 positions
def printInstructionBoard():
    print(board[0] + " | " + board[1] + " | " + board[2] + "\t    \t" + "1" + " | " + "2" + " | " + "3")
    print("---------" + "\t    \t" + "---------")
    print(board[3] + " | " + board[4] + " | " + board[5] + "\t>>>>\t" + "4" + " | " + "5" + " | " + "6")
    print("---------" + "\t    \t" + "---------")
    print(board[6] + " | " + board[7] + " | " + board[8] + "\t    \t" + "7" + " | " + "8" + " | " + "9")

#function to print the board
def printBoard():
    print(board[0] + " | " + board[1] + " | " + board[2])
    print("---------")
    print(board[3] + " | " + board[4] + " | " + board[5])
    print("---------")
    print(board[6] + " | " + board[7] + " | " + board[8])

#main function for the game itself
def game():
    currentPlayer = "X"
    currentGame = True
    move = 0
    usedMoves = []
    inputValid = False
    
    #loops until game is won
    while currentGame:
        #loops until user enters a number 1-9
        while not inputValid:
            move = None
            #loops until user enters a 1-9 int
            while move is None:
                print("")
                print("Player " + currentPlayer + ": ")
                try:
                    move = int(input())
                    print("")
                except ValueError:
                    print("Enter a number between 1 and 9.")
            #need to check if number is 1-9
            if move >= 1 and move <= 9:
                #need to ensure the choosen move has not already been taken                   
                if move not in usedMoves:
                    inputValid = True
                    continue
                else:
                    print("This position is already used.")
                    continue
            else:
                print("Enter a number between 1 and 9.")
                continue
        #make the move and update the board onscreen
        board[move - 1] = currentPlayer
        printBoard()
        #is player's move the winning move? 
        currentGame = checkBoard(currentPlayer)
        #swap to the next player
        if currentPlayer == "X":
            currentPlayer = "O"
        else:
            currentPlayer = "X"
        #keep track of the move just made
        usedMoves.append(move)
        #prepare for next input validation
        inputValid = False
        if len(usedMoves) == 9:
            currentGame = False
            print("")
            print("It's a draw!")
            print("")

#check board to see if the game has been won. takes the most recent player as input
#and if there is a winning move, that player wins. returns whether the game should keep
#going or not
def checkBoard(player):
    if (board[0] == player) and (board[1] == player) and (board[2] == player):
        win(player)
        return False
    elif (board[3] == player) and (board[4] == player) and (board[5] == player):
        win(player)
        return False
    elif (board[6] == player) and (board[7] == player) and (board[8] == player):
        win(player)
        return False
    elif (board[0] == player) and (board[3] == player) and (board[6] == player):
        win(player)
        return False
    elif (board[1] == player) and (board[4] == player) and (board[7] == player):
        win(player)
        return False
    elif (board[2] == player) and (board[5] == player) and (board[8] == player):
        win(player)
        return False
    elif (board[0] == player) and (board[4] == player) and (board[8] == player):
        win(player)
        return False
    elif (board[2] == player) and (board[4] == player) and (board[6] == player):
        win(player)
        return False
    else:
        return True

#print out the winning message
def win(player):
    print("")
    print("Player {player} won!".format(player=player))
    print("")

#run the game
ready()        

What I Learned

I am going to have to say that the coolest thing that I learned through the course of this project was using git and GitHub. I had very limited knowledge of either before starting this journey, and after completing the Tic Tac Toe project, I really wanted to create a repo on GitHub...so I worked on learning the ins and outs of that next. It was so exciting to finally get the code and README live using only the command line, and it has been so beneficial to get hands on practice using code repositories, working with branches, and committing code, just like our developers do daily on the scrum team in which I am a Product Owner for.

Another aspect that really stood out was the importance of validating input and providing the player with proper error messages. This is something that I discovered when testing an early version of my game - it would crash immediately if I didn't enter 1-9. Spending a little more time ensuring that input was validated made for a better user experience overall.

What's Next

This is very much an MVP version of the game. Here are some ideas of things I could improve or enhance in the future:

  1. Allow the user to start a new game.
  2. Keep score if you play multiple games in a row, and provide a means of retrieving the score.
  3. Implement a "computer" player so one person can play the game by themselves. Give the user the option for a 1 or 2 player game.

Conclusion

Overall this was a great project to showcase Python and computer science skills that I have gained so far in this journey. It makes use of decision statements, loops, and functions to create a simple game. It also now lives in its own repo on GitHub...and the learning experience to get it there was one of my favorite parts of all.

To view or add a comment, sign in

Others also viewed

Explore content categories