I've been working on for awhile but i can't seem to fix it and get it to wrong correctly. It tells me where the exception is but I don't see any problems.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at TicTacToe.displayWinner(TicTacToe.java:243)
at TicTacToe.playerMove(TicTacToe.java:151)
at TicTacToe.playGame(TicTacToe.java:303)
at TicTacToeTester.main(TicTacToeTester.java:20)
Java Result: 1
import java.util.Scanner; //Used for player's input in game
public class TicTacToe
{
//instance variables
private char[][] board; //Tic Tac Toe Board, 2d array
private boolean xTurn; // true when X's turn, false if O's turn
private Scanner input; // Scanner for reading input from keyboard
//Constants for creation of gameboard
public final int ROWS = 3; //total rows
public final int COLS = 3; //total columns
public final int WIN = 3; //amount needed to win
public TicTacToe()
{
//creates the board
board = new char[ROWS][COLS];
for(int r = 0; r < ROWS; r++)
{
for(int c = 0; c < COLS; c++)
{
board[r][c] = ' ';
}
}
//X's turn when game starts
xTurn = true;
//creates our input object for the turn player
input = new Scanner(System.in);
}
//shows game board
public void displayBoard()
{
int colNum = 0; //number of columns
int rowNum = 0; //number of rows
//creates column labels
System.out.println(" \n");
System.out.println(" Columns ");
for (int num = 0; num < COLS; num++)
{
System.out.print(" " + colNum);
colNum++;
}
//creates vertical columns and spaces between each spot
System.out.println(" \n");
for (int row = 0; row < ROWS; row++)
{
//numbers rows
System.out.print(" " + rowNum + " ");
rowNum++;
for (int col = 0; col < COLS; ++col)
{
System.out.print(board[row][col]); // print each of the cells
if (col != COLS - 1)
{
System.out.print(" | "); // print vertical partition
}
}
System.out.println();
//creates seperation of rows
if (row != ROWS - 1)
{
System.out.println(" ------------"); // print horizontal
partition
}
}
//labels row
System.out.println("Rows \n");
}
//displays turn player
public void displayTurn()
{
if (xTurn)
{
System.out.println("X's Turn");
}
else
{
System.out.println("O's Turn");
}
}
//allows you to make move
public boolean playerMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
while(invalid)
{
System.out.println("Which row (first) then column (second)
would you like to \n"
+ "play this turn? Enter 2 numbers between 0-2 as \n"
+ "displayed on the board, seperated by a space to
\n"
+ "choose your position.");
row = input.nextInt();
column = input.nextInt();
//checks if spot is filled
if (row >= 0 && row <= ROWS - 1 &&
column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
else
{
System.out.println("Invalid position");
}
//fills spot if not taken
if (xTurn)
{
board[row][column] = 'X';
}
else
{
board[row][column] = 'O';
}
}
return displayWinner(row,column);
}
public boolean displayWinner(int lastR, int lastC)
{
boolean winner = false;
int letter = board[lastR][lastC];
//checks row for win
int spotsFilled = 0;
for (int c = 0; c < COLS; c++)
{
if(board[lastR][c] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks columns for win
spotsFilled = 0;
for (int r = 0; r < ROWS; r++)
{
if(board[r][lastC] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks diagonals for win
spotsFilled = 0;
for (int i = 0; i < WIN; i++)
{
if(board[i][i] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-i] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
return winner;
}
//checks if board is full
public boolean fullBoard()
{
int filledSpots = 0;
for(int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
if (board[r][c] == 'X' || board[r][c] == 'O')
{
filledSpots++;
}
}
}
return filledSpots == ROWS*COLS;
}
//plays game
public void playGame()
{
boolean finish = true;
System.out.println("Are your ready to start?");
System.out.println("1 for Yes or 0 for No? : ");
int choice = input.nextInt();
if (choice == 1)
{
while (finish)
{
displayBoard();
displayTurn();
if (playerMove())
{
displayBoard();
}
else if (fullBoard())
{
displayBoard();
System.out.println("Draw");
}
else
{
xTurn=!xTurn;
}
}
}
}
}
my tester
public class TicTacToeTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
TicTacToe tictactoe = new TicTacToe();
tictactoe.playGame();
}
}
Your Player Move method has an issue take a look at this if you notice you have commented saying "// fills spot when not taken" but you misplaced the while loop bracket and included move part inside it so it threw that exception, just close the while loop bracket before moving as follows (also follow #oblivion Creations Answer these are the two issues with your code) :-
public boolean playerMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
while (invalid)
{
System.out.println("Which row (first) then column (second)" + "would you like to \n"
+ "play this turn? Enter 2 numbers between 0-2 as \n"
+ "displayed on the board, seperated by a space to" + "\n" + "choose your position.");
row = input.nextInt();
column = input.nextInt();
// checks if spot is filled
if (row >= 0 && row <= ROWS - 1 && column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
else
{
System.out.println("Invalid position");
}
} // close while loop here
// fills spot if not taken
if (xTurn)
{
board[row][column] = 'X';
}
else
{
board[row][column] = 'O';
}
return displayWinner(row, column);
}
The reason you are getting your exception is this section of code inside your displayWinner method:
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-i] == letter)
{
spotsFilled++;
}
}
When i = 0 then COLS-i will be 3. This is outside the bounds of your array.
There are multiple ways to solve this, one would be to increase i by 1 during comparison.
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-(i+1)] == letter)
{
spotsFilled++;
}
}
Edit: also make sure you check out Null Saints answer, as it will cause you headaches later if you don't address it now.
Related
This question already has answers here:
How do you stop a loop from running in Java
(3 answers)
Closed 4 years ago.
I'm working on a simple tic-tac-toe 4x4 game. I have input() function where user enters his data, printBoard() which prints the board itself, analyzeBoard() where are all the calculations for choosing the winner and done() which simply returns status. My problem is that even when I find the winner I can't stop input() working and it keeps printing board over and over. For the first time, I thought that problem is in analyzeBoard() but then I figured out that it actually returns everything I need and the problem is in input(). When I try to return from input, it either says missing return statement either just doesn't stop even though it can see the winner.
public char input ()
{
while (status == false || numberOfMovesLeft > 0)
{
System.out.println("User "+ whoseTurn + " enter your move: "); //prompt user to make a move
char userInput = reader.next().charAt(0); // local variable to hold user input
// validation of user input
while (userInput != 'a' && userInput != 'b' && userInput != 'c'
&& userInput != 'd' && userInput != 'e' && userInput != 'f'
&& userInput != 'g' && userInput != '1' && userInput != '2'
&& userInput != '3' && userInput != '5' && userInput != '6'
&& userInput != '6' && userInput != '7' && userInput != '8'
&& userInput != '9')
{
System.out.println("Try again, user "+ whoseTurn + " enter your move: ");
userInput = reader.next().charAt(0);
}
// places user input into a board cell
for (int row = 0; row < board.length; row++)
{
for (int col = 0; col < board[row].length; col++)
{
if (board[row][col] == userInput)
{
board[row][col] = whoseTurn;
}
}
}
// check for tie result
numberOfMovesLeft--;
if (numberOfMovesLeft==0)
{
System.out.println("Tie!");
winner = 'T';
System.out.println(winner);
}
analyzeBoard();
printBoard();
done();
whoseTurn = (whoseTurn == 'X') ? '0' : 'X';
}
return winner;
}
public void analyzeBoard()
{
// row winner algoritm
for (int row = 0; row <=3; row++)
{
for (int col = 0; col < 2; col++)
{
if (board[row][col] == board[row][col + 1]
&&
board[row][col] == board[row][col + 2])
{
System.out.println("winner");
winner = whoseTurn;
System.out.println("winner "+ winner);
System.out.println("whoseTurn "+ whoseTurn);
status = true;
System.out.println("status "+status);
done();
}
else
{
//System.out.println("status "+status);
}
}
}
//column winner algoritm
for (int row = 0; row <2; row++)
{
for (int col = 0; col <= 3; col++)
{
if (board[row][col] == board[row+1][col] &&
board[row][col] == board[row+2][col])
{
System.out.println("winner");
winner = whoseTurn;
System.out.println("winner "+ winner);
System.out.println("whoseTurn "+ whoseTurn);
status = true;
//System.out.println("status "+status);
}
}
}
//diagonal winner algoritm
for (int row = 0; row <2; row++)
{
for (int col = 0; col <2; col++)
{
if (board[row][col] == board[row+1][col+1] &&
board[row][col] == board[row+2][col+2])
{
System.out.println("winner");
winner = whoseTurn;
System.out.println("winner "+ winner);
System.out.println("whoseTurn "+ whoseTurn);
status = true;
//System.out.println("status "+status);
}
}
}
//diagonal winner algoritm
for (int row = 0; row <2; row++)
{
for (int col = 2; col <=3; col++)
{
if (board[row][col] == board[row+1][col-1])
{
System.out.println("winner");
winner = whoseTurn;
System.out.println("winner "+ winner);
System.out.println("whoseTurn "+ whoseTurn);
status = true;
//System.out.println("status "+status);
}
}
}
}
you can use break; to terminate current loop or return; to terminate entire function call.
I am trying to make a tic tac toe game and am new to java. I am getting outofbounds at the first if statement within the method isHorizontalWin and I am assuming it would happen within isVerticalWin as well. Correct me if I am wrong but I believe it is happening because part of gameboard has no value so the if statement is outofbounds however I am unsure in how to fix this. A side note: the formatting got messed up a little bit when pasting the code so I had to make some of the JOptionPanes go onto multiple lines to fit. Thanks!
import javax.swing.JOptionPane;
public class TicTacToe
{
public static void main(String[] args)
{
char gameboard[][] = new char[3][3];
printCurrentState(gameboard);
int Turn = 0;
int gameon=0;
while(gameon<9)
{
if(Turn==0)
{
JOptionPane.showMessageDialog(null, "Player 1's turn aka X");
}
else
{
JOptionPane.showMessageDialog(null, "Player 2's turn aka O");
}
boolean proceed=true;
String yo =JOptionPane.showInputDialog("Enter the row and column"+ "one"+
"after another. Example-for row 1 and comlumn 2 type \"12\"");
if(yo.length()!=2)
{
JOptionPane.showMessageDialog(null, "You did not put the row"+ "and column one after another- Try again");
proceed=false;
}
if(proceed==true) {
String aa= yo.charAt(0)+"";
int x = Integer.parseInt(aa)-1;
String ba= yo.charAt(1)+"";
int y = Integer.parseInt(ba)-1;
if((x < 0 || x > 2)||(y<0||y>2))
{
JOptionPane.showMessageDialog(null, "Please enter a row and"+
"column that both at least 1 and no bigger than 3. Try again!");
yo =JOptionPane.showInputDialog("Enter the row and column one"+
"after another. Example-for row 1 and comlumn 2 type \"12\"");
aa= yo.charAt(0)+"";
x = Integer.parseInt(aa)-1;
ba= yo.charAt(1)+"";
y = Integer.parseInt(ba)-1;
}
if(gameboard[x][y] == 'X' || gameboard[x][y] == 'O')
{
JOptionPane.showMessageDialog(null, "That is already taken"+
"by an "+ gameboard[x][y]+". Go again!");
yo =JOptionPane.showInputDialog("Enter the row and column"+
"one after another. Example-for row 1 and comlumn 2 type \"12\"");
aa= yo.charAt(0)+"";
x = Integer.parseInt(aa)-1;
ba= yo.charAt(1)+"";
y = Integer.parseInt(ba)-1;
}
if(Turn== 0)
{
gameboard[x][y] = 'X';
printCurrentState(gameboard);
isHorizontalWin(gameboard);
isVerticalWin(gameboard);
isDiagnolWin(gameboard);
Turn++;
}
else if(Turn == 1)
{
gameboard[x][y] = 'O';
printCurrentState(gameboard);
isHorizontalWin(gameboard);
isVerticalWin(gameboard);
isDiagnolWin(gameboard);
Turn--;
}
gameon++;
}
}
if(isHorizontalWin(gameboard)==false&&isVerticalWin(gameboard)==false&&isDiagnolWin(gameboard)==false)
{
JOptionPane.showMessageDialog(null, "There was no winner this game ");
}
}
public static void printCurrentState(char gameboard[][])
{
System.out.println(" COLUMN");
System.out.println(" 1 2 3");
System.out.print(gameboard[0][0] + " | " + gameboard[0][1] + " | " + gameboard[0][2] +" 1 R"+ "\n"
+ "--|---|--\n" +
gameboard[1][0] + " | " + gameboard[1][1] + " | " + gameboard[1][2] +" 2 O"+ "\n"
+ "--|---|--\n" +
gameboard[2][0] + " | " + gameboard[2][1] + " | " + gameboard[2][2] +" 3 W "+"\n");
System.out.println();
}
public static boolean isHorizontalWin(char[][] gameboard)
{
int tally[][]= new int[3][3];
for(int r = 0; r < 3; r++)
{
for(int c = 0; c < 3; r++)
{
if(gameboard[r][c]=='O')
{
tally[r][c]=10;
}
else if(gameboard[r][c]=='X')
{
tally[r][c]=1;
}
else
{
tally[r][c]=0;
}
}
}
int c=0;
for(int m = 0; m < 3; m++)
{
c++;
int cool = 0;
for(int n = 0; n < 3; n++)
{
cool += tally[m][n];
if(cool == 30)
{
JOptionPane.showMessageDialog(null, "Player 2(O) is the winner with a horizontal win in row " +c);
System.exit(0);
return true;
}
else if(cool==3)
{
JOptionPane.showMessageDialog(null, "Player 1(X) is the winner with a horizontal win in row " + c);
System.exit(0);
return true;
}
}
}
return false;
}
public static boolean isVerticalWin(char[][] gameboard)
{
int tally[][]= new int[3][3];
for(int r = 0; r < 3; r++)
{
for(int c = 0; c < 3; r++)
{
if(gameboard[r][c]=='O')
{
tally[r][c]=10;
}
else if(gameboard[r][c]=='X')
{
tally[r][c]=1;
}
else
{
tally[r][c]=0;
}
}
}
int r=0;
for(int m = 0; m < 3; m++)
{
r++;
int cool = 0;
for(int n = 0; n < 3; n++)
{
cool += tally[n][m];
if(cool == 30)
{
JOptionPane.showMessageDialog(null, "Player 2(O) is the winner with a vertical win in column " +r);
System.exit(0);
return true;
}
else if(cool==3)
{
JOptionPane.showMessageDialog(null, "Player 1(X) is the winner with a vertical win in column " + r);
System.exit(0);
return true;
}
}
}
return false;
}
public static boolean isDiagnolWin(char[][] gameboard)
{
if((gameboard[0][0]=='O'&&gameboard[1][1]=='O'&&gameboard[2][2]=='O')||(gameboard[0][2]=='O'&&gameboard[1][1]=='O'&&gameboard[3][1]=='O'))
{
JOptionPane.showMessageDialog(null, "Player 2(O) is the winner with a diagonal win" );
System.exit(0);
return true;
}
if((gameboard[0][0]=='X'&&gameboard[1][1]=='X'&&gameboard[2][2]=='X')||(gameboard[0][2]=='X'&&gameboard[1][1]=='X'&&gameboard[2][0]=='X'))
{
JOptionPane.showMessageDialog(null, "Player 1(X) is the winner with a diagonal win" );
System.exit(0);
return true;
}
return false;
}
}
In isHorizontalWin, you probably forgot to change the r++ into c++ in the second for loop.
This results into r being incremented too many times.
So when r reaches a number that is higher than the amount of entries, the index (r) is out of bounds.
for(int r = 0; r < 3; r++)
{
for(int c = 0; c < 3; r++)
{
Needs to be:
for(int r = 0; r < 3; r++)
{
for(int c = 0; c < 3; c++)
{
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I am making a tic tac toe game and one of the requirements is to have the game randomly decide who goes first. I assume I should be using Math.random() but I don't know how to implement it. If anyone can, please help adjust my code thanks :)
import java.util.Scanner;
public class TicTacToe
{
public static void main(String[] args)
{
Scanner console = new Scanner (System.in);
Game ticTacToe = new Game();
String no = "no";
System.out.println("~~~Tic Tac Toe~~~");
System.out.println("Would you like to play?");
String playerAnswer = console.nextLine();
while(!playerAnswer.equals(no))
{
ticTacToe.play();
System.out.println("Thanks for playing");
System.out.println("Would you like to play again? Press any key for yes, type no if you don't ");
playerAnswer=console.nextLine();
}
}
}
class Game
{
private final int empty = 0;
private final int player = 1;
private final int com = 2;
private final int size = 3;
private int[][] board;
public void printScreen()
{
int col;
int row;
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print(" " + (col+1));
}
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print("--");
}
System.out.println("-");
for (row = 0; row < size; row ++)
{
System.out.print((row+1) + "|");
for (col = 0; col < size; col ++)
{
if (board[row][col] == empty)
{
System.out.print(" ");
}
else if (board[row][col] == player)
{
System.out.print("X");
}
else if (board[row][col] == com)
{
System.out.print("O");
}
System.out.print("|");
}
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print("--");
}
System.out.println("-");
}
}
public void clear()
{
int col;
int row;
board = new int[size][size];
for (row = 0; row < size; row ++)
{
for (col = 0; col < size; col ++)
{
board[row][col] = empty;
}
}
}
public void computerMove()
{
int col;
int row;
int count;
int select;
count = 0;
for (row = 0; row < size; row ++)
for (col = 0; col < size; col ++)
if (board[row][col] == empty)
count ++;
select = (int) (Math.random() * count);
count = 0;
for (row = 0; row < size; row ++)
{
for (col = 0; col < size; col ++)
{
if (board[row][col] == empty)
{
if (count == select)
{
board[row][col] = com;
System.out.println("The computer selects row" + (row+1) + " column " + (col+1) + ".");
}
count ++;
}
}
}
}
public void playerMove()
{
Scanner console = new Scanner (System.in);
boolean a;
int col;
int row;
a = true;
while (a)
{
System.out.println("What is your move? Select a row number from 1 to " + size + " and a column number from 1 to " + size + ".");
row = console.nextInt();
col = console.nextInt();
if ((row < 1) || (row > size) || (col < 1) || (col > size))
{
System.out.println("Invalid choice, row " + row + " or column " + col + " must be from 1 to " + size + ".");
}
else
{
row --;
col --;
if (board[row][col] != empty)
{
System.out.println("That spot is already filled");
printScreen();
}
else
{
board[row][col] =player;
a = false;
}
}
}
}
public boolean checkWinner()
{
int col;
int row;
int count;
int win;
win = empty;
for (row = 0; row < size; row ++)
{
count = 0;
if (board[row][0] != empty)
for (col = 0; col < size; col ++)
if (board[row][0] == board[row][col])
count ++;
if (count == size)
win = board[row][0];
}
for (col = 0; col < size; col ++)
{
count = 0;
if (board[0][col] != empty)
for (row = 0; row < size; row ++)
if (board[0][col] == board[row][col])
count ++;
if (count == size)
win = board[0][col];
}
count = 0;
if (board[0][0] != empty)
for (row = 0; row < size; row ++)
if (board[0][0] == board[row][row])
count ++;
if (count == size)
win = board[0][0];
count = 0;
if (board[0][size-1] != empty)
for (row = 0; row < size; row ++)
if (board[0][size-1] == board[row][size-row-1])
count ++;
if (count == size)
win = board[0][size-1];
if (win != empty)
{
if (win == player)
System.out.println("Congratz you won");
else if(win == 3)
System.out.println("you lost");
return true;
}
count = 0;
for (row = 0; row < size; row ++)
for (col = 0; col < size; col ++)
if (board[row][col] == empty)
count ++;
if (count == 0)
{
System.out.println("Its a tie!");
return true;
}
return false;
}
public void play()
{
boolean e;
clear();
e=false;
while (!e)
{
printScreen();
playerMove();
printScreen();
e = checkWinner();
if (!e)
{
computerMove();
e = checkWinner();
if (e)
printScreen();
}
}
}
}
There may be many ways to do this including using a Random generator class, but as tic-tac only has two players, this can simply be done as getting a boolean
boolean player1Starts = (System.currentTimeMillis() % 2) == 0;
To implement this you would have to change your play method.
public void play()
{
boolean playerTurn = Math.random() <= .5
//this function returns a value between 0 an 1 exclusive
clear();
printScreen();
while (!checkWinner())
{
if (playerTurn) {
playerMove;
} else {
computerMove();
}
playerTurn = !playerTurn;
printScreen();
}
}
What this does is first determine if the player starts.
Then it clears and prints the empty board.
Then It loops through checking if there is a winner
If there isn't a winner we go into the loop and then if its the players turn they move else the computer moves
Then we update the playerTurn to be the opposite of what it was.
Then print the screen to see the move.
If there is a winner we exit the loop and finish the play method
I cannot get my write to file code working the error message- writeFile cannot be resolved. I a trying to write the board positions to a text file so the game can be saved. If the user chooses to save the game then it should call a new subroutine that will write the pieces to the file.
/*
* Skeleton program code for the AQA COMP1 Summer 2016 examination
* This code to be used in conjunction with the Preliminary Material
* written by the AQA Programmer Team
* Developed in the NetBeans 7.3.1. programming environment
* Additional classes AQAConsole2016, AQAReadTextFile2016 and
* AQAWriteTextFile2016 may be used.
*
* A package name may be chosen and private and public modifiers added -
* permission to make these changes to the Skeleton Program does not need
* to be obtained from AQA or the AQA Programmer
*/
import java.util.Random;
public class Aaa {
AQAConsole2016 console = new AQAConsole2016();
Random random = new Random();
int boardSize;
public Aaa() {
char choice;
String playerName;
// int boardSize;
boardSize = 6;
playerName = "";
do {
displayMenu();
choice = getMenuChoice(playerName);
switch (choice) {
case 'p' : playGame(playerName, boardSize);
break;
case 'e' : playerName = getPlayersName();
break;
case 'c' : boardSize = changeBoardSize();
break;
}
} while (choice != 'q');
}
void setUpGameBoard(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (row == (boardSize + 1) / 2 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2 + 1) {
board[row][column] = 'C';
} else {
if (row == (boardSize + 1) / 2 + 1 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2) {
board[row][column] = 'H';
} else {
board[row][column] = ' ';
}
}
}
}
}
int changeBoardSize() {
int boardSize;
do {
console.print("Enter a board size (between 4 and 9): ");
boardSize = console.readInteger("");
} while (!(boardSize >= 4 && boardSize <= 9));
return boardSize;
}
int getHumanPlayerMove(String playerName) {
int coordinates;
console.print(playerName + " enter the coordinates of the square where you want to place your piece: ");
coordinates = console.readInteger("");
return coordinates;
}
int getComputerPlayerMove(int boardSize) {
return ((random.nextInt(boardSize) + 1) * 10 + (random.nextInt(boardSize) + 1));
}
boolean gameOver(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == ' ')
return false;
}
}
return true;
}
String getPlayersName() {
String playerName;
console.print("What is your name? ");
playerName = console.readLine();
return playerName;
}
boolean checkIfMoveIsValid(char[][] board, int move) {
int row;
int column;
boolean moveIsValid;
row = move % 10;
column = move / 10;
moveIsValid = false;
if (((row<=boardSize) &&(row>0)) && ((column<=boardSize) && (column>0))){
if (board[row][column] == ' ') {
moveIsValid = true;
}
}
return moveIsValid;
}
int getPlayerScore(char[][] board, int boardSize, char piece) {
int score;
score = 0;
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == piece) {
score = score + 1;
}
}
}
return score;
}
boolean checkIfThereArePiecesToFlip(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipStillPossible;
boolean flipFound;
boolean opponentPieceFound;
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
flipStillPossible = true;
flipFound = false;
opponentPieceFound = false;
while (rowCount <= boardSize && rowCount >= 1 && columnCount >= 1 && columnCount <= boardSize && flipStillPossible && !flipFound ) {
if (board[rowCount][columnCount] == ' ') {
flipStillPossible = false;
} else {
if (board[rowCount][columnCount] != board[startRow][startColumn]) {
opponentPieceFound = true;
} else {
if (board[rowCount][columnCount] == board[startRow][startColumn] && !opponentPieceFound) {
flipStillPossible = false;
} else {
flipFound = true;
}
}
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
return flipFound;
}
void flipOpponentPiecesInOneDirection(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipFound;
flipFound = checkIfThereArePiecesToFlip(board, boardSize, startRow, startColumn, rowDirection, columnDirection);
if (flipFound) {
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
while (board[rowCount][columnCount] != ' ' && board[rowCount][columnCount] != board[startRow][startColumn]) {
if (board[rowCount][columnCount] == 'H') {
board[rowCount][columnCount] = 'C';
} else {
board[rowCount][columnCount] = 'H';
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
}
}
void makeMove(char[][] board, int boardSize, int move, boolean humanPlayersTurn) {
int row;
int column;
row = move % 10;
column = move / 10;
if (humanPlayersTurn) {
board[row][column] = 'H';
} else {
board[row][column] = 'C';
}
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, -1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, 1);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, -1);
}
void printLine(int boardSize) {
console.print(" ");
for (int count = 1; count <= boardSize * 2 - 1; count++) {
console.print("_");
}
console.println();
}
void displayGameBoard(char[][] board, int boardSize) {
console.println();
console.print(" ");
for (int column = 1; column <= boardSize; column++)
{
console.print(" ");
console.print(column);
}
console.println();
printLine(boardSize);
for (int row = 1; row <= boardSize; row++) {
console.print(row);
console.print(" ");
for (int column = 1; column <= boardSize; column++) {
console.print("|");
console.print(board[row][column]);
}
console.println("|");
printLine(boardSize);
console.println();
}
}
void displayMenu() {
console.println("(p)lay game");
console.println("(e)nter name");
console.println("(c)hange board size");
console.println("(q)uit");
console.println();
}
char getMenuChoice(String playerName) {
char choice;
console.print(playerName + " enter the letter of your chosen option: ");
choice = console.readChar();
return choice;
}
void playGame(String playerName, int boardSize) {
char[][] board = new char[boardSize + 1][boardSize + 1];
boolean humanPlayersTurn;
int move;
int humanPlayerScore;
int computerPlayerScore;
boolean moveIsValid;
setUpGameBoard(board, boardSize);
humanPlayersTurn = false;
int NoOfMoves=0;
do {
humanPlayersTurn = !humanPlayersTurn;
displayGameBoard(board, boardSize);
moveIsValid = false;
do {
if (humanPlayersTurn) {
move = getHumanPlayerMove(playerName);
} else {
move = getComputerPlayerMove(boardSize);
}
moveIsValid = checkIfMoveIsValid(board, move);
} while (!moveIsValid);
if (!humanPlayersTurn) {
NoOfMoves++;
console.println("The number of moves completed so far: " +NoOfMoves);
console.print("Press the Enter key and the computer will make its move");
console.readLine("");
}
makeMove(board, boardSize, move, humanPlayersTurn);
console.println();
String answer = console.readLine("Do you want to save the board? (y/n)");
if (answer.equalsIgnoreCase("y")){
writeBoard(board, boardSize);
console.println("Saved!");
}
} while (!gameOver(board, boardSize));
displayGameBoard(board, boardSize);
humanPlayerScore = getPlayerScore(board, boardSize, 'H');
computerPlayerScore = getPlayerScore(board, boardSize, 'C');
if (humanPlayerScore > computerPlayerScore) {
console.println("Well done, " + playerName + ", you have won the game!");
}
else {
if (humanPlayerScore == computerPlayerScore) {
console.println("that was a draw!");
} else {
console.println("The computer has won the game!");
}
console.println();
}
}
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
public static void main(String[] args) {
new Aaa();
}
}
This Section contains the errors:
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
The problematic section contains a variable named writeFile which can not be resolved. No where in the class Aaa that you have shared, neither this variable has been declared nor initialized with an instance of its type. So the method void writeBoard(char[][] board, int boardSize) gives compilation error.
From the usage of this variable it is clear that it belongs to a class which has following instance methods:
1) openFile(String filename)
2) writeToTextFile(String piece)
3) closeFile()
Please search the class which has the above methods and on finding create an instance of that as the first statement inside the method void writeBoard(char[][] board, int boardSize). Hope it helps.
So I did a Tic Tac Toe assignment for my class. I have successfully created a simple Tic Tac Toe program but somehow the method to check for draw sometimes doesn't come out right. If everything is filled but there's no winner, then it's a draw. But if everything else is filled except for row 0 column 1, it will still show "draw" even if that box is still blank. If you don't get what I mean, just try filling out everything but the middle box on the top row but don't win, it will say "draw" even though that last box is not filled. What did I do wrong in my code???? Here's the driver:
import javax.swing.JOptionPane;
public class TwoDimensionalArray_Driverr
{
public static void main(String[]args)
{
char player = 'o';
TwoDimensionalArrayy game = new TwoDimensionalArrayy();
while (game.checkGame() == "PLAY")
{
if (player == 'o') player = 'x';
else player = 'o';
System.out.println(game);
String input = JOptionPane.showInputDialog("Enter Position of Row for player "+ player +" or press Cancel to exit");
if (input == null)
System.exit(0);
int row = Integer.parseInt(input);
input = JOptionPane.showInputDialog("Enter Position of Column for player " + player);
int column = Integer.parseInt(input);
game.set(row,column,player);
game.isDraw();
game.hasWon(row,column,player);
game.checkGame();
System.out.println(game.checkGame());
}
if (game.checkGame()=="DRAW"){
System.out.println(game);
System.out.println("It's a draw.");
}
else {
System.out.println(game);
System.out.println(player + " has won.");}
}
}
And here is the Object:
public class TwoDimensionalArrayy
{
private String currentState = "GO";
private char[][] board;
private static final int ROWS = 3;
private static final int COLUMNS = 3;
public TwoDimensionalArrayy(){
board = new char[ROWS][COLUMNS];
for(int i=0;i<ROWS;i++) //always do ROWS first!!!!
for(int j = 0;j<COLUMNS;j++)
board[i][j]=' ';
}
public void set(int i, int j, char player)
{
if(board[i][j] != ' ' )
throw new IllegalArgumentException("Position Occupied");
board[i][j] = player;
}
public String toString()
{
System.out.println("This is the board. 3x3");
System.out.println("Position start # row[0]col[0],row[0]col[1],row[0]col[2]");
String dString= "";
for (int row = 0; row<ROWS; row++)
{
if (COLUMNS>0)
dString += board[row][0];
for (int col = 1; col<COLUMNS; col++)
{
dString+= "|" + board[row][col];
} //end 2nd for
dString += "\n";
}//end first for
return dString;
}
public String checkGame(){
if (currentState=="Win"){
return "END";}
else if (currentState=="Draw"){
return "DRAW";}
else return "PLAY";
}
public void hasWon(int i,int j,char player){
if (board[i][0] == player // 3-in-the-row
&& board[i][1] == player
&& board[i][2] == player
|| board[0][j] == player // 3-in-the-column
&& board[1][j] == player
&& board[2][j] == player
|| i == j // 3-in-the-diagonal
&& board[0][0] == player
&& board[1][1] == player
&& board[2][2] == player
|| i + j == 2 // 3-in-the-opposite-diagonal
&& board[0][2] == player
&& board[1][1] == player
&& board[2][0] == player)
currentState = "Win";
}
public void isDraw(){
for ( int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLUMNS; col++) {
if (board[row][col] == ' ') {
currentState = "Play";
break;
}
else {currentState = "Draw";} // no empty cell, it's a draw}
}
}
}
}
public void isDraw(){
for ( int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLUMNS; col++) {
if (board[row][col] == ' ') {
currentState = "Play";
break;
} else {
currentState = "Draw"; // no empty cell, it's a draw
}
}
}
}
The break here will escape the inner for loop, but not the outer one. Essentially isDraw only considers the last row. You should try using return instead.