So I'm trying to make a boardgame where I have a player class. In this class I want to save different things, such as the position on the board, amount of money etc.
Problem is, when I try to make two players walk across the board. It adds up both values from the movePlayer method and moves up 10 spaces.
Am I missing something obvious here?
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 method, and all associated with it:
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();
}
}
Your ChangePosition method is static and modifies some static variables. That means that you don't have the coordinates safed for every player, but they all share the same, hence the two methods add up. You need to declare the coordinates without the static modifier to make them fields that are individual on every instance of that class.