Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

please answer correctly and show working code and output. Also tictactoe.java is

ID: 3856812 • Letter: P

Question

please answer correctly and show working code and output. Also tictactoe.java is given below

Tic-Tac-Toe++

You will implement a variation of the game tic-tac-toe. Our version of the game will allow for different sizes of the board and a different winning condition. The game you are (or might be) familiar with is played on a 3x3 grid. Our normal game is played on a 10x10 grid and the winning condition is that a player (either X or O) has ten of their symbol in a row (either vertically, horizontally or diagonally). In general, a game can be played any NxM grid and the winning condition will be when K of the same symbols are in a row (again, either vertically, horizontally or diagonally). Here, N, M and K will be specified by an initialization file that your game will read when it starts. We will use N-M-K to denote the parameters of a given game. For example, a regular real life game of tic-tac-toe is a 3-3-3 game, our default game is a 10-10-10 game, and a 12-5-4 game has a grid with 12 rows, 5 columns and the winning condition is 4 of the same symbols in a row.

Start by cloning this repository. It has start-up code (skeleton files) for the assignment that you will modify, commit and then push back to you github repository. The start-up consists of a single Java class (called TicTacToeGame.java), an initialization file for the game (called init) and single plain text file (called submit-01). You will modify the TicTacToeGame.java and submit.1 files, commit your changes, and then push them back in order to submit your assignment.

If there is a method declared in the starter TicTacToeGame.java file, you must complete it. In particular, for this assignment, you must complete the win method. Do not change its modifiers, return type, argument list or name though. As part of testing, we will call your win method from a testing program with various inputs without running your game. If anything other than the body of the method is modified by you, we will not be able to test it and you will receive zero marks for this part. We will, of course, also run your game to test the actual game play.

init [0 marks]

The initialization file consists of three lines that specify N, M and K, respectively for the game. N is the number of rows in the grid, M is the number of columns and K is the number of symbols needed in a row to trigger a win. You do not have to submit (commit and push) this file. However, you should be using this file to test that your code works on a game that is not standard if you want full marks for the assignment. The default game is a regular game of tic-tac-toe with all parameters equal to 10. We will test your code with the default values and various different configurations (N,M,K values). See the rubric for more details.

TicTacToeGame.java [90 marks]

The game is a two player text-based game between either two human players or between one human player and the computer. Players take turns entering a position in the grid that they would like to play their symbol. The game is won when a players plays a symbol and that move completes a row/column/diagaonal of at least K of that symbol. If the entire grid is filled with symbols and there is no winner then the game is a draw.

Valid input for a position to play is a line of text of the form RR r CC c or CC c RR r, where RR is any case variant of the string "ROW" or "R", r is a number (using digits, not in words), CC is any case variant of the string "COLUMN", "COL" or "C", and c is a number. For example, each of the following are valid inputs

while

are invalid. Note that the first row or column is indicated with 0 and NOT 1.

The game uses command line arguments to specify if it will be a human-human or human-computer game.

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

BELOW IS TICTACTOE.JAVA

/** COMP 1006/1406 * Summer 2017 * * Assignment 1 */ 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;
public class TTTConsoleNonOO2P {
// Name-constants to represent the seeds and cell contents
public static final int EMPTY = 0;
public static final int CROSS = 1;
public static final int NOUGHT = 2;

// Name-constants to represent the various states of the game
public static final int PLAYING = 0;
public static final int DRAW = 1;
public static final int CROSS_WON = 2;
public static final int NOUGHT_WON = 3;

// The game board and the game status
public static final int ROWS = 3, COLS = 3; // number of rows and columns
public static int[][] board = new int[ROWS][COLS]; // game board in 2D array
// containing (EMPTY, CROSS, NOUGHT)
public static int currentState; // the current state of the game
// (PLAYING, DRAW, CROSS_WON, NOUGHT_WON)
public static int currentPlayer; // the current player (CROSS or NOUGHT)
public static int currntRow, currentCol; // current seed's row and column

public static Scanner in = new Scanner(System.in); // the input Scanner

/** The entry main method (the program starts here) */
public static void main(String[] args) {
// Initialize the game-board and current status
initGame();
// Play the game once
do {
playerMove(currentPlayer); // update currentRow and currentCol
updateGame(currentPlayer, currntRow, currentCol); // update currentState
printBoard();
// Print message if game-over
if (currentState == CROSS_WON) {
System.out.println("'X' won! Bye!");
} else if (currentState == NOUGHT_WON) {
System.out.println("'O' won! Bye!");
} else if (currentState == DRAW) {
System.out.println("It's a Draw! Bye!");
}
// Switch player
currentPlayer = (currentPlayer == CROSS) ? NOUGHT : CROSS;
} while (currentState == PLAYING); // repeat if not game-over
}

/** Initialize the game-board contents and the current states */
public static void initGame() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
board[row][col] = EMPTY; // all cells empty
}
}
currentState = PLAYING; // ready to play
currentPlayer = CROSS; // cross plays first
}

/** Player with the "theSeed" makes one move, with input validation.
Update global variables "currentRow" and "currentCol". */
public static void playerMove(int theSeed) {
boolean validInput = false; // for input validation
do {
if (theSeed == CROSS) {
System.out.print("Player 'X', enter your move (row[1-3] column[1-3]): ");
} else {
System.out.print("Player 'O', enter your move (row[1-3] column[1-3]): ");
}
int row = in.nextInt() - 1; // array index starts at 0 instead of 1
int col = in.nextInt() - 1;
if (row >= 0 && row < ROWS && col >= 0 && col < COLS && board[row][col] == EMPTY) {
currntRow = row;
currentCol = col;
board[currntRow][currentCol] = theSeed; // update game-board content
validInput = true; // input okay, exit loop
} else {
System.out.println("This move at (" + (row + 1) + "," + (col + 1)
+ ") is not valid. Try again...");
}
} while (!validInput); // repeat until input is valid
}

/** Update the "currentState" after the player with "theSeed" has placed on
(currentRow, currentCol). */
public static void updateGame(int theSeed, int currentRow, int currentCol) {
if (hasWon(theSeed, currentRow, currentCol)) { // check if winning move
currentState = (theSeed == CROSS) ? CROSS_WON : NOUGHT_WON;
} else if (isDraw()) { // check for draw
currentState = DRAW;
}
// Otherwise, no change to currentState (still PLAYING).
}

/** Return true if it is a draw (no more empty cell) */
// TODO: Shall declare draw if no player can "possibly" win
public static boolean isDraw() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
if (board[row][col] == EMPTY) {
return false; // an empty cell found, not draw, exit
}
}
}
return true; // no empty cell, it's a draw
}

/** Return true if the player with "theSeed" has won after placing at
(currentRow, currentCol) */
public static boolean hasWon(int theSeed, int currentRow, int currentCol) {
return (board[currentRow][0] == theSeed // 3-in-the-row
&& board[currentRow][1] == theSeed
&& board[currentRow][2] == theSeed
|| board[0][currentCol] == theSeed // 3-in-the-column
&& board[1][currentCol] == theSeed
&& board[2][currentCol] == theSeed
|| currentRow == currentCol // 3-in-the-diagonal
&& board[0][0] == theSeed
&& board[1][1] == theSeed
&& board[2][2] == theSeed
|| currentRow + currentCol == 2 // 3-in-the-opposite-diagonal
&& board[0][2] == theSeed
&& board[1][1] == theSeed
&& board[2][0] == theSeed);
}

/** Print the game board */
public static void printBoard() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
printCell(board[row][col]); // print each of the cells
if (col != COLS - 1) {
System.out.print("|"); // print vertical partition
}
}
System.out.println();
if (row != ROWS - 1) {
System.out.println("-----------"); // print horizontal partition
}
}
System.out.println();
}

/** Print a cell with the specified "content" */
public static void printCell(int content) {
switch (content) {
case EMPTY: System.out.print(" "); break;
case NOUGHT: System.out.print(" O "); break;
case CROSS: System.out.print(" X "); break;
}
}
}

public class Board { // save as Board.java
// Named-constants for the dimensions
public static final int ROWS = 3;
public static final int COLS = 3;

// package access
Cell[][] cells; // a board composes of ROWS-by-COLS Cell instances
int currentRow, currentCol; // the current seed's row and column

/** Constructor to initialize the game board */
public Board() {
cells = new Cell[ROWS][COLS]; // allocate the array
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
cells[row][col] = new Cell(row, col); // allocate element of the array
}
}
}

/** Initialize (or re-initialize) the contents of the game board */
public void init() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
cells[row][col].clear(); // clear the cell content
}
}
}

/** Return true if it is a draw (i.e., no more EMPTY cell) */
public boolean isDraw() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
if (cells[row][col].content == Seed.EMPTY) {
return false; // an empty seed found, not a draw, exit
}
}
}
return true; // no empty cell, it's a draw
}

/** Return true if the player with "theSeed" has won after placing at
(currentRow, currentCol) */
public boolean hasWon(Seed theSeed) {
return (cells[currentRow][0].content == theSeed // 3-in-the-row
&& cells[currentRow][1].content == theSeed
&& cells[currentRow][2].content == theSeed
|| cells[0][currentCol].content == theSeed // 3-in-the-column
&& cells[1][currentCol].content == theSeed
&& cells[2][currentCol].content == theSeed
|| currentRow == currentCol // 3-in-the-diagonal
&& cells[0][0].content == theSeed
&& cells[1][1].content == theSeed
&& cells[2][2].content == theSeed
|| currentRow + currentCol == 2 // 3-in-the-opposite-diagonal
&& cells[0][2].content == theSeed
&& cells[1][1].content == theSeed
&& cells[2][0].content == theSeed);
}


public void paint() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
cells[row][col].paint(); itself
if (col < COLS - 1) System.out.print("|");
}
System.out.println();
if (row < ROWS - 1) {
System.out.println("-----------");
}
}
}
}

=======================================================================================

import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.*;

public class TicTacToe {

public static Game game;
public static int count = 0;
public static String user_input;
  
private static int gameMode;
private static boolean valid_input;
  
public static void main(String[] args){
  
int gameSize;
int minimumGameSize = 1;
int maximumGameSize = 26;
  
//When program starts, user is met with a welcome message
System.out.println(" Welcome to this wonderful and lovely game of TicTacToe.");
System.out.println(" Please select your Game mode.");
System.out.println(" (1) Human vs. Computer");
System.out.println(" (2) Computer vs. Computer");
user_input = getInput(" Which mode would you like to play? (1/2): ");
  
//Keep asking for an answer from the user until we get a 1 or a 2
gameMode(user_input); //gameMode() is defines below
  
System.out.println(" How large of a grid would you like to use? ");
user_input = getInput(" Please enter an integer between " + minimumGameSize + " and " + maximumGameSize + ": ");
  
//validate user unput for game size
valid_input = false;
while(!valid_input){
  
if( user_input.length() > 0 && (user_input.substring(0, 1).matches("[1-9]")) && (minimumGameSize <= Integer.parseInt(user_input)) && (Integer.parseInt(user_input) <= maximumGameSize) ){
  
valid_input = true;
  
} else {
  
user_input = getInput(" You must enter a number between " + minimumGameSize + " and " + maximumGameSize + ": ");
  
}
}
  
//issue warning for game sizes larger than 15
if(Integer.parseInt(user_input) > 15){
  
System.out.println(" !!WARNING!! !!WARNING!! Games large than 15 will not display correctly if console width is restricted to 80 col (neither will this message) !!WARNING!!");
getInput("");
  
}
  
gameSize = Integer.parseInt(user_input);
  
//Create a new Game instance
game = new Game(gameSize);
  
//create an array of two players
Player[] players = new Player[2];
  
//set players to AI or Human depending on game mode
if(gameMode==1){
  
players[0] = new Player("Human");
players[1] = new Player("AI");
  
} else {
  
players[0] = new Player("AI");
players[1] = new Player("AI");
  
}
  
//Draw the blank board initially to show user which columns and rows to choose from
System.out.println(game.output());
  
//until the game is over, go back and forth between players in players array
//output the game map to the screen after each move
while (!game.finished) {
  
for(Player player : players){
  
player.go();
System.out.println(" " + game.output());
count += 1;
  
if(game.finished){
break;
}
  
}
}
  
//output an ending message to the game
if (game.draw) {
  
System.out.println(" Cat's game!");
  
} else {
  
//count variable from earlier is used to decide who went last and therefore won.
if(count%2==1){
  
System.out.println(" X's win!");
  
} else {
  
System.out.println(" O's win!");
  
}
}
}
  
//encapsulated code for input stream buffer
public static String getInput(String prompt) {
  
BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in));
  
System.out.print(prompt);
System.out.flush();
  
try {
  
return stdin.readLine();
  
} catch (Exception e) {
  
return "Error: " + e.getMessage();
  
}
}
  
//validates user input and sets the game mode
private static void gameMode(String user_input) {
  
valid_input = false;
  
while(!valid_input){
  
if((user_input.length() == 1) && (user_input.substring(0,1).matches("[1-2]"))){
  
valid_input = true;
  
} else {
  
user_input = getInput(" You must enter '1' or '2' for the game mode: ");
  
}
}
  
//Set user input to gameMode for use later
gameMode = Integer.parseInt(user_input);
  
}
}