Weird java recursion nullpointerexception on a method - java

Hi I'm writing a checkers engine and defining a canEat(Point1,Point2) method for player class which returns true or false based on if player can eat eat the piece at the specified points by checking if the pieces and landing path is on board, if the two pieces belong to the same player or not and also considering the king/super status of piece.
Anyways it works pretty pleasantly without recursion, but without recursion method must get points of the pieces instead of the landing piece which is okay if I manage the recursion. But I want the method to also consider if it gets the landing point instead of piece location. When I run the code it fixes the location and calls itself again there is no problem with that but. I get NullPointerException on
caneat = Checker2.isAlive() ? true : false; because Checker2 is null. My pointToChecker method returns null on this guy so Checker2 is null. What is causing this I'm new to recursion, even OOP to be honest and
Here is my code and console error log
public boolean canEat(Point Piece, Point target)
{
//INITIALIZING
//POINT1 & CHECKER1-> piece which eats
//POINT2 & CHECKER2-> piece to eat
//POINT3 & CHECKER3-> landing path
if (samePoint(Piece, target))
return false;
boolean caneat = true;
boolean king1 = false;
Point Point1,Point2,Point3;
Checker Checker1,Checker2,Checker3;
int ownerID, victimID,axis;
axis = getDirection(Piece, target);
//CHECK IF PLAYER POINTED THE SQUARE AHEAD TARGET PIECE OR THE PIECE TO EAT
int distance = getStep(Piece, target);
if(distance == 2)
{
boolean resolution;
System.err.println("Recoordinated target");
Point fixed = getBackwards(target, axis);
System.err.println("Fixed is: " + Piece + " " + fixed);
resolution = canEat(Piece, fixed);
return resolution;
}
Point1 = Piece;
Point2 = target;
Point3 = findMovePosition(target, axis);
if(!inBoard(Point1) || !inBoard(Point2) || !inBoard(Point3))
{
System.err.println("Error: Invalid Move --> Thinking outside the box");
return false;
}
Checker1 = PointToPiece(Point1);
Checker2 = PointToPiece(Point2);
Checker3 = PointToPiece(Point3);
//CHECK IF PIECES ARE ALIVE
caneat = Checker1.isAlive() ? true : false;
caneat = Checker2.isAlive() ? true : false;
if(!Checker2.isAlive())
{
return false;
}
//THERE SHOULD BE TARGET AND VICTIM PIECES AND AN EMPTY LANDING POINT
if(!isOccupied(Piece))
{
System.err.println("#OccupyChecker invalid piece to move");
return false;
}
if(!isOccupiedbyEnemy(target))
{
System.err.println("#OccupyChecker invalid piece to eat");
return false;
}
if(!(Checker3 == null))
{
System.err.println("#OccupyChecker landing piece error");
return false;
}
ownerID = Checker1.getOwner().getID();
victimID = Checker2.getOwner().getID();
if(ownerID == victimID)
{
System.err.println("owner ID: " + ownerID + " victimID: " + victimID);
System.err.println("#OCCUPY identity");
return false;
}
if(ownerID == 1 && king1)
{
if(axis == 3 || axis == 4)
System.err.println("#OccupyPoint wrong axis");
caneat = false;
}
if(ownerID == 2 && king1)
{
if(axis == 1 || axis == 2)
System.err.println("#OccupyPoint wrong axis");
caneat = false;
}
return caneat;
}
Checker PointToPiece(Point piece)
{
Checker[] allPieces = allPieces();
Checker found = null;
for(Checker k : allPieces)
{
if(samePoint(k.getPosition(), piece))
found = k;
}
return found;
}

Related

Game score via collision detection increment

So i have a game where if my user collides with an image it will increase the score by 1. However because i use this method of collision detection and an if statement to increment my score, during the duration of the collision the score will go up by about 30 as the collision method detects it colliding multiple times as they pass through each other. How would i stop it from incrementing by more than one each time.
Here is my code:
void draw () {
if (gameMode == Active) {
if(crash() == false) {
drawBackground();
textSize(32);
fill(22,100,8);
text("Score: " + score ,20,40); //calls the drawBackground method
alien1.update();
alien2.update(); //constantly calls the move and render method for the alien and defender
alien3.update();
user1.render();
Burger.update();
if(Bcrash() == true) {
if(Bcrash() == false) {
score = score + 1;
}
}
} else {
gameMode = End;
textSize(32);
fill(22,100,8);
text("Game Over, press 'r' to restart",150,200);
}
}
}
boolean Bcrash() {
return user1.crash(Burger));
}
// Burger.class (Editor's note: I guess it's User.class)
public class User {
boolean crash(Burger A) {
return(abs(x-A.x)<=30) && abs(y-A.y)<=30;
}
}
Check to see if collision is false before allowing it to add another number.
something like:
Boolean collisionInProgress = false;
if(collision == true && collisionInProgress == false){
score = score+1;
collisionInProgess = true;
}
…loop…
if(collision == false){
collisionInProgess = false;
}

For loop to search through 2D array in Java returns NullPointerException

For a project at University, I have to create a game of Tic Tac Toe.
I have this for loop with if statements to search through the 2D array of 3x3 size, and return if it's either X or O (enum). That results in showing which side has won the game.
However, the problem I have is that if the 2D array is not complete, as in if all the 9 boxes are not filled with X or O, the method shows a NullPointerException.
Edit: I have to add that I require the empty grid to be null as few other unit tests assume grid[][] is initialized as null.
Error:
Exception in thread "main" java.lang.NullPointerException
at TicTacToeImplementation.whoHasWon(TicTacToeImplementation.java:80)
at ApplicationRunner.main(ApplicationRunner.java:24)
Code:
public enum Symbol {
X, O
}
private Symbol winner;
public Symbol whoHasWon() {
for (Symbol xORo : Symbol.values()) {
if ((grid[0][0].equals(xORo) &&
grid[0][1].equals(xORo) &&
grid[0][2].equals(xORo))) {
winner = xORo;
isGameOver = true;
break;
} else if ((grid[1][0].equals(xORo) &&
grid[1][1].equals(xORo) &&
grid[1][2].equals(xORo))) {
winner = xORo;
isGameOver = true;
break;}
else if { //Code carries on to account for all 8 different ways of winning
} else {
isGameOver = true;
}
}
return winner;
}
You can use multiple ways to ignore the "null" exception with an empty array.
The 1st way is to fill it with a different default symbol such as E. So when you initialize your arry at the beginning, instead of making it all empty and null, you can fill it with E's
for(int i=0;i<=2;i++){
for(int k=0;k<=2;k++){
grid[i][k] = "E";
}
}
Add this to beginning to fill it with E's first instead of nulls.
Another method is to find how to ignore the nulls using try or the following methods that can be found in this linkhttps://www.javacodegeeks.com/2012/06/avoid-null-pointer-exception-in-java.html:
I won't be going into it because I believe the 1st method is easier to use and implement. However, depending on your requirements for your assignment, I would look at both just to be sure.
Hope this helps, Good luck!
You can change the comparasion of String.The code may be like this ;
public Symbol whoHasWon() {
for (Symbol xORo : Symbol.values()) {
if ((grid[0][0] == xORo.name() &&
grid[0][1] == xORo.name() &&
grid[0][2] == xORo.name())) {
winner = xORo;
isGameOver = true;
break;
} else if ((grid[1][0] == xORo.name() &&
grid[1][1] == xORo.name() &&
grid[1][2] == xORo.name())) {
winner = xORo;
isGameOver = true;
break;}
else if { //Code carries on to account for all 8 different ways of winning
} else {
isGameOver = true;
}
}
return winner;
}
Enum like your's implemented
public enum Symbol{
X, O
}
}
As stated in this post, you can use either equals() or == to compare enums but using == is null safe while equals() isn't.
So basically, just write your checks like this:
if (grid[0][0] == xORo &&
grid[0][1] == xORo &&
// etc.
However, if you want to use the equals() method, you could just write a method that checks for null then compares the two values and returns the result:
public boolean isEqual(Symbol s1, Symbol s2) {
if (s1 != null && s1.equals(s2)) {
return true;
}
return false;
}
You could then call the isEqual() method like this:
if (isEqual(grid[0][0], xORo) &&
isEqual(grid[0][1], xORo) &&
// etc.

Function Repeating Itself Even After Returning

I am making a Tic-Tac-Toe game with a computer player. However, whenever I call the computer's makeMove method, the computer continues to play without the user being able to do anything. Just to be sure that the function stopped, I made it return after each move, but it still plays the entire game without the user's input.
Here are the relevant parts:
Board Class:
public String addToBoard(char c, int square) {
if (!spaceFull(board, square)) {
int[] coords = getRowAndColumn(square);
//System.out.println("[" + coords[0] + "][" + coords[1] + "]");
board[coords[0]][coords[1]] = c;
return "VALID";
} else {
System.out.println("Space Is Occupied");
return "OCCUPIED";
}
}
public boolean spaceFull(char[][] b, int square) {
return (twoDimenToOneDimen(b).get(square - 1) == 'X' || twoDimenToOneDimen(b).get(square - 1) == 'O');
}
Computer Class
public void makeMove() {
int square;
//Checks For Any Winning Computer Moves
System.out.println("Here");
if ((square = nextMoveWinCheck(playerChar)) != 0) {
board.addToBoard(playerChar, square);
return;
//Checks For Any Opponent Winning Moves
} else if ((square = nextMoveWinCheck(opponentChar)) != 0) {
board.addToBoard(playerChar, square);
return;
} else {
//Checks If Computer Has First Move
if (boardEmpty()) {
board.addToBoard(playerChar, 9);
return;
} else {
//Moves Into Opposite Corner if Bottom Corner is Occupied By Itself
if (!board.spaceFull(board.board,1) && board.board[2][2] == playerChar) {
board.addToBoard(playerChar, 1);
return;
//Move Into Center If Second Move or Possible
} else if (!board.spaceFull(board.board,5)) {
board.addToBoard(playerChar, 5);
return;
} else if ((square = emptyCorner()) != 0) {
board.addToBoard(playerChar, square);
return;
} else {
board.addToBoard(playerChar, randomEmptySpot());
return;
}
}
}
}
If you want the full code, it's:
Computer
Board
Player
Tic-Tac-Toe Main Class
Your problem lies in your class Computer. On line 57, you assign board.board to tempBoard. However tempBoard still holds the reference to the object board.board, so whatever modifications you make there is reflected on the actual board. To resolve this, COPY the board values to tempboard:
http://www.java2s.com/Code/Java/Collections-Data-Structure/clonetwodimensionalarray.htm

Keeping track of path through a maze

The program is using backtracking to find out a way out of the maze(which it does fine). The problem occurs when I try to print out the correct path I took.
This is my solveMaze() method.
boolean result = false;
while(result==false){
if((row > 29) || (row < 0) || (col > 19) || (col < 0)) //check if position is within the array
return false;
if(maze[row][col].getVar().equals("E")) // check if youre at the exit
return true;
if(maze[row][col].getVar().equals("1")) // check if youre hitting a wall
return false;
if(maze[row][col].position.size() > 2){ // check if youre at an intersection
intersection[numIntersection] = maze[row][col]; // add intersection to intersection array
numIntersection++;
}
//this section does not need to be checked if youve never visited the position before
if(maze[row][col].getVisted() == true && numIntersection > 0){
if(intersection[numIntersection-1] == null)
return false;
else if(intersection[numIntersection-1] != null){ //as you backtrack to the last intersection pick up your "markers"
maze[row][col].setVar("0");
if(maze[row][col].position == intersection[numIntersection-1].position && intersection[numIntersection-1].getVisted()==true){ //remove intersection from the array as you pass back thru
maze[row][col].setVar("+");
intersection[numIntersection-1] = null;
numIntersection--;
}
}
}
if(maze[row][col].position.empty()==true) //check if the stack is empty
return false;
maze[row][col].position.pop();
if(maze[row][col].getVisted() == false)
maze[row][col].setVar("+"); //mark path as you land on unvisted positions
maze[row][col].setVisted(true);
//look north
if(solveMaze(row-1,col)== true)
return true;
//look east
if(solveMaze(row,col+1)== true){
return true;
}
//look west
if(solveMaze(row,col-1)== true){
return true;
}
//look south
if(solveMaze(row+1,col)== true){
return true;
}
}
return false;
}
As I backtrack I am picking back up my markers but it seems to be picking up markers on the correct path also and prints a maze with a broken up path.

Why is my break statement being ignored?

In my method under the if statement:
if (currentLocationX == 0 && currentLocationY == 4)
I have a break statement that should make the program exit out of the while loop and return true for 'answer' and for the method. Yet after some testing it seems that after returning true for 'answer', it goes back into the while loop giving the wrong results int the end. Why is my break statement not doing what it's supposed to? Thank you!
P.S. (this method calls on some other method that were not relevant to mention here)
public boolean solveMaze()
{
boolean answer = false;
int currentLocationX;
int currentLocationY;
//push starting location
pushX(2);
pushY(1);
while((isEmptyX() == false) && (isEmptyY() == false))
{
printMaze();
System.out.println();
currentLocationX = popX();
currentLocationY = popY();
//mark current location as visited
visited(currentLocationX, currentLocationY, maze);
System.out.println("Current Location: " + currentLocationX + ", " + currentLocationY);
if (currentLocationX == 0 && currentLocationY == 4)
{
answer = true;
break;
}
else
{
//push all unvisited OPEN neighbor locations into stack
if (checkEast(currentLocationX, currentLocationY) == 0)
{
pushX(eastX(currentLocationX));
pushY(eastY(currentLocationY));
}
else;
if (checkSouth(currentLocationX, currentLocationY)== 0)
{
pushX(southX(currentLocationX));
pushY(southY(currentLocationY));
}
else;
if (checkWest(currentLocationX, currentLocationY)== 0)
{
pushX(westX(currentLocationX));
pushY(westY(currentLocationY));
}
else;
if (checkNorth(currentLocationX, currentLocationY)== 0)
{
pushX (northX(currentLocationX));
pushY(northY(currentLocationY));
}
else;
}
}
return answer;
}
I wrote out the basic logic of your method as
public static boolean solveMaze() {
boolean answer = false;
int currentLocationX = 0;
int currentLocationY = 4;
while (true) {
if (currentLocationX == 0 && currentLocationY == 4) {
System.out.println("Hit the break");
break;
} else {
System.out.println("Missed the break");
}
}
return answer;
}
and if you execute it you get Hit the break. So your solveMaze() method is fine in terms of breaking out of the loop once it satisfies your if-statement. I would say that if you see your code subsequently going back into the while loop, it must be that solveMaze() was called a second time.

Categories