CPSC120A
Fundamentals of Computer Science I

Lab 27

Two-dimensional Lists

Use the command line to create a new directory called lab27 in your labs directory. Make sure all of the .py files that you create for this activity are in that directory.

Tic-Tac-Toe

Tic-tac-toe is a classic pen and paper game that you have likely been playing since grade school. You simply create a 3x3 grid, and take turns writing your associated symbol in the grid. Typically, player one is assigned the 'X' symbol, and player two is assigned the 'O' symbol. The winner is the first player to assign their symbol three times in a row, either horizontally, vertically, or diagonally.

The game is incredibly simply to learn and play. As a matter of fact, you can buy a book that demonstrates the optimal way to play a game of tic-tac-toe. Writing a program that lets two people play tic-tac-toe not than trivial. A fully functioning tic-tac-toe game is probably not feasible in 2 hours. So instead we will write some key functions so that you can finish the whole game later.

Print the Board

It will be very difficult to visualize the game unless you write a function that will print the grid list formatted nicely.

Details

Create a function called print_board(game_board) in a file called tic_tac_toe.py. The function has a single parameter, a 3 x 3 list of characters. This function does not return any values. Instead, it prints the board to the command line.

Example

Function Call Expected Output
print_board([['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])
-|-|-
-----
-|-|- 
-----
-|-|- 
print_board([['X', '-', '-'], ['-', 'O', 'X'], ['O', '-', '-']])
X|-|-
-----
-|O|X
-----
O|-|- 
Victory!

To create a tic-tac-toe game you will also need a function to determine whether someone has won the game. The rules for victory are simple: a player wins if they have 3 of their tokens in a row either horizontally, vertically, or diagonally.

Details

Create a function called won_game(game_board, player_token) in a file called tic_tac_toe.py. The function has two parameters: a 3 x 3 list of characters and a player_token. The function returns a boolean value, True if the player_token won the game and False otherwise.

Example

Function Call Expected Output
won_game([['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']], 'X') False
won_game([['X', '-', '-'], ['-', 'O', 'X'], ['O', '-', '-']], 'X') False
won_game([['X', '-', 'O'], ['-', 'O', 'X'], ['O', '-', 'X']], 'O') True

 

Challenge

Fantastic! You have completed the majority of the difficult parts of the game. For today's challenge, finish the game. The game should allow two players to alternate making moves onto the board. It should stop when one of the players has won.

Submission

Please show your source code and run your programs for the instructor or lab assistant. Only a programs that have perfect style and flawless functionality will be accepted as complete.