Practice Python

Beginner Python exercises

11 September 2016

Tic Tac Toe Game Solutions

Exercise 29

This exercise is Part 4 of 4 of the Tic Tac Toe exercise series. The other exercises are: Part 1, Part 2, and Part 3.

In 3 previous exercises, we built up a few components needed to build a Tic Tac Toe game in Python:

  1. Draw the Tic Tac Toe game board
  2. Checking whether a game board has a winner
  3. Handle a player move from user input

The next step is to put all these three components together to make a two-player Tic Tac Toe game!

Sample solution

This exercise is unique because it relies on the output of the other exercises that need to be put together to make the final solution. The goal is to get practice with functions and how they work together in larger programs.

The 3 exercises above suggest breaking your Tic Tac Toe game into (at least) 4 functions:

  1. A function for drawing the game board (and the location of pieces)
  2. A function for checking whether there is a winner in the game
  3. A function for adding user input into the game state
  4. A main function that calls the others and plays the game

The way to solve this problem is to look back at all 3 solutions to the previous exercises, copy them into one file, and modify what you had before. This is a different way of coding than coding an entire program from scratch, and can often save a lot of time.

For my solution, I decided to copy all the functions from the older exercises into one file, and work from the main game logic from Part 3. Part 3 almost made you write the entire game - the main loop asking users for positions and input is already there, so starting from that point and modifying will let you finish this exercise in 30 minutes!

Here is what my code looks like after copying in my solutions to Part 1, Part 2, and Part 3 of this exercise:

After some modifications:

The final product is here:

Happy hacking!

Enjoying Practice Python?


Explore Yubico
Explore Yubico
comments powered by Disqus