I am working on a program that will solve find a path in a maze. The maze is represented by 0's, 1's and an E to represent the Exit. The maze is represented by a 20x30 (0's represent the path, 1's represent walls). I am using a stack to keep track of a previous usable location.
I think I have most of the code figured out, but when I run it and enter the starting position, the final maze doesn't print out.
My code is as follows:
import java.util.*;
import java.io.*;
public class MazeGenerator {
//main
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int userRow, userCol;
MazeGenerator maze = new MazeGenerator();
maze.fillArray();
maze.print();
System.out.println();
//asking for user starting position
System.out.print("What row would you like to start in?: " );
userRow = sc.nextInt();
while(userRow > 29 || userRow < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 -
29 INCLUSIVE: " );
userRow = sc.nextInt();
}
System.out.println();
System.out.print("What column would you like to start in? ");
userCol = sc.nextInt();
while(userCol > 19 || userCol < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 -
19 INCLUSIVE: " );
userCol= sc.nextInt();
}
System.out.println("\n\nFind a path using a stack: ");
//maze.userStart(userRow,userCol);
maze.setUserRow(userRow);
maze.setUserColumn(userCol);
maze.solveStack();
//solveStack(maze);
}
//methods for creating maze
public static final int ROW = 30;
public static final int COLUMN = 20;
public int userRow = 0;
public int userColumn = 0;
private static String[][] maze = new String[ROW][COLUMN];
public void fillArray() throws IOException {
File file = new File("maze.txt");
FileReader reader = new FileReader(file);
BufferedReader buff = new BufferedReader(reader);
for(int counter1 = 0; counter1 < ROW; counter1++) {
String l = buff.readLine();
for(int counter2 = 0; counter2 < COLUMN; counter2++) {
maze[counter1][counter2] = String.valueOf(l.charAt(counter2));
}
}
buff.close();
}
public void print() throws IOException {
System.out.printf("%-4s", ""); //spaces column
for (int counter = 0; counter < COLUMN; counter++){
System.out.printf("%-4d",counter); //print the column number
}
System.out.println();
for(int counter1 = 0; counter1 < maze.length; counter1++) { //loop for
printing rows
System.out.printf("%-4d",counter1); //print row number
for(int counter2 = 0; counter2 < maze[counter1].length; counter2++)
{ //loop for printing columns
System.out.printf("%-4s", maze[counter1][counter2]); //printing
values of maze
}
System.out.println(); // new line
}
}
public int getWidth(){
return maze[0].length;
}
public int getHeight(){
return maze.length;
}
public void setUserRow (int userRow) {
this.userRow = userRow;
}
public void setUserColumn (int userColumn) {
this.userColumn = userColumn;
}
public int getUserRow() {
return userRow;
}
public int getUserColumn() {
return userColumn;
}
public String mark(int row, int col, String value) {
assert(inMaze(row,col));
String temp = maze[row][col];
maze[row][col] = value;
return temp;
}
public String mark (MazePosition pos, String value) {
return mark(pos.row(), pos.col(), value);
}
public boolean isMarked(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col].equals("+"));
}
public boolean isMarked(MazePosition pos) {
return isMarked(pos.row(), pos.col());
}
public boolean Clear(int row, int col) {
assert(inMaze(row,col));
return (maze[row+1][col+1] != "1" && maze[row+1][col+1] != "+");
}
public boolean Clear(MazePosition pos) {
return Clear(pos.row(), pos.col());
}
//true if cell is within maze
public boolean inMaze(int row, int col) {
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
return true;
}
return false;
}
//true if cell is within maze
public boolean inMaze(MazePosition pos) {
return inMaze(pos.row(), pos.col());
}
public boolean Done( int row, int col) {
return (maze[row][col].equals("E"));
}
public boolean Done(MazePosition pos) {
return Done(pos.row(), pos.col());
}
public String[][] clone() {
String[][] copy = new String[ROW][COLUMN];
for (int counter1 = 0; counter1 < ROW; counter1++) {
for (int counter2 = 0; counter2 < COLUMN; counter2++) {
copy[counter1][counter2] = maze[counter1][counter2];
}
}
return copy;
}
public void restore(String[][] savedMaze) {
for (int i=0; i< ROW; i++)
for (int j=0; j<COLUMN; j++)
maze[i][j] = savedMaze[i][j];
}
public MazeGenerator clone(MazeGenerator m) {
MazeGenerator maze = new MazeGenerator();
maze = m;
return maze;
}
//**************************************************
//this solution uses a stack to keep track of possible
//states/positions to explore; it marks the maze to remember the
//positions that it's already explored.
public void solveStack() throws IOException {
//save the maze
//MazeGenerator savedMaze = new MazeGenerator();
//savedMaze.clone(m);
String[][] savedMaze = clone();
//declare the locations stack
Stack<MazePosition> candidates = new Stack<MazePosition>();
//insert the start
candidates.push(new MazePosition(userRow,userColumn));
MazePosition current, next;
while (!candidates.empty()) {
//get current position
current = candidates.pop();
if (Done(current)) {
break;
}
//mark the current position
mark(current, "+");
//put its neighbors in the queue
next = current.north();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.east();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.west();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.south();
if (inMaze(next) && Clear(next)) candidates.push(next);
}
if (!candidates.empty()) {
System.out.println("You got it!");
}
else System.out.println("You're stuck in the maze!");
//savedMaze.print();
print();
restore(savedMaze);
}
class MazePosition {
public int row;
public int col;
public MazePosition(int row, int col) {
this.row = row;
this.col = col;
}
public int row() { return row; }
public int col() { return col; }
public void print() {
System.out.println("(" + row + "," + col + ")");
}
//positions
public MazePosition north() {
return new MazePosition(row-1, col);
}
public MazePosition south() {
return new MazePosition(row+1, col);
}
public MazePosition east() {
return new MazePosition(row, col+1);
}
public MazePosition west() {
return new MazePosition(row, col-1);
}
};
}
Without the benefit of a maze.txt, I created one based on your description. Here's what I found...
Short answer:
Your program hits an infinite loop searching for the exit, so it never reaches the code to print it out.
Long answer:
I see 3 problems on 2 lines of code:
1) A simple typo:
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
getHeight() and getWidth() should be swapped:
if (row >= 0 && col >= 0 && row < getHeight() && col < getWidth() ) {
2) In one spot, you're using 1-based indices, when Java uses 0-based indices:
In this line here:
return (maze[row+1][col+1] != "1" && maze[row+1][col+1] != "+");
Array indices in java start at 0. Your row and col variables also start at 0. But you're adding one to them thereby converting them into 1-based indices. So, you'd want:
return (maze[row][col] != "1" && maze[row][col] != "+");
3) You're using != like !equals(), but in Java, == is not the same as .equals()
In the above line of code, you're comparing two Strings with the != operator. But that doesn't work like the String.equals() method, so your Clear() method always returns true.
This is the crux of your stated problem. The search routine, finding every cell clear, works its way into a corner, and then searches the same two adjacent cells forever.
So, what you really want is:
return (!maze[row][col].equals("1") && !maze[row][col].equals("+"));
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am working on a program that will solve find a path in a maze. The maze is represented by 0's, 1's and an E to represent the Exit. The maze is represented by a 20x30 (0's represent the path, 1's represent walls). I am using a stack to keep track of a previous usable location.
I think I have most of the code figured out, but whenever i try to run it, i get an ArrayIndexOutOfBoundsException. I think the main problem is that there are no defined walls around the border. Maybe surround the maze with a border of 1's?
My code is as follows:
import java.util.*;
import java.io.*;
public class MazeGenerator {
//main
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int userRow, userCol;
MazeGenerator maze = new MazeGenerator();
maze.fillArray();
maze.print();
System.out.println();
//asking for user starting position
System.out.print("What row would you like to start in?: " );
userRow = sc.nextInt();
while(userRow > 29 || userRow < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 - 29 INCLUSIVE: " );
userRow = sc.nextInt();
}
System.out.println();
System.out.print("What column would you like to start in? ");
userCol = sc.nextInt();
while(userCol > 19 || userCol < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 - 19 INCLUSIVE: " );
userCol= sc.nextInt();
}
System.out.println("\n\nFind a path using a stack: ");
//maze.userStart(userRow,userCol);
maze.setUserRow(userRow);
maze.setUserColumn(userCol);
maze.solveStack();
}
//methods for creating maze
public static final int ROW = 30;
public static final int COLUMN = 20;
public int userRow = 0;
public int userColumn = 0;
private static String[][] maze = new String[ROW][COLUMN];
public void fillArray() throws IOException {
File file = new File("maze.txt");
FileReader reader = new FileReader(file);
BufferedReader buff = new BufferedReader(reader);
for(int counter1 = 0; counter1 < ROW; counter1++) {
String l = buff.readLine();
for(int counter2 = 0; counter2 < COLUMN; counter2++) {
maze[counter1][counter2] = String.valueOf(l.charAt(counter2));
}
}
buff.close();
}
public void print() throws IOException {
System.out.printf("%-4s", ""); //spaces column
for (int counter = 0; counter < COLUMN; counter++){
System.out.printf("%-4d",counter); //print the column number
}
System.out.println();
for(int counter1 = 0; counter1 < maze.length; counter1++) { //loop for printing rows
System.out.printf("%-4d",counter1); //print row number
for(int counter2 = 0; counter2 < maze[counter1].length; counter2++) { //loop for printing columns
System.out.printf("%-4s", maze[counter1][counter2]); //printing values of maze
}
System.out.println(); // new line
}
}
public int size() {
return maze.length;
}
public void setUserRow (int userRow) {
this.userRow = userRow;
}
public void setUserColumn (int userColumn) {
this.userColumn = userColumn;
}
public int getUserRow() {
return userRow;
}
public int getUserColumn() {
return userColumn;
}
public String mark(int row, int col, String value) {
assert(inMaze(row,col));
String temp = maze[row][col];
maze[row][col] = value;
return temp;
}
public String mark (MazePosition pos, String value) {
return mark(pos.row(), pos.col(), value);
}
public boolean isMarked(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col].equals("+"));
}
public boolean isMarked(MazePosition pos) {
return isMarked(pos.row(), pos.col());
}
public boolean Clear(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col] != "1" && maze[row][col] != "+");
}
public boolean Clear(MazePosition pos) {
return Clear(pos.row(), pos.col());
}
//true if cell is within maze
public boolean inMaze(int row, int col) {
if (row >= 0 && col<size() && row>= 0 && col<size()) {
return true;
}
else if (row < 0 && col<size() && row >= 0 && col<size()) {
return false;
}
else return false;
}
//true if cell is within maze
public boolean inMaze(MazePosition pos) {
return inMaze(pos.row(), pos.col());
}
public boolean Done( int row, int col) {
return (maze[row][col].equals("E"));
}
public boolean Done(MazePosition pos) {
return Done(pos.row(), pos.col());
}
public String[][] clone() {
String[][] copy = new String[ROW][COLUMN];
for (int counter1 = 0; counter1 < ROW; counter1++) {
for (int counter2 = 0; counter2 < COLUMN; counter2++) {
copy[counter1][counter2] = maze[counter1][counter2];
}
}
return copy;
}
public void solveStack() throws IOException {
//save the maze
String[][] savedMaze = clone();
//declare the locations stack
Stack<MazePosition> candidates = new Stack<MazePosition>();
//insert the start
candidates.push(new MazePosition(userRow,userColumn));
MazePosition current, next;
while (!candidates.empty()) {
//get current position
current = candidates.pop();
if (Done(current)) {
break;
}
//mark the current position
mark(current, "S");
//put its neighbors in the queue
next = current.north();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.east();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.west();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.south();
if (inMaze(next) && Clear(next)) candidates.push(next);
}
if (!candidates.empty())
System.out.println("You got it!");
else System.out.println("You're stuck in the maze!");
print();
}
class MazePosition {
public int row;
public int col;
public MazePosition(int row, int col) {
this.row = row;
this.col = col;
}
public int row() { return row; }
public int col() { return col; }
public void print() {
System.out.println("(" + row + "," + col + ")");
}
//positions
public MazePosition north() {
return new MazePosition(row-1, col);
}
public MazePosition south() {
return new MazePosition(row+1, col);
}
public MazePosition east() {
return new MazePosition(row, col+1);
}
public MazePosition west() {
return new MazePosition(row, col-1);
}
};
}
The error is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at MazeGenerator.Clear(MazeGenerator.java:137)
at MazeGenerator.Clear(MazeGenerator.java:141)
at MazeGenerator.solveStack(MazeGenerator.java:217)
at MazeGenerator.main(MazeGenerator.java:40)
i think you're doing a mistake in inMaze(int row, int col) method. I'll try to correct it for you
public boolean inMaze(int row, int col) {
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
return true;
}
return false;
}
therefore you have to change the size() method into getWidth() and getHeight()
public int getWidth(){
return maze[0].length;
}
public int getHeight(){
return maze.length;
}
This question already has answers here:
Auto errors detection in IntelliJ IDEA
(8 answers)
Closed 5 years ago.
enter image description here import java.util.Scanner;
public class EnglishCheckers {
// Global constants
public static final int RED = 1;
public static final int BLUE = -1;
public static final int EMPTY = 0;
public static final int SIZE = 8;
// You can ignore these constants
public static final int MARK = 3;
public static EnglishCheckersGUI grid;
public static Scanner getPlayerFullMoveScanner = null;
public static Scanner getStrategyScanner = null;
public static final int RANDOM = 1;
public static final int DEFENSIVE = 2;
public static final int SIDES = 3;
public static final int CUSTOM = 4;
public static void main(String[] args) {
// ******** Don't delete *********
// CREATE THE GRAPHICAL GRID
grid = new EnglishCheckersGUI(SIZE);
// *******************************
//showBoard(example);
//printMatrix(example);
//interactivePlay();
//twoPlayers();
/* ******** Don't delete ********* */
if (getPlayerFullMoveScanner != null){
getPlayerFullMoveScanner.close();
}
if (getStrategyScanner != null){
getStrategyScanner.close();
}
/* ******************************* */
}
public static int[][] createBoard() {
int[][] board = null;
board=new int[8][8]; // defines the new length of the array
for (int j=0; j<8; j=j+1)
{
for (int m=0; m<8; m=m+1) // these two "for" loops will set the value of each square of the board according to the instructions regarding it's location.
{
if (j==0|j==2)
{
if (m%2==0)
board[j][m]=1;
else
board[j][m]=0;
}
if (j==1)
{
if (m%2!=0)
board[j][m]=1;
else
board[j][m]=0;
}
if (j>2&j<5)
board[j][m]=0;
if (j==5|j==7)
{
if (m%2!=0)
board[j][m]=-1;
else
board[j][m]=0;
}
if (j==6)
{
if (m%2==0)
board[j][m]=-1;
else
board[j][m]=0;
}
}
}
return board;
}
public static int howManyDiscs (int[][] board, int player){ // this function will return the number of discs a player has on the board
int positive=0;
int negative=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1)
{
if (board[i][j]>0) positive=positive+1;
if (board[i][j]<0) negative=negative+1;
}
}
if (player>0) return positive;
else return negative;
}
public static int[][] playerDiscs(int[][] board, int player) {
int[][] positions = null;
if (howManyDiscs(board,player)>0)
{
positions=new int[howManyDiscs(board,player)][2]; // defines the new length of the array
int line=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1)
{
if (player>0&&board[i][j]>0) // will update the array if the player is 1
{
positions[line][0]=i;
positions[line][1]=j;
line=line+1;
}
if (player<0&&board[i][j]<0) // will update the array if the player is (-1)
{
positions[line][0]=i;
positions[line][1]=j;
line=line+1;
}
}
}
}
return positions;
}
public static boolean isBasicMoveValid(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
boolean ans = false;
if (fromRow>=0&&fromRow<8&&fromCol>=0&&fromCol<8&&toRow>=0&&toRow<8&&toCol>=0&&toCol<8) // makes sure the coordinates are legal
{
if (board[fromRow][fromCol]==player|board[fromRow][fromCol]==player*2) // checks if a disc of the player exists in the origin square
{
if(board[toRow][toCol]==0) // checks if the destination square is legal
{
if (toCol==fromCol+1||toCol==fromCol-1) // checks if the destination column is legal
{
if (toRow==fromRow+1&&player!=-1) // makes sure the move is legal for a player that isn't (-1)
{
ans=true;
}
if (toRow==fromRow-1&&player!=1) // makes sure the move is legal for a player that isn't 1
{
ans=true;
}
}
}
}
}
return ans;
}
public static int[][] getAllBasicMoves(int[][] board, int player) {
int[][] moves = null;
int line=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1) // these 2 "for" loops will add 1 to the counter "line" for each legal move a square has
{
if (isBasicMoveValid(board,player,i,j,i+1,j+1)) line=line+1;
if (isBasicMoveValid(board,player,i,j,i+1,j-1)) line=line+1;
if (isBasicMoveValid(board,player,i,j,i-1,j+1)) line=line+1;
if (isBasicMoveValid(board,player,i,j,i-1,j-1)) line=line+1;
}
}
moves=new int[line][4]; // creating the length of the output array according to the amount of possibilities found
line=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1) // the if's below will insert every move that exists for each square to the array
{
if (isBasicMoveValid(board,player,i,j,i+1,j+1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i+1;
moves[line][3]=j+1;
line=line+1;
}
if (isBasicMoveValid(board,player,i,j,i+1,j-1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i+1;
moves[line][3]=j-1;
line=line+1;
}
if (isBasicMoveValid(board,player,i,j,i-1,j+1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i-1;
moves[line][3]=j+1;
line=line+1;
}
if (isBasicMoveValid(board,player,i,j,i-1,j-1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i-1;
moves[line][3]=j-1;
line=line+1;
}
}
}
return moves;
}
public static boolean isBasicJumpValid(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
boolean ans = false;
if (fromRow>=0&&fromRow<8&&fromCol>=0&&fromCol<8&&toRow>=0&&toRow<8&&toCol>=0&&toCol<8) // makes sure the coordinates are legal
{
if (board[fromRow][fromCol]==player|board[fromRow][fromCol]==player*2) // checks if a disc of the player exists in the origin square
{
if(board[toRow][toCol]==0) // checks if the destination square is legal
{
if (toRow==fromRow+2)
{
if (toCol==fromCol+2)
{
if (player==1|player==2)
{
if (board[fromRow+1][fromCol+1]<0)
ans=true;
}
if (player==-2)
{
if (board[fromRow+1][fromCol+1]>0)
ans=true;
}
}
if (toCol==fromCol-2)
{
if (player==1|player==2)
{
if (board[fromRow+1][fromCol-1]<0)
ans=true;
}
if (player==-2)
{
if (board[fromRow+1][fromCol-1]>0)
ans=true;
}
}
}
if (toRow==fromRow-2)
{
if (toCol==fromCol+2)
{
if (player==-1|player==-2)
{
if (board[fromRow-1][fromCol+1]>0)
ans=true;
}
if (player==2)
{
if (board[fromRow-1][fromCol+1]<0)
ans=true;
}
}
if (toCol==fromCol-2)
{
if (player==-1|player==-2)
{
if (board[fromRow-1][fromCol-1]>0)
ans=true;
}
if (player==2)
{
if (board[fromRow-1][fromCol-1]<0)
ans=true;
}
}
}
}
}
}
return ans;
}
public static int [][] getRestrictedBasicJumps(int[][] board, int player, int row, int col) {
int[][] moves = null;
int line=0;
for (int i=row-2; i<=row+2; i=i+2)
{
for (int j=col-2; j<=col+2; j=j+2) // these 2 "for" loops will add 1 to the counter "line" for each legal move a square has
{
if (isBasicJumpValid(board,player,row,col,i,j)) line=line+1;
}
}
moves=new int[line][4]; // creating the length of the output array according to the amount of possibilities found
line=0;
for (int i=row-2; i<=row+2; i=i+2)
{
for (int j=col-2; j<=col+2; j=j+2)
{
if (isBasicJumpValid(board,player,row,col,i,j)) // will insert every possible jump to the array
{
moves[line][0]=row;
moves[line][1]=col;
moves[line][2]=i;
moves[line][3]=j;
line=line+1;
}
}
}
return moves;
}
public static int[][] getAllBasicJumps(int[][] board, int player) {
int [][] moves = null;
int [][] discs = playerDiscs(board,player); // this array holds a list of the discs the player has on the board currently
int counter=0;
for (int i=0; i<discs.length; i=i+1) // will add each disc's amount of possible moves to the counter
counter=counter+getRestrictedBasicJumps(board,player,discs[i][0],discs[i][1]).length;
moves=new int[counter][4]; // defining the array's size according to the sum of all discs possible jumps
int line=0;
for (int a=0; a<discs.length; a=a+1)
{
int [][] jumps = getRestrictedBasicJumps(board,player,discs[a][0],discs[a][1]); // creates the array "jumps" that holds the possible jumps for the current "for" disc
for (int i=0; i<jumps.length; i=i+1) // will insert each line of the jumps array to the moves array
{
moves[line][0]=jumps[i][0];
moves[line][1]=jumps[i][1];
moves[line][2]=jumps[i][2];
moves[line][3]=jumps[i][3];
line=line+1;
}
}
return moves;
}
public static boolean canJump(int[][] board, int player) {
boolean ans = false;
if (getAllBasicJumps(board,player).length>0) ans=true;
return ans;
}
public static boolean isMoveValid(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
boolean ans = false;
if (isBasicJumpValid(board,player,fromRow,fromCol,toRow,toCol))
ans=true;
else
if (isBasicMoveValid (board,player,fromRow,fromCol,toRow,toCol))
ans=true;
return ans;
}
public static boolean hasValidMoves(int[][] board, int player) {
boolean ans = false;
if (getAllBasicMoves(board,player).length>0) ans=true;
if (canJump(board,player)) ans=true;
return ans;
}
public static int[][] playMove(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
if (isBasicJumpValid(board,player,fromRow,fromCol,toRow,toCol)) // in case it's a jump- will replace the eaten player with 0
{
if (fromRow>toRow)
{
if (fromCol>toCol) board[fromRow-1][fromCol-1]=0;
else board[fromRow-1][fromCol+1]=0;
}
else
{
if (fromCol>toCol) board[fromRow+1][fromCol-1]=0;
else board[fromRow+1][fromCol+1]=0;
}
}
if (player==1&toRow==7)
{
board[toRow][toCol]=2;
board[fromRow][fromCol]=0;
}
else
{
if (player==-1&toRow==0)
{
board[toRow][toCol]=-2;
board[fromRow][fromCol]=0;
}
else
{
board[toRow][toCol]=player;
board[fromRow][fromCol]=0;
}
}
return board;
}
public static boolean gameOver(int[][] board, int player) {
boolean ans = false;
if (!hasValidMoves(board,player)) ans=true;
if (playerDiscs(board,1)==null | playerDiscs(board,-1)==null) ans=true;
return ans;
}
public static int findTheLeader(int[][] board) {
int ans = 0;
int player1=0, player2=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1)
{
if (board[i][j]==1) player1=player1+1;
if (board[i][j]==2) player1=player1+2;
if (board[i][j]==-1) player1=player2+1;
if (board[i][j]==-2) player1=player2+2;
}
}
if (player1>player2)
ans=1;
else
if (player2>player1)
ans=-1;
else
ans=0;
return ans;
}
public static int[][] randomPlayer(int[][] board, int player) {
if (hasValidMoves(board,player))
{
if (getAllBasicMoves(board,player).length>0 && isMoveValid(board,player,getAllBasicMoves(board,player)[0][0],getAllBasicMoves(board,player)[0][1],getAllBasicMoves(board,player)[0][2],getAllBasicMoves(board,player)[0][3]))
board=playMove(board,player,getAllBasicMoves(board,player)[0][0],getAllBasicMoves(board,player)[0][1],getAllBasicMoves(board,player)[0][2],getAllBasicMoves(board,player)[0][3]);
else
if (getAllBasicJumps(board,player).length>0 && isMoveValid(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]))
board=playMove(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]);
}
return board;
}
public static int[][] defensivePlayer(int[][] board, int player) {
if (hasValidMoves(board,player))
{
if (canJump(board,player))
board=playMove(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]);
else
{
boolean goodMove=false;
int i=0;
int [][] arr=board;
while (i<getAllBasicMoves(board,player).length && !goodMove)
{
arr=playMove(board,player,getAllBasicMoves(board,player)[i][0],getAllBasicMoves(board,player)[i][1],getAllBasicMoves(board,player)[i][2],getAllBasicMoves(board,player)[i][3]);
if (!canJump(arr,-player))
goodMove=true;
i=i+1;
}
board=arr;
}
}
return board;
}
public static int[][] sidesPlayer(int[][] board, int player) {
if (hasValidMoves(board,player))
{
if (canJump(board,player))
board=playMove(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]);
else
{
if (getAllBasicMoves(board,player).length>1)
{
int bestMove=0, minHefresh=7;
for (int i=1; i<getAllBasicMoves(board,player).length; i=i+1)
{
if (Math.abs(0-getAllBasicMoves(board,player)[i][3])<minHefresh)
{
bestMove=i;
minHefresh=Math.abs(0-getAllBasicMoves(board,player)[i][3]);
}
if (Math.abs(0-getAllBasicMoves(board,player)[i-1][3])<minHefresh)
{
bestMove=i-1;
minHefresh=Math.abs(0-getAllBasicMoves(board,player)[i-1][3]);
}
if (Math.abs(7-getAllBasicMoves(board,player)[i][3])<minHefresh)
{
bestMove=i;
minHefresh=Math.abs(7-getAllBasicMoves(board,player)[i][3]);
}
if (Math.abs(7-getAllBasicMoves(board,player)[i-1][3])<minHefresh)
{
bestMove=i-1;
minHefresh=Math.abs(7-getAllBasicMoves(board,player)[i-1][3]);
}
}
board=playMove(board,player,getAllBasicMoves(board,player)[bestMove][0],getAllBasicMoves(board,player)[bestMove][1],getAllBasicMoves(board,player)[bestMove][2],getAllBasicMoves(board,player)[bestMove][3]);
}
else
board=playMove(board,player,getAllBasicMoves(board,player)[0][0],getAllBasicMoves(board,player)[0][1],getAllBasicMoves(board,player)[0][2],getAllBasicMoves(board,player)[0][3]);
}
}
return board;
}
//******************************************************************************//
/* ---------------------------------------------------------- *
* Play an interactive game between the computer and you *
* ---------------------------------------------------------- */
public static void interactivePlay() {
int[][] board = createBoard();
showBoard(board);
System.out.println("Welcome to the interactive Checkers Game !");
int strategy = getStrategyChoice();
System.out.println("You are the first player (RED discs)");
boolean oppGameOver = false;
while (!gameOver(board, RED) && !oppGameOver) {
board = getPlayerFullMove(board, RED);
oppGameOver = gameOver(board, BLUE);
if (!oppGameOver) {
EnglishCheckersGUI.sleep(200);
board = getStrategyFullMove(board, BLUE, strategy);
}
}
int winner = 0;
if (playerDiscs(board, RED).length == 0 | playerDiscs(board, BLUE).length == 0){
winner = findTheLeader(board);
}
if (winner == RED) {
System.out.println();
System.out.println("\t *************************");
System.out.println("\t * You are the winner !! *");
System.out.println("\t *************************");
}
else if (winner == BLUE) {
System.out.println("\n======= You lost :( =======");
}
else
System.out.println("\n======= DRAW =======");
}
/* --------------------------------------------------------- *
* A game between two players *
* --------------------------------------------------------- */
public static void twoPlayers() {
int[][] board = createBoard();
showBoard(board);
System.out.println("Welcome to the 2-player Checkers Game !");
boolean oppGameOver = false;
while (!gameOver(board, RED) & !oppGameOver) {
System.out.println("\nRED's turn");
board = getPlayerFullMove(board, RED);
oppGameOver = gameOver(board, BLUE);
if (!oppGameOver) {
System.out.println("\nBLUE's turn");
board = getPlayerFullMove(board, BLUE);
}
}
int winner = 0;
if (playerDiscs(board, RED).length == 0 | playerDiscs(board, BLUE).length == 0)
winner = findTheLeader(board);
System.out.println();
System.out.println("\t ************************************");
if (winner == RED)
System.out.println("\t * The red player is the winner !! *");
else if (winner == BLUE)
System.out.println("\t * The blue player is the winner !! *");
else
System.out.println("\t * DRAW !! *");
System.out.println("\t ************************************");
}
/* --------------------------------------------------------- *
* Get a complete (possibly a sequence of jumps) move *
* from a human player. *
* --------------------------------------------------------- */
public static int[][] getPlayerFullMove(int[][] board, int player) {
// Get first move/jump
int fromRow = -1, fromCol = -1, toRow = -1, toCol = -1;
boolean jumpingMove = canJump(board, player);
boolean badMove = true;
getPlayerFullMoveScanner = new Scanner(System.in);//I've modified it
while (badMove) {
if (player == 1){
System.out.println("Red, Please play:");
} else {
System.out.println("Blue, Please play:");
}
fromRow = getPlayerFullMoveScanner.nextInt();
fromCol = getPlayerFullMoveScanner.nextInt();
int[][] moves = jumpingMove ? getAllBasicJumps(board, player) : getAllBasicMoves(board, player);
markPossibleMoves(board, moves, fromRow, fromCol, MARK);
toRow = getPlayerFullMoveScanner.nextInt();
toCol = getPlayerFullMoveScanner.nextInt();
markPossibleMoves(board, moves, fromRow, fromCol, EMPTY);
badMove = !isMoveValid(board, player, fromRow, fromCol, toRow, toCol);
if (badMove)
System.out.println("\nThis is an illegal move");
}
// Apply move/jump
board = playMove(board, player, fromRow, fromCol, toRow, toCol);
showBoard(board);
// Get extra jumps
if (jumpingMove) {
boolean longMove = (getRestrictedBasicJumps(board, player, toRow, toCol).length > 0);
while (longMove) {
fromRow = toRow;
fromCol = toCol;
int[][] moves = getRestrictedBasicJumps(board, player, fromRow, fromCol);
boolean badExtraMove = true;
while (badExtraMove) {
markPossibleMoves(board, moves, fromRow, fromCol, MARK);
System.out.println("Continue jump:");
toRow = getPlayerFullMoveScanner.nextInt();
toCol = getPlayerFullMoveScanner.nextInt();
markPossibleMoves(board, moves, fromRow, fromCol, EMPTY);
badExtraMove = !isMoveValid(board, player, fromRow, fromCol, toRow, toCol);
if (badExtraMove)
System.out.println("\nThis is an illegal jump destination :(");
}
// Apply extra jump
board = playMove(board, player, fromRow, fromCol, toRow, toCol);
showBoard(board);
longMove = (getRestrictedBasicJumps(board, player, toRow, toCol).length > 0);
}
}
return board;
}
/* --------------------------------------------------------- *
* Get a complete (possibly a sequence of jumps) move *
* from a strategy. *
* --------------------------------------------------------- */
public static int[][] getStrategyFullMove(int[][] board, int player, int strategy) {
if (strategy == RANDOM)
board = randomPlayer(board, player);
else if (strategy == DEFENSIVE)
board = defensivePlayer(board, player);
else if (strategy == SIDES)
board = sidesPlayer(board, player);
showBoard(board);
return board;
}
/* --------------------------------------------------------- *
* Get a strategy choice before the game. *
* --------------------------------------------------------- */
public static int getStrategyChoice() {
int strategy = -1;
getStrategyScanner = new Scanner(System.in);
System.out.println("Choose the strategy of your opponent:" +
"\n\t(" + RANDOM + ") - Random player" +
"\n\t(" + DEFENSIVE + ") - Defensive player" +
"\n\t(" + SIDES + ") - To-the-Sides player player");
while (strategy != RANDOM & strategy != DEFENSIVE
& strategy != SIDES) {
strategy=getStrategyScanner.nextInt();
}
return strategy;
}
/* --------------------------------------- *
* Print the possible moves *
* --------------------------------------- */
public static void printMoves(int[][] possibleMoves) {
for (int i = 0; i < 4; i = i+1) {
for (int j = 0; j < possibleMoves.length; j = j+1)
System.out.print(" " + possibleMoves[j][i]);
System.out.println();
}
}
/* --------------------------------------- *
* Mark/unmark the possible moves *
* --------------------------------------- */
public static void markPossibleMoves(int[][] board, int[][] moves, int fromRow, int fromColumn, int value) {
for (int i = 0; i < moves.length; i = i+1)
if (moves[i][0] == fromRow & moves[i][1] == fromColumn)
board[moves[i][2]][moves[i][3]] = value;
showBoard(board);
}
/* --------------------------------------------------------------------------- *
* Shows the board in a graphic window *
* you can use it without understanding how it works. *
* --------------------------------------------------------------------------- */
public static void showBoard(int[][] board) {
grid.showBoard(board);
}
/* --------------------------------------------------------------------------- *
* Print the board *
* you can use it without understanding how it works. *
* --------------------------------------------------------------------------- */
public static void printMatrix(int[][] matrix){
for (int i = matrix.length-1; i >= 0; i = i-1){
for (int j = 0; j < matrix.length; j = j+1){
System.out.format("%4d", matrix[i][j]);
}
System.out.println();
}
}
}
hi. just started coding for , installed ide intellij but i cant run the code.
thanks so much!
As you can see the green arrow of the run command is disabled. in addition when i try to run from the run menu of the toolbar it just says edit configuration.
Just place cursor to the "main" method line and press right button and select run.
Right click in main method code and tap Run.