So I created a checkWinner method, using 'row' and 'col' private variables so I can locate the 'curPlayer' position in the 2D array.
import java.util.Scanner;
public class TicTacBoard
{
private char[][] board; // 2-D array of characters
private char curPlayer; // the player whose turn it is (X or O)
// added so I can locate the current player location in the board
private int row;
private int col;
// Constructor: board will be size x size
public TicTacBoard(int size)
{
board = new char[size][size];
// initialize the board with all spaces:
for(row=0; row < board.length; row++)
for(col=0; col < board[row].length; col++)
board[row][col] = ' ';
curPlayer = 'X'; // X gets the first move
}
public void playGame()
{
display();
do
{
takeTurn();
display();
}while(!checkWinner(row, col));
}
/////// display ////////
// Display the current status of the board on the
// screen, using hyphens (-) for horizontal lines
// and pipes (|) for vertical lines.
public void display()
{
System.out.println();
dispRow(0);
System.out.println("-----");
dispRow(1);
System.out.println("-----");
dispRow(2);
System.out.println();
}
// Display the current status of row r of the board
// on the screen, using hyphens (-) for horizontal
// lines and pipes (|) for vertical lines.
private void dispRow(int r)
{
System.out.println(board[r][0] + "|" + board[r][1]
+ "|" + board[r][2]);
}
/////// takeTurn ////////
// Allow the curPlayer to take a turn.
// Send output to screen saying whose turn
// it is and specifying the format for input.
// Read user's input and verify that it is a
// valid move. If it's invalid, make them
// re-enter it. When a valid move is entered,
// put it on the board.
public void takeTurn()
{
Scanner scan = new Scanner(System.in);
int row, col;
boolean invalid;
do{
invalid = false; // assume correct entry
System.out.println("It is now " + curPlayer + "'s turn.");
System.out.println("Please enter your move in the form row column.");
System.out.println("So 0 0 would be the top left, and 0 2 would be the top right.");
row = scan.nextInt();
col = scan.nextInt();
if(row < 0 || col < 0 || row > 2 || col > 2)
{
System.out.println("Invalid entry: row and column must both be between 0 and 2 (inclusive).");
System.out.println("Please try again.");
invalid = true;
}
else if(board[row][col] != ' ')
{
System.out.println("Invalid entry: Row " + row + " at Column " + col
+ " already contains: " + board[row][col]);
System.out.println("Please try again.");
invalid = true;
}
}while(invalid);
// Now that input validation loop is finished, put the move on the board:
board[row][col] = curPlayer;
// Switch to the other player (take turns):
if(curPlayer == 'X')
curPlayer = 'O';
else
curPlayer = 'X';
}
// If the game is over, print who won (if anyone),
// and return true. If the game is not over, return false.
public boolean checkWinner(int row, int col)
{
// YOUR CODE GOES HERE
int x = row;
int y = col;
// board length is always 3 here
// check winner on column
for (int i = 0; i < board.length; i++) {
if (board[x][i] != curPlayer)
break;
if (i == board.length - 1)
System.out.println("Player " + curPlayer + " wins!");
return true;
}
//check winner on row
for (int i = 0; i < board.length; i++) {
if (board[i][y] != curPlayer)
break;
if (i == board.length - 1)
System.out.println("Player " + curPlayer + " wins!");
return true;
}
// checks winner on diagonal up
if (x == y) {
for (int i = 0; i < board.length; i++) {
if (board[i][i] != curPlayer)
break;
if (i == board.length - 1)
System.out.println("Player " + curPlayer + " wins!");
return true;
}
}
// check winner on diagonal down
if (x + y == board.length - 1){
for (int i = 0; i < board.length; i++) {
if (board[i][(board.length-1)-i] != curPlayer)
break;
if (i == board.length - 1)
System.out.println("Player " + curPlayer + " wins!");
return true;
}
}
// checks if board is full
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j] == '-')
System.out.println("Nobody won, game ends in a draw!");
return true;
}
}
return false;
}
}
The code works but I while I was checking I got this:
| |
-----
| |
-----
| |
It is now X's turn.
Please enter your move in the form row column.
So 0 0 would be the top left, and 0 2 would be the top right.
2 0
| |
-----
| |
-----
X| |
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at TicTacBoard.checkWinner(TicTacBoard.java:126)
at TicTacBoard.playGame(TicTacBoard.java:43)
at Main.main(Main.java:14)
I thought the board length is always 3 with the location ranging from 0 to 3. Any solutions to this error? Any more efficient ways to do this? Please let me know!
You have a "shadowing" problem - that is, you're shadowing the instance fields row and col with local variables in your takeTurn method.
In it's current state...
// Constructor: board will be size x size
public TicTacBoard(int size) {
board = new char[size][size];
// initialize the board with all spaces:
for (row = 0; row < board.length; row++) {
for (col = 0; col < board[row].length; col++) {
board[row][col] = ' ';
}
}
curPlayer = 'X'; // X gets the first move
}
after the constructor has run, row and col will be 3, but in takeTurn, you define row and col as local variables...
public void takeTurn() {
Scanner scan = new Scanner(System.in);
int row, col;
boolean invalid;
This means, that when you call checkWinner in the playGame method...
public void playGame() {
display();
do {
takeTurn();
display();
} while (!checkWinner(row, col));
}
You're passing the instance field values (of 3/3) and everything breaks.
So, the "quick" solution would be to remove the local declaration of row/col from takeTurn
public void takeTurn() {
Scanner scan = new Scanner(System.in);
//int row, col;
boolean invalid;
You could also fix this in the constructor, but making row/col local variables
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = ' ';
}
}
but at some point, you need to update the row/col value for the player, but I might consider passing this information back from takeTurn rather than trying to use instance fields.
You also have a subtle, but common bug in your if statements. Without brackets, { and }, only the line IMMEDIATELY following the if statement will be executed when the conditional statement above is true. Your INDENTATION, however, indicates that you expected a different behavior.
For instance, your very first for loop is:
for (int i = 0; i < board.length; i++) {
if (board[x][i] != curPlayer)
break;
if (i == board.length - 1)
System.out.println("Player " + curPlayer + " wins!");
return true;
}
Here, only the System.out.println() line is executed when the if statement is true. The indentation of the return true; statement indicates that you expect it to only run with the println(), only when the conditional is true.
The return true; line is NOT dependent upon the preceding if statement, though, because it is not within brackets and the if statement only runs the line immediately following it. This means that the for loop is only ever running ONE ITERATION because the return line is STAND-ALONE and executes every single time, regardless of how those if statements evaluate.
You should ALWAYS, ALWAYS, ALWAYS add brackets to your if statements, even if they are "one-liners". With that in mind, I'd expect it to look more like:
for (int i = 0; i < board.length; i++) {
if (board[x][i] != curPlayer) {
break;
}
if (i == board.length - 1) {
System.out.println("Player " + curPlayer + " wins!");
return true;
}
}
Now the return line is only executed when the preceding if statement is true.
Related
I'm working on a Connect Four game for the console in Java. I have problems with the winning conditions, as I don't know how to program them. Here is my code my Main:
public class Main {
public static char[] playerNumber = new char[]{'1', '2'};
public static char[] Badge = new char[]{'X', 'O'};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int moves = 7 * 6;
int whichPlayer = 0;
for (int i = 0; i < 10; i++) {
System.out.println(" FOUR IN A ROW");
System.out.println("-------------------------------------------------------");
System.out.println("Welcome to the amazing game Four In A Row:");
System.out.println("Enter a number between 0 and 6 for choosing a column.");
System.out.println();
Board board = new Board();
board.fillBoard();
board.presentBoard();
do {
// 1. get a badge
char Player = playerNumber[whichPlayer];
char badge = Badge[whichPlayer];
// 2. make a turn
board.makeTurn(badge, Player);
board.presentBoard();
// 3. Tjek om der er vinder
if (board.checkWinHorizontal() || board.checkWinVertical()) {
System.out.println("Player " + Player + " has won!");
break;
}
// 4. change the player
whichPlayer = 1 - whichPlayer;
// 5. decrease moves
--moves;
if (moves == 0) {
System.out.println("Game over, nobody has won.");
System.out.println("Do you want to play again? 'Y' or 'N':");
String newGame = scanner.nextLine();
if (newGame.equals("Y") || newGame.equals("y")) {
break;
}
if (newGame.equals("N") || newGame.equals("n")) {
System.out.println("Thanks for the game!");
return;
}
}
// 6. repeat
} while (true);
}
}
And here is my code for my Board class:
public class Board {
char[][] board = new char[6][7];
int column;
// Fills the empty spaces
public void fillBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
board[i][j] = ' ';
}
}
}
// Prints the board
public void presentBoard() {
for (int i = 0; i < 6; i++) {
System.out.print(" | ");
for (int j = 0; j < 7; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.print(" -----------------------------");
System.out.println();
}
}
// Turn
public void makeTurn(char badge, char Player) {
Scanner scanner = new Scanner(System.in);
do {
// 1. Ask for a column
System.out.println("Player " + Player + " turn: ");
column = scanner.nextInt();
// 2. Check if it's between 0 and 6
if (column > 6) {
System.out.println("That is not a valid number. Please enter a number between 0 and 6: ");
continue;
}
// 3. Place a badge
for (int i = 6 - 1; i >= 0; i--) {
if (board[i][column] == ' ') {
board[i][column] = badge;
return;
}
}
// If column is full
System.out.println("Column " + column + " is full. Try another column:");
} while (true);
}
// Check for vertical win
public boolean checkWinVertical() {
return verticalWin(5, column);
}
// Check for horizontal win
public boolean checkWinHorizontal() {
return horizontalWin(5,column);
}
// Conditions for vertical win
private boolean verticalWin(int x, int y) {
char charToCheck = board[x][y];
if (board[x-1][y] == charToCheck &&
board[x-2][y] == charToCheck &&
board[x-3][y] == charToCheck) {
return true;
}
return false;
}
// Conditions for horizontal win
private boolean horizontalWin(int x, int y) {
char charToCheck = board[x][y];
if (board[x][y+1] == charToCheck &&
board[x][y+2] == charToCheck &&
board[x][y+3] == charToCheck) {
return true;
}
return false;
}
I have succeeded in getting the game recognize a win horizontally and vertically at the bottom row of my array, but I don't know how to make the game recognize for the whole array. I'm only concentrating about the horizontal and vertical, as the diagonal is too complicated for me. And I don't know if this is the right approach or there is a better one.
Thanks!
Here's another solution. It's the same general idea as previously mentioned: loop through each row/column, checking for a streak of 4 in a row. Maybe this implementation will provide some other insight. Below, I've shown an example method checking the horizontal streaks. For vertical, you would iterate over the rows in the inner for loop instead.
public boolean checkWin(char badge) {
return checkHorizontalStreaks(board, badge)
|| checkVerticalStreaks(board, badge);
}
private boolean checkHorizontalStreaks(char[][] board, char badge) {
for (int row = 0; row < board.length; row++) {
// loop throught each row
int currentStreak = 0;
for (int col = 0; col < board[row].length; col++) {
// loop through each column in the row
if (board[row][col] == badge) {
// keep the streak of 'badge' going
currentStreak++;
if (currentStreak == 4) {
// winner
return true;
}
} else {
// restart the streak
currentStreak = 0;
}
}
}
return false;
}
And then update your Main class with
if (board.checkWin(badge)) {
System.out.println("Player " + Player + " has won!");
break;
}
I'd wager there is a more efficient way to determine a winner (perhaps by treating the grid as a graph and traversing it with some special logic). However, I suspect this may be enough for what you need. I'll spare you the output, but it worked with a few different test cases.
Possibly you could check all the adjacent fields around the last played field, so after the user did his turn. So for checking upwards you could do this:
public boolean checkUp(int rowPlayed, int columnPlayed){
boolean checked = false;
if(rowplayed + 1 <= maxrows){ //Checks if you didn't hit the top
if(board[rowPlayed+1][columnPlayed] != null){
if(board[rowPlayed+1][columnPlayed].getPlayer() == currentPlayer){
checked = true;
}
}
}
return checked;
}
and for example implemented like this:
public void checkWin(int rowPlayed, int columnPlayed){
boolean checkingWin = true;
int countWin = 0;
while(checkingWin){
if(checkUp(rowPlayed + countWin, columnPlayed)){
countWin++;
}
else{
checkingWin = false;
}
if(countWin == 4){
checkinWin = false;
//Insert win confirmation here
}
}
}
It's partially pseudo code because I don't know exactly how you handle things in your code, nor do I know if this is the best way to do it. But I hope it was of help for you.
This is a long answer and I'll go around the houses a bit so you can see how I reached my solution (which also expands to diagonal checking at the end).
I would use the last piece added as a starting point and work from there since checking all combinations is exhaustive and unnecessary.
Given the row and column of the last piece added I need to decide what I need to achieve.
I already know that the current row and column has the piece of the colour I'm looking for so I can ignore that.
For horizontal matching, I want to check I want to checking pieces to left and right in the same row have the same colour, and stop if the colour is different or there is no piece.
So imagine the following board (# = empty, R = Red piece, Y = Yellow piece:
6 # # # # # # # #
5 # # # # # # # #
4 # # # # # # # #
3 # # # # # # # #
2 # # # # # # # #
1 # # # # # # # #
0 Y R R R Y Y Y R
0 1 2 3 4 5 6 7
The last move was Yellow, row 0, col 4.
So I want to check left and right from [0][4] and see if the total number of consecutive pieces of the colour is 3, (not 4) since I know [0][4] is Yellow and can be discounted.
Based on this I can take a recursive approach where I check the adjacent to one side, then recursively do the same thing as long as I keep matching pieces of the same colour or do not encounter an empty slot.
I'll start of with a check to the right (to demonstrate):
private static final int COLS = 7;
private static final int ROWS = 6;
public enum Piece {RED, YELLOW}; // null is empty
private Piece[][] board = new Piece[ROWS][COLS]; // the board
private int checkRight(Piece piece, int row, int col) {
// assume valid row for now
col++; // moving col to the right
if (col >= COLS || board[row][col] != piece) {
// We're outside the limits of the column or the Piece doesn't match
return 0; // So return 0, nothing to add
} else {
// otherwise return 1 + the result of checkRight for the next col
return 1 + checkRight(piece, row, col);
}
}
Now I can perform the same to the left.
private int checkLeft(Piece piece, int row, int col) {
// assume valid row for now
col--; // moving col to the left
if (col < 0 || board[row][col] != piece) {
// We're outside the limits of the column or the Piece doesn't match
return 0; // So return 0, nothing to add
} else {
// otherwise return 1 + the result of checkLeft for the next col
return 1 + checkLeft(piece, row, col);
}
}
And to check a winner for horizontal, I could do this:
public boolean checkWinner(Piece piece, int row, int col) {
// if the sum is 3, we have a winner (horizontal only).
return checkRight(piece, row, col) + checkLeft(piece, row, col) == 3;
}
Ugh, there's a lot of repetition isn't there?
We can condense the two methods into one by introducing a new parameter direction which can change if we move col positive or negative through the values 1 and -1 respectively:
private int check(Piece piece, int row, int col, int direction) {
col += direction; // direction is either 1 (right) or -1 (left)
if (col < 0 || col >= COLS || board[row][col] != piece) {
return 0;
} else {
return 1 + check(piece, row, col);
}
}
Update checkWinner() for this new parameter:
private static final int POSITIVE = 1; // right at the moment
private static final int NEGATIVE = -1; // left at the moment
public boolean checkWinner(Piece piece, int row, int col) {
// if the sum is 3, we have a winner (horizontal only).
return check(piece, row, col, POSITIVE) + check(piece, row, col, NEGATIVE) == 3;
}
Now I could implement the same sort of logic for vertical, but instead stay on the same col and change the row. I will skip this part in detail and move onto a solution which includes this and diagonal checking.
This has been done using an enum called CheckType storing values for which row and col should change and is used by the check() method. e.g. for HORIZONTAL the column changes by 1 or -1 (depending upon the direction specified when check() is called) and the row remains 0.
public class Board {
public enum Piece {
RED, YELLOW
};
private enum CheckType {
HORIZONTAL(0, 1), VERTICAL(1, 0), DIAGNONAL_UP(1, 1), DIAGNONAL_DOWN(-1, 1);
int row;
int col;
CheckType(int row, int col) {
this.row = row;
this.col = col;
}
}
private static final int POSITIVE = 1;
private static final int NEGATIVE = -1;
private static final int ROWS = 6;
private static final int COLS = 7;
private Piece[][] board = new Piece[ROWS][COLS];
private boolean hasWinner = false;
public boolean hasWinner() {
return hasWinner;
}
private void checkWinner(Piece piece, int row, int col) {
// check all values of enum CheckType for a winner
// so HORIZONTAL, VERTICAL, etc..
int enumIndex = 0;
while (!hasWinner && enumIndex < CheckType.values().length) {
hasWinner = check(piece, row, col, POSITIVE, CheckType.values()[enumIndex])
+ check(piece, row, col, NEGATIVE, CheckType.values()[enumIndex]) == 3;
enumIndex++;
}
}
private int check(Piece piece, int row, int col, int direction, CheckType type) {
row += type.row * direction;
col += type.col * direction;
if (row >= ROWS || row < 0 || col >= COLS || col < 0 || board[row][col] != piece) {
return 0;
} else {
return 1 + check(piece, row, col, direction, type);
}
}
// for completeness, adding a Piece
public boolean add(Piece piece, int col) {
int row = 0;
while (row < ROWS && board[row][col] != null) {
row++;
}
if (row < ROWS) {
board[row][col] = piece;
// check for winner after successful add
checkWinner(piece, row, col);
}
return row < ROWS;
}
}
Hope this helps.
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.
so i a player on a 2d array, when i do an action i want the player to move to one of the 8 available blocks around him, the code below moves him randomly but does it twice
Map Before Moving
GrassGrassGrassGrass
Grass Rek GrassGrass
GrassGrassGrassGrass
GrassGrassGrassGrass
Random Movement
0 0
0 0 //This shouldn't be happening
Map After Moving
GrassGrassGrassGrass
GrassGrassGrassGrass
GrassGrassGrassGrass
GrassGrassGrass Rek
import java.util.Random;
public class command_Movment implements command_Move {
inSwamp map = new inSwamp();
inSwamp rek = new Rek();
Random random = new Random();
int row = random.nextInt(3);
int col = random.nextInt(3);
#Override
public Command move() {
for (int i = 0; i < map.grid.length; i++) {
for (int j = 0; j < map.grid[i].length; j++) {
if (map.grid[i][j] == rek.getName()) {
try {
map.grid[i][j] = "Grass";
if (row == 0) {
i++;
}
if (row == 1) {
i--;
}
if (col == 0) {
j++;
}
if (col == 1) {
j--;
}
map.grid[i][j] = rek.getName();
System.out.println(col + " " + row);
break;
} catch (ArrayIndexOutOfBoundsException exception) {
if (row == 0) {
i--;
}
if (row == 1) {
i++;
}
if (col == 0) {
j--;
}
if (col == 1) {
j++;
}
map.grid[i][j] = rek.getName();
System.out.println("Error");
break;
}
}
}
}
return null;
}
}
Firstly, you shouldn't use == to compare strings, you should use equals method. so replace if (map.grid[i][j] == rek.getName()) with if (map.grid[i][j].equals(rek.getName())).
Edit: PLEASE don't use label to break the modularity of the program!
Please don't use catching ArrayIndexOutofBound exception to determine if an array index is correct or not. The exception should NOT happen. You should check the index first.
I updated my program for your random move: basically I thin you want to:
1) randomly move up or move down from the original position 2) if move up or move down exceeds the boundary of the matrix, don't move in that direction.
The following program should move rek to one of its 8 neighbors randomly without causing any ArrayIndexOutOfBoundException.
public Command move() {
// randomly determine the moving direction
// -1 means move left, 1 means move right
int horizontal_direction = Math.random() > 0.5 ? -1 : 1;
// -1 means move up, 1 mean move down
int vertical_direction = Math.random() > 0.5 ? -1 : 1;
for (int i = 0; i < map.grid.length; i++) {
for (int j = 0; j < map.grid[i].length; j++) {
if (map.grid[i][j].equals(rek.getName())) {
map.grid[i][j] = "Grass"; // replace rek's current position with Grass\
// if the newRow exceeds the boundaries, don't move in that direction
int newRow = i + horizontal_direction;
if (newRow < 0 || newRow == map.grid.length)
newRow = i;
// if the newCol exceeds the boundaries, don't move in that direction
int newCol = j + vertical_direction;
if (newCol < 0 || newCol == map.grid[i].length)
newCol = j;
map.grid[newRow][newCol] = rek.getName(); // move rek to the new position
System.out.println(newRow + " " + newCol);
break;
}
}
}
return null;
}
Add a label like this to your outer loop:
outer:
for (int i = 0; i < map.grid.length; i++) {
......
}
And in the try block, break the loop this way:
map.grid[i][j] = rek.getName();
System.out.println(col + " " + row);
break outer;
I am a beginner java student writing a gui tic-tac-toe program for my class. (No players, just computer generated).
Everything in my program works as expected, except for one thing; it seems that the placement of my method call for checkWinner is not place correctly, because the assignment for the X's and O's always finish. Why won't the loop end as soon as there is a winner?
It will return the correct winner based on the method call, but the for-loop will continue to iterate and fill in the rest (so sometimes it looks like both the x and o win or one wins twice). I've been going crazy, thinking it might be the placement of my checkWinner method call and if statement. When I set the winner = true; shouldn't that cancel the loop? I have tried putting it between, inside and outside each for-loop with no luck :(
I have marked the area I think is the problem //What is wrong here?// off to the right of that part the code. Thank you for any input!! :)
public void actionPerformed(ActionEvent e)
{
int total = 0, i = 0;
boolean winner = false;
//stop current game if a winner is found
do{
// Generate random # 0-1 for the labels and assign
// X for a 0 value and O for a 1 value
for (int row = 0; row < gameboard.length; row++) //rows
{
for (int col = 0; col < gameboard[row].length; col++) //columns
{
//Generate random number
gameboard[row][col] = (int)(Math.random() * 2);
//Assign proper values
if(gameboard[row][col] == 0)
{
labels[i].setText("X");
gameboard[row][col] = 10; //this will help check for the winner
}
else if(gameboard[row][col] == 1)
{
labels[i].setText("O");
gameboard[row][col] = 100; //this will help check for winner
}
/**Send the array a the method to find a winner
The x's are counted as 10s
The 0s are counted as 100s
if any row, column or diag = 30, X wins
if any row, column or diag = 300, Y wins
else it will be a tie
*/
total = checkWinner(gameboard); **//Is this okay here??//**
if(total == 30 || total == 300) //
winner = true; //Shouldn't this cancel the do-while?
i++; //next label
}
}//end for
}while(!winner);//end while
//DISPLAY WINNER
if(total == 30)
JOptionPane.showMessageDialog(null, "X is the Winner!");
else if(total == 300)
JOptionPane.showMessageDialog(null, "0 is the Winner!");
else
JOptionPane.showMessageDialog(null, "It was a tie!");
}
The easiest way would be to break all loops at once. (Even if some people dont like this)
outerwhile: while(true){
// Generate random # 0-1 for the labels and assign
// X for a 0 value and O for a 1 value
for (int row = 0; row < gameboard.length; row++) //rows
{
for (int col = 0; col < gameboard[row].length; col++) //columns
{
total = checkWinner(gameboard);
if(total == 30 || total == 300)
break outerwhile; //leave outer while, implicit canceling all inner fors.
i++; //next label
}
}//end for
}//end while
This However would not allow for the "tie" option, because the while will basically restart a game, if no winner has been found. To allow tie, you dont need the outer while at all, and can leave both fors at once, when a winner is found:
Boolean winner = false;
outerfor: for (int row = 0; row < gameboard.length; row++) //rows
{
for (int col = 0; col < gameboard[row].length; col++) //columns
{
total = checkWinner(gameboard);
if(total == 30 || total == 300){
winner = true;
break outerfor; //leave outer for, implicit canceling inner for.
}
i++; //next label
}
}//end for
if (winner){
//winner
}else{
//tie.
}
First of all, your code iterates through a board and generates random marks of X and O. This leads to some very odd board states, being always filled row-by-row, and possibly with unbalanced number of X and O marks.
IMHO you should organize your code in opposite manner to fill a board similary to a true game. I mean a series of 9 marks 'XOXOXOXOX' spreaded over the board.
Let Labels labels be a nine-character array, initialized to 9 spaces.
public int doGame( Labels labels)
{
labels = " ";
int itisXmove = true; // player X or O turn
for( int movesLeft = 9; movesLeft > 0; movesLeft --)
{
int position = // 0 .. movesLeft-1
(int) Math.floor(Math.random() * movesLeft);
for( int pos = 0; pos < 9; pos ++) // find position
if( labels[ pos] == " ") // unused pos?
if( position-- == 0) // countdown
{
if( itisXmove) // use the pos
labels[ pos] = "X"; // for current player
else
labels[ pos] = "O";
break;
}
int result = checkWinner( labels); // who wins (non-zero)?
if( result != 0)
return result;
itisXmove = ! itisXmove; // next turn
}
return 0; // a tie
}
then
public void actionPerformed(ActionEvent e)
{
Labels labels;
int result = doGame( labels);
if( result == valueForX)
JOptionPane.showMessageDialog(null, "X is the Winner!");
else if( result == valueForO)
JOptionPane.showMessageDialog(null, "O is the Winner!");
else
JOptionPane.showMessageDialog(null, "It's a tie!");
for( int rowpos = 0; rowpos < 9; rowpos += 3)
{
for( int colpos = 0; colpos < 3; colpos ++)
/* output (char)label[ rowpos + colpos] */;
/* output (char)newline */;
}
}
I think you should change your loop condition and add one more bool.
You have a "tie" condition but currently you only check for winner. The only explanation without the checkWinner code is that you are encountering a tie every time.
So...
boolean tie;
boolean winner;
do {
//your stuff
}
while(!(tie || winner))
Edit: I didn't realize you put the while loop outside your for loop, you will need to break out of your for loops in order for the while condition to be checked.
//stop current game if a winner is found
do{
for (int row = 0; row < gameboard.length; row++) //rows
{
for (int col = 0; col < gameboard[row].length; col++) //columns
{
if(winner || tie)
break;
}//end for
if(winner || tie)
break;
}//end for
}while(!(winner || tie));//end while
//the rest of your stuff here
You're not checking the value of winner until both for loops complete. Add a break right after you set winner = true, and add an
if (winner)
{
break;
}
to the beginning or end of your outer for loop.
Your issue is that your do/while statement is wrapped around the for statements. So the for statements end up running their entire cycle before it ever reaches the while statement. A solution to get around this is checking for a winner in the for statements and breaking:
//stop current game if a winner is found
do {
for (int row = 0; row < gameboard.length; row++) //rows
{
for (int col = 0; col < gameboard[row].length; col++) //columns
{
// ... your other code ...
total = checkWinner(gameboard);
if(total == 30 || total == 300) {
winner = true;
break; // end current for-loop
}
i++; //next label
}
if (winner) break; // we have a winner so we want to kill the for-loop
} //end for
} while(!winner); //end while
So you should be able to just loop through the two for-statements and break upon a winner. Your code also does not seem to handle a tied case, but I am guessing you already know that.
I am trying to create a program that does the game TicTacToe. I have finished creating
all the methods and I just need to create the driver program. Before creating the
driver program, I tried to just print the board along with a character but I don't
think my methods are correct. Here is what my error looks like:
java.lang.ArrayIndexOutOfBoundsException: 3
at TicTacToeBoard.move(TicTacToeBoard.java:75)
at TicTacToe.main(TicTacToe.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
Here are my two programs:
This is my driver program that I can't seem to complete. The last thing that will be shown is the
template so that you have the idea of how each program works.
class TicTacToe
{
public static void main(String [] args)
{
//System.out.println("Welcome! Tic-Tac-Toe is a two player game.");
//System.out.println("Enter player one's name: ");
TicTacToeBoard game = new TicTacToeBoard();
System.out.println(game.toString());
//int count = 0;
game.move('x', 1, 3);
// game.move('o', 1, 1);
/* while (game.gameWon() !true || count != 9)
{
System.out.print(game.move());
System.out.print(game.isEmpty());
}*/
}
}
This is where all the methods are......
class TicTacToeBoard
{
private char [][] board = new char[3][3];
String b;
// This a new constructor that creates a tic-tac-toe board
public TicTacToeBoard()
{
for (int rows = 0; rows < board.length; rows++)// creates rows
{
for (int columns = 0; columns <board[rows].length;columns++)// creates columns
{
//System.out.println("| ");
board[rows][columns] = ' ';
//System.out.println(" |\n" );
}
}
}
// creates a string form of the tic-tac-toe board and allows the user
// to access it during the game.
public String toString()
{
String b = "";
// creates a vertical bar at the beginning and the end of each row
for (int rows = 0; rows < board.length; rows++)
{
b += "| ";
// adds a space for each row and column character in tic-tac-toe board.
for (int columns = 0; columns < board[rows].length; columns++)
{
b += board[rows][columns] + " ";
}
b += "|\n";// prints a | space space space | and breaks off to create two new lines.
}
return b; // prints the tic-tac-toe board to be accessed by the user.
}
String move(char x, int rows, int columns)
{
String b = "";
// creates a vertical bar at the beginning and the end of each row
for (int r = 0; r < board.length; r++)
{
b += "| ";
for (int c = 0; c < board[r].length; c++)
{
b += board[r][c] + " "; //prints 3 spaces on each line.
// prints string character from user input if row and column not equal to zero
if (board[rows - 1][columns - 1] >= 0 && board[rows - 1][columns - 1] <= 2 )
{
board[rows - 1][columns - 1] = x;// prints character in the specified index from user input
b += board[rows - 1][columns - 1];// prints out the board and the new character in specified space.
}
else if (board[rows - 1][columns - 1] < 0) // makes user pick another choice
return "ILLEGAL MOVE, TRY AGAIN!";
// adds a space for each row and column character in tic-tac-toe board.
}
b += "|\n";// prints a | space space space | and breaks off to create two new lines.
}
return b; // prints the tic-tac-toe board to be accessed by the user.
}
// checks if a space character is empty
void isEmpty(char x, int row, int col)
{
if (board [row - 1][col - 1] == ' ')
board[row - 1][col - 1] = x;
else // makes user pick another row and column if space character is not empty
System.out.println("ILLEGAL CHOICE, PICK AGAIN!");
}
// checks if game is won
public boolean gameWon(int row, int col)
{
if ((board[2][0] == board[1][1]) && (board[2][0] == board[0][2]))
return true;
else if ((board[2][0] != board[1][1]) && (board[2][0] != board[0][2]))
return false;
if ((board[2][2] == board[1][1])&& (board[2][2] == board[0][0]))
return true;
else if ((board[2][2] != board[1][1])&& (board[2][2] != board[0][0]))
return false;
if ((board[0][0] == board[1][0]) && (board[0][0] == board[2][0]))
return true;
else if ((board[0][0] != board[1][0]) && (board[0][0] != board[2][0]))
return false;
if ((board[0][1] == board[1][1]) && (board[0][1] == board[2][1]))
return true;
else if ((board[0][1] != board[1][1]) && (board[0][1] != board[2][1]))
return false;
if ((board[0][2] == board[1][2]) && (board[0][2] == board[2][2]))
return true;
else if ((board[0][2] != board[1][2]) && (board[0][2] != board[2][2]))
return false;
if ((board[0][0] == board[0][1]) && (board[0][0] == board[0][2]))
return true;
else if ((board[0][0] != board[0][1]) && (board[0][0] != board[0][2]))
return false;
if ((board[1][0] == board[1][1]) && (board[1][0] == board[1][2]))
return true;
else if ((board[1][0] != board[1][1]) && (board[1][0] != board[1][2]))
return false;
if ((board[2][0] == board[2][1]) && (board[2][0] == board[2][2]))
return true;
else
return false;
}
}
Here is the template for the whole thing!!!!!
class TicTacToe
{
public static void main (String [] args)
{
TicTacToeBoard b = new TicTacToeBoard();
while (game not over)
{
swtich player
increment turn counter
until user enters a valid move
{
prompt for move
}
make move
b.makeMove (player, row, col);
print board
System.out.println(b);
}
print outcome
}
}
class TicTacToeBoard
{
private char [][] board = ...;
public TicTacToeBoard()
{
initialize board with spaces
}
public void makeMove (char c, int row, int col)
{
store symbol in specified position
}
public boolean isEmpty(int row, int col)
{
return true if square is unfilled
}
public boolean gameWon()
{
check board for a win
}
public String toString ()
{
return String representation of board
}
}
Programming languages are unforgiving for errors and force rigor and care on us.
Your code is quite difficult for us to read and thus for both us and you to debug, starting with your indentation which is all over the place, but there are also careless errors, especially this one:
for (int r = 0; r < board.length; rows++)
Do you see what is wrong here? r is not the same as rows, and you can't use one as the index for the loop and then increment the other. You're using both of these variables inside of the loop. There are several other careless errors in the code as well.
I recommend that you start over but be much more careful with your code and be especially careful with your indentation. If you don't line up your curly braces correctly, you will not see when one code block ends and another begins (nor will we!).
Oh, and next time, please let us know which lines of your code are causing your error. It will be much easier to help you if we don't have to guess this information.
Edit
Your new code indentation is some better, but still is off. This is what you have:
String move(char x, int rows, int columns)
{
String b = "";
// creates a vertical bar at the beginning and the end of each row
for (int r = 0; r < board.length; r++)
{
b += "| ";
for (int c = 0; c < board[r].length; c++)
{
b += board[rows][columns] + " ";
and this is what I recommend:
String move(char x, int rows, int columns) {
String b = "";
// creates a vertical bar at the beginning and the end of each row
for (int r = 0; r < board.length; r++) {
b += "| ";
for (int c = 0; c < board[r].length; c++) {
// let's check to see what the variables hold!
System.out.printf("rows: %d, columns %d, r: %d, c: %d%n", rows, columns, r, c);
b += board[rows][columns] + " "; // **** the offending line ****
Even more important, note the result from the printf statement followed immediately by the exception:
rows: 1, columns 3, r: 0, c: 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
So here it is the column variable that holds the value of 3 and causes your array to explode. You will need to track back to see how you call this method and why it is passing a 3 into the column parmaeter.
Edit 2
On re-review of your latest post, you're still hard coding your move method to accept a 3 as the column parameter:
game.move('x', 1, 3);
Fix that first and foremost. That parameter can't be 3.