Here is a list of the specifications for your submission. Read the entire list a
ID: 3857489 • Letter: H
Question
Here is a list of the specifications for your submission. Read the entire list and decide which items should be considered first. Don't try and finish the entire assignment in one sitting. Programming is an incremental process. Do one thing at a time (starting early) and you will that progress is being made.
You must use the Scanner class for user input (from the keyboard).
You must use a 2-dimensional array of type Character to represent the game grid.
You can use String and StringBuilder objects as you need.
You should not use any other classes in your code. There will be some other classes for reading the init file, but you won't be coding with these yourself in this assignment. You can use always the Math class if you wish.
Your main method will drive your game by calling other static methods in your class. The overall control flow of your game will be in main but the details of the different actions will be in other static methods.
Particular tasks should have their own method. (This is procedural programming!)
If zero command line arguments are given then your game will be between one human player and the computer. The human player will play first and they will play X. The computer will initially be O and play second.
If one command line argument is given and it is the string 2p, then the game will be between two human players. Player 1 will start with X (and player 2 will be O). Do not ask the players for their names. They are simply player 1 and player 2.
A game ends when either a player wins or all positions are played and there is no winner (a draw). You do not need to recognize a draw until the entire grid is filled. (A better version of the game would determine if at any point in the game is must end in a draw. You are not responsible for this.)
When a game ends, a user friendly message will say which player won the game (player 1 or player 2 or computer) and how many symbols in a row they won with. This number might be greater than K (if K is smaller then N and/or M).
Your program will let a player (or players) play as many games as they wish. After the user friendly message is displayed when a game ends the user (or users) is asked if they would like to player another game or end. The answer to this question (text input) will be yes or no (in lower case only).
When a new game is started, the player that previously started the game will now play second and the player that previously stated second will start the game. The starting player will always play the symbol X, but their name(denoted player 1 or player 2 or computer) will remain fixed. In each subsequent game, the player that starts will change (alternate).
The game grid will be displayed (showing all X's, O's and blanks) after each move is played (by either a human player or the computer). When the computer plays a move, a line of text stating its move should be be displayed before the grid is shown.
Your game must be user friendly. That is, it must provide useful prompts to the user during the game.
You can assume that all input text is valid. That is, we will only test your code with input that follows this specification.
If a user enters a position to play that is not allowed, because there is already a symbol in that position or the position does not exist in the grid, a useful message is displayed to the screen and they are asked to enter another position. This repeats until a position is played that is currently empty in the grid. An example of a position that does not exists is trying to play in position r 12 c 4 in 10-10-10 game.
When the user(s) decide to stop playing, after completing a game, some statistics will be displayed. You will output the total number of games played, the total number of wins by each player, the total number of draws, and the largest winning row/column/diagonal of any game played. For example, the output might look like
There will be no other input asked for or expected from the user during the game.
Your game must play a valid game of tic-tac-toe++.
Remember to push your changes back to your master repository on GitHib (so that your assignment can be graded).
Example
A run of a human versus computer 2-4-3 game might look like the following
The code is the bellow just complete it:
import java.util.Scanner; import java.io.FileReader; import java.io.BufferedReader; public class TicTacToeGame{ /** symbol for X */ public static final Character ex = 'X'; /** symbol for O */ public static final Character oh = 'O'; /** symbol for empty grid element */ public static final Character empty = ' '; /** board is the grid that the game is played on; * each element must be one of ex, oh or empty*/ public static Character[][] board; /** rows is the number of rows (N) in the game board */ public static int rows; /** columns is the number of columns (M) in the game board */ public static int columns; /** win_condition is the value of K, the winning condition of the game */ public static int win_condition; /** specifies if the game is 1p (human-human) or 2p (human-computer) */ public static boolean human_human_game; /** Checks for a win based on the last symbol played in the game * * It is assumed that the position specified by the last_row_played * and last_column_played is valid and that the symbol in the board * at that position is not empty. (It must be <em>ex</em> or <em>oh</em>) * * @param last_row_played is the row of the last symbol played * @param last_column_played is the column of the last symbol played * @return the length of the winning row/column/diagonal of symbols * if the last move is a winning move, or -1 if the last move is not * a winning move. */ public static int win(int last_row_played, int last_column_played){ // add your code and change the return value return -2; } /** main method to run the game * * @param args optional command line arguments to * specify if the game is 1p (human-computer) or * 2p (human-human). Expect the string "2p" if any * command line argument is given. */ public static void main(String[] args){ /*------------------------------------------ * handle command line arguments if any * to determine if the game is human-human * or human-computer *------------------------------------------*/ if( args.length > 0){ /* there are commend line arguments present */ // add your code here }else{ /* there are no command line argument present */ // add your code here } /*------------------------------------ * read N-M-K data from init file * N = rows * M = columns * K = win_condition *------------------------------------*/ /*------------------------------------- *------------------------------------- * BEGIN : Do NOT change the code here *-------------------------------------*/ BufferedReader file_input; FileReader file; String file_name = "init"; String line; try{ file = new FileReader(file_name); file_input = new BufferedReader(file); line = file_input.readLine(); rows = Integer.parseInt(line); line = file_input.readLine(); columns = Integer.parseInt(line); line = file_input.readLine(); win_condition = Integer.parseInt(line); /* always close your files you are done with them! */ file_input.close(); }catch(Exception e){ /* somethine went wrong! */ System.err.println("Failure to read data from init file properly"); System.err.println(e); System.err.println("Program ending"); return; } /*------------------------------------- * END : Do NOT change the code here *------------------------------------- *-------------------------------------*/ /* create and initialize the game board */ /* allocate memory for the board array */ board = new Character[rows][columns]; // add code to initialize all elements to empty /* code to drive the game */ // add your code here } }Explanation / Answer
import java.util.Scanner;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Random;
//testing
public class TicTacToeGame{
/** symbol for X */
public static final Character ex = 'X';
/** symbol for O */
public static final Character oh = 'O';
/** symbol for empty grid element */
public static final Character empty = ' ';
/** board is the grid that the game is played on;
* each element must be one of ex, oh or empty*/
public static Character[][] board;
/** rows is the number of rows (N) in the game board */
public static int rows;
/** columns is the number of columns (M) in the game board */
public static int columns;
/** win_condition is the value of K, the winning condition of the game */
public static int win_condition;
/** specifies if the game is 1p (human-human) or 2p (human-computer) */
public static boolean human_human_game;
//array to store game stats
public static int[] gameData;
//stores who is moving
public static int currentPlayer;
//moves counter
public static int moveCount;
//test count for running multiple times
public static int testCount = 0;
/** main method to run the game
*
* @param args optional command line arguments to
* specify if the game is 1p (human-computer) or
* 2p (human-human). Expect the string "2p" if any
* command line argument is given.
*/
public static void main(String[] args){
/*------------------------------------------
* handle command line arguments if any
* to determine if the game is human-human
* or human-computer
*------------------------------------------*/
//game switch
if( args.length > 0){
/* there are commend line arguments present */
human_human_game = true;
System.out.println("This is a 2 player game.");
} else {
/* there are no command line argument present */
// add your code here
human_human_game = false;
System.out.println("This is a computer game.");
}
/*------------------------------------
* read N-M-K data from init file
N = rows
M = columns
K = win_condition
*------------------------------------*/
/*-------------------------------------
*-------------------------------------
* BEGIN : Do NOT change the code here
*-------------------------------------*/
BufferedReader file_input;
FileReader file;
String file_name = "init";
String line;
try{
file = new FileReader(file_name);
file_input = new BufferedReader(file);
line = file_input.readLine();
rows = Integer.parseInt(line);
line = file_input.readLine();
columns = Integer.parseInt(line);
line = file_input.readLine();
win_condition = Integer.parseInt(line);
/* always close your files you are done with them! */
file_input.close();
}catch(Exception e){
/* somethine went wrong! */
System.err.println("Failure to read data from init file properly");
System.err.println(e);
System.err.println("Program ending");
return;
}
/*-------------------------------------
* END : Do NOT change the code here
*-------------------------------------
*-------------------------------------*/
/* create and initialize the game board */
/* allocate memory for the board array */
board = new Character[rows][columns];
gameData = new int[5];
/** game data array
0 : games played
1 : player one wins
2 : opponent wins
3 : draws
4 : best win
*/
gameData[0] = 0;
gameData[1] = 0;
gameData[2] = 0;
gameData[3] = 0;
gameData[4] = 0;
/* code to drive the game */
// add your code here
gameInit();
//enter move message
}
//method to initialize game
public static void gameInit() {
moveCount = 0;
currentPlayer = 1;
clearBoard();
humanMove();
}
/**method to get move input
* send to :
-addToBoard function
*/
public static void humanMove() {
/* testing */
computerMove();
return;
/*
Scanner keyboard;
keyboard = new Scanner(System.in);
int row;
int col;
int swap;
String a;
String b;
System.out.print("Player "+currentPlayer+" move : ");
a = keyboard.next();
a = textChange(a);
//check for end game command
if (a.equals("end")) {
System.exit(0);
}
row = keyboard.nextInt();
b = keyboard.next();
b = textChange(b);
col = keyboard.nextInt();
//checks for valid inputs and swaps value if needed
while (true) {
if (((b.equals("r"))||(b.equals("row"))) && ((a.equals("c"))||(a.equals("col"))||(a.equals("column")))) {
swap = row;
row = col;
col = swap;
addToBoard(row, col);
break;
} else if (((a.equals("r"))||(a.equals("row"))) && ((b.equals("c"))||(b.equals("col"))||(b.equals("column")))) {
row = row;
col = col;
addToBoard(row, col);
break;
} else {
System.out.println("Invalid input!");
humanMove();
break;
}
}
*/
}
/** Checks for a win based on the last symbol played in the game
*
* It is assumed that the position specified by the last_row_played
* and last_column_played is valid and that the symbol in the board
* at that position is not empty. (It must be <em>ex</em> or <em>oh</em>)
*
* @param last_row_played is the row of the last symbol played
* @param last_column_played is the column of the last symbol played
* @return the length of the winning row/column/diagonal of symbols
* if the last move is a winning move, or -1 if the last move is not
* a winning move.
*/
public static int win(int last_row_played, int last_column_played){
char player = board[last_row_played][last_column_played];
int x = last_row_played;
int y = last_column_played;
if ((horizontalCheck(x,y))||(verticalCheck(x,y))||(diagonalCheck(x,y))) {
gameOver();
return win_condition;
}
if (moveCount == (rows*columns)-1) {
System.out.println("Draw!");
gameOver();
return -1;
}
gameSwitch();
return -1;
}
/**statistics method
* updates gameData info
* inputs :
-draw boolean
*/
public static void statistics(boolean draw) {
//total games += 1
gameData[0] += 1;
if (!draw) {
if (currentPlayer == 1) {
//player one wins
gameData[1] += 1;
} else {
//opponent wins
gameData[2] += 1;
}
if (win_condition > gameData[4]) {
//new best win
gameData[4] = win_condition;
}
} else {
//add to draw count
gameData[3] += 1;
}
}
/**method for horizontal check
* inputs :
@param row
@param column
* outputs :
-win boolean
*/
public static boolean horizontalCheck(int row, int col) {
int right = 1;
int left = 1;
int horizontal = 1;
while((col + right) < columns) {
if (board[row][col] == board[row][col+right]) {
horizontal += 1;
} else {
break;
}
right += 1;
}
while((col - left) >= 0) {
if (board[row][col] == board[row][col-left]) {
horizontal += 1;
} else {
break;
}
left += 1;
}
if (horizontal >= win_condition) {
System.out.println("Horizontal Win! at : "+row +" "+ col);
return true;
}
return false;
}
/**method for vertical check
* inputs :
@param row
@param column
* outputs :
-win boolean
*/
public static boolean verticalCheck(int row, int col) {
int up = 1;
int down = 1;
int vertical = 1;
while((row + down) < rows) {
if (board[row][col] == board[row+down][col]) {
vertical += 1;
} else {
break;
}
down += 1;
}
while((row - up) >= 0) {
if (board[row][col] == board[row-up][col]) {
vertical += 1;
} else {
break;
}
up += 1;
}
if (vertical >= win_condition) {
System.out.println("Vertical Win! at : "+row +" "+ col);
return true;
}
return false;
}
/**method for diagonal check
* inputs :
@param row
@param column
* outputs :
-win boolean
*/
public static boolean diagonalCheck(int row, int col) {
int upRight = 1;
int downLeft = 1;
int diag = 1;
while(((row - upRight) >= 0) && ((col + upRight) < columns)) {
if (board[row][col] == board[row-upRight][col+upRight]) {
diag += 1;
} else {
break;
}
upRight += 1;
}
while(((row + downLeft) < rows) && ((col - downLeft) >= 0)) {
if (board[row][col] == board[row+downLeft][col-downLeft]) {
diag += 1;
} else {
break;
}
downLeft += 1;
}
int downRight = 1;
int upLeft = 1;
int antiDiag = 1;
while(((row - upLeft) >= 0) && ((col + upLeft) < columns)) {
if (board[row][col] == board[row-upLeft][col+upLeft]) {
antiDiag += 1;
} else {
break;
}
upLeft += 1;
}
while(((row + downRight) < rows) && ((col - downRight) >= 0)) {
if (board[row][col] == board[row+downRight][col-downRight]) {
antiDiag += 1;
} else {
break;
}
downRight += 1;
}
if ((diag >= win_condition)||(antiDiag >= win_condition)) {
System.out.println("Diagonal Win! at : "+row +" "+ col);
return true;
}
return false;
}
/**game over display stats
* calls :
-displayStats function
gameInit function
*/
public static void gameOver() {
Scanner keyboard;
keyboard = new Scanner(System.in);
String game;
gameData[0] += 1;
displayStats();
System.out.println("Would you like to play again?");
//game = keyboard.next();
testCount += 1;
if (testCount < 1) {
gameInit();
}
/*testing
if (game.equals("yes")) {
gameInit();
}
*/
}
//display game info
public static void displayStats() {
System.out.println("Game Over!");
System.out.println("Total games played: "+gameData[0]);
System.out.println("Player one wins: "+gameData[1]);
System.out.println("Opponent wins: "+gameData[2]);
System.out.println("Draws: "+gameData[3]);
System.out.println("Best win: "+gameData[4]);
}
/**computer move
* @sends to :
-addToBoard
*/
public static void computerMove() {
System.out.println("Starting computer move");
Random rand = new Random();
int row;
int col;
boolean played = true;
do {
row = rand.nextInt(rows);
col = rand.nextInt(columns);
if (board[row][col] == empty) {
System.out.println(row+""+col);
played = false;
addToBoard(row,col);
break;
}
} while (played);
}
//method to control game flow path
public static void gameSwitch() {
moveCount += 1;
if ((human_human_game == false) && (currentPlayer == 1)) {
currentPlayer = 3;
computerMove();
return;
}
if ((human_human_game == true) && (currentPlayer == 1)) {
currentPlayer = 2;
humanMove();
return;
}
if (currentPlayer != 1) {
currentPlayer = 1;
/*testing mode
humanMove();
*/
computerMove();
return;
}
}
//method for converting string input to good format
public static String textChange(String i) {
i = i.toLowerCase();
i = i.trim();
return i;
}
/*method to display the board*/
public static void drawBoard() {
System.out.println(moveCount);
System.out.print(" ");
for (int x = 0; x < columns; x++) {
System.out.print(x + " ");
}
System.out.println("");
for (int r = 0; r < rows; r++) {
System.out.print(r + "");
for (int c = 0; c < columns; c++) {
System.out.print("|" + board[r][c] );
if (c == (columns-1)) {
System.out.print("|");
System.out.print(" ");
}
}
}
/*
for (int y = 0;y < rows; y++) {
System.out.print("|");
for (int z = 0;z < columns; z++) {
System.out.print(board[y][z] + "|");
if (z == 9) {
System.out.print(" ");
}
}
}
*/
}
/*method to clear board*/
public static void clearBoard() {
for (int i = 0; i < rows; i++) {
for (int x = 0; x < columns; x++) {
board[i][x] = empty;
}
}
}
/**method to add to board
* inputs :
-row
-column
* sends to :
-drawBoard function
-win function
*/
public static void addToBoard(int row, int col) {
if (board[row][col] == empty) {
if (currentPlayer == 1) {
board[row][col] = ex;
} else {
board[row][col] = oh;
}
drawBoard();
if (moveCount > (win_condition*2)-1) {
win(row,col);
} else {
gameSwitch();
}
} else {
System.out.println("Already taken!");
humanMove();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.