As usual, create a directory to hold today's files. All programs that you write today should be stored in this directory.
$ cd ~/cs120/labs $ mkdir lab30 $ cd lab30
Write a function called create_nxn_matrix(size)
, which takes a
single integer as a parameter. Your function should return a size×size matrix of 0's.
Write a function called sum_column(a_matrix, col_index)
, which
takes a 2-dimensional list and a positive integer as parameters. Your
function should return the sum of all of the values along the specified
column of the list.
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 simple 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 that trivial. Writing 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.
It will be very difficult to visualize the game unless you write a function that will print the grid list formatted nicely.
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.
Function Call | Expected Output |
---|---|
print_board([['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]) | -|-|- ----- -|-|- ----- -|-|- |
print_board([['X', '-', '-'], ['-', 'O', 'X'], ['O', '-', '-']]) | X|-|- ----- -|O|X ----- O|-|- |
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.
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.
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 |
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.