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];
}
Related
I made the 8x8 chess board and have a lot of the code done, but for some reason it only print out one solution, does anyone know why this may be and how I can fix it?
public class NonAttackingQueens {
private int[][] board;
private int solutionCount = 0;
private boolean solutionFound = false;
public NonAttackingQueens() {
board = new int[8][8];
}
public boolean canPlace(int x, int y) {
// Check if a queen is already placed at position (x, y)
if (board[x][y] == 1) {
return false;
}
// Check horizontal positions
for (int i = 0; i < 8; i++) {
if (board[x][i] == 1) {
return false;
}
}
// Check vertical positions
for (int i = 0; i < 8; i++) {
if (board[i][y] == 1) {
return false;
}
}
// Check diagonal positions
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == 1 && (Math.abs(i - x) == Math.abs(j - y))) {
return false;
}
}
}
return true;
}
public void solve() {
// Check if the solutionCount has reached 92
if (solutionCount == 92) {
return;
}
// Check if all 8 queens have been placed
int queensPlaced = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == 1) {
queensPlaced++;
}
}
}
if (queensPlaced == 8) {
// All positions have been checked, so we have found a solution
solutionCount++;
System.out.println("Solution " + solutionCount + ":");
print();
return;
}
// Try to place a queen at each position on the board
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (canPlace(i, j)) {
// Place a queen at position (i, j) and try to solve the rest of the board
board[i][j] = 1;
solve();
// Backtrack: remove the queen from position (i, j) and try the next position
board[i][j] = 0;
}
}
}
}
public void print() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == 1) {
System.out.print(" X");
} else {
System.out.print(" O");
}
}
System.out.println();
}
System.out.println("---------------");
}
}
I'm doing this in blueJ, so I tried to run the void solve(); method and it runs, but it only prints out the first of 92 solutions 92 times. It should print out all 92 different solutions.
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.
I'm trying to figure how answer to these question in my code:
create a method called getValidValues that: returns an array of 9 boolean values that corresponds to 9 digits (1-9) and, it is true if that digit can be placed in that position [row][column] without violating game rules.
This is my code:
public class SudokuClass {
private final int SIZE = 9;
boolean board = new int[SIZE][SIZE];
boolean[][] start = new boolean[SIZE][SIZE];
public SudokuClass() {
for(int i=0; i < SIZE; i++) {
for(int j=0; j < SIZE; j++) {
board[i][j] = 0;
}
}
}
public String toString () {
String result = "";
for (int i = 0; i < SIZE; i++) {
if (i % 3 == 0) {
result = result + "+-------+-------+-------+\n";
}
for (int j = 0; j < SIZE; j++) {
if (j % 3 == 0) {
result = result + "| ";
}
if (scacchiera [i] [j] == 0) {
result = result + " ";
} else {
result = result + board[i][j] + " ";
}
}
result = result + "|\n";
}
result = result + "+-------+-------+-------+\n";
return result;
}
public void addStartValues(int row,int col, int val) {
board[row][col] = value;
start[row][col] = true;
}
public void addMove(int row,int col,int val) {
scacchiera[row][col] = val;
inizio[row][col] = false;
}
public boolean verifyGame () {
if (board.length != 9) {
System.out.println("Board should have 9 rows");
return false;
}
for (int i = 0; i < board.length; i++) {
if (board[i].length != 9) {
System.out.println("Row "+ i +" should have 9 cells.");
return false;
}
}
/* check each cell for conflicts */
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
int cell = board[i][j];
if (cell == 0) {
continue; /* blanks are always OK */
}
if ((cell < 1) || (cell > 9)) {
System.out.println("Row "+ i +", column "+ j +" has value illegal "+ cell);
return false;
}
/* does it match any other value in the same row? */
for (int m = 0; m < board.length; m++) {
if ((j != m) && (cell == board[i][m]))
{
System.out.println("Row "+ i +" has "+ cell +" in position "+ j +" and "+ m);
return false;
}
}
/* does it match any other value it in the same column? */
for (int k = 0; k < board.length; k++) {
if ((i != k) && (cell == board[k][j])) {
System.out.println("Column "+ j +" has "+ cell +" in position "+ i +" and "+ k);
return false;
}
}
/* does it match any other value in the 3x3? */
for (int k = 0; k < 3; k++) {
for (int m = 0; m < 3; m++) {
int testRow = (i / 3 * 3) + k; /* test this row */
int testCol = (j / 3 * 3) + m; /* test this col */
if ((i != testRow) && (j != testCol) && (cell == board[testRow][testCol])) {
System.out.println("Value "+ cella +" at row "+ i +", column "+ j +" matches with value at row "+ testRow +", column "+ testColumn);
return false;
}
}
}
}
}
return true;
}
public int getValoreIn(int row, int col) {
return scacchiera[row][col];
}
private boolean isInRow(int row, int num) {
for (int i = 0; i < SIZE; i++)
if (board[row][i] == num) {
return true;
}
return false;
}
// we check if a possible number is already in a column
private boolean isInCol(int col, int number) {
for (int i = 0; i < SIZE; i++)
if (board[i][col] == number) {
return true;
}
return false;
}
// we check if a possible number is in its 3x3 box
private boolean isInBox(int row, int col, int number) {
int r = row - row % 3;
int c = col - col % 3;
for (int i = r; i < r + 3; i++)
for (int j = c; j < c + 3; j++)
if (board[i][j] == number) {
return true;
}
return false;
}
public boolean[][] getValidValues(int row, int col) {
boolean[][] validValues = new boolean[9][9];
int[] digit = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for(int i=0; i < digit.length; i++) {
for(int j=0; j < digit.length; j++) {
if(!isInRow(row,digit[i]) && !isInCol(col,digit[i]) && !isInBox(row,col,digit[i])) {
validValues[i][j] = true;
} else {
validValues[i][j] = false;
}
}
}
return validValues;
}
I edited the code, adding other, private, methods called: isInRow, isInCol, isInBox. I thought to do this to get an easier way to implement the method getValidValues. What do you think about? Are there any suggestions?
The main rule in sudoku is: all numbers in a column, a row and a 3x3 square have to be unique. Based on that you have to do three thing:
Iterate over all cells in the same column. If given column contains a number, set that number to invalid.
Same as above but for the row.
Find out the 3x3 square for the cell you're validating. It will start at coordinates like [floor(x/3), floor(y/3)]. Then you iterate over cells in that square and set numbers to invalid, just like above.
I hope that is enough to get you started. Don't want to post the code because that will take away the learning process.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I was trying to solve the Game of life problem for a teacher. Rules of that game are:
Any live cell with fewer than two live neighbors dies, as if caused by under-population. Any live cell with two or three live neighbors’ lives on to the next generation. Any live cell with more than three live neighbors dies, as if by overcrowding. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
There are two problems with my code - first of all, my main class doesn't seem to be working. Secondly, I performed the problem through many many if else statements. Are there more concise ways of writing the exceptions for my getNeighbors() method?
Thanks!
import java.util.Random;
public class GameOfLife {
final static int ROWS = 6;
final static int COLUMNS = 7;
String[][] simulator;
private Random randomGenerator;
public GameOfLife() {
simulator = new String[ROWS][COLUMNS];
randomGenerator = new Random();
}
public void fillSpot (int row, int column) {
simulator [row][column] = "O";
}
private void deleteSpot (int row, int column) {
simulator[row][column] = "";
}
// Do I need the above methods? really?
public void randomSimulation() {
for (int i = 0; i <= ROWS; i++) {
for (int j = 0; j <= COLUMNS; j++) {
int random = randomGenerator.nextInt(1);
if (random == 1) {
fillSpot(i,j);
}
}
}
}
private void getNeighbors (int row, int column) {
int neighbors = 0;
if (row < ROWS && row > 0 && column < COLUMNS && column > 0) {
for (int i = row - 1; i <= row + 1; i++) {
for (int j = column - 1; j <= column + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
if (row > ROWS || column > COLUMNS || row < 0 || column < 0) {
}
else if (row == ROWS && column < COLUMNS && column != 0) {
for (int i = row - 1; i <= ROWS; i++) {
for (int j = column - 1; j <= column + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else if (row < ROWS && column == COLUMNS && row != 0) {
for (int i = row - 1; i <= row + 1; i++) {
for (int j = column - 1; j <= COLUMNS; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else if (row == 0 && column < COLUMNS && column != 0) {
for (int i = 0; i <= row + 1; i++) {
for (int j = column - 1; j <= COLUMNS + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else if (row == 0 && column == COLUMNS) {
for (int i = row; i <= row + 1; i++) {
for (int j = column - 1; j <=COLUMNS; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else if (column == 0 && row < ROWS && row != 0) {
for (int i = row - 1; i <= row + 1; i++) {
for (int j = column; j <= COLUMNS + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else {
for (int i = row; i <= row + 1; i++) {
for (int j = column; j <= column + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
// for row == 0 && column == 0
if (simulator [row][column].contains("O")) {
neighbors--;
}
simulator[row][column] += " " + neighbors;
}
//There are wayyy too manyy clauses here for me to be comfortable. There's got to be a way to do this cleaner
private void nextGenPlanning() {
for (int i = 0; i <= ROWS; i++) {
for (int j = 0; j <= COLUMNS; j++) {
getNeighbors(i,j);
}
}
}
private void nextGen() {
nextGenPlanning();
for (int i = 0; i <= ROWS; i++) {
for (int j = 0; j <= COLUMNS; j++) {
String temp = simulator[i][j];
if (temp.charAt(temp.length()) <= 1 || temp.charAt(temp.length()) >= 4) {
deleteSpot(i,j);
}
else {
fillSpot (i,j);
}
}
}
}
public String toString() {
String string = "";
for (int i = 0; i < ROWS; i++) {
string = string + "|";
for (int j = 0; j < COLUMNS; j++) {
String temp = simulator[i][j];
string = string + temp.charAt(0);
}
string = string + "|\n";
}
return string;
}
public String simulate (int numOfTrials) {
String string = "";
for (int i = 0; i <= numOfTrials; i++) {
nextGen();
string += toString();
}
return string;
}
public void main (String [] args) {
randomSimulation();
System.out.println(simulate(2));
}
}
First, you have:
public void main (String [] args) {
randomSimulation();
System.out.println(simulate(2));
}
You should have:
public static void main (String[] args) {
GameOfLife game = new GameOfLife();
game.randomSimulation();
System.out.println(game.simulate(2));
}
Second, for getNeighbors, first consider that a 'get' method usually returns a value. If you're counting the number of neighbors, consider:
public int getNeighbors(int x, int y) {
int neighbors = 0;
int leftX = Math.max(x-1, 0);
int rightX = Math.min(x+1, COLUMNS);
int topY = Math.max(y-1, 0);
int bottomY = Math.min(y+1, ROWS);
for (int i=leftX; i < rightX; i++) {
for (int j=topY; j < bottomY; j++) {
if (simulator[i][j].contains('O')) { // Notice I'm using a char here, see my next comment
neighbors++;
}
}
}
return neighbors;
}
Third, I recommend using char[][] instead of String[][] for your simulator if each space in the simulator only holds one character value. There are some things about Strings in Java that you don't need to get tripped up with - for example, in Java, you cannot compare the value of Strings using == (you need to use String's equals() method).
First , your main class should be Public static void main(String[] args) and you can use switch case except of if else if you really sure on if else you can use if ( blabla == blablabla &(this means and ) blaba == babalaba)
I am trying to make the game Go-Moku. The game compiles, but doesn not run properly.
When I run the game I am able to have the empty board printed and then i am prompted to enter the row and column integers, but once I hit enter to submit the column int, nothing else happens.
Here is my code:
import java.util.Scanner;
public class GoMoku extends Board{
Scanner input = new Scanner(System.in);
//play turn method
boolean play (int player){
this.printBoard();
System.out.println("It's Player "+ player + "'s turn.");
System.out.print("Choose Row: ");
int row = input.nextInt();
System.out.print("Choose Column: ");
int column = input.nextInt();
return this.place(row, column, player);
}
public static void main(String[] args) {
System.out.println("Welcome to Go-Moku!");
GoMoku gomoku = new GoMoku();
int gameLoop = 1;
//Turn taking Loop
while ( gameLoop != 0) {
//Player 1 Loop
while (gameLoop == 1) {
gameLoop++;
if (gomoku.play(1) == true) gameLoop = 0;
}
//Player 2 Loop
while (gameLoop == 2) {
gameLoop--;
if (gomoku.play(2) == true) gameLoop = 0;
}
}
}
public class Board {
int[][] board = new int[19][19];
//Board Contructor
public Board() {
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
board[i][j] = 0;
}
}
}
//Places token for player
public boolean place(int row, int column, int player) {
if (board[row][column] == 0) {
board[row][column] = player;
}
return this.hasWin(row, column, player);
}
//Checks to see if the player won the game horizontally
public boolean hasHorizontalWin(int row, int column,int player) {
int left = 0;
int right = 0;
//Counts connections made on left side of placement
for (int k = 1; k < 6; k++){
if (board[row - k][column] == player) left++;
}
//Counts connectons made on right side of placement
for (int l = 1; l < 6; l++) {
if (board[row + l][column] == player) right++;
}
int count = left + right;
if (count == 5) {
return true;
} else return false;
}
//Checks to see if the player won the game vertically
public boolean hasVerticalWin(int row, int column, int player) {
int down = 0;
int up = 0;
//Counts connections made on down side of placement
for (int n = 1; n < 6; n++){
if (board[row][column - n] == player) down++;
}
//Counts connections made on up side of placement
for (int p = 1; p < 6; p++) {
if (board[row][column + p] == player) up++;
}
int count = up + down;
if (count == 5) {
return true;
} else return false;
}
//Player wins method
boolean hasWin(int row, int column, int player) {
if (this.hasHorizontalWin(row, column, player) == true ||
this.hasVerticalWin(row, column, player) == true) {
System.out.println("Player " + player + " wins!");
return true;
} else return false;
}
//Prints board as string
public void printBoard(){
for (int m = 0; m < 19; m++){
for (int b = 0 ; b < 19; b++){
if (board[m][b] == 0) System.out.print("-");
if (board[m][b] == 1) System.out.print("o");
if (board[m][b] == 2) System.out.print("x");
}
System.out.println();
}
}
}
}
thanks
The problem is in the Board class - when you check for winning lines you can get an ArrayOutOfBounds exception.
You can fix it with something like this:
public class Board {
static final int WIDTH = 19;
static final int HEIGHT = 19;
int[][] board = new int[HEIGHT][WIDTH];
//Board Contructor
public Board() {
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
board[i][j] = 0;
}
}
}
//Places token for player
public boolean place(int row, int column, int player) {
if (board[row][column] == 0) {
board[row][column] = player;
}
return this.hasWin(row, column, player);
}
//Checks to see if the player won the game horizontally
public boolean hasHorizontalWin(int row, int column,int player) {
int total = 1;
//Counts connections made on left side of placement
for ( int k = row - 1; k >= 0 && k > row - 5; --k ) {
if ( board[k][column] != player ) break;
++total;
}
for ( int k = row + 1; k < HEIGHT && k < row + 5; ++k ) {
if ( board[k][column] != player ) break;
++total;
}
return total >= 5;
}
//Checks to see if the player won the game vertically
public boolean hasVerticalWin(int row, int column, int player) {
int total = 1;
//Counts connections made on left side of placement
for ( int k = column - 1; k >= 0 && k > column - 5; --k ) {
if ( board[row][k] != player ) break;
++total;
}
for ( int k = column + 1; k < WIDTH && k < column + 5; ++k ) {
if ( board[row][k] != player ) break;
++total;
}
return total >= 5;
}
//Player wins method
boolean hasWin(int row, int column, int player) {
if (this.hasHorizontalWin(row, column, player) == true ||
this.hasVerticalWin(row, column, player) == true) {
System.out.println("Player " + player + " wins!");
return true;
} else return false;
}
//Prints board as string
public void printBoard(){
for (int m = 0; m < HEIGHT; m++){
for (int b = 0 ; b < WIDTH; b++){
if (board[m][b] == 0) System.out.print("-");
if (board[m][b] == 1) System.out.print("o");
if (board[m][b] == 2) System.out.print("x");
}
System.out.println();
}
}
}
You can also simplify the main method:
public static void main(String[] args) {
System.out.println("Welcome to Go-Moku!");
GoMoku gomoku = new GoMoku();
int player = 1;
//Turn taking Loop
while ( true ) {
if ( gomoku.play( player ) ) break;
player = 3 - player;
}
}
Apart from that there are still other places where you can get errors (i.e. if the user enters a row or column that is negative or greater than the board size) and players can enter the same co-ordinates over and over.
public boolean verticaleWin(int ligne, int colonne, int player) {
int total = 1;
for (int k = ligne - 1; (k >= 0 && k > ligne - 5); k--) {
if (dimension[k][colonne] != player) break;
++total;
}
for (int k = ligne + 1; k < dimension.length && k < ligne + 5; k++) {
if (dimension[k][colonne] != player) break;
++total;
}
return total >= 5;
}
public boolean horizontaleWin(int ligne, int colonne, int player) {
int total = 1;
for (int k = colonne - 1; k >= 0 && k > colonne - 5; k--) {
if (dimension[ligne][k] != player) break;
++total;
}
for (int k = ++colonne; k < dimension.length && k < colonne + 5; k++) {
if (dimension[ligne][k] != player) break;
++total;
}
return total >= 5;
}
public boolean diagonaleWin(int ligne, int colonne, int player) {
int total1 = 1;
int total2 = 1;
for (int k = ligne - 1, j = colonne + 1; (k >= 0 && k > ligne - 5 && j < dimension.length && j < colonne + 5); k--, j++) {
if (dimension[k][j] != player) break;
++total1;
}
for (int k = ligne + 1, j = colonne - 1; (k < dimension.length && k < ligne + 5 && j >= 0 && j > colonne - 5); k++, j--) {
if (dimension[k][j] != player) break;
++total1;
}
for (int k = ligne + 1, j = colonne + 1; (k < dimension.length && k < ligne + 5 && j < dimension.length && j < colonne + 5); k++, j++) {
if (dimension[k][j] != player) break;
++total2;
}
for (int k = ligne - 1, j = colonne - 1; (k >= 0 && k > ligne - 5 && j >= 0 && j > colonne - 5); k--, j--) {
if (dimension[k][j] != player) break;
++total2;
}
return ((total1 >= 5) || (total2 >= 5));
}