15-110 FALL 2009 [CORTINA]

LAB 10

In this lab, you will complete a simple Java game that allows a user to complete a 3 X 3 Magic Square. A 3 X 3 magic square is a square matrix with the numbers 1-9 used only once such that every row, every column and every main diagonal consists of 3 numbers that add up to the same value.


An early stage of the game (left). A completed magic square (right).

EXERCISES

Click HERE to download a project named MagicSquare that you will complete for this lab. You may use either Eclipse or the Terminal window to work on your program.

  1. Complete the MagicSquare class so that each position in the initialBoard array is initialized to a random value between 1 and 9, inclusive. You can initialize two positions to the same value. Compile and run the game to see that this is working correctly before moving on.

  2. Complete the isBoardValid method of the MagicSquareGUI interface so that it returns false if the current board is not a magic square or true otherwise. This boolean value will be used in the actionPerformed method to set the background of the entire window (behind the combo boxes) to red for false or green for true. You can see the background along the bottom of the window where there are no combo boxes. The actionPerformed method is called whenever the user changes a value of any combobox in the window.

    HINT: CHECKING FOR A MAGIC SQUARE

    For a 3 X 3 magic square, the sum of each row, column and main diagonal should be 15. So compute each sum and see if it matches 15. If not, return false immediately. If all of the sums match, then determine if each number is used exactly once. You can do this by setting up an array of 10 booleans initially set to false. (You won't use index 0.) Then for each number, set the boolean value at that index in the array to true if it is false. If it is already true, then you've seen this number already, which means the array can't be a magic square, so return false. If all of these tests pass, return true.

    Compile and run the game to see that this is working correctly before moving on.

  3. EXTRA EXERCISE IF YOU HAVE TIME: Modify the program so that it will work with any magic square of size 3 X 3 through 6 X 6. Some things you will need to change:

HANDIN

At the end of lab, create a zip file of your program and submit it to the handin server: http://handin.intro.cs.cmu.edu/v1