001    package core;
002    
003    import java.util.*;
004    import rules.*;
005    
006    public class PowerupHelper {
007            public static Map<Position, Piece> stringToMap(String s){
008                    Map<Position, Piece> changes = new HashMap<Position, Piece>();
009                    
010                    // For an empty String, return an empty map
011                    if (s.equals("")) {
012                            return changes;
013                    }
014                    
015                    // Otherwise build the map from the substrings
016                    for(String powerupstr: s.split(",")) {
017                            String[] values = powerupstr.split("-");
018                            Piece powerup = PieceFactory.pieceFromString("powerup_"+values[0], null, 0);
019                            Position place = Position.fromString(values[1]);
020                            changes.put(place, powerup);
021                    }
022                    return changes;
023            }
024    
025        public static String mapToString(Map<Position, Piece> m){
026            String ans = "";
027            boolean started = false;
028            for (Position pos: m.keySet()) {
029                Piece piece = m.get(pos);
030                String pieceName = piece.pieceString().split("_")[1];
031                if (started)
032                    ans += ",";
033                ans += pieceName+"-"+pos.toString();
034                started = true;
035            }
036            return ans;
037        }
038    
039        public static String randomPowerupString(int halfn) {
040            Map<Position, Piece> m = new HashMap<Position, Piece>();
041            Random r = new Random();
042            for(int i = 0; i < halfn; i++) {
043                Position pos, otherPos;
044                do {
045                    int x = r.nextInt(8);
046                    int y = r.nextInt(2)+2;
047                    pos = Position.get(x, y);
048                    otherPos = Position.get(7-x, 7-y);
049                } while (m.containsKey(pos));
050                Piece powerup;
051                int powerupType = r.nextInt(3);
052                if (powerupType == 0)
053                    powerup = new Spawn();
054                else if (powerupType == 1)
055                    powerup = new Destroy();
056                else
057                    powerup = new Upgrade();
058                m.put(pos, powerup);
059                m.put(otherPos, powerup);
060            }
061            return mapToString(m);
062        }
063    }