java programmng
TIC-TAC-TOE
Your task is to develop a tic-tac-toe game. There are two options for you to choose from. One option is a tic-tac-toe game where two humans may play. The second option is one where a human may play against the computer. Option one is worth less points (90% of total points) than option two (100% of total points).
PROGRAM REQUIREMENTS
The program prompts users for their names and ensures (validates) them; users are allowed to enter a single username consisting of alpha chars ONLY.
Use one-dimensional arrays to keep track of the game:
Human moves in the case of option one.
Computer moves as well in the case of option two.
Use functions to pass arrays and implement other program requirements such as input validation, checking to ensure that places selected by users are available on the “game board”.
Validate user input at every opportunity.
Do not allow number entries less than 0 or entries greater than 8 (in the case you are using numbers 0-8 on the “grid”.
Do not allow number entries less than 0 or entries greater than 8 (in the case you are using numbers 1-9 on the “grid”.
Do not allow non-numeric entries.
If your program crashes due to an invalid entry made by the user, then you will not pass the final exam.
The program must be developed using functions so that the main() function consists mostly of function calls. This is exactly the same requirement as your midterm!
Below is a suggested list of functions for you to consider in the development of this project:
splashScreen()//displays game and developer’s information
askForUserNames()//requests for username
validateUserName()//validate username
switchPlayer()//switch from one player to another
resetGame()//reset the game when one concludes; this includes filling the array with vales 0-8
displayGrid()//display the grid after each player makes a move
playerMakeMove()//prompts player to make a move, invokes validatePlayersMove, checkPositionAvailability
validatePlayersMove()//validates that user entry X is such that 0<=X<=8
checkPositionAvailability()//check that the position selected by the user is available
checkWin()//check for a winning player
checkTie()//check for a tie
In the case of option two, additional functions you may want to consider are:
makeBestMove()//select best option
computerMakeMove()//used to make the move, in other words populate the array
The main() function must use a loop to keep the user in the program until he/she wants to quit. Users should be allowed to play as many games as they want.
You must use meaningful variable names.
You must comment your code.
You must use variables of the correct type and initialize them with a proper value.
Your program must detect a winner if there is one
Your program must determine if a tie occurs
Expert Answer
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private String username;
private Scanner input;
private char board[];
private Random random;
//constructor to initialize the scanner , board, random generator
public TicTacToe()
{
input = new Scanner(System.in);
board = new char[9];
random = new Random();
resetGame();
}
//displays the splash screen
public void splashScreen() throws IOException
{
System.out.println(“********************************”);
System.out.println(“********************************”);
System.out.println(“********************************”);
System.out.println(“********* **********”);
System.out.println(“********* TIC TAC TOE **********”);
System.out.println(“********* **********”);
System.out.println(“********* **********”);
System.out.println(“********************************”);
System.out.println(“********************************”);
System.out.println(“********************************”);
System.out.println(“nnPress any key to continue…”);
input.nextLine();
}
//ask for valid user name. Username should be a single word with only alphabet chars only. If invalid
//input is given, user is repeatedly prompted to give valid input
public void askForUserName()
{
System.out.println(“Player, enter your name”);
while(true)
{
System.out.println(“Enter a single word with alpha chars only!”);
username=input.nextLine();
if(!validateUserName())
{
System.out.println(“Invalid name”);
}
else
break;
}
}
//function to check if the instance variable username is a valid username or not. Returns true if valid and
//false otherwise
private boolean validateUserName()
{
char ch;
if(username == null || username.equals(“”)) //check if null or empty string
return false;
for(int i=0;i<username.length();i++)
{
ch = username.charAt(i);
if(!(ch>=’a’ && ch<=’z’ || ch>=’A’ && ch<=’Z’)) //only lower case and upper case chars allowed
return false;
}
return true;
}
//resets the game, board is initialized again from 0-8
public void resetGame()
{
for(int i = 0; i < 9; i++)
board[i] = (char)(i + 48); //initialize using ascii value, numbers start from 48 for 0
}
//displays the board on screen after clearing the screen
public void displayGrid()
{
int idx;
try {
Runtime.getRuntime().exec(“clear”); //try clear command (works on linux based system)
} catch (IOException e) {
try {
Runtime.getRuntime().exec(“cls”); //if previous clear failed, try cls on windows system
} catch (IOException e1) {
}
}
System.out.println(” TIC-TAC-TOE”);
for(int i=0;i<3; i++)
{
System.out.print(“n|———–|”);
System.out.print(“n| “);
for(int j = 0; j<3; j++)
{
idx = i * 3 + j;
System.out.print(board[idx]+” | “);
}
}
System.out.print(“n|———–|nn”);
}
//prompts the player for a move and validates his move i.e checks if input if in range 0-8.
//if valid , then checks if the specified position is available and not occupied yet.
//If available, then marks it with ‘H’ to indicate human move. Otherwise prompts user for
//a different position
public void playerMakeMove()
{
while(true)
{
System.out.println(“It is “+username+”‘s move”);
System.out.println(“Give me your best move!”);
int move=input.nextInt();
if(validatePlayerMove(move))
{
if(checkPositionAvailability(move))
{
board[move] = ‘H’; //make ‘H’ for player move
break;
}
else
{
System.out.println(“Position not available.nMake a different choice.”);
continue;
}
}
else
{
System.out.println(“Invalid entry!”);
continue;
}
}
}
//checks if user’s move is valid i.e in range 0-8
private boolean validatePlayerMove(int move)
{
if(move<0 || move >8)
return false;
else
return true;
}
//check if the specified
private boolean checkPositionAvailability(int move)
{
if(board[move]!=’C’ && board[move]!=’H’)
return true;
else
return false;
}
//checks if the board has a winner. Returns ‘H’ if human wins, ‘C’ if computer wins
//’ ‘ if nobody has won
public char checkWin()
{
if(board[0]==board[1] && board[1]==board[2]) //check top horizontal line
return board[0];
else if(board[3]==board[4] && board[4]==board[5]) //check middle horizontal line
return board[3];
else if(board[6]==board[7] && board[7]==board[8])//check last horizontal line
return board[6];
else if(board[0]==board[3] && board[3]==board[6])//check left vertical line
return board[0];
else if(board[1]==board[4] && board[4]==board[7])//check middle vertical line
return board[1];
else if(board[2]==board[5] && board[5]==board[8])//check right vertical line
return board[2];
else if(board[0]==board[4] && board[4]==board[8])//check diagonal line from left top to right bottom
return board[0];
else if(board[2]==board[4] && board[4]==board[6]) //check diagonal from right top to left bottom
return board[2];
else
return ‘ ‘;
}
//checks if there is tie. Returns true if tie and false otherwise
public boolean checkTie()
{
//first see if all the positions are occupied or not
for(int i=0;i<9;i++)
{
if(board[i]!=’C’ && board[i]!=’H’)
return false;
}
//if all are occupied, now check winner, if ‘ ‘ is returned, then its a tie since already all positions are occupied
if(checkWin()==’ ‘)
return true;
else
return false;
}
//makes a computer’s move
public void computerMakeMove()
{
int move = makeBestMove();
board[move] = ‘C’;
}
//generates a random number in range 0-8 which is not yet occupied.
private int makeBestMove()
{
while(true)
{
int move = random.nextInt(9);
if(!checkPositionAvailability(move))
continue;
else
return move;
}
}
//returns the human player name
public String getUserName()
{
return username;
}
//prompts user if he wants to play again and returns true if user wants to continue and fals otherwise
public boolean playAgain()
{
System.out.println(“Game over! Play again ? y/n: “);
input.nextLine();//flush newline from previous input for positions
if(input.nextLine().trim().equalsIgnoreCase(“y”))
return true;
else
return false;
}
public static void main(String[] args) {
TicTacToe game=new TicTacToe();
char winner;
int turn=1;
try {
while(true) //keep repeating
{
game.splashScreen();
game.askForUserName();
while(true)
{
//check if already the game is over
winner = game.checkWin();
if(winner==’C’ || winner==’H’ || (winner == ‘ ‘ && game.checkTie()))
break;//break if game over
game.displayGrid();
if(turn == 1)
game.playerMakeMove();
else
game.computerMakeMove();
turn = 1 – turn;
}
//display game status
game.displayGrid();
if(winner == ‘C’)
System.out.println(“Computer wins!”);
else if(winner == ‘H’)
System.out.println(“Player “+game.getUserName()+” wins!”);
else
System.out.println(“It’s a tie!”);
//ask if user wants to continue
if(game.playAgain())
{
game.resetGame();
turn = 1;
}
else
{
System.out.println(“Thank you for playing TIC-TAC-TOE!”);
break;
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
output
********************************
********************************
********************************
********* **********
********* TIC TAC TOE **********
********* **********
********* **********
********************************
********************************
********************************
Press any key to continue…
Player, enter your name
Enter a single word with alpha chars only!
human
TIC-TAC-TOE
|———–|
| 0 | 1 | 2 |
|———–|
| 3 | 4 | 5 |
|———–|
| 6 | 7 | 8 |
|———–|
It is human’s move
Give me your best move!
1
TIC-TAC-TOE
|———–|
| 0 | H | 2 |
|———–|
| 3 | 4 | 5 |
|———–|
| 6 | 7 | 8 |
|———–|
TIC-TAC-TOE
|———–|
| 0 | H | 2 |
|———–|
| 3 | 4 | C |
|———–|
| 6 | 7 | 8 |
|———–|
It is human’s move
Give me your best move!
2
TIC-TAC-TOE
|———–|
| 0 | H | H |
|———–|
| 3 | 4 | C |
|———–|
| 6 | 7 | 8 |
|———–|
TIC-TAC-TOE
|———–|
| 0 | H | H |
|———–|
| 3 | 4 | C |
|———–|
| C | 7 | 8 |
|———–|
It is human’s move
Give me your best move!
3
TIC-TAC-TOE
|———–|
| 0 | H | H |
|———–|
| H | 4 | C |
|———–|
| C | 7 | 8 |
|———–|
TIC-TAC-TOE
|———–|
| 0 | H | H |
|———–|
| H | C | C |
|———–|
| C | 7 | 8 |
|———–|
It is human’s move
Give me your best move!
3
Position not available.
Make a different choice.
It is human’s move
Give me your best move!
7
TIC-TAC-TOE
|———–|
| 0 | H | H |
|———–|
| H | C | C |
|———–|
| C | H | 8 |
|———–|
TIC-TAC-TOE
|———–|
| 0 | H | H |
|———–|
| H | C | C |
|———–|
| C | H | C |
|———–|
It is human’s move
Give me your best move!
0
TIC-TAC-TOE
|———–|
| H | H | H |
|———–|
| H | C | C |
|———–|
| C | H | C |
|———–|
Player human wins!
Game over! Play again ? y/n:
y
********************************
********************************
********************************
********* **********
********* TIC TAC TOE **********
********* **********
********* **********
********************************
********************************
********************************
Press any key to continue…
Player, enter your name
Enter a single word with alpha chars only!
alice
TIC-TAC-TOE
|———–|
| 0 | 1 | 2 |
|———–|
| 3 | 4 | 5 |
|———–|
| 6 | 7 | 8 |
|———–|
It is alice’s move
Give me your best move!
1
TIC-TAC-TOE
|———–|
| 0 | H | 2 |
|———–|
| 3 | 4 | 5 |
|———–|
| 6 | 7 | 8 |
|———–|
TIC-TAC-TOE
|———–|
| 0 | H | 2 |
|———–|
| 3 | C | 5 |
|———–|
| 6 | 7 | 8 |
|———–|
It is alice’s move
Give me your best move!
5
TIC-TAC-TOE
|———–|
| 0 | H | 2 |
|———–|
| 3 | C | H |
|———–|
| 6 | 7 | 8 |
|———–|
TIC-TAC-TOE
|———–|
| 0 | H | 2 |
|———–|
| C | C | H |
|———–|
| 6 | 7 | 8 |
|———–|
It is alice’s move
Give me your best move!
2
TIC-TAC-TOE
|———–|
| 0 | H | H |
|———–|
| C | C | H |
|———–|
| 6 | 7 | 8 |
|———–|
TIC-TAC-TOE
|———–|
| C | H | H |
|———–|
| C | C | H |
|———–|
| 6 | 7 | 8 |
|———–|
It is alice’s move
Give me your best move!
8
TIC-TAC-TOE
|———–|
| C | H | H |
|———–|
| C | C | H |
|———–|
| 6 | 7 | H |
|———–|
Player alice wins!
Game over! Play again ? y/n:
n