Why is this loop within a loop not running to completion? - java

I need the loop to iterate through A1,A2..A8..B8...H8 but it stops at C3 for some reason. For the life of me I cannot figure out why this loop within a loop is not running.
P.S letters is just an arraylist of the alphabet {A,B,C...Z} and getValue() just returns a value depending on how much a letter is worth.
int bestMove = 0;
for(int i = 0; i < 8; i++){
for(int x = 0; x < 8; x++){
System.out.println(letters.get(i) + "" + (x+1));
int distanceRow = currentRow - i;
int distanceCol = currentCol - x;
distanceRow = Math.abs(distanceRow);
distanceCol = Math.abs(distanceCol);
if(currentRow == i && currentCol == x){
System.out.println("if");
} else if (distanceRow - distanceCol == 0) {
bestMove = getValue(getPiece(i, x));
System.out.print("else if");
System.out.println(letters.get(i) + "" + (x+1));
} else {
System.out.print(letters.get(i) + "" + (x+1));
System.out.println("else");
}
}
Edit: I tested it as was suggested and it seems theres an error with this method although I dont know what since it just returns a value
public int getValue(String piece) {
if (piece.equals(w1)) {
return 1;
} else if (piece.equals(w2)) {
return 3;
} else if (piece.equals(w3)) {
return 3;
} else if (piece.equals(w4)) {
return 5;
} else if (piece.equals(w5)) {
return 9;
}
return 0;
}

Related

Minimax algorithm for Tic Tac Toe not working

I am attempting to make an unbeatable Tic Tac Toe game using a simplified minimax algorithm. The code looks like this:
private static int findBestMove(String[][] board, boolean comp) {
// comp returns true if the computer is the one looking for the best move
// findBestMove is always called by the program as findBestMove(board, true)
// since the computer is the only one that uses it
// If the board in its current state is a win for the
// player, return -1 to indicate a loss
if (playerWon(board)) return -1;
// If the board in its current state is a win for the
// computer, return 1 to indicate a win
if (compWon(board)) return 1;
// If the board in its current state is a tie
// return 0 to indicate a tie
if (tie(board)) return 0;
// Set the default possible outcome as the opposite of what
// the respective player wants
int bestPossibleOutcome = comp ? -1 : 1;
// Loop through the board looking for empty spaces
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
// Once an empty space is found, create a copy of the board
// with that space occupied by the respective player
if (board[i][j].equals(" ")) {
String[][] newBoard = new String[3][3];
for (int a = 0; a < 3; a++) {
System.arraycopy(board[a], 0, newBoard[a], 0, 3);
}
newBoard[i][j] = comp ? "O" : "X";
// Recursively call findBestMove() on this copy
// and see what the outcome is
int outCome = findBestMove(newBoard, !comp);
// If this is the computer's turn, and the outcome
// is higher than the value currently stored as the
// best, replace it
if (comp && outCome > bestPossibleOutcome) {
bestPossibleOutcome = outCome;
// r and c are instance variables that store the row
// and column of what the computer's next move should be
r = i;
c = j;
// If this is the player's turn, and the outcome
// is lower than the value currently stored as the
// best, replace it
} else if (!comp && outCome < bestPossibleOutcome) {
bestPossibleOutcome = outCome;
}
}
}
}
// Return the ultimate value deemed to be the best
return bestPossibleOutcome;
}
The idea is that after I run this program, the instance variables r and c should contain the row and column, respectively, of the computer's best move. However, the program only successfully prevents a loss about half the time, and I can't tell if the other half is luck, or if the program is actually working.
I am aware that the computer will respond to every scenario exactly the same way each game. That is fine.
In the event anyone would like to run the program, I have included the full class below:
import java.util.Scanner;
public class TicTacToe {
private static int r;
private static int c;
private static void printBoard(String[][] board) {
System.out.println(" 0 1 2");
System.out.println("0 " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " ");
System.out.println(" ---+---+---");
System.out.println("1 " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " ");
System.out.println(" ---+---+---");
System.out.println("2 " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " ");
}
private static boolean playerWon(String[][] board) {
return playerHasThreeInCol(board) || playerHasThreeInDiag(board) || playerHasThreeInRow(board);
}
private static boolean playerHasThreeInRow(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[i][0].equals(board[i][1]) && board[i][0].equals(board[i][2]) && board[i][0].equals("X")) return true;
}
return false;
}
private static boolean playerHasThreeInCol(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i]) && board[0][i].equals("X")) return true;
}
return false;
}
private static boolean playerHasThreeInDiag(String[][] board) {
if (board[0][0].equals(board[1][1]) && board[0][0].equals(board[2][2]) && board[0][0].equals("X")) return true;
return board[0][2].equals(board[1][1]) && board[0][2].equals(board[2][0]) && board[0][2].equals("X");
}
private static boolean compWon(String[][] board) {
return compHasThreeInCol(board) || compHasThreeInDiag(board) || compHasThreeInRow(board);
}
private static boolean compHasThreeInRow(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[i][0].equals(board[i][1]) && board[i][0].equals(board[i][2]) && board[i][0].equals("O")) return true;
}
return false;
}
private static boolean compHasThreeInCol(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i]) && board[0][i].equals("O")) return true;
}
return false;
}
private static boolean compHasThreeInDiag(String[][] board) {
if (board[0][0].equals(board[1][1]) && board[0][0].equals(board[2][2]) && board[0][0].equals("O")) return true;
return board[0][2].equals(board[1][1]) && board[0][2].equals(board[2][0]) && board[0][2].equals("O");
}
private static boolean tie(String[][] board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) return false;
}
}
return true;
}
private static int findBestMove(String[][] board, boolean comp) {
if (playerWon(board)) return -1;
if (compWon(board)) return 1;
if (tie(board)) return 0;
int bestPossibleOutcome = comp ? -1 : 1;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) {
String[][] newBoard = new String[3][3];
for (int a = 0; a < 3; a++) {
System.arraycopy(board[a], 0, newBoard[a], 0, 3);
}
newBoard[i][j] = comp ? "O" : "X";
int outCome = findBestMove(newBoard, !comp);
if (comp && outCome > bestPossibleOutcome) {
bestPossibleOutcome = outCome;
r = i;
c = j;
} else if (!comp && outCome < bestPossibleOutcome) {
bestPossibleOutcome = outCome;
}
}
}
}
return bestPossibleOutcome;
}
private static void go() {
Scanner input = new Scanner(System.in);
String[][] board = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = " ";
}
}
printBoard(board);
for (int i = 0;; i++) {
if (i % 2 == 0) {
while (true) {
System.out.println("Enter position: ");
String position = input.nextLine();
int row, column;
try {
row = Integer.parseInt(position.substring(0, 1));
column = Integer.parseInt(position.substring(1, 2));
} catch (Exception e) {
System.out.println("Invalid entry. ");
continue;
}
if (row < 0 || row > 2 || column < 0 || column > 2) {
System.out.println("That position is not on the board. ");
continue;
}
if (!board[row][column].equals(" ")) {
System.out.println("That space is already taken. ");
continue;
}
board[row][column] = "X";
break;
}
} else {
System.out.println("\nMy move: ");
findBestMove(board, true);
board[r][c] = "O";
}
printBoard(board);
if (playerWon(board)) {
System.out.println("You win!");
break;
} else if (compWon(board)) {
System.out.println("I win!");
break;
} else if (tie(board)) {
System.out.println("Tie game");
break;
}
}
}
public static void main(String[] args) {
go();
}
}
I'm not asking for anyone to rewrite the whole thing for me, but if you can point out any obvious mistakes or point me in the right direction, that would be appreciated. I am also open to any suggestions or comments that you may have.
I haven't extensively tested it yet, but I believe that I resolved the issue. The new code looks like this:
private static void findBestMove(String[][] board) {
double bestMove = Double.NEGATIVE_INFINITY;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) {
board[i][j] = "O";
double score = minimax(board, false);
board[i][j] = " ";
if (score > bestMove) {
bestMove = score;
r = i;
c = j;
}
}
}
}
}
private static double minimax(String[][] board, boolean comp) {
if (playerWon(board)) {
return -1;
}
if (compWon(board)) {
return 1;
}
if (tie(board)) return 0;
double bestScore;
if (comp) {
bestScore = Double.NEGATIVE_INFINITY;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) {
board[i][j] = "O";
double score = minimax(board, false);
board[i][j] = " ";
bestScore = Math.max(score, bestScore);
}
}
}
} else {
bestScore = Double.POSITIVE_INFINITY;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) {
board[i][j] = "X";
double score = minimax(board, true);
board[i][j] = " ";
bestScore = Math.min(score, bestScore);
}
}
}
}
return bestScore;
}
I abstracted the minimax algorithm away from the next move coordinate setter, which I think may have made a difference. Otherwise, it is very similar.

Customizable TicTacToe game board with Java

I need to create a method to check wether the tictactoe game is PLAYING, DRAW, XWIN or OWIN. However, I am having difficulty writing the code to check if X or O has won, given that the size of the gameboard and the size needed to win (sizeWin) are changing according to the user's input. AND I am forced to use a 1D array for the game board. I simply do not know where to go from here. My latest idea was to use nested for loops to check for a win by row, column or diagonal but I'm not sure how to implement it. If anyone has any tips on how to approach this problem or has any other solutions I would be very grateful
private void setGameState(int i) {
// Check rows
getLines();
getColumns();
getSizeWin();
for (row = 0; row == lines; row++) {
for (col = 0; col == columns; col++) {
}
}
}
public TicTacToeGame(int lines, int columns, int sizeWin) {
// linesXcolumns game, starts with X, need sizeWin in a line/column/diag to win
this.lines = lines;
this.columns = columns;
CellValue currentCellValue = CellValue.X;
this.sizeWin = sizeWin;
// Creating board according to given size
int size = lines * columns;
this.board = new CellValue[size];
// Setting up board to be empty
for (int i = 0; i < size; i++) {
board[i] = CellValue.EMPTY;
}
}
PS. If someone were to call the operator TicTacToe(3,4,3), a game board of 3 lines and 4 columns would print. And the number of X's or O's to win would be 3.
CAM$ java TicTacToe 3 4 3
| | |
---------------
| | |
---------------
| | |
It is a little more complicated than it looks but after you get it it's simple. I've made a function that works just fine:
private static String checkGameState() {
// Looking for errors.
if (rowCount <= 0 || columnCount <= 0) {
return "ERROR: Illegal board size: " + rowCount + "*" + columnCount;
}
if (boradContent.length != rowCount * columnCount) {
return "ERROR: boradContent not compatible with rowSize and columnSize.";
}
if (sizeWin > rowCount && sizeWin > columnCount) {
return "ERROR: Board is too small for this sizeWin: " + sizeWin + ".";
}
String gameState = "PLAYING";
// Checking rows
for (int i = 0; i < rowCount; i++) {
char currentChar = getField(i, 0);
int score = 1;
for (int j = 1; j < columnCount; j++) {
if (currentChar == getField(i, j)) {
score++;
if (score >= sizeWin) {
if (gameState.equals("PLAYING")) {
gameState = currentChar + "WIN";
} else if (!gameState.equals(currentChar + "WIN")) {
gameState = "DRAW";
return gameState;
}
}
} else {
if (j > columnCount - sizeWin) {
break;
}
score = 1;
currentChar = getField(i, j);
}
}
}
// Checking columns
for (int j = 0; j < columnCount; j++) {
char currentChar = getField(0, j);
int score = 1;
for (int i = 1; i < rowCount; i++) {
if (currentChar == getField(i, j)) {
score++;
if (score >= sizeWin) {
if (gameState.equals("PLAYING")) {
gameState = currentChar + "WIN";
} else if (!gameState.equals(currentChar + "WIN")) {
gameState = "DRAW";
return gameState;
}
}
} else {
if (j > rowCount - sizeWin) {
break;
}
score = 1;
currentChar = getField(i, j);
}
}
}
// Checking diagonally
// Checking diagonally - from top-left to bottom-right
for (int i = 0; i < rowCount - sizeWin + 1; i++) {
for (int j = 0; j < columnCount - sizeWin + 1; j++) {
char currentChar = getField(i, j);
int score = 1;
for (int k = 1; k < sizeWin; k++) {
if (currentChar == getField(i + k, j + k)) {
score++;
if (score >= sizeWin) {
if (gameState.equals("PLAYING")) {
gameState = currentChar + "WIN";
} else if (!gameState.equals(currentChar + "WIN")) {
gameState = "DRAW";
return gameState;
}
}
} else {
break;
}
}
}
}
// Checking diagonally - from top-right to bottom-left
for (int i = 0; i < rowCount - sizeWin + 1; i++) {
for (int j = sizeWin -1; j < columnCount; j++) {
char currentChar = getField(i, j);
int score = 1;
for (int k = 1; k < sizeWin; k++) {
if (currentChar == getField(i + k, j - k)) {
score++;
if (score >= sizeWin) {
if (gameState.equals("PLAYING")) {
gameState = currentChar + "WIN";
} else if (!gameState.equals(currentChar + "WIN")) {
gameState = "DRAW";
return gameState;
}
}
} else {
break;
}
}
}
}
return gameState;
}
It is worth to mention that the rowCount, columnCount, sizeWin and boradContent variables are class level variables and i used a getField(int X, int Y) method that is not a very complicated thing but is more useful. It just converts the given field coordinates to the place in a 1D array and returns it's content:
private static char getField(int X, int Y) {
return boradContent[X * columnCount + Y];
}

Checking adjacent tiles in 2-dimensional array

So i'm trying to make a game of Connect Four in Java, instead I'm connecting 6 instead of 4.
I have a 2-dimensional array and X amount of players. I have to check if 6 blocks in succession (horizontal, vertical and diagonal) are marked by the same player. If they are, the program should print who won.
Now, I don't have problems with the checking or determining who won, though for the life of me I can't figure out how to prevent the program from crashing whenever it tries to check for a block that's outside the array.
Now, I'm trying to avoid using try-catch or plopping 8 loops one after the other, and instead use one method for all of the directions with just variation in the parameters but I can't seem to make it work :\
Does anyone have a suggestion on how this might work?
I'm a beginner in programming and I've possibly missed something so that's why I'm asking for help :)
Cheers
Edit: here's the code. It's a bit long, that's why i want to shorten it and make it work somehow. the Terminal class is the same as the System.out.println one.
void checkIfPlayerWins(Field field, Integer rowNumber, Integer colNumber) {
Integer counter = 1;
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber, colNumber + i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber - i, colNumber + i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber - i, colNumber)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber - i, colNumber - i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber, colNumber - i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber + i, colNumber - i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber + i, colNumber)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber + i, colNumber + i)) {
counter++;
} else {
break;
}
}
if (counter == 6) {
Terminal.printLine("");
}
}
here's the isOccupied method
boolean isOccupied(Integer x, Integer y) {
return !this.field[x][y].equals("**");
}
You could simply handle the case where you're attempting to check whether the Field is occupied at invalid coordinates in your isOccupied method:
boolean isOccupied(Integer x, Integer y) {
if(x < 0 || y < 0 || x >= numberOfColumns || y >= numberOfRows) {
// Attempting to check outside the grid: it's non-occupied.
return false;
}
return !this.field[x][y].equals("**");
}

Is there a way to make this code more efficient?

public int Neighbours(int xCoordinate, int yCoordinate)
{
xCoordinate -= 1;
yCoordinate -= 1;
int NeighbourCounter = 0;
int incrementer = 0;
int m1 = -1; //istart
int n1 = -1; //jstart
int m2 = 1; //iend
int n2 = 1; //jend
if (xCoordinate == 0)
{
m1 = 1;
}
if (yCoordinate == 0)
{
n1 = -1;
}
if (xCoordinate + 1 == yLen)
{
m2 = 0;
}
if (yCoordinate + 1 == xLen)
{
n2 = 0;
}
for (int xNeighbour = m1; xNeighbour <= m2; xNeighbour++)
{
if (xNeighbour == 0)
{
incrementer = 2;
}
else
{
incrementer = 1;
}
for (int yNeighbour = n1; yNeighbour<n2; yNeighbour += incrementer)
{
if (CurrentGen[yCoordinate + yNeighbour][xCoordinate + xNeighbour] == 1)
{
NeighbourCounter++;
}
}
}
return NeighbourCounter;
}
Is it possible to make this code more efficient? This code is for my Game of Life project, and I seem to be getting an error when I try to run this code for the next generation of the game of life. For my NextGeneration I seem to be getting an ArrayOutOfBoundsException: -2. This error occurs in the line 45.
Look at ArrayIndexOutOfBoundsException.
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
if(CurrentGen[yCoordinate + yNeighbour][xCoordinate + xNeighbour] == 1)
You are accessing CurrentGen.
yCoordinate + yNeighbour or xCoordinate + xNeighbour equals -2. Arrays start from index 0.

Cannot read repeating characters

I'm writing a code to read a string and count sets of repeating
public int countRepeatedCharacters()
{
int c = 0;
for (int i = 1; i < word.length() - 1; i++)
{
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
if ( word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
return c;
}
If I try the input
aabbcdaaaabb
I should have 4 sets of repeat decimals
aa | bb | aaaa | bb
and I know I'm not reading the first set aa because my index starts at 1. I tried fixing it around to read zero but then I tr to fix the entire loop to work with the change and I failed, is there any advice as to how to change my index or loop?
Try this code:
public int countRepeatedCharacters(String word)
{
int c = 0;
Character last = null;
bool counted = false;
for (int i = 0; i < word.length(); i++)
{
if (last != null && last.equals(word.charAt(i))) { // same as previous characted
if (!counted) { // if not counted this character yet, count it
c++;
counted = true;
}
}
else { // new char, so update last and reset counted to false
last = word.charAt(i);
counted = false
}
}
return c;
}
Edit - counted aaaa as 4, fixed to count as 1
from what I understood from your question, you want to count number of repeating sets, then this should help.
for (int i = 0; i < word.length()-1; i++){
if (word.charAt(i) == word.charAt(i + 1)){ // found a repetition
if (i==0 || word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
Try this----
public int countRepeatedCharacters()
{
int c = 0,x=0;
boolean charMatched=false;
for (int i = 0; i < word.length(); i++)
{
if(i==word.length()-1)
{
if (word.charAt(i-1) == word.charAt(i))
c++;
break;
}
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
charMatched=true;
continue;
}
if(charMatched==true)
c++;
charMatched=false;
}
return c;
}
Try this method. It counts the sets of repeating charactors.
public static void main(String[] args) {
String word = "aabbcdaaaabbc";
int c = 0;
for (int i = 0; i < word.length()-1; i++) {
// found a repetition
if (word.charAt(i) == word.charAt(i + 1)) {
int k = 0;
while((i + k + 1) < word.length()) {
if(word.charAt(i+k) == word.charAt(i + k + 1)) {
k++;
continue;
}
else {
break;
}
}
c++;
i+=k-1;
}
}
System.out.println(c);
}
You can try something like this:-
public static void main(String str[]) {
String word = "aabbcdaaaabbc";
int c = 1;
for (int i = 0; i < word.length() - 1; i++) {
if (word.charAt(i) == word.charAt(i + 1)) {
c++;
} else {
System.out.println(word.charAt(i)+ " = " +c);
c = 1;
}
}
System.out.println(word.charAt(word.length()-1)+ " = " +c);
}
You can modify this as per your needs, by removing the sysouts and other stuffs.
Using length() -1 is causing you to not consider the last character in your calculations.
This is causing you to lose the last repetitive character.
Finally, I would have done this as follows:
public static int countRepeatedCharacters(String word)
{
boolean withinRepeating = false;
int c = 0;
for (int i = 1; i < word.length(); i++)
{
if (!withinRepeating && (withinRepeating = word.charAt(i) == word.charAt(i - 1)))
c++;
else
withinRepeating = word.charAt(i) == word.charAt(i - 1);
}
return c;
}

Categories

Resources