From 91a5fe03e61250d7f566792a5e0ecacdcb93be8d Mon Sep 17 00:00:00 2001 From: Chris Kearney <chris@kearneymail.com> Date: Sun, 7 Aug 2016 19:02:18 -0700 Subject: [PATCH] code cleanup --- .../comandante/creeper/command/Command.java | 77 +-- .../command/admin/TeleportCommand.java | 1 - .../creeper/entity/EntityManager.java | 2 +- .../creeper/managers/GameManager.java | 333 +++++++------ .../java/com/comandante/creeper/npc/Npc.java | 457 +++++++++--------- .../com/comandante/creeper/npc/NpcMover.java | 6 +- .../com/comandante/creeper/player/Player.java | 307 ++++++------ .../creeper/player/PlayerManager.java | 56 +-- .../comandante/creeper/server/GameAuth.java | 3 +- .../comandante/creeper/world/RoomManager.java | 45 +- 10 files changed, 637 insertions(+), 650 deletions(-) diff --git a/src/main/java/com/comandante/creeper/command/Command.java b/src/main/java/com/comandante/creeper/command/Command.java index b6f30262..b369a20e 100644 --- a/src/main/java/com/comandante/creeper/command/Command.java +++ b/src/main/java/com/comandante/creeper/command/Command.java @@ -12,7 +12,10 @@ import com.comandante.creeper.server.CreeperSession; import com.comandante.creeper.world.*; import com.google.common.collect.Sets; import org.apache.log4j.Logger; -import org.jboss.netty.channel.*; +import org.jboss.netty.channel.ChannelEvent; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -22,6 +25,7 @@ import java.util.Set; public abstract class Command extends SimpleChannelUpstreamHandler { + public static final Logger log = Logger.getLogger(Command.class); public final List<String> validTriggers; public final String description; public final Set<PlayerRole> roles; @@ -42,7 +46,6 @@ public abstract class Command extends SimpleChannelUpstreamHandler { public Coords currentRoomCoords; public List<String> originalMessageParts; public WorldExporter worldExporter; - public static final Logger log = Logger.getLogger(Command.class); public String rootCommand; protected Command(GameManager gameManager, List<String> validTriggers, String description, String correctUsage) { @@ -65,6 +68,17 @@ public abstract class Command extends SimpleChannelUpstreamHandler { this.roles = roles; } + @Override + public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { + try { + if (e instanceof MessageEvent) { + init((MessageEvent) e); + } + } finally { + super.handleUpstream(ctx, e); + } + } + private void init(MessageEvent e) { this.creeperSession = (CreeperSession) e.getChannel().getAttachment();; this.originalMessageParts = getOriginalMessageParts(e); @@ -76,15 +90,14 @@ public abstract class Command extends SimpleChannelUpstreamHandler { this.currentRoomCoords = mapMatrix.getCoords(currentRoom.getRoomId()); } - @Override - public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { - try { - if (e instanceof MessageEvent) { - init((MessageEvent) e); - } - } finally { - super.handleUpstream(ctx, e); - } + private List<String> getOriginalMessageParts(MessageEvent e) { + String origMessage = (String) e.getMessage(); + return new ArrayList<>(Arrays.asList(origMessage.split(" "))); + } + + private String getRootCommand(MessageEvent e) { + String origMessage = (String) e.getMessage(); + return origMessage.split(" ")[0].toLowerCase(); } public void execCommandThreadSafe(ChannelHandlerContext ctx, MessageEvent e, Class c, CommandRunnable commandRunnable) throws Exception { @@ -100,6 +113,22 @@ public abstract class Command extends SimpleChannelUpstreamHandler { } } + private void removeCurrentHandlerAndWritePrompt(ChannelHandlerContext ctx, MessageEvent e) { + removeCurrentHandlerAndWritePrompt(ctx, e, true); + } + + public void removeCurrentHandlerAndWritePrompt(ChannelHandlerContext ctx, MessageEvent e, boolean newLine) { + e.getChannel().getPipeline().remove(ctx.getHandler()); + if (creeperSession.getGrabMerchant().isPresent()) { + return; + } + gameManager.getChannelUtils().write(playerId, getPrompt(), newLine); + } + + public String getPrompt() { + return gameManager.buildPrompt(playerId); + } + public void execCommandBackgroundThread(ChannelHandlerContext ctx, MessageEvent e, CommandRunnable commandRunnable) throws Exception { try { new Thread(() -> { @@ -124,28 +153,6 @@ public abstract class Command extends SimpleChannelUpstreamHandler { } } - private void removeCurrentHandlerAndWritePrompt(ChannelHandlerContext ctx, MessageEvent e) { - removeCurrentHandlerAndWritePrompt(ctx, e, true); - } - - public void removeCurrentHandlerAndWritePrompt(ChannelHandlerContext ctx, MessageEvent e, boolean newLine) { - e.getChannel().getPipeline().remove(ctx.getHandler()); - if (creeperSession.getGrabMerchant().isPresent()) { - return; - } - gameManager.getChannelUtils().write(playerId, getPrompt(), newLine); - } - - private String getRootCommand(MessageEvent e) { - String origMessage = (String) e.getMessage(); - return origMessage.split(" ")[0].toLowerCase(); - } - - private List<String> getOriginalMessageParts(MessageEvent e) { - String origMessage = (String) e.getMessage(); - return new ArrayList<>(Arrays.asList(origMessage.split(" "))); - } - public void write(String msg) { channelUtils.write(playerId, msg); } @@ -166,10 +173,6 @@ public abstract class Command extends SimpleChannelUpstreamHandler { gameManager.currentRoomLogic(playerId, playerCurrentRoom); } - public String getPrompt() { - return gameManager.buildPrompt(playerId); - } - public String getDescription() { return description; } diff --git a/src/main/java/com/comandante/creeper/command/admin/TeleportCommand.java b/src/main/java/com/comandante/creeper/command/admin/TeleportCommand.java index 25ba1f24..a0ba7ce2 100644 --- a/src/main/java/com/comandante/creeper/command/admin/TeleportCommand.java +++ b/src/main/java/com/comandante/creeper/command/admin/TeleportCommand.java @@ -2,7 +2,6 @@ package com.comandante.creeper.command.admin; import com.comandante.creeper.command.Command; -import com.comandante.creeper.command.CommandRunnable; import com.comandante.creeper.managers.GameManager; import com.comandante.creeper.player.CoolDownType; import com.comandante.creeper.player.Player; diff --git a/src/main/java/com/comandante/creeper/entity/EntityManager.java b/src/main/java/com/comandante/creeper/entity/EntityManager.java index 2704cd13..ff637721 100644 --- a/src/main/java/com/comandante/creeper/entity/EntityManager.java +++ b/src/main/java/com/comandante/creeper/entity/EntityManager.java @@ -25,6 +25,7 @@ import static com.codahale.metrics.MetricRegistry.name; public class EntityManager { + private static final Logger log = Logger.getLogger(EntityManager.class); private final ConcurrentHashMap<String, Npc> npcs = new ConcurrentHashMap<>(); private final HTreeMap<String, Item> items; private final HTreeMap<String, Effect> effects; @@ -32,7 +33,6 @@ public class EntityManager { private final ExecutorService mainTickExecutorService = Executors.newFixedThreadPool(50); private final RoomManager roomManager; private final PlayerManager playerManager; - private static final Logger log = Logger.getLogger(EntityManager.class); public EntityManager(RoomManager roomManager, PlayerManager playerManager, DB db) { this.roomManager = roomManager; diff --git a/src/main/java/com/comandante/creeper/managers/GameManager.java b/src/main/java/com/comandante/creeper/managers/GameManager.java index 14af45cb..6a3ab9d3 100755 --- a/src/main/java/com/comandante/creeper/managers/GameManager.java +++ b/src/main/java/com/comandante/creeper/managers/GameManager.java @@ -42,8 +42,9 @@ import static com.comandante.creeper.server.Color.*; public class GameManager { + public static final Integer LOBBY_ID = 1; + private static final Logger log = Logger.getLogger(GameManager.class); public static String LOGO = "Creeper."; - private final RoomManager roomManager; private final PlayerManager playerManager; private final ChannelCommunicationUtils channelUtils; @@ -63,7 +64,6 @@ public class GameManager { private final StatsModifierFactory statsModifierFactory; private final GossipCache gossipCache; private final Interner<String> interner = Interners.newWeakInterner(); - private static final Logger log = Logger.getLogger(GameManager.class); private final TimeTracker timeTracker; private final ItemUseHandler itemUseHandler; private final NpcMover npcMover; @@ -154,10 +154,6 @@ public class GameManager { return newUserRegistrationManager; } - public ChannelCommunicationUtils getChannelUtils() { - return channelUtils; - } - public ItemDecayManager getItemDecayManager() { return itemDecayManager; } @@ -166,20 +162,29 @@ public class GameManager { return entityManager; } - public RoomManager getRoomManager() { - return roomManager; + public TimeTracker getTimeTracker() { + return timeTracker; } - public PlayerManager getPlayerManager() { - return playerManager; + public void placePlayerInLobby(Player player) { + Room room = roomManager.getRoom(LOBBY_ID); + room.addPresentPlayer(player.getPlayerId()); + player.setCurrentRoom(room); + for (Player next : roomManager.getPresentPlayers(room)) { + if (next.getPlayerId().equals(player.getPlayerId())) { + continue; + } + channelUtils.write(next.getPlayerId(), player.getPlayerName() + " arrived.", true); + } } - public TimeTracker getTimeTracker() { - return timeTracker; + public void announceConnect(String userName) { + Set<Player> allPlayers = getAllPlayers(); + for (Player p : allPlayers) { + getChannelUtils().write(p.getPlayerId(), Color.GREEN + userName + " has connected." + Color.RESET + "\r\n", true); + } } - public static final Integer LOBBY_ID = 1; - public Set<Player> getAllPlayers() { ImmutableSet.Builder<Player> builder = ImmutableSet.builder(); Iterator<Map.Entry<Integer, Room>> rooms = roomManager.getRoomsIterator(); @@ -194,23 +199,75 @@ public class GameManager { return builder.build(); } - public void placePlayerInLobby(Player player) { - Room room = roomManager.getRoom(LOBBY_ID); - room.addPresentPlayer(player.getPlayerId()); - player.setCurrentRoom(room); - for (Player next : roomManager.getPresentPlayers(room)) { - if (next.getPlayerId().equals(player.getPlayerId())) { + public ChannelCommunicationUtils getChannelUtils() { + return channelUtils; + } + + public void currentRoomLogic(String playerId) { + Player player = playerManager.getPlayer(playerId); + final Room playerCurrentRoom = roomManager.getPlayerCurrentRoom(player).get(); + currentRoomLogic(playerId, playerCurrentRoom); + } + + public void currentRoomLogic(String playerId, Room playerCurrentRoom) { + Player player = playerManager.getPlayer(playerId); + StringBuilder sb = new StringBuilder(); + sb.append(Color.BOLD_ON + Color.GREEN); + sb.append(playerCurrentRoom.getRoomTitle()); + sb.append(RESET); + sb.append("\r\n\r\n"); + sb.append(WordUtils.wrap(playerCurrentRoom.getRoomDescription(), 80, "\r\n", true)).append("\r\n").append("\r\n"); + String auto_map = player.getPlayerSetting("auto_map"); + if (playerCurrentRoom.getMapData().isPresent() && auto_map != null) { + int i = Integer.parseInt(auto_map); + sb.append(mapsManager.drawMap(playerCurrentRoom.getRoomId(), new Coords(i, i))).append("\r\n"); + } + sb.append(getExits(playerCurrentRoom, player)).append("\r\n"); + + Set<Merchant> merchants = playerCurrentRoom.getMerchants(); + for (Merchant merchant : merchants) { + sb.append(merchant.getColorName()).append(" is here.").append(RESET).append("\r\n"); + } + for (Player searchPlayer : roomManager.getPresentPlayers(playerCurrentRoom)) { + if (searchPlayer.getPlayerId().equals(player.getPlayerId())) { continue; } - channelUtils.write(next.getPlayerId(), player.getPlayerName() + " arrived.", true); + sb.append(searchPlayer.getPlayerName()).append(" is here.").append(RESET).append("\r\n"); } - } - public void announceConnect(String userName) { - Set<Player> allPlayers = getAllPlayers(); - for (Player p : allPlayers) { - getChannelUtils().write(p.getPlayerId(), Color.GREEN + userName + " has connected." + Color.RESET + "\r\n", true); + for (String itemId : playerCurrentRoom.getItemIds()) { + Item itemEntity = entityManager.getItemEntity(itemId); + if (itemEntity == null) { + playerCurrentRoom.removePresentItem(itemId); + continue; + } + sb.append(" ").append(entityManager.getItemEntity(itemId).getRestingName()).append("\r\n"); + } + + List<String> npcs = Lists.newArrayList(); + for (String npcId : playerCurrentRoom.getNpcIds()) { + StringBuilder sbb = new StringBuilder(); + Npc npcEntity = entityManager.getNpcEntity(npcId); + if (Main.vowels.contains(Character.toLowerCase(npcEntity.getName().charAt(0)))) { + sbb.append("an "); + } else { + sbb.append("a "); + } + sbb.append(npcEntity.getColorName()).append(" is here.\r\n"); + npcs.add(sbb.toString()); + } + Collections.sort(npcs, String.CASE_INSENSITIVE_ORDER); + for (String s : npcs) { + sb.append(s); + } + String msg = null; + if (sb.toString().substring(sb.toString().length() - 2).equals("\r\n")) { + CharSequence charSequence = sb.toString().subSequence(0, sb.toString().length() - 2); + msg = charSequence.toString(); + } else { + msg = sb.toString(); } + channelUtils.write(player.getPlayerId(), msg); } private String getExits(Room room, Player player) { @@ -299,75 +356,21 @@ public class GameManager { return fin; } - public void currentRoomLogic(String playerId) { - Player player = playerManager.getPlayer(playerId); - final Room playerCurrentRoom = roomManager.getPlayerCurrentRoom(player).get(); - currentRoomLogic(playerId, playerCurrentRoom); + public void placeItemInRoom(Integer roomId, String itemId) { + roomManager.getRoom(roomId).addPresentItem(entityManager.getItemEntity(itemId).getItemId()); } - public void currentRoomLogic(String playerId, Room playerCurrentRoom) { - Player player = playerManager.getPlayer(playerId); - StringBuilder sb = new StringBuilder(); - sb.append(Color.BOLD_ON + Color.GREEN); - sb.append(playerCurrentRoom.getRoomTitle()); - sb.append(RESET); - sb.append("\r\n\r\n"); - sb.append(WordUtils.wrap(playerCurrentRoom.getRoomDescription(), 80, "\r\n", true)).append("\r\n").append("\r\n"); - String auto_map = player.getPlayerSetting("auto_map"); - if (playerCurrentRoom.getMapData().isPresent() && auto_map != null) { - int i = Integer.parseInt(auto_map); - sb.append(mapsManager.drawMap(playerCurrentRoom.getRoomId(), new Coords(i, i))).append("\r\n"); - } - sb.append(getExits(playerCurrentRoom, player)).append("\r\n"); - - Set<Merchant> merchants = playerCurrentRoom.getMerchants(); - for (Merchant merchant : merchants) { - sb.append(merchant.getColorName()).append(" is here.").append(RESET).append("\r\n"); - } - for (Player searchPlayer : roomManager.getPresentPlayers(playerCurrentRoom)) { - if (searchPlayer.getPlayerId().equals(player.getPlayerId())) { - continue; - } - sb.append(searchPlayer.getPlayerName()).append(" is here.").append(RESET).append("\r\n"); - } - - for (String itemId : playerCurrentRoom.getItemIds()) { - Item itemEntity = entityManager.getItemEntity(itemId); - if (itemEntity == null) { - playerCurrentRoom.removePresentItem(itemId); - continue; + public boolean acquireItemFromRoom(Player player, String itemId) { + synchronized (interner.intern(itemId)) { + Room playerCurrentRoom = roomManager.getPlayerCurrentRoom(player).get(); + if (playerCurrentRoom.getItemIds().contains(itemId)) { + if (acquireItem(player, itemId)) { + playerCurrentRoom.getItemIds().remove(itemId); + return true; + } } - sb.append(" ").append(entityManager.getItemEntity(itemId).getRestingName()).append("\r\n"); } - - List<String> npcs = Lists.newArrayList(); - for (String npcId : playerCurrentRoom.getNpcIds()) { - StringBuilder sbb = new StringBuilder(); - Npc npcEntity = entityManager.getNpcEntity(npcId); - if (Main.vowels.contains(Character.toLowerCase(npcEntity.getName().charAt(0)))) { - sbb.append("an "); - } else { - sbb.append("a "); - } - sbb.append(npcEntity.getColorName()).append(" is here.\r\n"); - npcs.add(sbb.toString()); - } - Collections.sort(npcs, String.CASE_INSENSITIVE_ORDER); - for (String s : npcs) { - sb.append(s); - } - String msg = null; - if (sb.toString().substring(sb.toString().length() - 2).equals("\r\n")) { - CharSequence charSequence = sb.toString().subSequence(0, sb.toString().length() - 2); - msg = charSequence.toString(); - } else { - msg = sb.toString(); - } - channelUtils.write(player.getPlayerId(), msg); - } - - public void placeItemInRoom(Integer roomId, String itemId) { - roomManager.getRoom(roomId).addPresentItem(entityManager.getItemEntity(itemId).getItemId()); + return false; } public boolean acquireItem(Player player, String itemId) { @@ -386,19 +389,6 @@ public class GameManager { } } - public boolean acquireItemFromRoom(Player player, String itemId) { - synchronized (interner.intern(itemId)) { - Room playerCurrentRoom = roomManager.getPlayerCurrentRoom(player).get(); - if (playerCurrentRoom.getItemIds().contains(itemId)) { - if (acquireItem(player, itemId)) { - playerCurrentRoom.getItemIds().remove(itemId); - return true; - } - } - } - return false; - } - public void roomSay(Integer roomId, String message, String sourcePlayerId) { Set<Player> presentPlayers = roomManager.getPresentPlayers(roomManager.getRoom(roomId)); for (Player player : presentPlayers) { @@ -426,45 +416,6 @@ public class GameManager { return sb.toString(); } - public String buldEffectsString(Npc npc) { - return renderEffectsString(npc.getEffects()); - - } - - public String renderEffectsString(List<Effect> effects) { - Table t = new Table(2, BorderStyle.CLASSIC_COMPATIBLE, - ShownBorders.NONE); - - t.setColumnWidth(0, 16, 20); - // t.setColumnWidth(1, 10, 13); - - int i = 1; - for (Effect effect : effects) { - int percent = 100 - (int) ((effect.getEffectApplications() * 100.0f) / effect.getMaxEffectApplications()); - t.addCell(drawProgressBar(percent)); - t.addCell(effect.getEffectName()); - i++; - } - return t.render(); - } - - public String renderCoolDownString(Set<CoolDown> coolDowns) { - Table t = new Table(2, BorderStyle.CLASSIC_COMPATIBLE, - ShownBorders.NONE); - - t.setColumnWidth(0, 16, 20); - // t.setColumnWidth(1, 10, 13); - - int i = 1; - for (CoolDown coolDown : coolDowns) { - int percent = 100 - (int) (((coolDown.getOriginalNumberOfTicks() - coolDown.getNumberOfTicks()) * 100.0f) / coolDown.getOriginalNumberOfTicks()); - t.addCell(drawProgressBar(percent)); - t.addCell(coolDown.getName()); - i++; - } - return t.render(); - } - public String buildLookString(String name, Stats stats, Stats diff) { StringBuilder returnString = new StringBuilder(); Table t = new Table(3, BorderStyle.CLASSIC_COMPATIBLE, @@ -565,10 +516,72 @@ public class GameManager { return returnString.toString(); } + public String buldEffectsString(Npc npc) { + return renderEffectsString(npc.getEffects()); + + } + private String getFormattedNumber(Long longval) { return NumberFormat.getNumberInstance(Locale.US).format(longval); } + public String renderEffectsString(List<Effect> effects) { + Table t = new Table(2, BorderStyle.CLASSIC_COMPATIBLE, + ShownBorders.NONE); + + t.setColumnWidth(0, 16, 20); + // t.setColumnWidth(1, 10, 13); + + int i = 1; + for (Effect effect : effects) { + int percent = 100 - (int) ((effect.getEffectApplications() * 100.0f) / effect.getMaxEffectApplications()); + t.addCell(drawProgressBar(percent)); + t.addCell(effect.getEffectName()); + i++; + } + return t.render(); + } + + public String drawProgressBar(int pct) { + StringBuilder sb = new StringBuilder(); + sb.append("["); + int numberOfProgressBarNotches = getNumberOfProgressBarNotches(pct); + for (int i = 0; i < numberOfProgressBarNotches; i++) { + sb.append("+"); + } + for (int i = numberOfProgressBarNotches; i < 10; i++) { + sb.append(" "); + } + sb.append("]"); + return sb.toString(); + } + + public int getNumberOfProgressBarNotches(int y) { + int x = (int) (Math.round(y / 10.0) * 10); + String str = Integer.toString(x); + if (str.length() > 1) { + str = str.substring(0, str.length() - 1); + } + return Integer.parseInt(str); + } + + public String renderCoolDownString(Set<CoolDown> coolDowns) { + Table t = new Table(2, BorderStyle.CLASSIC_COMPATIBLE, + ShownBorders.NONE); + + t.setColumnWidth(0, 16, 20); + // t.setColumnWidth(1, 10, 13); + + int i = 1; + for (CoolDown coolDown : coolDowns) { + int percent = 100 - (int) (((coolDown.getOriginalNumberOfTicks() - coolDown.getNumberOfTicks()) * 100.0f) / coolDown.getOriginalNumberOfTicks()); + t.addCell(drawProgressBar(percent)); + t.addCell(coolDown.getName()); + i++; + } + return t.render(); + } + public void writeToPlayerCurrentRoom(String playerId, String message) { if (playerManager.getSessionManager().getSession(playerId).getGrabMultiLineInput().isPresent()) { return; @@ -604,7 +617,7 @@ public class GameManager { Map.Entry<String, Long> damageEntry = iterator.next(); totalDamageDone += damageEntry.getValue(); PlayerMetadata playerMetadata = getPlayerManager().getPlayerMetadata(damageEntry.getKey()); - Optional<Room> playerCurrentRoom = getRoomManager().getPlayerCurrentRoom(playerMetadata.getPlayerId()); + java.util.Optional<Room> playerCurrentRoom = getRoomManager().getPlayerCurrentRoom(playerMetadata.getPlayerId()); if (!playerCurrentRoom.isPresent()) { iterator.remove(); } else if (!Objects.equals(npcCurrentRoom.getRoomId(), playerCurrentRoom.get().getRoomId())) { @@ -631,6 +644,14 @@ public class GameManager { return damagePcts; } + public PlayerManager getPlayerManager() { + return playerManager; + } + + public RoomManager getRoomManager() { + return roomManager; + } + public synchronized void removeAllNpcs() { for (Npc npc : entityManager.getNpcs().values()) { Iterator<Map.Entry<Integer, Room>> rooms = roomManager.getRoomsIterator(); @@ -648,7 +669,6 @@ public class GameManager { } } - public String buildPrompt(String playerId) { Player player = playerManager.getPlayer(playerId); boolean isFight = player.isActiveFights(); @@ -694,28 +714,5 @@ public class GameManager { sb.append(Color.RESET); return sb.toString(); } - - public String drawProgressBar(int pct) { - StringBuilder sb = new StringBuilder(); - sb.append("["); - int numberOfProgressBarNotches = getNumberOfProgressBarNotches(pct); - for (int i = 0; i < numberOfProgressBarNotches; i++) { - sb.append("+"); - } - for (int i = numberOfProgressBarNotches; i < 10; i++) { - sb.append(" "); - } - sb.append("]"); - return sb.toString(); - } - - public int getNumberOfProgressBarNotches(int y) { - int x = (int) (Math.round(y / 10.0) * 10); - String str = Integer.toString(x); - if (str.length() > 1) { - str = str.substring(0, str.length() - 1); - } - return Integer.parseInt(str); - } } diff --git a/src/main/java/com/comandante/creeper/npc/Npc.java b/src/main/java/com/comandante/creeper/npc/Npc.java index 98c0d23c..658b4664 100644 --- a/src/main/java/com/comandante/creeper/npc/Npc.java +++ b/src/main/java/com/comandante/creeper/npc/Npc.java @@ -19,15 +19,14 @@ import com.comandante.creeper.stat.StatsBuilder; import com.comandante.creeper.stat.StatsHelper; import com.comandante.creeper.world.Area; import com.comandante.creeper.world.Room; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.api.client.util.Sets; -import com.google.common.base.Optional; import com.google.common.collect.Interner; import com.google.common.collect.Interners; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.nocrala.tools.texttablefmt.BorderStyle; import org.nocrala.tools.texttablefmt.ShownBorders; +import org.nocrala.tools.texttablefmt.Table; import java.text.NumberFormat; import java.util.*; @@ -40,7 +39,6 @@ import static com.comandante.creeper.server.Color.RESET; public class Npc extends CreeperEntity { - private long lastPhraseTimestamp; private final GameManager gameManager; private final String name; private final String colorName; @@ -49,18 +47,19 @@ public class Npc extends CreeperEntity { private final Temperament temperament; private final Set<Area> roamAreas; private final Set<String> validTriggers; - private Loot loot; private final Set<SpawnRule> spawnRules; + private final ArrayBlockingQueue<NpcStatsChange> npcStatsChanges = new ArrayBlockingQueue<>(3000); + private final Interner<Npc> interner = Interners.newWeakInterner(); + private final AtomicBoolean isAlive = new AtomicBoolean(true); + private final Random random = new Random(); + private long lastPhraseTimestamp; + private Loot loot; private List<Effect> effects = Lists.newCopyOnWriteArrayList(); private int maxEffects = 4; private Map<String, Long> playerDamageMap = Maps.newHashMap(); private Room currentRoom; - private final ArrayBlockingQueue<NpcStatsChange> npcStatsChanges = new ArrayBlockingQueue<>(3000); private int effectsTickBucket = 0; - private final Interner<Npc> interner = Interners.newWeakInterner(); - private final AtomicBoolean isAlive = new AtomicBoolean(true); private Set<CoolDown> coolDowns = Sets.newHashSet(); - private final Random random = new Random(); protected Npc(GameManager gameManager, String name, String colorName, long lastPhraseTimestamp, Stats stats, String dieMessage, Temperament temperament, Set<Area> roamAreas, Set<String> validTriggers, Loot loot, Set<SpawnRule> spawnRules) { @@ -128,176 +127,10 @@ public class Npc extends CreeperEntity { } } - private boolean getRandPercent(double percent) { - double rangeMin = 0; - double rangeMax = 100; - double randomValue = rangeMin + (rangeMax - rangeMin) * random.nextDouble(); - return randomValue <= percent; - } - - private void tickAllActiveCoolDowns() { - Iterator<CoolDown> iterator = coolDowns.iterator(); - while (iterator.hasNext()) { - CoolDown coolDown = iterator.next(); - if (coolDown.isActive()) { - coolDown.decrementTick(); - } else { - iterator.remove(); - } - } - } - - public void addCoolDown(CoolDown coolDown) { - this.coolDowns.add(coolDown); - } - - public Set<CoolDown> getCoolDowns() { - return coolDowns; - } - - - public void setLastPhraseTimestamp(long lastPhraseTimestamp) { - this.lastPhraseTimestamp = lastPhraseTimestamp; - } - - public String getColorName() { - return colorName; - } - - public Set<String> getValidTriggers() { - return validTriggers; - } - - public Set<Area> getRoamAreas() { - return roamAreas; - } - - public Stats getStats() { - return stats; - } - - public GameManager getGameManager() { - return gameManager; - } - - public long getLastPhraseTimestamp() { - return lastPhraseTimestamp; - } - public String getName() { return name; } - public String getDieMessage() { - return dieMessage; - } - - public void npcSay(Integer roomId, String message) { - StringBuilder sb = new StringBuilder(); - sb.append(RED); - sb.append(name).append(": ").append(message); - sb.append(RESET); - } - - public Loot getLoot() { - return loot; - } - - public Set<SpawnRule> getSpawnRules() { - return spawnRules; - } - - public Optional<SpawnRule> getSpawnRuleByArea(Area area) { - Set<SpawnRule> spawnRules = getSpawnRules(); - for (SpawnRule spawnRule : spawnRules) { - if (spawnRule.getArea().equals(area)) { - return Optional.of(spawnRule); - } - } - return Optional.absent(); - } - - public void addEffect(Effect effect) { - Interner<String> interner = Interners.newWeakInterner(); - synchronized (interner.intern(getEntityId())) { - if (effects.size() >= maxEffects) { - } else { - effects.add(effect); - } - } - } - - public List<Effect> getEffects() { - return effects; - } - - public long getExperience() { - return getStats().getExperience(); - } - - public double getPctOFExperience(double pct, long playerLevel) { - return getExperience() * pct; - } - - public void addDamageToMap(String playerId, long amt) { - playerDamageMap.put(playerId, amt); - } - - public Map<String, Long> getPlayerDamageMap() { - return playerDamageMap; - } - - public void setLoot(Loot loot) { - this.loot = loot; - } - - public Room getCurrentRoom() { - return currentRoom; - } - - public Temperament getTemperament() { - return temperament; - } - - public AtomicBoolean getIsAlive() { - return isAlive; - } - - public void setCurrentRoom(Room currentRoom) { - this.currentRoom = currentRoom; - } - - public void addNpcDamage(NpcStatsChange npcStatsChange) { - if (!isActiveCooldown(CoolDownType.NPC_FIGHT)) { - addCoolDown(new CoolDown(CoolDownType.NPC_FIGHT)); - } else { - for (CoolDown coolDown : coolDowns) { - if (coolDown.getCoolDownType().equals(CoolDownType.NPC_FIGHT)) { - coolDown.setNumberOfTicks(coolDown.getOriginalNumberOfTicks()); - } - } - } - this.npcStatsChanges.add(npcStatsChange); - } - - public boolean isActiveCooldown(CoolDownType coolDownType) { - for (CoolDown c : coolDowns) { - if (c.getCoolDownType().equals(coolDownType)) { - if (c.isActive()) { - return true; - } - } - } - return false; - } - - - public void doHealthDamage(Player player, List<String> damageStrings, long amt) { - NpcStatsChange npcStatsChange = - new NpcStatsChangeBuilder().setStats(new StatsBuilder().setCurrentHealth(amt).createStats()).setDamageStrings(damageStrings).setPlayer(player).createNpcStatsChange(); - addNpcDamage(npcStatsChange); - } - private void processNpcStatChange(NpcStatsChange npcStatsChange) { try { if (npcStatsChange.getPlayer().isActive(CoolDownType.DEATH) && !npcStatsChange.isItemDamage()) { @@ -341,39 +174,46 @@ public class Npc extends CreeperEntity { } } - private String getBattleReport(long xpEarned) { - StringBuilder sb = new StringBuilder(); - sb.append(Color.MAGENTA).append("Battle Report----------------------------").append(Color.RESET).append("\r\n"); - sb.append("You killed a "); - sb.append(getColorName()); - sb.append(" for "); - sb.append(Color.GREEN); - sb.append("+"); - sb.append(NumberFormat.getNumberInstance(Locale.US).format(xpEarned)); - sb.append(Color.RESET); - sb.append(" experience points."); - sb.append("\r\n"); + public boolean isActiveCooldown(CoolDownType coolDownType) { + for (CoolDown c : coolDowns) { + if (c.getCoolDownType().equals(coolDownType)) { + if (c.isActive()) { + return true; + } + } + } + return false; + } - Set<Map.Entry<String, Long>> entries = getPlayerDamageMap().entrySet(); - org.nocrala.tools.texttablefmt.Table t = new org.nocrala.tools.texttablefmt.Table(2, BorderStyle.CLASSIC_COMPATIBLE, - ShownBorders.NONE); + private boolean getRandPercent(double percent) { + double rangeMin = 0; + double rangeMax = 100; + double randomValue = rangeMin + (rangeMax - rangeMin) * random.nextDouble(); + return randomValue <= percent; + } - t.setColumnWidth(0, 14, 24); - t.setColumnWidth(1, 10, 13); - t.addCell("Player"); - t.addCell("Damage"); - for (Map.Entry<String, Long> entry : entries) { - Player player = gameManager.getPlayerManager().getPlayer(entry.getKey()); - String name = null; - if (player != null) { - name = player.getPlayerName(); + private void tickAllActiveCoolDowns() { + Iterator<CoolDown> iterator = coolDowns.iterator(); + while (iterator.hasNext()) { + CoolDown coolDown = iterator.next(); + if (coolDown.isActive()) { + coolDown.decrementTick(); + } else { + iterator.remove(); } - long damageAmt = entry.getValue(); - t.addCell(name); - t.addCell(NumberFormat.getNumberInstance(Locale.US).format(damageAmt)); } - sb.append(t.render()); - return sb.toString(); + } + + public Stats getStats() { + return stats; + } + + public Map<String, Long> getPlayerDamageMap() { + return playerDamageMap; + } + + public void addDamageToMap(String playerId, long amt) { + playerDamageMap.put(playerId, amt); } private void killNpc(Player player) { @@ -408,23 +248,73 @@ public class Npc extends CreeperEntity { } } - public static enum NpcLevelColor { + public Loot getLoot() { + return loot; + } - RED(Color.RED + "Red"), - ORANGE(Color.CYAN + "Cyan"), - YELLOW(Color.YELLOW + "Yellow"), - GREEN(Color.GREEN + "Green"), - WHITE(Color.WHITE + "White"); + public String getDieMessage() { + return dieMessage; + } - private final String color; + public Room getCurrentRoom() { + return currentRoom; + } - NpcLevelColor(String color) { - this.color = color; + public void setCurrentRoom(Room currentRoom) { + this.currentRoom = currentRoom; + } + + private int getNpcXp(int playerLevel, int npcLevel) { + if (npcLevel >= playerLevel) { + double temp = ((playerLevel * 5) + 45) * (1 + (0.05 * (npcLevel - playerLevel))); + double tempCap = ((playerLevel * 5) + 45) * 1.2; + if (temp > tempCap) { + return (int) Math.floor(tempCap); + } else { + return (int) Math.floor(temp); + } + } else { + if (getLevelColor(playerLevel).equals(NpcLevelColor.WHITE)) { + return 0; + } else { + return (int) (Math.floor((playerLevel * 5) + 45) * (1 - (playerLevel - npcLevel) / getZD(playerLevel))); + } } + } - public String getColor() { - return "(" + Color.BOLD_ON + color + Color.RESET + ")"; + private String getBattleReport(long xpEarned) { + StringBuilder sb = new StringBuilder(); + sb.append(Color.MAGENTA).append("Battle Report----------------------------").append(Color.RESET).append("\r\n"); + sb.append("You killed a "); + sb.append(getColorName()); + sb.append(" for "); + sb.append(Color.GREEN); + sb.append("+"); + sb.append(NumberFormat.getNumberInstance(Locale.US).format(xpEarned)); + sb.append(Color.RESET); + sb.append(" experience points."); + sb.append("\r\n"); + + Set<Map.Entry<String, Long>> entries = getPlayerDamageMap().entrySet(); + Table t = new Table(2, BorderStyle.CLASSIC_COMPATIBLE, + ShownBorders.NONE); + + t.setColumnWidth(0, 14, 24); + t.setColumnWidth(1, 10, 13); + t.addCell("Player"); + t.addCell("Damage"); + for (Map.Entry<String, Long> entry : entries) { + Player player = gameManager.getPlayerManager().getPlayer(entry.getKey()); + String name = null; + if (player != null) { + name = player.getPlayerName(); + } + long damageAmt = entry.getValue(); + t.addCell(name); + t.addCell(NumberFormat.getNumberInstance(Locale.US).format(damageAmt)); } + sb.append(t.render()); + return sb.toString(); } public NpcLevelColor getLevelColor(int playerLevel) { @@ -466,24 +356,6 @@ public class Npc extends CreeperEntity { } } - private int getNpcXp(int playerLevel, int npcLevel) { - if (npcLevel >= playerLevel) { - double temp = ((playerLevel * 5) + 45) * (1 + (0.05 * (npcLevel - playerLevel))); - double tempCap = ((playerLevel * 5) + 45) * 1.2; - if (temp > tempCap) { - return (int) Math.floor(tempCap); - } else { - return (int) Math.floor(temp); - } - } else { - if (getLevelColor(playerLevel).equals(NpcLevelColor.WHITE)) { - return 0; - } else { - return (int) (Math.floor((playerLevel * 5) + 45) * (1 - (playerLevel - npcLevel) / getZD(playerLevel))); - } - } - } - private int getZD(int lvl) { if (lvl <= 7) { return 5; @@ -528,4 +400,125 @@ public class Npc extends CreeperEntity { } } + public String getColorName() { + return colorName; + } + + public void setLoot(Loot loot) { + this.loot = loot; + } + + public Set<CoolDown> getCoolDowns() { + return coolDowns; + } + + public Set<String> getValidTriggers() { + return validTriggers; + } + + public Set<Area> getRoamAreas() { + return roamAreas; + } + + public GameManager getGameManager() { + return gameManager; + } + + public long getLastPhraseTimestamp() { + return lastPhraseTimestamp; + } + + public void setLastPhraseTimestamp(long lastPhraseTimestamp) { + this.lastPhraseTimestamp = lastPhraseTimestamp; + } + + public void npcSay(Integer roomId, String message) { + StringBuilder sb = new StringBuilder(); + sb.append(RED); + sb.append(name).append(": ").append(message); + sb.append(RESET); + } + + public Optional<SpawnRule> getSpawnRuleByArea(Area area) { + Set<SpawnRule> spawnRules = getSpawnRules(); + for (SpawnRule spawnRule : spawnRules) { + if (spawnRule.getArea().equals(area)) { + return Optional.of(spawnRule); + } + } + return Optional.empty(); + } + + public Set<SpawnRule> getSpawnRules() { + return spawnRules; + } + + public void addEffect(Effect effect) { + Interner<String> interner = Interners.newWeakInterner(); + synchronized (interner.intern(getEntityId())) { + if (effects.size() >= maxEffects) { + } else { + effects.add(effect); + } + } + } + + public List<Effect> getEffects() { + return effects; + } + + public long getExperience() { + return getStats().getExperience(); + } + + public Temperament getTemperament() { + return temperament; + } + + public AtomicBoolean getIsAlive() { + return isAlive; + } + + public void doHealthDamage(Player player, List<String> damageStrings, long amt) { + NpcStatsChange npcStatsChange = + new NpcStatsChangeBuilder().setStats(new StatsBuilder().setCurrentHealth(amt).createStats()).setDamageStrings(damageStrings).setPlayer(player).createNpcStatsChange(); + addNpcDamage(npcStatsChange); + } + + public void addNpcDamage(NpcStatsChange npcStatsChange) { + if (!isActiveCooldown(CoolDownType.NPC_FIGHT)) { + addCoolDown(new CoolDown(CoolDownType.NPC_FIGHT)); + } else { + for (CoolDown coolDown : coolDowns) { + if (coolDown.getCoolDownType().equals(CoolDownType.NPC_FIGHT)) { + coolDown.setNumberOfTicks(coolDown.getOriginalNumberOfTicks()); + } + } + } + this.npcStatsChanges.add(npcStatsChange); + } + + public void addCoolDown(CoolDown coolDown) { + this.coolDowns.add(coolDown); + } + + public enum NpcLevelColor { + + RED(Color.RED + "Red"), + ORANGE(Color.CYAN + "Cyan"), + YELLOW(Color.YELLOW + "Yellow"), + GREEN(Color.GREEN + "Green"), + WHITE(Color.WHITE + "White"); + + private final String color; + + NpcLevelColor(String color) { + this.color = color; + } + + public String getColor() { + return "(" + Color.BOLD_ON + color + Color.RESET + ")"; + } + } + } diff --git a/src/main/java/com/comandante/creeper/npc/NpcMover.java b/src/main/java/com/comandante/creeper/npc/NpcMover.java index 0032bafe..b3271a73 100644 --- a/src/main/java/com/comandante/creeper/npc/NpcMover.java +++ b/src/main/java/com/comandante/creeper/npc/NpcMover.java @@ -6,7 +6,6 @@ import com.comandante.creeper.player.CoolDownType; import com.comandante.creeper.spawner.SpawnRule; import com.comandante.creeper.world.Area; import com.comandante.creeper.world.Room; -import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; @@ -14,6 +13,7 @@ import com.google.common.collect.Sets; import org.apache.log4j.Logger; import java.util.List; +import java.util.Optional; import java.util.Random; import java.util.Set; @@ -120,7 +120,7 @@ public class NpcMover { } public Set<Integer> getPossibleExits(Room room) { - List<java.util.Optional<Integer>> opts = Lists.newArrayList(); + List<Optional<Integer>> opts = Lists.newArrayList(); opts.add(room.getDownId()); opts.add(room.getUpId()); opts.add(room.getNorthId()); @@ -129,7 +129,7 @@ public class NpcMover { opts.add(room.getWestId()); Set<Integer> exits = Sets.newHashSet(); - for (java.util.Optional<Integer> opt : opts) { + for (Optional<Integer> opt : opts) { if (opt.isPresent()) { exits.add(opt.get()); } diff --git a/src/main/java/com/comandante/creeper/player/Player.java b/src/main/java/com/comandante/creeper/player/Player.java index 0fb4b409..29e88507 100755 --- a/src/main/java/com/comandante/creeper/player/Player.java +++ b/src/main/java/com/comandante/creeper/player/Player.java @@ -19,32 +19,34 @@ import com.comandante.creeper.stat.StatsHelper; import com.comandante.creeper.world.Room; import com.google.common.base.Optional; import com.google.common.collect.*; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.jboss.netty.channel.Channel; -import org.nocrala.tools.texttablefmt.BorderStyle; -import org.nocrala.tools.texttablefmt.ShownBorders; +import org.nocrala.tools.texttablefmt.*; +import org.nocrala.tools.texttablefmt.Table; import java.text.NumberFormat; import java.util.*; public class Player extends CreeperEntity { + private static final Logger log = Logger.getLogger(Player.class); + private final GameManager gameManager; + private final String playerId; + private final Interner<String> interner = Interners.newWeakInterner(); + private final Random random = new Random(); private String playerName; private Channel channel; private Optional<String> returnDirection = Optional.absent(); - private final GameManager gameManager; private Room currentRoom; private SortedMap<Long, ActiveFight> activeFights = Collections.synchronizedSortedMap(new TreeMap<Long, ActiveFight>()); - private final String playerId; private Set<CoolDown> coolDowns = Collections.synchronizedSet(new HashSet<CoolDown>()); - private final Interner<String> interner = Interners.newWeakInterner(); - private final Random random = new Random(); private int tickBucket = 0; private int fightTickBucket = 0; - private static final Logger log = Logger.getLogger(Player.class); - public Player(String playerName, GameManager gameManager) { this.playerName = playerName; this.playerId = new String(Base64.encodeBase64(playerName.getBytes())); @@ -248,6 +250,14 @@ public class Player extends CreeperEntity { } } + private PlayerMetadata getPlayerMetadata() { + return gameManager.getPlayerManager().getPlayerMetadata(playerId); + } + + private void savePlayerMetadata(PlayerMetadata playerMetadata) { + gameManager.getPlayerManager().savePlayerMetadata(playerMetadata); + } + public long getCurrentHealth() { synchronized (interner.intern(playerId)) { return gameManager.getPlayerManager().getPlayerMetadata(playerId).getStats().getCurrentHealth(); @@ -298,22 +308,6 @@ public class Player extends CreeperEntity { } } - public void addLockerInventoryId(String entityId) { - synchronized (interner.intern(playerId)) { - PlayerMetadata playerMetadata = getPlayerMetadata(); - playerMetadata.addLockerEntityId(entityId); - savePlayerMetadata(playerMetadata); - } - } - - public void removeLockerInventoryId(String lockerInventoryId) { - synchronized (interner.intern(playerId)) { - PlayerMetadata playerMetadata = getPlayerMetadata(); - playerMetadata.removeLockerEntityId(lockerInventoryId); - savePlayerMetadata(playerMetadata); - } - } - public void addLearnedSpellByName(String spellName) { synchronized (interner.intern(playerId)) { PlayerMetadata playerMetadata = getPlayerMetadata(); @@ -339,27 +333,18 @@ public class Player extends CreeperEntity { } } - public void addEquipmentId(String equipmentId) { - synchronized (interner.intern(playerId)) { - PlayerMetadata playerMetadata = getPlayerMetadata(); - playerMetadata.addEquipmentEntityId(equipmentId); - savePlayerMetadata(playerMetadata); - } - } - - public void removeEquipmentId(String equipmentId) { + public void addInventoryId(String inventoryId) { synchronized (interner.intern(playerId)) { PlayerMetadata playerMetadata = getPlayerMetadata(); - playerMetadata.removeEquipmentEntityId(equipmentId); + playerMetadata.addInventoryEntityId(inventoryId); savePlayerMetadata(playerMetadata); } } - public void addInventoryId(String inventoryId) { + public void transferItemToLocker(String inventoryId) { synchronized (interner.intern(playerId)) { - PlayerMetadata playerMetadata = getPlayerMetadata(); - playerMetadata.addInventoryEntityId(inventoryId); - savePlayerMetadata(playerMetadata); + removeInventoryId(inventoryId); + addLockerInventoryId(inventoryId); } } @@ -371,10 +356,11 @@ public class Player extends CreeperEntity { } } - public void transferItemToLocker(String inventoryId) { + public void addLockerInventoryId(String entityId) { synchronized (interner.intern(playerId)) { - removeInventoryId(inventoryId); - addLockerInventoryId(inventoryId); + PlayerMetadata playerMetadata = getPlayerMetadata(); + playerMetadata.addLockerEntityId(entityId); + savePlayerMetadata(playerMetadata); } } @@ -386,6 +372,14 @@ public class Player extends CreeperEntity { } } + public void removeLockerInventoryId(String lockerInventoryId) { + synchronized (interner.intern(playerId)) { + PlayerMetadata playerMetadata = getPlayerMetadata(); + playerMetadata.removeLockerEntityId(lockerInventoryId); + savePlayerMetadata(playerMetadata); + } + } + public void updatePlayerMana(int amount) { synchronized (interner.intern(playerId)) { PlayerMetadata playerMetadata = getPlayerMetadata(); @@ -412,17 +406,6 @@ public class Player extends CreeperEntity { return coolDowns; } - public boolean isActive(CoolDownType coolDownType) { - for (CoolDown c : coolDowns) { - if (c.getCoolDownType().equals(coolDownType)) { - if (c.isActive()) { - return true; - } - } - } - return false; - } - public boolean isActiveCoolDown() { return coolDowns.size() > 0; } @@ -437,6 +420,17 @@ public class Player extends CreeperEntity { return false; } + public boolean isActive(CoolDownType coolDownType) { + for (CoolDown c : coolDowns) { + if (c.getCoolDownType().equals(coolDownType)) { + if (c.isActive()) { + return true; + } + } + } + return false; + } + public boolean isActiveSpellCoolDown(String spellName) { for (CoolDown coolDown : coolDowns) { if (coolDown.getName().equalsIgnoreCase(spellName)) { @@ -463,10 +457,6 @@ public class Player extends CreeperEntity { gameManager.getChannelUtils().write(playerId, prompt, true); } - public String getPlayerName() { - return playerName; - } - public String getPlayerId() { return playerId; } @@ -534,54 +524,8 @@ public class Player extends CreeperEntity { } } - public List<Item> getInventory() { - synchronized (interner.intern(playerId)) { - PlayerMetadata playerMetadata = getPlayerMetadata(); - List<Item> inventoryItems = Lists.newArrayList(); - List<String> inventory = playerMetadata.getInventory(); - if (inventory != null) { - for (String itemId : inventory) { - Item itemEntity = gameManager.getEntityManager().getItemEntity(itemId); - if (itemEntity == null) { - log.info("Orphaned inventoryId:" + itemId + " player: " + getPlayerName()); - continue; - } - inventoryItems.add(itemEntity); - } - } - Collections.sort(inventoryItems, new Comparator<Item>() { - @Override - public int compare(final Item object1, final Item object2) { - return object1.getItemName().compareTo(object2.getItemName()); - } - }); - return inventoryItems; - } - } - - public List<Item> getLockerInventory() { - synchronized (interner.intern(playerId)) { - PlayerMetadata playerMetadata = getPlayerMetadata(); - List<Item> inventoryItems = Lists.newArrayList(); - List<String> inventory = playerMetadata.getLockerInventory(); - if (inventory != null) { - for (String itemId : inventory) { - Item itemEntity = gameManager.getEntityManager().getItemEntity(itemId); - if (itemEntity == null) { - log.info("Orphaned inventoryId:" + itemId + " player: " + getPlayerName()); - continue; - } - inventoryItems.add(itemEntity); - } - } - Collections.sort(inventoryItems, new Comparator<Item>() { - @Override - public int compare(final Item object1, final Item object2) { - return object1.getItemName().compareTo(object2.getItemName()); - } - }); - return inventoryItems; - } + public String getPlayerName() { + return playerName; } public List<String> getRolledUpLockerInventory() { @@ -625,6 +569,31 @@ public class Player extends CreeperEntity { } } + public List<Item> getLockerInventory() { + synchronized (interner.intern(playerId)) { + PlayerMetadata playerMetadata = getPlayerMetadata(); + List<Item> inventoryItems = Lists.newArrayList(); + List<String> inventory = playerMetadata.getLockerInventory(); + if (inventory != null) { + for (String itemId : inventory) { + Item itemEntity = gameManager.getEntityManager().getItemEntity(itemId); + if (itemEntity == null) { + log.info("Orphaned inventoryId:" + itemId + " player: " + getPlayerName()); + continue; + } + inventoryItems.add(itemEntity); + } + } + Collections.sort(inventoryItems, new Comparator<Item>() { + @Override + public int compare(final Item object1, final Item object2) { + return object1.getItemName().compareTo(object2.getItemName()); + } + }); + return inventoryItems; + } + } + public List<String> getRolledUpIntentory() { synchronized (interner.intern(playerId)) { List<String> rolledUp = Lists.newArrayList(); @@ -666,6 +635,31 @@ public class Player extends CreeperEntity { } } + public List<Item> getInventory() { + synchronized (interner.intern(playerId)) { + PlayerMetadata playerMetadata = getPlayerMetadata(); + List<Item> inventoryItems = Lists.newArrayList(); + List<String> inventory = playerMetadata.getInventory(); + if (inventory != null) { + for (String itemId : inventory) { + Item itemEntity = gameManager.getEntityManager().getItemEntity(itemId); + if (itemEntity == null) { + log.info("Orphaned inventoryId:" + itemId + " player: " + getPlayerName()); + continue; + } + inventoryItems.add(itemEntity); + } + } + Collections.sort(inventoryItems, new Comparator<Item>() { + @Override + public int compare(final Item object1, final Item object2) { + return object1.getItemName().compareTo(object2.getItemName()); + } + }); + return inventoryItems; + } + } + public Set<Item> getEquipment() { synchronized (interner.intern(playerId)) { PlayerMetadata playerMetadata = getPlayerMetadata(); @@ -730,6 +724,42 @@ public class Player extends CreeperEntity { } } + public void addEquipmentId(String equipmentId) { + synchronized (interner.intern(playerId)) { + PlayerMetadata playerMetadata = getPlayerMetadata(); + playerMetadata.addEquipmentEntityId(equipmentId); + savePlayerMetadata(playerMetadata); + } + } + + public void removeEquipmentId(String equipmentId) { + synchronized (interner.intern(playerId)) { + PlayerMetadata playerMetadata = getPlayerMetadata(); + playerMetadata.removeEquipmentEntityId(equipmentId); + savePlayerMetadata(playerMetadata); + } + } + + public String getLookString() { + StringBuilder sb = new StringBuilder(); + Stats origStats = gameManager.getStatsModifierFactory().getStatsModifier(this); + Stats modifiedStats = getPlayerStatsWithEquipmentAndLevel(); + Stats diffStats = StatsHelper.getDifference(modifiedStats, origStats); + sb.append(Color.MAGENTA + "-+=[ " + Color.RESET).append(playerName).append(Color.MAGENTA + " ]=+- " + Color.RESET).append("\r\n"); + sb.append("Level ").append(Levels.getLevel(origStats.getExperience())).append("\r\n"); + sb.append("Foraging Level ").append(ForageManager.getLevel(modifiedStats.getForaging())).append("\r\n"); + sb.append(Color.MAGENTA + "Equip--------------------------------" + Color.RESET).append("\r\n"); + sb.append(buildEquipmentString()).append("\r\n"); + sb.append(Color.MAGENTA + "Stats--------------------------------" + Color.RESET).append("\r\n"); + sb.append(gameManager.buildLookString(playerName, modifiedStats, diffStats)).append("\r\n"); + PlayerMetadata playerMetadata = getPlayerMetadata(); + if (playerMetadata.getEffects() != null && playerMetadata.getEffects().size() > 0) { + sb.append(Color.MAGENTA + "Effects--------------------------------" + Color.RESET).append("\r\n"); + sb.append(buldEffectsString()).append("\r\n"); + } + return sb.toString(); + } + public Stats getPlayerStatsWithEquipmentAndLevel() { synchronized (interner.intern(playerId)) { PlayerMetadata playerMetadata = getPlayerMetadata(); @@ -759,28 +789,8 @@ public class Player extends CreeperEntity { } } - public String getLookString() { - StringBuilder sb = new StringBuilder(); - Stats origStats = gameManager.getStatsModifierFactory().getStatsModifier(this); - Stats modifiedStats = getPlayerStatsWithEquipmentAndLevel(); - Stats diffStats = StatsHelper.getDifference(modifiedStats, origStats); - sb.append(Color.MAGENTA + "-+=[ " + Color.RESET).append(playerName).append(Color.MAGENTA + " ]=+- " + Color.RESET).append("\r\n"); - sb.append("Level ").append(Levels.getLevel(origStats.getExperience())).append("\r\n"); - sb.append("Foraging Level ").append(ForageManager.getLevel(modifiedStats.getForaging())).append("\r\n"); - sb.append(Color.MAGENTA + "Equip--------------------------------" + Color.RESET).append("\r\n"); - sb.append(buildEquipmentString()).append("\r\n"); - sb.append(Color.MAGENTA + "Stats--------------------------------" + Color.RESET).append("\r\n"); - sb.append(gameManager.buildLookString(playerName, modifiedStats, diffStats)).append("\r\n"); - PlayerMetadata playerMetadata = getPlayerMetadata(); - if (playerMetadata.getEffects() != null && playerMetadata.getEffects().size() > 0) { - sb.append(Color.MAGENTA + "Effects--------------------------------" + Color.RESET).append("\r\n"); - sb.append(buldEffectsString()).append("\r\n"); - } - return sb.toString(); - } - public String buildEquipmentString() { - org.nocrala.tools.texttablefmt.Table t = new org.nocrala.tools.texttablefmt.Table(2, BorderStyle.CLASSIC_COMPATIBLE, + org.nocrala.tools.texttablefmt.Table t = new Table(2, BorderStyle.CLASSIC_COMPATIBLE, ShownBorders.NONE); t.setColumnWidth(0, 16, 20); @@ -797,6 +807,7 @@ public class Player extends CreeperEntity { return t.render(); } + /* FIGHT FIGHT FIGHT FIGHT */ public String buldEffectsString() { PlayerMetadata playerMetadata = getPlayerMetadata(); @@ -816,8 +827,6 @@ public class Player extends CreeperEntity { return Character.toUpperCase(line.charAt(0)) + line.substring(1); } - /* FIGHT FIGHT FIGHT FIGHT */ - public void removeAllActiveFights() { synchronized (interner.intern(playerId)) { Iterator<Map.Entry<Long, ActiveFight>> iterator = activeFights.entrySet().iterator(); @@ -854,20 +863,6 @@ public class Player extends CreeperEntity { return getPlayerMetadata().getPlayerSettings(); } - public void removeActiveFight(Npc npc) { - synchronized (interner.intern(playerId)) { - Iterator<Map.Entry<Long, ActiveFight>> iterator = activeFights.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry<Long, ActiveFight> next = iterator.next(); - if (next.getValue().getNpcId().equals(npc.getEntityId())) { - if (next.getValue().isPrimary) { - } - iterator.remove(); - } - } - } - } - public boolean addActiveFight(Npc npc) { synchronized (interner.intern(playerId)) { if (gameManager.getEntityManager().getNpcEntity(npc.getEntityId()) != null) { @@ -896,6 +891,20 @@ public class Player extends CreeperEntity { } } + public void removeActiveFight(Npc npc) { + synchronized (interner.intern(playerId)) { + Iterator<Map.Entry<Long, ActiveFight>> iterator = activeFights.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry<Long, ActiveFight> next = iterator.next(); + if (next.getValue().getNpcId().equals(npc.getEntityId())) { + if (next.getValue().isPrimary) { + } + iterator.remove(); + } + } + } + } + public boolean isActiveFights() { synchronized (interner.intern(playerId)) { if (activeFights.size() > 0) { @@ -1019,6 +1028,10 @@ public class Player extends CreeperEntity { return random.nextInt((max - min) + 1) + min; } + public Interner<String> getInterner() { + return interner; + } + class ActiveFight { private final String npcId; private boolean isPrimary; @@ -1041,16 +1054,4 @@ public class Player extends CreeperEntity { } } - - private PlayerMetadata getPlayerMetadata() { - return gameManager.getPlayerManager().getPlayerMetadata(playerId); - } - - private void savePlayerMetadata(PlayerMetadata playerMetadata) { - gameManager.getPlayerManager().savePlayerMetadata(playerMetadata); - } - - public Interner<String> getInterner() { - return interner; - } } diff --git a/src/main/java/com/comandante/creeper/player/PlayerManager.java b/src/main/java/com/comandante/creeper/player/PlayerManager.java index c0287937..8b3c3312 100644 --- a/src/main/java/com/comandante/creeper/player/PlayerManager.java +++ b/src/main/java/com/comandante/creeper/player/PlayerManager.java @@ -18,14 +18,10 @@ import static com.codahale.metrics.MetricRegistry.name; public class PlayerManager { - private ConcurrentHashMap<String, Player> players = new ConcurrentHashMap<String, Player>(); - private HTreeMap<String, PlayerMetadata> playerMetadataStore; private final DB db; private final SessionManager sessionManager; - - public SessionManager getSessionManager() { - return sessionManager; - } + private ConcurrentHashMap<String, Player> players = new ConcurrentHashMap<String, Player>(); + private HTreeMap<String, PlayerMetadata> playerMetadataStore; public PlayerManager(DB db, SessionManager sessionManager) { this.db = db; @@ -39,12 +35,8 @@ public class PlayerManager { this.sessionManager = sessionManager; } - public PlayerMetadata getPlayerMetadata(String playerId) { - PlayerMetadata playerMetadata = playerMetadataStore.get(playerId); - if (playerMetadata == null) { - return playerMetadata; - } - return new PlayerMetadata(playerMetadata); + public SessionManager getSessionManager() { + return sessionManager; } public void savePlayerMetadata(PlayerMetadata playerMetadata) { @@ -55,14 +47,6 @@ public class PlayerManager { return players.put(player.getPlayerId(), player); } - public Player getPlayerByUsername(String username) { - return getPlayer(new String(Base64.encodeBase64(username.getBytes()))); - } - - public Player getPlayer(String playerId) { - return players.get(playerId); - } - public Iterator<java.util.Map.Entry<String, Player>> getPlayers() { return players.entrySet().iterator(); } @@ -79,6 +63,14 @@ public class PlayerManager { players.remove(player.getPlayerId()); } + public Player getPlayerByUsername(String username) { + return getPlayer(new String(Base64.encodeBase64(username.getBytes()))); + } + + public Player getPlayer(String playerId) { + return players.get(playerId); + } + public boolean doesPlayerExist(String username) { return players.containsKey(new String(Base64.encodeBase64(username.getBytes()))); } @@ -93,6 +85,14 @@ public class PlayerManager { } } + public PlayerMetadata getPlayerMetadata(String playerId) { + PlayerMetadata playerMetadata = playerMetadataStore.get(playerId); + if (playerMetadata == null) { + return playerMetadata; + } + return new PlayerMetadata(playerMetadata); + } + public boolean hasAnyOfRoles(Player player, Set<PlayerRole> checkRoles) { PlayerMetadata playerMetadata = getPlayerMetadata(player.getPlayerId()); Set<PlayerRole> playerRoleSet = playerMetadata.getPlayerRoleSet(); @@ -108,6 +108,14 @@ public class PlayerManager { return false; } + public void createAllGauges() { + Iterator<Map.Entry<String, PlayerMetadata>> iterator = playerMetadataStore.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry<String, PlayerMetadata> next = iterator.next(); + createGauges(next.getValue()); + } + } + public void createGauges(final PlayerMetadata playerMetadata) { String guageName = name(PlayerManager.class, playerMetadata.getPlayerName(), "gold"); if (!doesGaugeExist(guageName)) { @@ -143,14 +151,6 @@ public class PlayerManager { } } - public void createAllGauges() { - Iterator<Map.Entry<String, PlayerMetadata>> iterator = playerMetadataStore.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry<String, PlayerMetadata> next = iterator.next(); - createGauges(next.getValue()); - } - } - private boolean doesGaugeExist(String name) { return Main.metrics.getGauges().containsKey(name); } diff --git a/src/main/java/com/comandante/creeper/server/GameAuth.java b/src/main/java/com/comandante/creeper/server/GameAuth.java index 46763438..c6a31b57 100644 --- a/src/main/java/com/comandante/creeper/server/GameAuth.java +++ b/src/main/java/com/comandante/creeper/server/GameAuth.java @@ -5,9 +5,10 @@ import com.comandante.creeper.managers.GameManager; import com.comandante.creeper.player.Player; import com.comandante.creeper.player.PlayerMetadata; import com.comandante.creeper.world.Room; -import com.google.common.base.Optional; import org.jboss.netty.channel.Channel; +import java.util.Optional; + public class GameAuth implements CreeperAuthenticator { private final GameManager gameManager; diff --git a/src/main/java/com/comandante/creeper/world/RoomManager.java b/src/main/java/com/comandante/creeper/world/RoomManager.java index c8fb6751..121cf7ad 100644 --- a/src/main/java/com/comandante/creeper/world/RoomManager.java +++ b/src/main/java/com/comandante/creeper/world/RoomManager.java @@ -4,35 +4,26 @@ import com.comandante.creeper.merchant.Merchant; import com.comandante.creeper.npc.Npc; import com.comandante.creeper.player.Player; import com.comandante.creeper.player.PlayerManager; -import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class RoomManager { private final PlayerManager playerManager; + private ConcurrentHashMap<Integer, Room> rooms = new ConcurrentHashMap<>(); public RoomManager(PlayerManager playerManager) { this.playerManager = playerManager; } - private ConcurrentHashMap<Integer, Room> rooms = new ConcurrentHashMap<Integer, Room>(); - public void addRoom(Room room) { rooms.put(room.getRoomId(), room); } - public Room getRoom(Integer roomId) { - return rooms.get(roomId); - } - public Set<Player> getPresentPlayers(Room room) { Set<String> presentPlayerIds = room.getPresentPlayerIds(); Set<Player> players = Sets.newHashSet(); @@ -57,15 +48,21 @@ public class RoomManager { if (matchedRooms.size() > 0) { return Optional.of(matchedRooms); - } else { - return Optional.absent(); - } + } else return Optional.empty(); + } + + public Iterator<Map.Entry<Integer, Room>> getRoomsIterator() { + return rooms.entrySet().iterator(); } public void addMerchant(Integer roomId, Merchant merchant) { getRoom(roomId).addMerchant(merchant); } + public Room getRoom(Integer roomId) { + return rooms.get(roomId); + } + public void tagRoom(Integer roomId, String tag) { getRoom(roomId).addTag(tag); } @@ -74,10 +71,6 @@ public class RoomManager { return getRoom(roomId).getRoomTags(); } - public Iterator<java.util.Map.Entry<Integer, Room>> getRoomsIterator() { - return rooms.entrySet().iterator(); - } - public Map<Integer, Room> getrooms() { return rooms; } @@ -94,6 +87,13 @@ public class RoomManager { return rooms; } + public Optional<Room> getPlayerCurrentRoom(Player player) { + if (player.getCurrentRoom() != null) { + return Optional.of(player.getCurrentRoom()); + } + return getPlayerCurrentRoom(player.getPlayerId()); + } + public Optional<Room> getPlayerCurrentRoom(String playerId) { Iterator<Map.Entry<Integer, Room>> rooms = getRoomsIterator(); while (rooms.hasNext()) { @@ -105,14 +105,7 @@ public class RoomManager { } } } - return Optional.absent(); - } - - public Optional<Room> getPlayerCurrentRoom(Player player) { - if (player.getCurrentRoom() != null) { - return Optional.of(player.getCurrentRoom()); - } - return getPlayerCurrentRoom(player.getPlayerId()); + return Optional.empty(); } public Optional<Room> getNpcCurrentRoom(Npc npc) { -- GitLab