Practice Python

follow us in feedly Atom feed XML

Weekly beginner Python exercises

26 November 2015

Tic Tac Toe Draw

Exercise 27 (and Solution)

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

In a previous exercise we explored the idea of using a list of lists as a “data structure” to store information about a tic tac toe game. In a tic tac toe game, the “game server” needs to know where the Xs and Os are in the board, to know whether player 1 or player 2 (or whoever is X and O won).

There has also been an exercise about drawing the actual tic tac toe gameboard using text characters.

The next logical step is to deal with handling user input. When a player (say player 1, who is X) wants to place an X on the screen, they can’t just click on a terminal. So we are going to approximate this clicking simply by asking the user for a coordinate of where they want to place their piece.

As a reminder, our tic tac toe game is really a list of lists. The game starts out with an empty game board like this:

game = [[0, 0, 0],
	[0, 0, 0],
	[0, 0, 0]]

The computer asks Player 1 (X) what their move is (in the format row,col), and say they type 1,3. Then the game would print out

game = [[0, 0, X],
	[0, 0, 0],
	[0, 0, 0]]

And ask Player 2 for their move, printing an O in that place.

Things to note:

Bonus:

Concepts

One review concept that is definitely needed (in addition to the user input that is the core of the exercise) is the need to “split” strings.

The user will input coordinates in the form “row,col”, which input() will then read in as a string. But we really want the numbers that come out of that string, to know which row and column to place the piece at.

One approach is to use the idea of strings as lists to extract the row and column numbers. This works great if your row and column numbers are always single digits - the row will always be at index 0 and the column will always be at index 2. But this breaks when the numbers are larger than one digit (I know, not going to happen in tic tac toe, but it’s easy to image extending this to other games).

Instead, there are two string manipulation functions that will help you:

  1. .split() - Takes a string and returns a list, using the separator as the split criteria. So if you have a string name = "John Doe" and do name_list = name.split(" "), name_list will be ["John", "Doe"]. You can use any separator / split character you want. Just remember, that each of the elements returned back will be a string as well.
  2. .strip() - Takes a string and removes the whitespace on the left and right sides of it. So you have a string name = " Michele ", and you do name = name.strip(), and now name will just be "Michele" - nice and clean.

I challenge you to figure out how to use them in the exercise!

Happy Coding!

Happy coding!

Forgot how to submit exercises?

comments powered by Disqus