Introduction to Python

Tic-Tac-Toe

We're going to make a program that allows to players to play tic-tac-toe against each other, almost entirely using what we've learned in the last two lectures. When it's finished your game should run something like this:

$ python tictac.py
argyle:intro_python gabow$ python tictac.py 
 |1|2|3
 ------
1| | | 
 ------
2| | | 
 ------
3| | | 
Select position for player 1: 0,0
 |1|2|3
 ------
1|X| | 
 ------
2| | | 
 ------
3| | | 
Select position for player 2: 0,0
That space is not open
 |1|2|3
 ------
1|X| | 
 ------
2| | | 
 ------
3| | | 
Select position for player 2: 1,0
 |1|2|3
 ------
1|X|Y| 
 ------
2| | | 
 ------
3| | | 
Select position for player 1: 0,1
 |1|2|3
 ------
1|X|Y| 
 ------
2|X| | 
 ------
3| | | 
Select position for player 2: 1,1
 |1|2|3
 ------
1|X|Y| 
 ------
2|X|Y| 
 ------
3| | | 
Select position for player 1: 0,2
Congratulations player 1
The winner is you.
Thanks for playing.

More concretely, you want your program to alternate between two players, asking them for positions to put their mark in. Assume all inputs are correctly formatted, such that the first value is an index from 0 to 2 for the column they want to mark, and the 0 to 2 index following the comma is the row index. It is possible that a player tries to mark a space that isn't blank (that is to say it already has an "X" or a "Y"). If that happens, the program should inform the players that this space isn't open and should keep prompting the player for a move until the player puts in an open space.

The game should end when either a row or column has three "X"s or three "Y"s. Also, either player should be able to quit the game at any time by typing "q".

Here is some skeleton code if you don't want to start from scratch.

Here are the steps you probably want to follow to get your program running. Remember it's easier to write a chunk of code, test that it works, and then add to it then to write everything and testing at the very end. You'll want to make sure you can at least get through Step 3.

Step 1: Figure out how to store a 3 by 3 game board. Think about what we've learned about lists.

Step 2: Make the program print out the game board. The function "join" might be helpful here. On day 1 we learned about split that takes a string and makes a list. Join is sort of the inverse, taking a list of strings and making one string. For example:

>>> pets = ["cat", "dog", "rabbit"]
>>> ",".join(pets)
'cat,dog,rabbit'
>>> ", ".join(pets)
'cat, dog, rabbit'
>>> "! ".join(pets)
'cat! dog! rabbit'
>>> 

Step 3: Prompt the player for a move until the player types "q". Remember the raw_input function.

Step 4: Figure out the if the space the player tried to mark is open, and if it is, mark it.

Step 5: Make the program switch between players after each succesful turn.

Step 6: Check to see if a succesful turn wins the game.