GROUP WORK
Most turn-based games have the
following setup:
//Initialize variables here
//Show starting state of game
while(true)
{
//Play one turn of game
//Show new state of game
//Exit loop if game is over
}
STEP 1
Inside the main function of TicTacToe.java,
create 9 String variables named v1, v2, v3, … v8, v9. They will hold the nine values that appear
on a Tic Tac Toe board. Make each string hold a space.
These String variables can hold
one of three values: “ “, “X” or “O”. Note that the space represents that the
spot is available to be chosen on the board.
STEP 2
Create the following function:
public
static void displayBoard(String s1, String s2,
String s3, …, String s9)
It will display the following:
* *
X * O *
* *
***********
* *
* X *
* *
***********
* *
O * X * O
* *
STEP 3
From main, test the displayBoard function.
Pass the String values from Step 1 to the function. Make sure you understand how it
works. It is a good idea to set a
few of the String values to “X” and to “O” to see how the function works.
Move on once you are satisfied
that the function works well.
STEP 4
Write the following function:
public
static int humanPlayerTurn()
It simply returns a value from 1
to 9 that the human player chose.
You can assume that the human player will be smart enough to choose
a legal square.
STEP 5
We will now start working with
the game setup. You need to
restructure your main function to look like this:
String v1 = “ “;
String v2 = “ “;
.
.
.
String v9 = “ “;
displayBoard(v1,
v2, v3, v4, v5, v6, v7, v8, v9);
while(true)
{
//get choice from human
//update board according to human’s
choice
displayBoard(v1, v2, v3, v4, v5, v6, v7,
v8, v9);
//check if game has been won
//check if board is full
//switch turn letter
}
STEP 6
We will need to keep track of who’s turn it is.
Is it “X” or “O” that is to go next.
We’ll have a variable to keep
track of the current turn.
Add the following at the top of
the main function:
String turn = “X”;
STEP 7
We will now deal with two parts
inside the while loop. We want to
get the human player’s choice and we want to update that in our variables.
The while loop should now look
like this (new content in blue):
while(true)
{
int choice = humanPlayerTurn();
if (choice == 1)
{
v1 = turn;
}
else if
(choice == 2)
{
v2 = turn;
}
else if (choice == 3)
{
v3 = turn;
}
.
.
.
else if (choice == 9)
{
v9 = turn;
}
displayBoard(v1,
v2, v3, v4, v5, v6, v7, v8, v9);
}
STEP 8
Create the function
public static String swapTurn(String ct)
It
returns “X” if ct is equal to
“O”. It return “O” if ct is equal to
“X”.
STEP 9
At the bottom of the while loop (inside
the loop), add the following statement:
turn = swapTurn(turn);
You can now fully play the
game. However, it doesn’t check for
possible end states yet (wins or ties).
|