Pacman Ghost类,这种方法有什么作用?

时间:2012-10-27 00:38:19

标签: java methods pacman

我不明白moveGhost的方法是什么?为什么选择0-7之间的随机数和追逐pacman有什么关系呢? 哦,我该怎么做才能创建幽灵的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;


}

}

1 个答案:

答案 0 :(得分:3)

moveGhost方法从8个罗盘方向(N,S,E,W,NW,SW,NE,NW)沿随机方向移动重影。八个不同的方向对应于0-7范围内的8个不同的数字。

如果方法checkMove返回false,则鬼魂不会移动。

相关问题