【问题标题】:Save data in separate objects from same class将数据保存在同一类的不同对象中
【发布时间】:2014-05-21 19:13:58
【问题描述】:

所以我正在尝试制作一个有玩家类的棋盘游戏。在这堂课中,我想保存不同的东西,比如在棋盘上的位置、金额等。

问题是,当我试图让两个玩家跨过棋盘时。它将 movePlayer 方法中的两个值相加并向上移动 10 个空格。

我在这里遗漏了什么明显的东西吗?

public class Board extends Component {
private Player playerOne;
private Player playerTwo;
public Board(){
    playerOne = new Player();
    playerTwo = new Player();
}

    g.fillOval(playerOne.getPositionX(), playerOne.getPositionY(), 50, 15); // draw player 1

    g.fillOval(playerTwo.getPositionX(), playerTwo.getPositionY(), 15, 50); // draw player 2

}

public  void rollDice(){
    playerOne.movePlayer(8);  // move player1 > 8 spots
    playerTwo.movePlayer(2); // move player2 > 2 spots            
}
}

movePlayer 方法,以及所有与之相关的:

public static void updatePlayerPos(int x){
    if (playerPos > 40){
        playerPos = 2;
    } else {
        playerPos = playerPos + x;
    }
}

public static void changePosition(){
    if (playerPos < 12){
        positionX = positionX - 50;
    }else if(playerPos < 22){
        positionY = positionY - 50;   
    } else if (playerPos < 32){
        positionX = positionX + 50;
    }else if(playerPos < 42){
        positionY = positionY + 50;   
    }
}

public void movePlayer(int dicerolls){  
    for (int i = 0;i < dicerolls;i++){
        updatePlayerPos(1);
        changePosition();
    }
}

【问题讨论】:

  • 你能展示你的 movePlayer() 的实现吗?
  • Ksven 是正确的。我们需要查看 Player.movePlayer。这个问题听起来像是您可能正在使用静态变量来包含玩家移动的距离,因此在任一玩家更新时都调用它。
  • 你是对的。实例变量是静态的。 /掌脸
  • 如果有人能解释他/她为什么投反对票会很好......

标签: java object graphics japplet


【解决方案1】:

您的 ChangePosition 方法是静态的,并且会修改一些静态变量。这意味着您没有为每个玩家保留坐标,但他们都共享相同的坐标,因此这两种方法相加。您需要在没有 static 修饰符的情况下声明坐标,以使它们在该类的每个实例上都是单独的字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多