From 596ce316680de8a82fbe5622f830b2a985a84644 Mon Sep 17 00:00:00 2001 From: Pacien TRAN-GIRARD Date: Mon, 9 May 2016 22:15:12 +0200 Subject: Implement player painting order --- src/ch/epfl/xblast/Lists.java | 14 ++++++++++++++ src/ch/epfl/xblast/client/XBlastComponent.java | 19 +++++++++++++------ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/ch/epfl/xblast/Lists.java b/src/ch/epfl/xblast/Lists.java index 073e0cc..da3f919 100644 --- a/src/ch/epfl/xblast/Lists.java +++ b/src/ch/epfl/xblast/Lists.java @@ -167,4 +167,18 @@ public final class Lists { .collect(Collectors.toList())); } + /** + * Returns an immutable copy of the given list, sorted using the supplied comparator. + * + * @param l the list to sort + * @param cmp the Comparator to use + * @param the type of the list's elements + * @return the sorted list + */ + public static List sorted(List l, Comparator cmp) { + List r = new ArrayList<>(l); + Collections.sort(r, cmp); + return Collections.unmodifiableList(r); + } + } diff --git a/src/ch/epfl/xblast/client/XBlastComponent.java b/src/ch/epfl/xblast/client/XBlastComponent.java index cab6fde..0b4f0bf 100644 --- a/src/ch/epfl/xblast/client/XBlastComponent.java +++ b/src/ch/epfl/xblast/client/XBlastComponent.java @@ -1,15 +1,14 @@ package ch.epfl.xblast.client; import ch.epfl.xblast.Cell; +import ch.epfl.xblast.Lists; import ch.epfl.xblast.PlayerID; import javax.swing.*; import java.awt.*; import java.awt.image.ImageObserver; -import java.util.Arrays; -import java.util.Collections; +import java.util.*; import java.util.List; -import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -64,6 +63,16 @@ public final class XBlastComponent extends JComponent { new Point(912, vShift)); } + private static Comparator buildPlayerComparator(PlayerID blackSheep) { + Comparator coordinateComparator = + (p1, p2) -> p2.position().y() - p1.position().y(); + + Comparator idComparator = + (p1, p2) -> p1.id() == blackSheep ? -1 : 0; + + return coordinateComparator.thenComparing(idComparator); + } + private static void drawImage(Graphics2D g, Image img, Point pos) { g.drawImage(img, pos.x, pos.y, IMG_OBSERVER); } @@ -89,9 +98,7 @@ public final class XBlastComponent extends JComponent { * @param players the list of players to be displayed */ private void drawPlayers(Graphics2D g, List players) { - // TODO: draw in preferred order - - for (GameState.Player p : players) + for (GameState.Player p : Lists.sorted(players, buildPlayerComparator(this.playerID))) drawImage(g, p.image(), playerPosition(p)); } -- cgit v1.2.3