Can Computers Think?
Introduction to Computer Science

CSC 106
Union College
Winter 2010

Working with grids

Preparation

Download the following two files and save them in the same place/folder:

Why do they need to be in the same folder? Make sure you can answer this question.

The file grid_display.py contains some code for displaying a grid of differently colored squares on the screen. example_grid.py is an example of how that code can be used. You don't need to understand the details of the code in grid_display.py, but you should understand how it is used. So, study example_grid.py and make sure that you understand what is going on. Do read the comments in file grid_display.py as they tell you how the function run_display is to be used.

Problem 1: mosaic of random colors

Write a program that creates a 30 by 30 grid (using a list of lists to represent the grid) where each cell contains a randomly chosen number between 0 and 9. Use the run_display function provided by the file grid_display.py to display this grid. You should see a 30 by 30 grid of differently colored squares.

Solution.

Problem 2: Lights Out (or On)

The goal of this problem is to implement a version of the game "Lights Out":Lights Out on Wikipedia.

Part 1: the starting configuration

The goal of part 1 is to create and display the starting configuration of the game board/grid. In part one we are not dealing with mouse clicks, yet.

Choose two numbers between 0 and 9 to represent your on and off states.

Write a program that creates a 5 by5 grid where each cell is randomly assigned to be either on or off (that is, each cell is randomly assigned to be one of the two numbers that you have chosen to represent the on and off states).

Display this grid using the run_display function provided by the file grid_display.py.

Part 2: reacting to clicks

Step 0: Notice how the function on_click prints out two numbers every time that you mouse click on a cell of the grid. The numbers indicate which cell (row and colum) was clicked.

Step 1: Change the status of the clicked cell: if it is on, it should become off, if it is off it should become on. That is, if the value of the clicked cell in the grid is on, change the grid so that the value of that cell is now off; and vice versa.

If you click on a cell now, the color of that cell should change.

Step 2: Change the status of each of the four cells neighboring the clicked cell as well. That is each of the cells to the top, bottom, left and right of the clicked cell should change their status to ON if it was OFF, and to OFF if it was ON.

Be careful of the edges of the grid. Cells that are at edge do not have all four neighbors.

Solution.