Saturday, January 29, 2011

Great Summative project

The first semester courses are done and I'm looking forward to posting more often during the second semester. All of my senior classes this semester were Computer Studies (programming) and so most of my thoughts have been focused on programming rather than technology.
The seniors capped off the year writing a version of the old Snakes and Ladders game. The program had to use a GUI input and show the postion of the players (person vs computer) by printing out the board, a grid of numbers, with symbols showing the player positions.

Printing out the game board lends itself to using a 2 dimensional array, lets call it board.
board[j][i] where j represents the row and i represents the number in the row. If all the rows in a Snakes and Ladders game counted up from left to right then it would be easy to fill up the array with a nested loop. The outer loop counts from zero to 9 - the rows. The inner loop counts from 1 to 10, 11 to 20, 21 to 30 etc to fill up the rows.

int i, j
for (j = 0; j<=9; j++)
{
for (i = 1; i<=10; i++)
{
board [j][i] = j*10 + i;
}
}

But in reality the Snakes and Ladders board counts up in a serpentine fashion so that 11 is above 10 and 21 is above 20 etc. Writing the code for the Snakes and Ladders board is only a little more complicated. The odd rows count up and the even rows count down.

for (int even = 0; even <=8; even +=2)
/** This for loop fills up rows 0, 2, 4, 6 & 8
* in the array. These rows represent
* the rows that count up from left to right**/
{
for (i = 0; i<=9;i++)
{
board[even][i] = count;
count++;
}
count+=10;
} // even
count = 11;
for (int odd = 1; odd <=9; odd +=2)
/** This for loop fills up rows 1,3,5,7,9
* in the array. These rows represent
* the rows that count up from right to left**/
{
for (i=9; i>=0; i--)
{
board [odd][i] = count;
count++;
}
count+=10;
} // odd

Now all we need to do is print out the array starting at row 9 and counting down to zero.

for (j=9; j>=0; j--)
{
for (i=0; i<=9; i++)
{
System.out.print(board[j][i] + " ");
}
}

Output:
100 99 98 97 96 95 94 93 92 91
81 82 83 84 85 86 87 88 89 90
80 79 78 77 76 75 74 73 72 71
61 62 63 64 65 66 67 68 69 70
60 59 58 57 56 55 54 53 52 51
41 42 43 44 45 46 47 48 49 50
40 39 38 37 36 35 34 33 32 31
21 22 23 24 25 26 27 28 29 30
20 19 18 17 16 15 14 13 12 11
1 2 3 4 5 6 7 8 9 10

No comments:

Post a Comment