Java keyListener网格游戏逻辑错误

时间:2014-06-06 13:21:40

标签: java swing logic keylistener

所以我有这个moveGrid类,它从正方形中抽出一个网格:

  • 绿色方块(类型1,可移动)
  • 蓝色方块(类型2,不可移动)
  • 演员(2型,橙色胖子纹理)

moveGrid扩展了Jpanel并实现了keyListener,因此它就是drawing和keyListeining发生的地方。每次按下一个键,它都会在PActor(从中输入actor的类)中测试是否可以移动可用空间。如果可以,则演员移动。简单吧?好吧它仍然占据一个空间的位置,就像它在那里一样,即使它不能移动到那里。下面我给出了moveGrid的keyReleased代码,以及PActor的canMove和Move方法。

public void keyPressed(KeyEvent e) {
    //here test if the grid can be updated
            if(e.getKeyCode() == KeyEvent.VK_UP){
                newx = pguy.getx();
                newy = pguy.gety() - 1;
            }else if(e.getKeyCode() == KeyEvent.VK_DOWN){
                newx = pguy.getx();
                newy = pguy.gety() + 1;
            } else if(e.getKeyCode() == KeyEvent.VK_LEFT){
                newx = pguy.getx() - 1;
                newy = pguy.gety();
            }else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
                newx = pguy.getx() + 1;
                newy = pguy.gety();
            }
}

public void keyReleased(KeyEvent arg0) {
    //update the grid if it can here
    if(pguy.canMove(newx, newy) == true){
    pguy.Move(newx, newy);
    repaint();
    }else{
        repaint();
    }
}

canMove and Move:

public boolean canMove(int x, int y){ //needs fixing
    //test if the space that the user is trying to move to can be moved to
    //first test if the space is in the grid

    if(x < PGame.width && y < PGame.height && x >= 0 && y>=0){
        int goPos = moveGrid.findpositioninlist(x, y);
        PGrid goGrid = moveGrid.pgrids.get(goPos);
        if(goGrid.getType() == 0){
            abletomove = false;
            curx = oldx;
            cury = oldy;
            curPos = oldPos;
        }else if(goGrid.getType() == 1){
            abletomove = true;
            oldx = curx;
            oldy = cury;
            curx = x;
            cury = y;
            oldPos = curPos;
            curPos = goPos;
        }else{
            abletomove = false;
            curx = oldx;
            cury = oldy;
            curPos = oldPos;
        }
    }

    return abletomove;
}
public void Move(int x, int y){
    int pos = moveGrid.findpositioninlist(x,y);
    int oldplace = moveGrid.findpositioninlist(oldx, oldy);

    if(abletomove == true)
    {
    PGrid temp = new PGrid(2,x,y);
    moveGrid.pgrids.set(pos,temp);
    PGrid moveable = new PGrid(1,oldx,oldy);
    moveGrid.pgrids.set(oldPos,moveable);
    }else{
        PGrid temp1 = new PGrid(2, curx, cury);
        moveGrid.pgrids.set(oldplace,temp1);
    }
}

我被问到了,所以这里是PGrid类:

public class PGrid {
private int type;
private int x, y;

public PGrid(int type, int x, int y){
    this.type = type;
    this.x = x;
    this.y = y;
}
public int getType(){
    return type;
}
public void changeType(int toChange){
    type = toChange;
}

public int getx(){
    return x;
}
public int gety(){
    return y;
}
}

0 个答案:

没有答案