1 package nl.tudelft.jpacman.ui;
2
3 import java.awt.GridLayout;
4 import java.util.LinkedHashMap;
5 import java.util.List;
6 import java.util.Map;
7
8 import javax.swing.JLabel;
9 import javax.swing.JPanel;
10
11 import nl.tudelft.jpacman.level.Player;
12
13 /**
14 * A panel consisting of a column for each player, with the numbered players on
15 * top and their respective scores underneath.
16 *
17 * @author Jeroen Roosen
18 *
19 */
20 public class ScorePanel extends JPanel {
21
22 /**
23 * Default serialisation ID.
24 */
25 private static final long serialVersionUID = 1L;
26
27 /**
28 * The map of players and the labels their scores are on.
29 */
30 private final Map<Player, JLabel> scoreLabels;
31
32 /**
33 * The default way in which the score is shown.
34 */
35 public static final ScoreFormatter DEFAULT_SCORE_FORMATTER =
36 (Player player) -> String.format("Score: %3d", player.getScore());
37
38 /**
39 * The way to format the score information.
40 */
41 private ScoreFormatter scoreFormatter = DEFAULT_SCORE_FORMATTER;
42
43 /**
44 * Creates a new score panel with a column for each player.
45 *
46 * @param players
47 * The players to display the scores of.
48 */
49 public ScorePanel(List<Player> players) {
50 super();
51 assert players != null;
52
53 setLayout(new GridLayout(2, players.size()));
54
55 for (int i = 1; i <= players.size(); i++) {
56 add(new JLabel("Player " + i, JLabel.CENTER));
57 }
58 scoreLabels = new LinkedHashMap<>();
59 for (Player player : players) {
60 JLabel scoreLabel = new JLabel("0", JLabel.CENTER);
61 scoreLabels.put(player, scoreLabel);
62 add(scoreLabel);
63 }
64 }
65
66 /**
67 * Refreshes the scores of the players.
68 */
69 protected void refresh() {
70 for (Map.Entry<Player, JLabel> entry : scoreLabels.entrySet()) {
71 Player player = entry.getKey();
72 String score = "";
73 if (!player.isAlive()) {
74 score = "You died. ";
75 }
76 score += scoreFormatter.format(player);
77 entry.getValue().setText(score);
78 }
79 }
80
81 /**
82 * Provide means to format the score for a given player.
83 */
84 public interface ScoreFormatter {
85
86 /**
87 * Format the score of a given player.
88 * @param player The player and its score
89 * @return Formatted score.
90 */
91 String format(Player player);
92 }
93
94 /**
95 * Let the score panel use a dedicated score formatter.
96 * @param scoreFormatter Score formatter to be used.
97 */
98 public void setScoreFormatter(ScoreFormatter scoreFormatter) {
99 assert scoreFormatter != null;
100 this.scoreFormatter = scoreFormatter;
101 }
102 }