Thread: Pacman Ghost class, what does this method do?

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2011
Posts
43
Rep Power
4

Pacman Ghost class, what does this method do?

I dont understand what the method moveGhost does? Why pick a random number between 0-7 and what does that have to do with chasing pacman?

Code:
```import java.util.Random;

public class GhostRed {

private int size;
private int row, col;

//constructor
public GhostRed(int r, int c, int s) {
row = r;
col = c;
size = s;

}

public int getRow() {
return row;
}
public int getCol() {
return col;
}
public void setRow(int r) {
row = r;

}
public void setCol(int c) {
col = c;
}

private boolean checkMove(int r, int c) {
boolean check=true;
if (r<0 || r > size-1 || c < 0 || c > size-1) {
check= false;
}
return check;
}

public boolean moveGhost() {

boolean move=true;
Random r = new Random();
int newMove = r.nextInt(7); //taking a random number btw 0-7

if (newMove == 0) {
if(checkMove(row-1, col)==false) {
move=false;
}
else{
row = row-1;
}

}
if (newMove == 1) {
if(checkMove(row+1, col)==false) {
move= false;
}
else{
row = row+1;
}

}
if (newMove == 2) {
if(checkMove(row, col-1)==false) {
move= false;
}else{
col = col-1;
}

}
if (newMove == 3) {
if(checkMove(row, col+1)==false) {
move= false;
}
else{
col = col+1;
}

}
if (newMove == 4) {
if(checkMove(row-1, col-1)==false) {
move= false;
}
else{
row = row-1;
col = col-1;
}

}
if (newMove == 5) {
if(checkMove(row-1, col+1)==false) {
move= false;
}
else{
row = row-1;
col = col+1;
}

}
if (newMove == 6) {
if(checkMove(row+1, col-1)==false) {
move= false;
}
else{
row = row+1;
col = col-1;
}

}
if (newMove == 7) {
if(checkMove(row+1, col+1)==false) {
move= false;
}else{
row = row+1;
col = col+1;
}

}

return move;

}```
2. It is to decide which direction the ghost should move.
Look at a tic-tac-toe board and place the "ghost" in the middle field. Then you can see there are 8 fields around it.