So I have a playerID
and numwalls
for each player in a board game I'm making.
Right now to remove walls when each player uses one, everyone is basically sharing walls.
So I figured I should make a hashmap
to hold playerID
as the key and numwalls
as the value.
But I don't know how to decrement the keys value when it is supposed to use a wall.
I'll show a snip out my code that has the issue.
public int getWallsRemaining(int i) {
return numWalls;
}
public void lastMove(PlayerMove playerMove) {
System.out.println("in lastMove... " + playerMove);
/**
* if piece moves, update its position
*/
if(playerMove.isMove() == true){
Integer player = playerMove.getPlayerId();
Coordinate newLoc = new Coordinate(playerMove.getEndRow(), playerMove.getEndCol());
playerHomes.put(player, newLoc);
}
/**
* if a wall is placed, subtract the wall form the player who placed it
* and subtract the appropriate neighbors.
*/
if(playerMove.isMove() == false){
numWalls-=1;
removeNeighbor(playerMove.getStart(), playerMove.getEnd());
}
}
Here's where I initialize everything, walls
is my map for what I'm trying to do:
private Map<Coordinate, HashSet<Coordinate>> graph;
private int PlayerID;
private int numWalls;
private Map<Integer, Coordinate> playerHomes;
private Map<Integer, Integer> walls;
@Override
public void init(Logger logger, int playerID, int numWalls, Map<Integer, Coordinate> playerHomes) {
this.PlayerID = playerID;
this.walls = new HashMap<Integer, Integer>();
this.numWalls = numWalls;
this.playerHomes = playerHomes;
this.graph = new HashMap<Coordinate, HashSet<Coordinate>>();
walls.put(playerID,numWalls);
for(int r = 0; r <= 10; r++){
for(int c = 0; c <= 10; c++){
HashSet<Coordinate> neighbors = new HashSet<Coordinate>();
if(r > 0){
neighbors.add(new Coordinate(r - 1, c));
}
if(r < 8){
neighbors.add(new Coordinate(r + 1, c));
}
if(c > 0){
neighbors.add(new Coordinate(r, c - 1));
}
if(c < 8){
neighbors.add(new Coordinate(r, c + 1));
}
graph.put((new Coordinate(r,c)), neighbors);
}
}
}
You can see in my lastMove
method that I decrement walls by 1. This is my problem. I want to decrement a specified playerID
numwall
by 1. What I have now works for 1-player only. I need this to work for up to 4-players.
A HashMap
can just contain objects (not primitives) so you must insert an Integer
as a value mapped.
Since an Integer
is an immutable class you can't directly modify the value, you need to replace it by discarding the old value, something like:
HashMap<Player, Integer> walls = new HashMap<Player,Integer>();
int currentWalls = walls.get(player);
walls.put(player, currentWalls-1);