我不明白 moveGhost 方法的作用是什么?为什么要选择 0-7 之间的随机数,这与追逐吃豆人有什么关系?哦,我能做些什么来创建幽灵的 GUI 图像?我找到了这段代码,并试图了解它是如何工作的。
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;
}
}