From fdf4d70e92aa5efff0b234b805c3d23c9f3133cc Mon Sep 17 00:00:00 2001 From: ronan Date: Tue, 11 Jun 2019 16:20:33 +0100 Subject: [PATCH 1/4] Began QueueProvider rework --- .../game/queueprovider/QueueProvider.java | 40 +++++++++++ .../queueprovider/ServerQueueProvider.java | 67 +++++++++++++++++++ .../StandAloneQueueProvider.java | 23 +++++++ .../queueprovider/TestingQueueProvider.java | 43 ++++++++++++ 4 files changed, 173 insertions(+) create mode 100644 src/main/java/com/jadventure/game/queueprovider/QueueProvider.java create mode 100644 src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java create mode 100644 src/main/java/com/jadventure/game/queueprovider/StandAloneQueueProvider.java create mode 100644 src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java diff --git a/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java new file mode 100644 index 00000000..e5ee368d --- /dev/null +++ b/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java @@ -0,0 +1,40 @@ +package com.jadventure.game.queueprovider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.Socket; + +public abstract class QueueProvider { + protected static Logger logger = LoggerFactory.getLogger(com.jadventure.game.QueueProvider.class); + + private static QueueProvider instance; + + public static QueueProvider getInstance() { + return instance; + } + + public static void startStandaloneMessenger() { + logger.debug("Starting messenger in STANDALONE mode"); + + instance = new StandAloneQueueProvider(); + } + + public static void startServerMessenger(Socket sockerInc) { + logger.debug("Starting messenger in SERVER mode"); + + instance = new ServerQueueProvider(sockerInc); + } + + public static void startTestingMessenger() { + logger.debug("Starting messenger for automated testing purposes"); + + instance = new TestingQueueProvider(); + } + + public void offer(String message) { + logger.debug("offer( " + message + " )"); + } + + public abstract String take(); +} diff --git a/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java new file mode 100644 index 00000000..a24a8b4c --- /dev/null +++ b/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java @@ -0,0 +1,67 @@ +package com.jadventure.game.queueprovider; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; + +public class ServerQueueProvider extends QueueProvider{ + private DataInputStream in; + private DataOutputStream out; + private Socket socket; + + protected ServerQueueProvider(Socket socket) { + this.socket = socket; + + try { + out = new DataOutputStream(socket.getOutputStream()); + in = new DataInputStream(socket.getInputStream()); + } catch (IOException ioe) { + logger.debug("Inside ServerQueueProvider( " + socket+ " )", ioe); + } + } + + @Override + public void offer(String message) { + super.offer(message); + + sendToServer(message); + } + + @Override + public String take() { + String message = getInput("QUERY"); + + if (message.equals("error")) { + message = "exit"; + } + + return message; + } + + public boolean sendToServer(String message) { + logger.debug("sendToServer( " + message + " )"); + try { + out.writeUTF(message + "END"); + } catch(IOException se) { + logger.debug("Inside sendToServer( " + message + " )", se); + return false; + } + return true; + } + + private String getInput(String message) { + logger.debug("getInput( " + message + " )"); + String input; + + try { + sendToServer(message); + input = in.readUTF(); + } catch(IOException ioe) { + logger.debug("Inside getInput( " + message + " )", ioe); + input = "error"; + } + + return input; + } +} diff --git a/src/main/java/com/jadventure/game/queueprovider/StandAloneQueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/StandAloneQueueProvider.java new file mode 100644 index 00000000..93d7c5d8 --- /dev/null +++ b/src/main/java/com/jadventure/game/queueprovider/StandAloneQueueProvider.java @@ -0,0 +1,23 @@ +package com.jadventure.game.queueprovider; + +import java.util.Scanner; + +public final class StandAloneQueueProvider extends QueueProvider { + private Scanner console; + + protected StandAloneQueueProvider() { + console = new Scanner(System.in); + } + + @Override + public void offer(String message) { + super.offer(message); + + System.out.println(message); + } + + @Override + public String take() { + return console.nextLine(); + } +} diff --git a/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java new file mode 100644 index 00000000..897f0566 --- /dev/null +++ b/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java @@ -0,0 +1,43 @@ +package com.jadventure.game.queueprovider; + +import java.util.ArrayDeque; +import java.util.Deque; + +public final class TestingQueueProvider extends QueueProvider { + private Deque messageHistory; + private Deque inputQueue; + + protected TestingQueueProvider() { + // initialise testing queues + resetTestingQueues(); + } + + public void resetTestingQueues() { + messageHistory = new ArrayDeque<>(); + inputQueue = new ArrayDeque<>(); + } + + public String getLastMessage() { + return messageHistory.peekLast(); + } + + public String[] getMessageHistory() { + return (String[]) messageHistory.toArray(); + } + + public void pushToInputQueue(String input) { + inputQueue.push(input); + } + + @Override + public void offer(String message) { + super.offer(message); + + messageHistory.push(message); + } + + @Override + public String take() { + return inputQueue.pop(); + } +} From 2a9aa90d04dfcf4be3bd6e0c05efb642f81bb2fa Mon Sep 17 00:00:00 2001 From: ronan Date: Tue, 17 Dec 2019 19:53:22 +0000 Subject: [PATCH 2/4] Replaced old QueueProvider method usages with new ones --- .../com/jadventure/game/CharacterChange.java | 9 +- src/main/java/com/jadventure/game/Game.java | 17 +-- .../java/com/jadventure/game/JAdventure.java | 6 +- .../com/jadventure/game/QueueProvider.java | 111 ------------------ .../java/com/jadventure/game/Trading.java | 34 +++--- .../conversation/ConversationManager.java | 8 +- .../jadventure/game/conversation/Line.java | 1 - .../com/jadventure/game/entities/Entity.java | 14 +-- .../com/jadventure/game/entities/NPC.java | 8 -- .../com/jadventure/game/entities/Player.java | 52 ++++---- .../java/com/jadventure/game/items/Item.java | 7 +- .../com/jadventure/game/items/Storage.java | 12 +- .../com/jadventure/game/menus/BattleMenu.java | 47 ++++---- .../game/menus/ChooseClassMenu.java | 4 +- .../com/jadventure/game/menus/MainMenu.java | 38 +++--- .../java/com/jadventure/game/menus/Menus.java | 10 +- .../jadventure/game/navigation/Location.java | 20 ++-- .../game/prompts/BackpackDebugPrompt.java | 12 +- .../game/prompts/CommandCollection.java | 41 ++++--- .../game/prompts/CommandParser.java | 10 +- .../game/queueprovider/QueueProvider.java | 2 +- .../queueprovider/ServerQueueProvider.java | 2 +- .../game/repository/LocationRepository.java | 9 +- 23 files changed, 173 insertions(+), 301 deletions(-) delete mode 100644 src/main/java/com/jadventure/game/QueueProvider.java diff --git a/src/main/java/com/jadventure/game/CharacterChange.java b/src/main/java/com/jadventure/game/CharacterChange.java index 23afa700..03123ca0 100644 --- a/src/main/java/com/jadventure/game/CharacterChange.java +++ b/src/main/java/com/jadventure/game/CharacterChange.java @@ -11,6 +11,7 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.jadventure.game.entities.Player; +import com.jadventure.game.queueprovider.QueueProvider; public class CharacterChange { public void trigger(Player player, String triggerType, String keyword) { @@ -34,13 +35,13 @@ public void trigger(Player player, String triggerType, String keyword) { characterEffects = events.get(keyword).getAsJsonObject(); goAhead = true; } else { - //QueueProvider.offer("Warning: The effects for the '" + triggerType + "' event and the '" + currentCharacter + "' character was not found"); + //QueueProvider.getInstance().offer("Warning: The effects for the '" + triggerType + "' event and the '" + currentCharacter + "' character was not found"); } } else { - //QueueProvider.offer("Warning: The event '" + triggerType + "' for the '" + currentCharacter + "' character was not found"); + //QueueProvider.getInstance().offer("Warning: The event '" + triggerType + "' for the '" + currentCharacter + "' character was not found"); } } else { - //QueueProvider.offer("Warning: The character '" + currentCharacter + "' was not found"); + //QueueProvider.getInstance().offer("Warning: The character '" + currentCharacter + "' was not found"); } if (goAhead == true) { @@ -75,7 +76,7 @@ public void checkForCharacterChange(Player player) { } if (!highestCharacter.equals(currentCharacter)) { player.setCurrentCharacterType(highestCharacter); - QueueProvider.offer("You're character type is now changed! You are now a " + highestCharacter + "!"); + QueueProvider.getInstance().offer("You're character type is now changed! You are now a " + highestCharacter + "!"); } it = characterLevels.entrySet().iterator(); while (it.hasNext()) { diff --git a/src/main/java/com/jadventure/game/Game.java b/src/main/java/com/jadventure/game/Game.java index 27e91685..28f0243b 100644 --- a/src/main/java/com/jadventure/game/Game.java +++ b/src/main/java/com/jadventure/game/Game.java @@ -5,6 +5,7 @@ import com.jadventure.game.monsters.MonsterFactory; import com.jadventure.game.repository.LocationRepository; import com.jadventure.game.prompts.CommandParser; +import com.jadventure.game.queueprovider.QueueProvider; import java.util.ArrayList; @@ -27,13 +28,13 @@ public Game(Player player, String playerType) throws DeathException { newGameStart(player); break; case "old": - QueueProvider.offer("Welcome back, " + player.getName() + "!"); - QueueProvider.offer(""); + QueueProvider.getInstance().offer("Welcome back, " + player.getName() + "!"); + QueueProvider.getInstance().offer(""); player.getLocation().print(); gamePrompt(player); break; default: - QueueProvider.offer("Invalid player type"); + QueueProvider.getInstance().offer("Invalid player type"); break; } } @@ -44,13 +45,13 @@ public Game(Player player, String playerType) throws DeathException { * character and welcomes him / her. After that, it goes to the normal game prompt. */ public void newGameStart(Player player) throws DeathException { - QueueProvider.offer(player.getIntro()); - String userInput = QueueProvider.take(); + QueueProvider.getInstance().offer(player.getIntro()); + String userInput = QueueProvider.getInstance().take(); player.setName(userInput); LocationRepository locationRepo = GameBeans.getLocationRepository(player.getName()); this.player.setLocation(locationRepo.getInitialLocation()); player.save(); - QueueProvider.offer("Welcome to Silliya, " + player.getName() + "."); + QueueProvider.getInstance().offer("Welcome to Silliya, " + player.getName() + "."); player.getLocation().print(); gamePrompt(player); } @@ -65,8 +66,8 @@ public void gamePrompt(Player player) throws DeathException { boolean continuePrompt = true; try { while (continuePrompt) { - QueueProvider.offer("\nPrompt:"); - String command = QueueProvider.take().toLowerCase(); + QueueProvider.getInstance().offer("\nPrompt:"); + String command = QueueProvider.getInstance().take().toLowerCase(); continuePrompt = parser.parse(player, command); } } catch (DeathException e) { diff --git a/src/main/java/com/jadventure/game/JAdventure.java b/src/main/java/com/jadventure/game/JAdventure.java index 4fc384d5..c792c6aa 100644 --- a/src/main/java/com/jadventure/game/JAdventure.java +++ b/src/main/java/com/jadventure/game/JAdventure.java @@ -1,14 +1,12 @@ package com.jadventure.game; import com.jadventure.game.menus.MainMenu; -import com.jadventure.game.QueueProvider; -import com.jadventure.game.Client; import java.net.ServerSocket; import java.net.Socket; import java.io.IOException; -import java.net.SocketException; +import com.jadventure.game.queueprovider.QueueProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,7 +54,7 @@ public static void main(String[] args) { } } } else { - QueueProvider.startMessenger(GameModeType.STAND_ALONE); + QueueProvider.startStandaloneMessenger(); new MainMenu(); } } diff --git a/src/main/java/com/jadventure/game/QueueProvider.java b/src/main/java/com/jadventure/game/QueueProvider.java deleted file mode 100644 index 9768ce8d..00000000 --- a/src/main/java/com/jadventure/game/QueueProvider.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.jadventure.game; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.net.Socket; -import java.net.SocketException; -import java.util.NoSuchElementException; -import java.util.Scanner; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class QueueProvider { - private static Logger logger = LoggerFactory.getLogger(QueueProvider.class); - public static BlockingQueue queue = new LinkedBlockingQueue<>(); - public static BlockingQueue inputQueue = new LinkedBlockingQueue<>(); - public static DataOutputStream out; - public static DataInputStream in; - public static GameModeType mode; - public static Socket server; - - public static void startMessenger(GameModeType modeInc, Socket sockerInc) { - logger.debug("startMessenger( " + modeInc + " , " + sockerInc + " )"); - mode = modeInc; - server = sockerInc; - } - - public static void startMessenger(GameModeType modeInc) { - logger.debug("startMessenger( " + modeInc + " )"); - mode = modeInc; - } - - public static BlockingQueue getQueue() { - return queue; - } - - public static void offer(String message) { - logger.debug("offer( " + message + " )"); - - if (GameModeType.SERVER == mode) { - try { - out = new DataOutputStream(server.getOutputStream()); - in = new DataInputStream(server.getInputStream()); - } catch (IOException ioe) { - logger.debug("Inside offer( " + message + " )", ioe); - } - } - - if (GameModeType.SERVER == mode) { - sendToServer(message); - } else { - System.out.println(message); - } - } - - public static boolean sendToServer(String message) { - logger.debug("sendToServer( " + message + " )"); - try { - out.writeUTF(message + "END"); - } catch(SocketException se) { - logger.debug("Inside sendToServer( " + message + " )", se); - return false; - } catch(IOException ioe) { - logger.debug("Inside sendToServer( " + message + " )", ioe); - return false; - } - return true; - } - - public static String getInput(String message) { - logger.debug("getInput( " + message + " )"); - String input = ""; - try { - out.writeUTF(message + "END"); - input = in.readUTF(); - } catch(SocketException se) { - logger.debug("Inside getInput( " + message + " )", se); - input = "error"; - } catch(IOException ioe) { - logger.debug("Inside getInput( " + message + " )", ioe); - input = "error"; - } - return input; - } - - public static String take() { - String message = null; - if (GameModeType.SERVER == mode) { - message = getInput("QUERY"); - if (message.equals("error")) { - message = "exit"; - } - } else { - Scanner input = null; - try { - input = new Scanner(System.in); - message = input.nextLine(); - } - catch (NoSuchElementException nsee) { - nsee.printStackTrace(); - } - catch (IllegalStateException ise) { - ise.printStackTrace(); - } - } - return message; - } -} diff --git a/src/main/java/com/jadventure/game/Trading.java b/src/main/java/com/jadventure/game/Trading.java index d9a0a8f0..249340da 100644 --- a/src/main/java/com/jadventure/game/Trading.java +++ b/src/main/java/com/jadventure/game/Trading.java @@ -13,6 +13,8 @@ import com.jadventure.game.menus.Menus; import com.jadventure.game.repository.ItemRepository; +import com.jadventure.game.queueprovider.QueueProvider; + public class Trading { NPC npc; Player player; @@ -48,11 +50,11 @@ public void trade(boolean buy, boolean sell) { } public void playerBuy() { - QueueProvider.offer(npc.getName() + "'s items:\t" + npc.getName() + "'s gold:" + npc.getGold() + "\n"); - QueueProvider.offer(npc.getStorage().displayWithValue(0, 0)); + QueueProvider.getInstance().offer(npc.getName() + "'s items:\t" + npc.getName() + "'s gold:" + npc.getGold() + "\n"); + QueueProvider.getInstance().offer(npc.getStorage().displayWithValue(0, 0)); - QueueProvider.offer("You have " + player.getGold() + " gold coins.\nWhat do you want to buy?"); - String itemName = QueueProvider.take(); + QueueProvider.getInstance().offer("You have " + player.getGold() + " gold coins.\nWhat do you want to buy?"); + String itemName = QueueProvider.getInstance().take(); if ("exit".equals(itemName) || "back".equals(itemName)) { return; @@ -61,23 +63,23 @@ public void playerBuy() { Item item = tradeItem(npc, player, itemName); if (item != null) { if (item != itemRepo.getItem("empty")) { - QueueProvider.offer("You have bought a " + item.getName() + " for " + item.getProperties().get("value") + " gold coins."); - QueueProvider.offer("You now have " + player.getGold() + " gold coins remaining."); + QueueProvider.getInstance().offer("You have bought a " + item.getName() + " for " + item.getProperties().get("value") + " gold coins."); + QueueProvider.getInstance().offer("You now have " + player.getGold() + " gold coins remaining."); } else { - QueueProvider.offer("You do not have enough money!"); + QueueProvider.getInstance().offer("You do not have enough money!"); } } else { - QueueProvider.offer("Either this item doesn't exist or this character does not own that item"); + QueueProvider.getInstance().offer("Either this item doesn't exist or this character does not own that item"); } } public void playerSell() { - QueueProvider.offer(player.getName() + "'s items:\t" + npc.getName() + "'s gold:" + npc.getGold() + "\n"); - QueueProvider.offer(player.getStorage().displayWithValue(player.getLuck(), player.getIntelligence())); + QueueProvider.getInstance().offer(player.getName() + "'s items:\t" + npc.getName() + "'s gold:" + npc.getGold() + "\n"); + QueueProvider.getInstance().offer(player.getStorage().displayWithValue(player.getLuck(), player.getIntelligence())); - QueueProvider.offer("You have " + player.getGold() + " gold coins.\nWhat do you want to sell?"); - String itemName = QueueProvider.take(); + QueueProvider.getInstance().offer("You have " + player.getGold() + " gold coins.\nWhat do you want to sell?"); + String itemName = QueueProvider.getInstance().take(); if ("exit".equals(itemName) || "back".equals(itemName)) { return; @@ -86,14 +88,14 @@ public void playerSell() { Item item = tradeItem(player, npc, itemName); if (item != null) { if (item != itemRepo.getItem("empty")) { - QueueProvider.offer("You have sold a " + item.getName() + " for " + (player.getGold() - goldBefore) + " gold coins."); - QueueProvider.offer("You now have " + player.getGold() + " gold coins remaining."); + QueueProvider.getInstance().offer("You have sold a " + item.getName() + " for " + (player.getGold() - goldBefore) + " gold coins."); + QueueProvider.getInstance().offer("You now have " + player.getGold() + " gold coins remaining."); } else { - QueueProvider.offer(npc.getName() + " does not have enough money!"); + QueueProvider.getInstance().offer(npc.getName() + " does not have enough money!"); } } else { - QueueProvider.offer("Either this item doesn't exist or this character does not own that item"); + QueueProvider.getInstance().offer("Either this item doesn't exist or this character does not own that item"); } } diff --git a/src/main/java/com/jadventure/game/conversation/ConversationManager.java b/src/main/java/com/jadventure/game/conversation/ConversationManager.java index c1bb57f0..62f1249e 100644 --- a/src/main/java/com/jadventure/game/conversation/ConversationManager.java +++ b/src/main/java/com/jadventure/game/conversation/ConversationManager.java @@ -6,9 +6,9 @@ import com.jadventure.game.items.Item; import com.jadventure.game.repository.EncounteredNpcRepository; import com.jadventure.game.repository.ItemRepository; -import com.jadventure.game.QueueProvider; import com.jadventure.game.DeathException; import com.jadventure.game.Trading; +import com.jadventure.game.queueprovider.QueueProvider; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -132,11 +132,11 @@ public void startConversation(NPC npc, Player player) throws DeathException { } } if (start != null) { - QueueProvider.offer(start.getText()); + QueueProvider.getInstance().offer(start.getText()); Line response = start.display(npc, player, conversation); triggerAction(start, npc, player); while (response != null) { - QueueProvider.offer(response.getText()); + QueueProvider.getInstance().offer(response.getText()); triggerAction(response, npc, player); Line temp_response = response.display(npc, player, conversation); response = temp_response; @@ -148,7 +148,7 @@ public void startConversation(NPC npc, Player player) throws DeathException { private void triggerAction(Line line, NPC npc, Player player) throws DeathException { switch (line.getAction()) { case ATTACK: - QueueProvider.offer("\n" + npc.getName() + " is now attacking you!\n"); + QueueProvider.getInstance().offer("\n" + npc.getName() + " is now attacking you!\n"); player.attack(npc.getName()); break; case TRADE: diff --git a/src/main/java/com/jadventure/game/conversation/Line.java b/src/main/java/com/jadventure/game/conversation/Line.java index 4acd82f5..8d68a1a9 100644 --- a/src/main/java/com/jadventure/game/conversation/Line.java +++ b/src/main/java/com/jadventure/game/conversation/Line.java @@ -1,6 +1,5 @@ package com.jadventure.game.conversation; -import com.jadventure.game.QueueProvider; import com.jadventure.game.entities.NPC; import com.jadventure.game.entities.Player; import com.jadventure.game.menus.Menus; diff --git a/src/main/java/com/jadventure/game/entities/Entity.java b/src/main/java/com/jadventure/game/entities/Entity.java index f51358ee..a6e63619 100644 --- a/src/main/java/com/jadventure/game/entities/Entity.java +++ b/src/main/java/com/jadventure/game/entities/Entity.java @@ -5,11 +5,11 @@ import java.util.Map; import com.jadventure.game.GameBeans; -import com.jadventure.game.QueueProvider; import com.jadventure.game.items.Item; import com.jadventure.game.items.ItemStack; import com.jadventure.game.items.Storage; import com.jadventure.game.repository.ItemRepository; +import com.jadventure.game.queueprovider.QueueProvider; /** * superclass for all entities (includes player, monsters...) @@ -295,10 +295,10 @@ public Map unequipItem(Item item) { } public void printEquipment() { - QueueProvider.offer("\n------------------------------------------------------------"); - QueueProvider.offer("Equipped Items:"); + QueueProvider.getInstance().offer("\n------------------------------------------------------------"); + QueueProvider.getInstance().offer("Equipped Items:"); if (equipment.keySet().size() == 0) { - QueueProvider.offer("--Empty--"); + QueueProvider.getInstance().offer("--Empty--"); } else { int i = 0; Item hands = itemRepo.getItem("hands"); @@ -315,16 +315,16 @@ public void printEquipment() { locations.put(EquipmentLocation.FEET, "Feet"); for (Map.Entry item : equipment.entrySet()) { if (item.getKey() != null && !hands.equals(item.getValue()) && item.getValue() != null) { - QueueProvider.offer(locations.get(item.getKey()) + " - " + item.getValue().getName()); + QueueProvider.getInstance().offer(locations.get(item.getKey()) + " - " + item.getValue().getName()); } else { i++; } } if (i == equipment.keySet().size()) { - QueueProvider.offer("--Empty--"); + QueueProvider.getInstance().offer("--Empty--"); } } - QueueProvider.offer("------------------------------------------------------------"); + QueueProvider.getInstance().offer("------------------------------------------------------------"); } public Storage getStorage() { diff --git a/src/main/java/com/jadventure/game/entities/NPC.java b/src/main/java/com/jadventure/game/entities/NPC.java index 25997ef1..4c75241d 100644 --- a/src/main/java/com/jadventure/game/entities/NPC.java +++ b/src/main/java/com/jadventure/game/entities/NPC.java @@ -1,20 +1,12 @@ package com.jadventure.game.entities; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.Reader; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.Random; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -import com.jadventure.game.QueueProvider; -import com.jadventure.game.items.Storage; /** * This class deals with Non Player Character (NPC) and all of their properties. diff --git a/src/main/java/com/jadventure/game/entities/Player.java b/src/main/java/com/jadventure/game/entities/Player.java index 73c4650b..57c5622d 100644 --- a/src/main/java/com/jadventure/game/entities/Player.java +++ b/src/main/java/com/jadventure/game/entities/Player.java @@ -7,10 +7,6 @@ import java.io.IOException; import java.io.Reader; import java.io.Writer; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -25,12 +21,9 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import com.google.gson.JsonArray; -import com.google.gson.JsonPrimitive; import com.google.gson.reflect.TypeToken; import com.jadventure.game.DeathException; import com.jadventure.game.GameBeans; -import com.jadventure.game.QueueProvider; import com.jadventure.game.items.Item; import com.jadventure.game.items.ItemStack; import com.jadventure.game.items.Storage; @@ -41,6 +34,7 @@ import com.jadventure.game.navigation.LocationType; import com.jadventure.game.repository.ItemRepository; import com.jadventure.game.repository.LocationRepository; +import com.jadventure.game.queueprovider.QueueProvider; /** * This class deals with the player and all of its properties. @@ -164,7 +158,7 @@ public static Player load(String name) { reader.close(); setUpCharacterLevels(); } catch (FileNotFoundException ex) { - QueueProvider.offer( "Unable to open file '" + fileName + "'."); + QueueProvider.getInstance().offer( "Unable to open file '" + fileName + "'."); } catch (IOException ex) { ex.printStackTrace(); } @@ -214,12 +208,12 @@ public static Player getInstance(String playerClass){ } else if (player.getName().equals("Sewer Rat")) { player.type = "Sewer Rat"; } else { - QueueProvider.offer("Not a valid class"); + QueueProvider.getInstance().offer("Not a valid class"); } reader.close(); setUpCharacterLevels(); } catch (FileNotFoundException ex) { - QueueProvider.offer( "Unable to open file '" + fileName + "'."); + QueueProvider.getInstance().offer( "Unable to open file '" + fileName + "'."); } catch (IOException ex) { ex.printStackTrace(); } @@ -259,7 +253,7 @@ public void getStats(){ message += "\nStealth: " + getStealth(); message += "\nXP: " + getXP(); message += "\n" + getName() + "'s level: " + getLevel(); - QueueProvider.offer(message); + QueueProvider.getInstance().offer(message); } public void printBackPack() { @@ -323,9 +317,9 @@ public void save() { writer.close(); locationRepo = GameBeans.getLocationRepository(getName()); locationRepo.writeLocations(); - QueueProvider.offer("\nYour game data was saved."); + QueueProvider.getInstance().offer("\nYour game data was saved."); } catch (IOException ex) { - QueueProvider.offer("\nUnable to save to file '" + fileName + "'."); + QueueProvider.getInstance().offer("\nUnable to save to file '" + fileName + "'."); } } @@ -360,7 +354,7 @@ public void pickUpItem(String itemName) { Item item = items.get(0); addItemToStorage(item); location.removeItem(item); - QueueProvider.offer(item.getName()+ " picked up"); + QueueProvider.getInstance().offer(item.getName()+ " picked up"); } } @@ -380,7 +374,7 @@ public void dropItem(String itemName) { } removeItemFromStorage(itemToDrop); location.addItem(itemToDrop); - QueueProvider.offer(item.getName() + " dropped"); + QueueProvider.getInstance().offer(item.getName() + " dropped"); } } @@ -390,13 +384,13 @@ public void equipItem(String itemName) { Item item = items.get(0); if (getLevel() >= item.getLevel()) { Map change = equipItem(item.getPosition(), item); - QueueProvider.offer(item.getName()+ " equipped"); + QueueProvider.getInstance().offer(item.getName()+ " equipped"); printStatChange(change); } else { - QueueProvider.offer("You do not have the required level to use this item"); + QueueProvider.getInstance().offer("You do not have the required level to use this item"); } } else { - QueueProvider.offer("You do not have that item"); + QueueProvider.getInstance().offer("You do not have that item"); } } @@ -405,7 +399,7 @@ public void dequipItem(String itemName) { if (!items.isEmpty()) { Item item = items.get(0); Map change = unequipItem(item); - QueueProvider.offer(item.getName()+" unequipped"); + QueueProvider.getInstance().offer(item.getName()+" unequipped"); printStatChange(change); } } @@ -419,33 +413,33 @@ private void printStatChange(Map stats) { switch ((String) me.getKey()) { case "damage": { if (value >= 0.0) { - QueueProvider.offer(me.getKey() + ": " + this.getDamage() + " (+" + me.getValue() + ")"); + QueueProvider.getInstance().offer(me.getKey() + ": " + this.getDamage() + " (+" + me.getValue() + ")"); } else { - QueueProvider.offer(me.getKey() + ": " + this.getDamage() + " (" + me.getValue() + ")"); + QueueProvider.getInstance().offer(me.getKey() + ": " + this.getDamage() + " (" + me.getValue() + ")"); } break; } case "health": { if (value >= 0) { - QueueProvider.offer(me.getKey() + ": " + this.getHealth() + " (+" + me.getValue() + ")"); + QueueProvider.getInstance().offer(me.getKey() + ": " + this.getHealth() + " (+" + me.getValue() + ")"); } else { - QueueProvider.offer(me.getKey() + ": " + this.getHealth() + " (" + me.getValue() + ")"); + QueueProvider.getInstance().offer(me.getKey() + ": " + this.getHealth() + " (" + me.getValue() + ")"); } break; } case "armour": { if (value >= 0) { - QueueProvider.offer(me.getKey() + ": " + this.getArmour() + " (+" + me.getValue() + ")"); + QueueProvider.getInstance().offer(me.getKey() + ": " + this.getArmour() + " (+" + me.getValue() + ")"); } else { - QueueProvider.offer(me.getKey() + ": " + this.getArmour() + " (" + me.getValue() + ")"); + QueueProvider.getInstance().offer(me.getKey() + ": " + this.getArmour() + " (" + me.getValue() + ")"); } break; } case "maxHealth": { if (value >= 0) { - QueueProvider.offer(me.getKey() + ": " + this.getHealthMax() + " (+" + me.getValue() + ")"); + QueueProvider.getInstance().offer(me.getKey() + ": " + this.getHealthMax() + " (+" + me.getValue() + ")"); } else { - QueueProvider.offer(me.getKey() + ": " + this.getHealthMax() + " (" + me.getValue() + ")"); + QueueProvider.getInstance().offer(me.getKey() + ": " + this.getHealthMax() + " (" + me.getValue() + ")"); } break; } @@ -462,7 +456,7 @@ public void inspectItem(String itemName) { Item item = itemMap.get(0); item.display(); } else { - QueueProvider.offer("Item doesn't exist within your view."); + QueueProvider.getInstance().offer("Item doesn't exist within your view."); } } @@ -499,7 +493,7 @@ public void attack(String opponentName) throws DeathException { } else if (npcOpponent != null) { new BattleMenu(npcOpponent, this); } else { - QueueProvider.offer("Opponent not found"); + QueueProvider.getInstance().offer("Opponent not found"); } } diff --git a/src/main/java/com/jadventure/game/items/Item.java b/src/main/java/com/jadventure/game/items/Item.java index d53330fa..22601067 100644 --- a/src/main/java/com/jadventure/game/items/Item.java +++ b/src/main/java/com/jadventure/game/items/Item.java @@ -1,10 +1,11 @@ package com.jadventure.game.items; +import com.jadventure.game.queueprovider.QueueProvider; + import java.util.Collections; import java.util.Map; import java.util.TreeMap; -import com.jadventure.game.QueueProvider; import com.jadventure.game.entities.EquipmentLocation; /** @@ -96,10 +97,10 @@ public boolean equals(Object obj) { } public void display() { - QueueProvider.offer("Name: " + name + + QueueProvider.getInstance().offer("Name: " + name + "\nDescription: " + description + "\nLevel: " + level); for (Map.Entry entry : properties.entrySet()) { - QueueProvider.offer(entry.getKey() + ": " + entry.getValue()); + QueueProvider.getInstance().offer(entry.getKey() + ": " + entry.getValue()); } } diff --git a/src/main/java/com/jadventure/game/items/Storage.java b/src/main/java/com/jadventure/game/items/Storage.java index ae6d2163..e60c3f87 100644 --- a/src/main/java/com/jadventure/game/items/Storage.java +++ b/src/main/java/com/jadventure/game/items/Storage.java @@ -1,10 +1,10 @@ package com.jadventure.game.items; +import com.jadventure.game.queueprovider.QueueProvider; + import java.util.ArrayList; import java.util.List; -import com.jadventure.game.QueueProvider; - /** * Defines an interface for any type of storage in this game. */ @@ -118,10 +118,10 @@ public Item removeItem(ItemStack itemStack, int amount) { * Prints out the content of the backpack to the console. */ public void display() { - QueueProvider.offer("\n--------------------------------------------------------------------"); - QueueProvider.offer("Backpack: "); - QueueProvider.offer(this.toString()); - QueueProvider.offer("--------------------------------------------------------------------"); + QueueProvider.getInstance().offer("\n--------------------------------------------------------------------"); + QueueProvider.getInstance().offer("Backpack: "); + QueueProvider.getInstance().offer(this.toString()); + QueueProvider.getInstance().offer("--------------------------------------------------------------------"); } public boolean isEmpty() { diff --git a/src/main/java/com/jadventure/game/menus/BattleMenu.java b/src/main/java/com/jadventure/game/menus/BattleMenu.java index b4169101..504ae357 100644 --- a/src/main/java/com/jadventure/game/menus/BattleMenu.java +++ b/src/main/java/com/jadventure/game/menus/BattleMenu.java @@ -4,12 +4,11 @@ import com.jadventure.game.entities.Entity; import com.jadventure.game.entities.Player; import com.jadventure.game.entities.NPC; -import com.jadventure.game.monsters.Monster; -import com.jadventure.game.QueueProvider; import com.jadventure.game.CharacterChange; import com.jadventure.game.items.ItemStack; import com.jadventure.game.items.Item; import com.jadventure.game.GameBeans; +import com.jadventure.game.queueprovider.QueueProvider; import java.util.Random; import java.util.List; @@ -34,16 +33,16 @@ public BattleMenu(NPC opponent, Player player) throws DeathException { while (opponent.getHealth() > 0 && player.getHealth() > 0 && (escapeSuccessfulAttempts <= 0)) { - QueueProvider.offer("\nWhat is your choice?"); + QueueProvider.getInstance().offer("\nWhat is your choice?"); MenuItem selectedItem = displayMenu(this.menuItems); testSelected(selectedItem); } if (player.getHealth() == 0) { - QueueProvider.offer("You died... Start again? (y/n)"); - String reply = QueueProvider.take().toLowerCase(); + QueueProvider.getInstance().offer("You died... Start again? (y/n)"); + String reply = QueueProvider.getInstance().take().toLowerCase(); while (!reply.startsWith("y") && !reply.startsWith("n")) { - QueueProvider.offer("You died... Start again? (y/n)"); - reply = QueueProvider.take().toLowerCase(); + QueueProvider.getInstance().offer("You died... Start again? (y/n)"); + reply = QueueProvider.getInstance().take().toLowerCase(); } if (reply.startsWith("y")) { throw new DeathException("restart"); @@ -70,17 +69,17 @@ public BattleMenu(NPC opponent, Player player) throws DeathException { Item item = GameBeans.getItemRepository().getItem(itemId); opponent.removeItemFromStorage(item); this.player.getLocation().addItem(item); - QueueProvider.offer("Your opponent dropped a " + + QueueProvider.getInstance().offer("Your opponent dropped a " + item.getName()); } this.player.getLocation().remove(opponent); this.player.setGold(this.player.getGold() + opponent.getGold()); - QueueProvider.offer("You killed a " + opponent.getName() + + QueueProvider.getInstance().offer("You killed a " + opponent.getName() + "\nYou have gained " + xp + " XP and " + opponent.getGold() + " gold"); if (oldLevel < newLevel) { - QueueProvider.offer("You've are now level " + newLevel + "!"); + QueueProvider.getInstance().offer("You've are now level " + newLevel + "!"); } CharacterChange cc = new CharacterChange(); cc.trigger(this.player, "kill", opponent.getName()); @@ -111,7 +110,7 @@ private void testSelected(MenuItem m) { } case "defend": { mutateStats(0.5, 1); - QueueProvider.offer("\nYou get ready to defend against " + + QueueProvider.getInstance().offer("\nYou get ready to defend against " + "the " + opponent.getName() + "."); attack(player, opponent); attack(opponent, player); @@ -160,14 +159,14 @@ private int escapeAttempt(Player player, NPC attacker, double minEscapeLevel = (rand.nextInt((upperBound - lowerBound) + 1) + lowerBound) / 100.0; if (escapeLevel > minEscapeLevel && (escapeAttempts == 0)) { - QueueProvider.offer("You have managed to escape the: " + + QueueProvider.getInstance().offer("You have managed to escape the: " + attacker.getName()); return 1; } else if (escapeAttempts < 0) { - QueueProvider.offer("You have tried to escape too many times!"); + QueueProvider.getInstance().offer("You have tried to escape too many times!"); return escapeAttempts - 1; } else { - QueueProvider.offer("You failed to escape the: " + + QueueProvider.getInstance().offer("You failed to escape the: " + attacker.getName()); return escapeAttempts-1; } @@ -181,7 +180,7 @@ private void attack(Entity attacker, Entity defender) { double critCalc = random.nextDouble(); if (critCalc < attacker.getCritChance()) { damage += damage; - QueueProvider.offer("Crit hit! Damage has been doubled!"); + QueueProvider.getInstance().offer("Crit hit! Damage has been doubled!"); } int healthReduction = (int) ((((3 * attacker.getLevel() / 50 + 2) * damage * damage / (defender.getArmour() + 1)/ 100) + 2) * @@ -190,12 +189,12 @@ private void attack(Entity attacker, Entity defender) { if (defender.getHealth() < 0) { defender.setHealth(0); } - QueueProvider.offer(healthReduction + " damage dealt!"); + QueueProvider.getInstance().offer(healthReduction + " damage dealt!"); if (attacker instanceof Player) { - QueueProvider.offer("The " + defender.getName() + "'s health is " + + QueueProvider.getInstance().offer("The " + defender.getName() + "'s health is " + defender.getHealth()); } else { - QueueProvider.offer("Your health is " + defender.getHealth()); + QueueProvider.getInstance().offer("Your health is " + defender.getHealth()); } } @@ -213,8 +212,8 @@ private void resetStats() { private void equip() { player.printStorage(); - QueueProvider.offer("What item do you want to use?"); - String itemName = QueueProvider.take(); + QueueProvider.getInstance().offer("What item do you want to use?"); + String itemName = QueueProvider.getInstance().take(); if (!itemName.equalsIgnoreCase("back")) { player.equipItem(itemName); } @@ -222,17 +221,17 @@ private void equip() { private void unequip() { player.printEquipment(); - QueueProvider.offer("What item do you want to unequip?"); - String itemName = QueueProvider.take(); + QueueProvider.getInstance().offer("What item do you want to unequip?"); + String itemName = QueueProvider.getInstance().take(); if (!itemName.equalsIgnoreCase("back")) { player.dequipItem(itemName); } } private void viewStats() { - QueueProvider.offer("\nWhat is your command? ex. View stats(vs), " + + QueueProvider.getInstance().offer("\nWhat is your command? ex. View stats(vs), " + "View Backpack(vb), View Equipment(ve) "); - String input = QueueProvider.take(); + String input = QueueProvider.getInstance().take(); switch (input) { case "vs": case "viewstats": diff --git a/src/main/java/com/jadventure/game/menus/ChooseClassMenu.java b/src/main/java/com/jadventure/game/menus/ChooseClassMenu.java index 20825b8c..50dca001 100644 --- a/src/main/java/com/jadventure/game/menus/ChooseClassMenu.java +++ b/src/main/java/com/jadventure/game/menus/ChooseClassMenu.java @@ -3,7 +3,7 @@ import com.jadventure.game.entities.Player; import com.jadventure.game.DeathException; import com.jadventure.game.Game; -import com.jadventure.game.QueueProvider; +import com.jadventure.game.queueprovider.QueueProvider; /** * Called when creating a new Player @@ -15,7 +15,7 @@ public ChooseClassMenu() throws DeathException { this.menuItems.add(new MenuItem("SewerRat", "A member of the underground of Silliya")); while(true) { - QueueProvider.offer("Choose a class to get started with:"); + QueueProvider.getInstance().offer("Choose a class to get started with:"); MenuItem selectedItem = displayMenu(this.menuItems); if(testOption(selectedItem)) { break; diff --git a/src/main/java/com/jadventure/game/menus/MainMenu.java b/src/main/java/com/jadventure/game/menus/MainMenu.java index 53776f25..1e850bad 100644 --- a/src/main/java/com/jadventure/game/menus/MainMenu.java +++ b/src/main/java/com/jadventure/game/menus/MainMenu.java @@ -7,8 +7,8 @@ import com.jadventure.game.Game; import com.jadventure.game.GameModeType; import com.jadventure.game.JAdventure; -import com.jadventure.game.QueueProvider; import com.jadventure.game.entities.Player; +import com.jadventure.game.queueprovider.QueueProvider; /** * The first menu displayed on user screen @@ -19,7 +19,7 @@ public class MainMenu extends Menus implements Runnable { public MainMenu(Socket server, GameModeType mode){ - QueueProvider.startMessenger(mode, server); + QueueProvider.startServerMessenger(server); } public MainMenu() { @@ -47,7 +47,7 @@ public void start() { } } } while(continuing); - QueueProvider.offer("EXIT"); + QueueProvider.getInstance().offer("EXIT"); } private static boolean testOption(MenuItem m) throws DeathException { @@ -63,7 +63,7 @@ private static boolean testOption(MenuItem m) throws DeathException { deleteProfileFromMenu(); break; case "exit": - QueueProvider.offer("Goodbye!"); + QueueProvider.getInstance().offer("Goodbye!"); return false; } return true; @@ -72,20 +72,20 @@ private static boolean testOption(MenuItem m) throws DeathException { private static void loadProfileFromMenu() throws DeathException { String key; if (isProfileDirEmpty()) { - QueueProvider.offer("\nThere are no profiles to load. Please start a new game instead."); + QueueProvider.getInstance().offer("\nThere are no profiles to load. Please start a new game instead."); return; } Player player = null; do { listProfiles(); - QueueProvider.offer("\nSelect a profile to load. Type 'back' to go back."); - key = QueueProvider.take(); + QueueProvider.getInstance().offer("\nSelect a profile to load. Type 'back' to go back."); + key = QueueProvider.getInstance().take(); if (key.equals("exit") || key.equals("back")) { return; } else if (Player.profileExists(key)) { player = Player.load(key); } else { - QueueProvider.offer("That user doesn't exist. Try again."); + QueueProvider.getInstance().offer("That user doesn't exist. Try again."); } } while (player == null); new Game(player, "old"); @@ -95,31 +95,31 @@ private static void deleteProfileFromMenu() { String key; while (true) { if (isProfileDirEmpty()) { - QueueProvider.offer("\nThere are no profiles to delete."); + QueueProvider.getInstance().offer("\nThere are no profiles to delete."); return; } listProfiles(); - QueueProvider.offer("\nWhich profile do you want to delete? Type 'back' to go back."); - key = QueueProvider.take(); + QueueProvider.getInstance().offer("\nWhich profile do you want to delete? Type 'back' to go back."); + key = QueueProvider.getInstance().take(); if ((key.equals("exit") || key.equals("back"))) { return; } if (Player.profileExists(key)) { String profileName = key; - QueueProvider.offer("Are you sure you want to delete " + profileName + "? y/n"); - key = QueueProvider.take(); + QueueProvider.getInstance().offer("Are you sure you want to delete " + profileName + "? y/n"); + key = QueueProvider.getInstance().take(); if ((key.equals("exit") || key.equals("back"))) { return; } else if (key.equals("y")) { File profile = new File("json/profiles/" + profileName); deleteDirectory(profile); - QueueProvider.offer(profileName + " has been deleted."); + QueueProvider.getInstance().offer(profileName + " has been deleted."); return; } else { - QueueProvider.offer(profileName + " will NOT be deleted."); + QueueProvider.getInstance().offer(profileName + " will NOT be deleted."); } } else { - QueueProvider.offer("That user doesn't exist. Try again."); + QueueProvider.getInstance().offer("That user doesn't exist. Try again."); } } } @@ -145,15 +145,15 @@ private static boolean isProfileDirEmpty() { private static void listProfiles() { if (isProfileDirEmpty()) { - QueueProvider.offer("No profiles found."); + QueueProvider.getInstance().offer("No profiles found."); return; } File file = new File("json/profiles"); String[] profiles = file.list(); - QueueProvider.offer("Profiles:"); + QueueProvider.getInstance().offer("Profiles:"); for (String name : profiles) { if (new File("json/profiles/" + name).isDirectory()) { - QueueProvider.offer(" " + name); + QueueProvider.getInstance().offer(" " + name); } } } diff --git a/src/main/java/com/jadventure/game/menus/Menus.java b/src/main/java/com/jadventure/game/menus/Menus.java index 83a924d9..faed7d55 100644 --- a/src/main/java/com/jadventure/game/menus/Menus.java +++ b/src/main/java/com/jadventure/game/menus/Menus.java @@ -1,6 +1,6 @@ package com.jadventure.game.menus; -import com.jadventure.game.QueueProvider; +import com.jadventure.game.queueprovider.QueueProvider; import java.util.ArrayList; import java.util.HashMap; @@ -32,11 +32,11 @@ public MenuItem displayMenu(List m) { // calls for user input from command line protected MenuItem selectMenu(List m) { this.printMenuItems(m); - String command = QueueProvider.take(); + String command = QueueProvider.getInstance().take(); if (commandMap.containsKey(command.toLowerCase())) { return commandMap.get(command.toLowerCase()); } else { - QueueProvider.offer("I don't know what '" + command + "' means."); + QueueProvider.getInstance().offer("I don't know what '" + command + "' means."); return this.displayMenu(m); } } @@ -45,9 +45,9 @@ private void printMenuItems(List m) { int i = 1; for (MenuItem menuItem: m) { if (menuItem.getDescription() != null) { - QueueProvider.offer("[" + i + "] " + menuItem.getCommand() + " - " + menuItem.getDescription()); + QueueProvider.getInstance().offer("[" + i + "] " + menuItem.getCommand() + " - " + menuItem.getDescription()); } else { - QueueProvider.offer("[" + i + "] " + menuItem.getCommand()); + QueueProvider.getInstance().offer("[" + i + "] " + menuItem.getCommand()); } i++; } diff --git a/src/main/java/com/jadventure/game/navigation/Location.java b/src/main/java/com/jadventure/game/navigation/Location.java index 53443724..1cf76464 100644 --- a/src/main/java/com/jadventure/game/navigation/Location.java +++ b/src/main/java/com/jadventure/game/navigation/Location.java @@ -7,7 +7,6 @@ import java.util.Map; import com.jadventure.game.GameBeans; -import com.jadventure.game.QueueProvider; import com.jadventure.game.entities.NPC; import com.jadventure.game.items.Item; import com.jadventure.game.items.Storage; @@ -16,6 +15,7 @@ import com.jadventure.game.repository.LocationRepository; import com.jadventure.game.repository.NpcRepository; import com.jadventure.game.repository.RepositoryException; +import com.jadventure.game.queueprovider.QueueProvider; /** * The location class mostly deals with getting and setting variables. @@ -170,26 +170,26 @@ public void addItem(Item item) { } public void print() { - QueueProvider.offer("\n" + getTitle() + ":"); - QueueProvider.offer(" " + getDescription()); + QueueProvider.getInstance().offer("\n" + getTitle() + ":"); + QueueProvider.getInstance().offer(" " + getDescription()); List items = getItems(); if (!items.isEmpty()) { - QueueProvider.offer("Items:"); + QueueProvider.getInstance().offer("Items:"); for (Item item : items) { - QueueProvider.offer(" " + item.getName()); + QueueProvider.getInstance().offer(" " + item.getName()); } } List npcs = getNpcs(); if (!npcs.isEmpty()) { - QueueProvider.offer("NPCs:"); + QueueProvider.getInstance().offer("NPCs:"); for (NPC npc : npcs) { - QueueProvider.offer(" " + npc.getName()); + QueueProvider.getInstance().offer(" " + npc.getName()); } } - QueueProvider.offer(""); + QueueProvider.getInstance().offer(""); for (Map.Entry direction : getExits().entrySet()) { - QueueProvider.offer(direction.getKey().getDescription() + ": "); - QueueProvider.offer(" " + direction.getValue().getDescription()); + QueueProvider.getInstance().offer(direction.getKey().getDescription() + ": "); + QueueProvider.getInstance().offer(" " + direction.getValue().getDescription()); } } } diff --git a/src/main/java/com/jadventure/game/prompts/BackpackDebugPrompt.java b/src/main/java/com/jadventure/game/prompts/BackpackDebugPrompt.java index ce330d1d..fabcaa43 100644 --- a/src/main/java/com/jadventure/game/prompts/BackpackDebugPrompt.java +++ b/src/main/java/com/jadventure/game/prompts/BackpackDebugPrompt.java @@ -5,7 +5,7 @@ import com.jadventure.game.repository.RepositoryException; import com.jadventure.game.repository.ItemRepository; import com.jadventure.game.GameBeans; -import com.jadventure.game.QueueProvider; +import com.jadventure.game.queueprovider.QueueProvider; /** @@ -27,8 +27,8 @@ public class BackpackDebugPrompt{ public BackpackDebugPrompt(Player player){ boolean continuePrompt = true; while(continuePrompt){ - QueueProvider.offer("Edit backpack:"); - String command = QueueProvider.take(); + QueueProvider.getInstance().offer("Edit backpack:"); + String command = QueueProvider.getInstance().take(); continuePrompt = parse(player, command.toLowerCase()); } } @@ -42,7 +42,7 @@ public static boolean parse(Player player, String command){ if (appendItem.getName() != null) player.addItemToStorage(appendItem); } catch (RepositoryException ex) { - QueueProvider.offer(ex.getMessage()); + QueueProvider.getInstance().offer(ex.getMessage()); } } else if (command.startsWith("remove")){ @@ -53,11 +53,11 @@ else if (command.equals("list")){ player.printBackPack(); } else if (command.equals("help")) - QueueProvider.offer(helpText); + QueueProvider.getInstance().offer(helpText); else if (command.equals("exit")) continuePrompt = false; } catch (NumberFormatException e){ - QueueProvider.offer("Invalid item name"); + QueueProvider.getInstance().offer("Invalid item name"); } return continuePrompt; diff --git a/src/main/java/com/jadventure/game/prompts/CommandCollection.java b/src/main/java/com/jadventure/game/prompts/CommandCollection.java index 3203cecb..b7891da2 100644 --- a/src/main/java/com/jadventure/game/prompts/CommandCollection.java +++ b/src/main/java/com/jadventure/game/prompts/CommandCollection.java @@ -10,7 +10,6 @@ import org.slf4j.LoggerFactory; import com.jadventure.game.DeathException; -import com.jadventure.game.QueueProvider; import com.jadventure.game.conversation.ConversationManager; import com.jadventure.game.entities.Player; import com.jadventure.game.entities.NPC; @@ -22,8 +21,8 @@ import com.jadventure.game.navigation.LocationType; import com.jadventure.game.repository.ItemRepository; import com.jadventure.game.repository.LocationRepository; -import com.jadventure.game.DeathException; import com.jadventure.game.GameBeans; +import com.jadventure.game.queueprovider.QueueProvider; /** * CommandCollection contains the declaration of the methods mapped to game commands @@ -64,7 +63,7 @@ public void command_help() { Method[] methods = CommandCollection.class.getMethods(); int commandWidth = 0; int descriptionWidth = 0; - QueueProvider.offer(""); + QueueProvider.getInstance().offer(""); for (Method method : methods) { if (!method.isAnnotationPresent(Command.class)) { continue; @@ -91,10 +90,10 @@ public void command_help() { annotation.description()); if (annotation.debug()) { if ("test".equals(player.getName())) { - QueueProvider.offer(message); + QueueProvider.getInstance().offer(message); } } else { - QueueProvider.offer(message); + QueueProvider.getInstance().offer(message); } } @@ -110,14 +109,14 @@ public void command_save() { public void command_m() { List monsterList = player.getLocation().getMonsters(); if (monsterList.size() > 0) { - QueueProvider.offer("Monsters around you:"); - QueueProvider.offer("----------------------------"); + QueueProvider.getInstance().offer("Monsters around you:"); + QueueProvider.getInstance().offer("----------------------------"); for (Monster monster : monsterList) { - QueueProvider.offer(monster.monsterType); + QueueProvider.getInstance().offer(monster.monsterType); } - QueueProvider.offer("----------------------------"); + QueueProvider.getInstance().offer("----------------------------"); } else { - QueueProvider.offer("There are no monsters around you'n"); + QueueProvider.getInstance().offer("There are no monsters around you'n"); } } @@ -134,7 +133,7 @@ public void command_g(String arg) throws DeathException { if (!newLocation.getLocationType().equals(LocationType.WALL)) { player.setLocation(newLocation); if ("test".equals(player.getName())) { - QueueProvider.offer(player.getLocation().getCoordinate().toString()); + QueueProvider.getInstance().offer(player.getLocation().getCoordinate().toString()); } player.getLocation().print(); Random random = new Random(); @@ -157,20 +156,20 @@ public void command_g(String arg) throws DeathException { if (monsters.size() > 0) { int posMonster = random.nextInt(monsters.size()); String monster = monsters.get(posMonster).monsterType; - QueueProvider.offer("A " + monster + " is attacking you!"); + QueueProvider.getInstance().offer("A " + monster + " is attacking you!"); player.attack(monster); } } } else { - QueueProvider.offer("You cannot walk through walls."); + QueueProvider.getInstance().offer("You cannot walk through walls."); } } else { - QueueProvider.offer("The is no exit that way."); + QueueProvider.getInstance().offer("The is no exit that way."); } } catch (IllegalArgumentException ex) { - QueueProvider.offer("That direction doesn't exist"); + QueueProvider.getInstance().offer("That direction doesn't exist"); } catch (NullPointerException ex) { - QueueProvider.offer("That direction doesn't exist"); + QueueProvider.getInstance().offer("That direction doesn't exist"); } } @@ -206,7 +205,7 @@ public void command_v(String arg) { player.printStorage(); break; default: - QueueProvider.offer("That is not a valid display"); + QueueProvider.getInstance().offer("That is not a valid display"); break; } } @@ -245,7 +244,7 @@ public void command_maxhealth(String arg) { if (healthMax > 0) { player.setHealthMax(healthMax); } else { - QueueProvider.offer("Maximum health must be possitive"); + QueueProvider.getInstance().offer("Maximum health must be possitive"); } } @@ -255,7 +254,7 @@ public void command_health(String arg) { if (health > 0) { player.setHealth(health); } else { - QueueProvider.offer("Health must be possitive"); + QueueProvider.getInstance().offer("Health must be possitive"); } } @@ -287,7 +286,7 @@ public void command_teleport(String arg) { player.getLocation().print(); } catch (NullPointerException e) { player.setLocation(oldLocation); - QueueProvider.offer("There is no such location"); + QueueProvider.getInstance().offer("There is no such location"); } } @@ -309,7 +308,7 @@ public void command_talk(String arg) throws DeathException { if (npc != null) { cm.startConversation(npc, player); } else { - QueueProvider.offer("Unable to talk to " + arg); + QueueProvider.getInstance().offer("Unable to talk to " + arg); } } diff --git a/src/main/java/com/jadventure/game/prompts/CommandParser.java b/src/main/java/com/jadventure/game/prompts/CommandParser.java index a583d39a..dce32e86 100644 --- a/src/main/java/com/jadventure/game/prompts/CommandParser.java +++ b/src/main/java/com/jadventure/game/prompts/CommandParser.java @@ -5,8 +5,8 @@ import java.util.TreeMap; import com.jadventure.game.DeathException; -import com.jadventure.game.QueueProvider; import com.jadventure.game.entities.Player; +import com.jadventure.game.queueprovider.QueueProvider; /** * CommandParser parses the game commands @@ -65,7 +65,7 @@ public boolean parse(Player player, String userCommand) throws DeathException { if ("test".equals(player.getName())) { method.invoke(com); } else { - QueueProvider.offer("Must be using test profile to debug"); + QueueProvider.getInstance().offer("Must be using test profile to debug"); } } else { method.invoke(com); @@ -78,7 +78,7 @@ public boolean parse(Player player, String userCommand) throws DeathException { } } } else { - QueueProvider.offer("I don't know what'" + userCommand + "' means."); + QueueProvider.getInstance().offer("I don't know what'" + userCommand + "' means."); return true; } } else if (method.getParameterTypes()[0] == String.class) { @@ -88,7 +88,7 @@ public boolean parse(Player player, String userCommand) throws DeathException { if ("test".equals(player.getName())) { method.invoke(com, arg); } else { - QueueProvider.offer("Must be using test profile to debug"); + QueueProvider.getInstance().offer("Must be using test profile to debug"); } } else { method.invoke(com, arg); @@ -104,7 +104,7 @@ public boolean parse(Player player, String userCommand) throws DeathException { return true; } } - QueueProvider.offer("I don't know what'" + userCommand + "' means."); + QueueProvider.getInstance().offer("I don't know what'" + userCommand + "' means."); return true; } diff --git a/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java index e5ee368d..a661e17a 100644 --- a/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java +++ b/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java @@ -6,7 +6,7 @@ import java.net.Socket; public abstract class QueueProvider { - protected static Logger logger = LoggerFactory.getLogger(com.jadventure.game.QueueProvider.class); + protected static Logger logger = LoggerFactory.getLogger(QueueProvider.class); private static QueueProvider instance; diff --git a/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java index a24a8b4c..598d04eb 100644 --- a/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java +++ b/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java @@ -61,7 +61,7 @@ private String getInput(String message) { logger.debug("Inside getInput( " + message + " )", ioe); input = "error"; } - + return input; } } diff --git a/src/main/java/com/jadventure/game/repository/LocationRepository.java b/src/main/java/com/jadventure/game/repository/LocationRepository.java index e83a6cc5..e00e9b5f 100644 --- a/src/main/java/com/jadventure/game/repository/LocationRepository.java +++ b/src/main/java/com/jadventure/game/repository/LocationRepository.java @@ -7,7 +7,7 @@ import com.jadventure.game.navigation.LocationType; import com.jadventure.game.navigation.Coordinate; import com.jadventure.game.GameBeans; -import com.jadventure.game.QueueProvider; +import com.jadventure.game.queueprovider.QueueProvider; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonArray; @@ -15,7 +15,6 @@ import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import com.google.gson.Gson; -import com.jadventure.game.JAdventure; import java.nio.file.Files; import java.nio.file.StandardCopyOption; @@ -29,8 +28,6 @@ import java.util.HashMap; import java.util.Map; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * This class loads the locations from the locations.json file on start. @@ -154,9 +151,9 @@ public void writeLocations() { Gson gson = new Gson(); gson.toJson(jsonObject, writer); writer.close(); - QueueProvider.offer("The game locations were saved."); + QueueProvider.getInstance().offer("The game locations were saved."); } catch (IOException ex) { - QueueProvider.offer("Unable to save to file " + fileName); + QueueProvider.getInstance().offer("Unable to save to file " + fileName); } } From 9c43df5d0b71816a209590311ba01ecba4200939 Mon Sep 17 00:00:00 2001 From: ronan Date: Tue, 17 Dec 2019 20:48:12 +0000 Subject: [PATCH 3/4] Worked use of TestingQueueProvider into CommandCollectionTest --- .../queueprovider/TestingQueueProvider.java | 14 +++++- .../game/prompts/CommandCollectionTest.java | 48 +++++++------------ 2 files changed, 31 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java index 897f0566..72fea7f4 100644 --- a/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java +++ b/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java @@ -22,7 +22,19 @@ public String getLastMessage() { } public String[] getMessageHistory() { - return (String[]) messageHistory.toArray(); + return messageHistory.toArray(new String[0]); + } + + public String getMessageHistoryAsString() { + // concatenate message history into a single string + StringBuilder sb = new StringBuilder(); + + for (String msg : messageHistory) { + sb.append(msg); + sb.append("\n"); + } + + return sb.toString(); } public void pushToInputQueue(String input) { diff --git a/src/test/java/com/jadventure/game/prompts/CommandCollectionTest.java b/src/test/java/com/jadventure/game/prompts/CommandCollectionTest.java index 97927a31..605bbb68 100644 --- a/src/test/java/com/jadventure/game/prompts/CommandCollectionTest.java +++ b/src/test/java/com/jadventure/game/prompts/CommandCollectionTest.java @@ -10,6 +10,8 @@ import java.nio.file.StandardCopyOption; import java.util.Collection; +import com.jadventure.game.queueprovider.QueueProvider; +import com.jadventure.game.queueprovider.TestingQueueProvider; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -26,11 +28,10 @@ import com.jadventure.game.repository.LocationRepository; public class CommandCollectionTest { - Player player; - Location location; - CommandCollection collection; - PrintStream stdout; - ByteArrayOutputStream outContent; + private Player player; + private Location location; + private CommandCollection collection; + private TestingQueueProvider testingQueueProvider; @Before public void setUp() { @@ -49,21 +50,15 @@ public void setUp() { collection = CommandCollection.getInstance(); collection.initPlayer(player); - stdout = System.out; - - outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - } - - @After - public void tearDown() { - System.setOut(stdout); + QueueProvider.startTestingMessenger(); + // get a reference to the created TestingQueueProvider object for testing + testingQueueProvider = (TestingQueueProvider) QueueProvider.getInstance(); } @Test public void commandHelpTest() { collection.command_help(); - int n = countLines(outContent.toString()); + int n = testingQueueProvider.getMessageHistory().length; //13 help commands + 1 extra line assertTrue(n == 14); @@ -72,19 +67,18 @@ public void commandHelpTest() { @Test public void commandSaveTest() { collection.command_save(); - assertTrue(outContent.toString().contains("data was saved")); + assertTrue(testingQueueProvider.getMessageHistoryAsString().contains("data was saved")); } @Test public void commandMonsterTest() { collection.command_m(); - assertTrue(outContent.toString().contains("no monsters")); + assertTrue(testingQueueProvider.getMessageHistoryAsString().contains("no monsters")); Troll troll = new Troll(player.getLevel()); player.getLocation().addMonster(troll); collection.command_m(); - assertTrue(outContent.toString().contains(troll.monsterType)); - + assertTrue(testingQueueProvider.getMessageHistoryAsString().contains(troll.monsterType)); } @Test @@ -96,30 +90,24 @@ public void commandGoTest() throws DeathException{ collection.command_g("s"); - assertTrue(outContent.toString().contains("Stairs:")); + assertTrue(testingQueueProvider.getMessageHistoryAsString().contains("Stairs:")); } @Test public void commandInspectTest() { collection.command_i(""); - assertTrue(outContent.toString().contains("Item doesn't exist")); + assertTrue(testingQueueProvider.getMessageHistoryAsString().contains("Item doesn't exist")); } @Test public void commandViewTest() { collection.command_v("b"); - assertTrue(outContent.toString().contains("Backpack")); + assertTrue(testingQueueProvider.getMessageHistoryAsString().contains("Backpack")); collection.command_v("s"); - assertTrue(outContent.toString().contains("Player name:")); + assertTrue(testingQueueProvider.getMessageHistoryAsString().contains("Player name:")); collection.command_v("e"); - assertTrue(outContent.toString().contains("Equipped Items:")); + assertTrue(testingQueueProvider.getMessageHistoryAsString().contains("Equipped Items:")); } - - private static int countLines(String str) { - String[] lines = str.split("\r\n|\r|\n"); - return lines.length; - } - } From 6e49b3355c84590af3e4b29856d3cd0fbf88367c Mon Sep 17 00:00:00 2001 From: ronan Date: Thu, 19 Dec 2019 12:44:59 +0000 Subject: [PATCH 4/4] Added JUnit tests for QueueProvider classes --- .../game/queueprovider/QueueProvider.java | 9 +- .../queueprovider/ServerQueueProvider.java | 4 +- .../queueprovider/TestingQueueProvider.java | 9 +- .../game/queueprovider/QueueProviderTest.java | 32 +++++++ .../ServerQueueProviderTest.java | 92 +++++++++++++++++++ .../TestingQueueProviderTest.java | 71 ++++++++++++++ 6 files changed, 209 insertions(+), 8 deletions(-) create mode 100644 src/test/java/com/jadventure/game/queueprovider/QueueProviderTest.java create mode 100644 src/test/java/com/jadventure/game/queueprovider/ServerQueueProviderTest.java create mode 100644 src/test/java/com/jadventure/game/queueprovider/TestingQueueProviderTest.java diff --git a/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java index a661e17a..4f6e9a9e 100644 --- a/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java +++ b/src/main/java/com/jadventure/game/queueprovider/QueueProvider.java @@ -8,7 +8,7 @@ public abstract class QueueProvider { protected static Logger logger = LoggerFactory.getLogger(QueueProvider.class); - private static QueueProvider instance; + private static QueueProvider instance = null; public static QueueProvider getInstance() { return instance; @@ -32,6 +32,13 @@ public static void startTestingMessenger() { instance = new TestingQueueProvider(); } + /** + * Used for testing + */ + public static void clearInstance() { + instance = null; + } + public void offer(String message) { logger.debug("offer( " + message + " )"); } diff --git a/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java index 598d04eb..f93f04ee 100644 --- a/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java +++ b/src/main/java/com/jadventure/game/queueprovider/ServerQueueProvider.java @@ -16,8 +16,8 @@ protected ServerQueueProvider(Socket socket) { try { out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); - } catch (IOException ioe) { - logger.debug("Inside ServerQueueProvider( " + socket+ " )", ioe); + } catch (Exception e) { + logger.debug("Inside ServerQueueProvider( " + socket+ " )", e); } } diff --git a/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java b/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java index 72fea7f4..d53ca8c4 100644 --- a/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java +++ b/src/main/java/com/jadventure/game/queueprovider/TestingQueueProvider.java @@ -37,19 +37,18 @@ public String getMessageHistoryAsString() { return sb.toString(); } - public void pushToInputQueue(String input) { - inputQueue.push(input); + public void offerToInputQueue(String input) { + inputQueue.offer(input); } @Override public void offer(String message) { super.offer(message); - - messageHistory.push(message); + messageHistory.offer(message); } @Override public String take() { - return inputQueue.pop(); + return inputQueue.poll(); } } diff --git a/src/test/java/com/jadventure/game/queueprovider/QueueProviderTest.java b/src/test/java/com/jadventure/game/queueprovider/QueueProviderTest.java new file mode 100644 index 00000000..cf4600b0 --- /dev/null +++ b/src/test/java/com/jadventure/game/queueprovider/QueueProviderTest.java @@ -0,0 +1,32 @@ +package com.jadventure.game.queueprovider; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class QueueProviderTest { + @AfterClass + public static void tearDown() { + QueueProvider.clearInstance(); + } + + @Test + public void testStartStandaloneMessenger() { + QueueProvider.startStandaloneMessenger(); + assertTrue(QueueProvider.getInstance() instanceof StandAloneQueueProvider); + } + + @Test + public void testStartServerMessenger() { + QueueProvider.startServerMessenger(null); + assertTrue(QueueProvider.getInstance() instanceof ServerQueueProvider); + } + + @Test + public void testStartTestingMessenger() { + QueueProvider.startTestingMessenger(); + assertTrue(QueueProvider.getInstance() instanceof TestingQueueProvider); + } +} \ No newline at end of file diff --git a/src/test/java/com/jadventure/game/queueprovider/ServerQueueProviderTest.java b/src/test/java/com/jadventure/game/queueprovider/ServerQueueProviderTest.java new file mode 100644 index 00000000..85e099a1 --- /dev/null +++ b/src/test/java/com/jadventure/game/queueprovider/ServerQueueProviderTest.java @@ -0,0 +1,92 @@ +package com.jadventure.game.queueprovider; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; + +import static org.junit.Assert.*; + +public class ServerQueueProviderTest { + // these need to be static for use in BeforeClass/AfterClass + private static QueueProvider queueProvider; + private static Socket testingSocket; + private static DataInputStream in; + private static DataOutputStream out; + + @BeforeClass + public static void setUp() throws IOException, InterruptedException { + // create a pair of client/server sockets for testing + // use any free port + final ServerSocket serverSocket = new ServerSocket(0); + final Socket[] testingSockets = new Socket[1]; + + Thread acceptThread = new Thread(new Runnable() { + @Override + public void run() { + try { + testingSockets[0] = serverSocket.accept(); + } catch (IOException e) { + fail("Error while creating sockets"); + } + } + }); + + acceptThread.start(); + Socket queueSocket = new Socket("localhost", serverSocket.getLocalPort()); + // wait for the connection to be established + acceptThread.join(); + QueueProvider.startServerMessenger(queueSocket); + queueProvider = QueueProvider.getInstance(); + + testingSocket = testingSockets[0]; + in = new DataInputStream(testingSocket.getInputStream()); + out = new DataOutputStream(testingSocket.getOutputStream()); + } + + @AfterClass + public static void tearDown() throws IOException{ + in.close(); + out.close(); + testingSocket.close(); + QueueProvider.clearInstance(); + } + + @Test + public void testOffer() throws IOException { + String offeredMsg = "Hello World!"; + String expectedMsg = "Hello World!END"; + queueProvider.offer(offeredMsg); + String actualMsg = in.readUTF(); + assertEquals(expectedMsg, actualMsg); + } + + @Test + public void testTake() throws IOException, InterruptedException { + final String messageSent = "Hello World!"; + + // must receive message in another thread since in.readUTF() blocks execution + Thread sendThread = new Thread(new Runnable() { + @Override + public void run() { + String messageReceived = queueProvider.take(); + assertEquals(messageSent, messageReceived); + } + }); + + sendThread.start(); + + String expectedQueryMsg = "QUERYEND"; + String actualQueryMsg = in.readUTF(); + assertEquals(expectedQueryMsg, actualQueryMsg); + out.writeUTF(messageSent); + out.flush(); + + sendThread.join(); + } +} \ No newline at end of file diff --git a/src/test/java/com/jadventure/game/queueprovider/TestingQueueProviderTest.java b/src/test/java/com/jadventure/game/queueprovider/TestingQueueProviderTest.java new file mode 100644 index 00000000..cfd571a3 --- /dev/null +++ b/src/test/java/com/jadventure/game/queueprovider/TestingQueueProviderTest.java @@ -0,0 +1,71 @@ +package com.jadventure.game.queueprovider; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +import java.util.NoSuchElementException; + +import static org.junit.Assert.*; + +public class TestingQueueProviderTest { + private TestingQueueProvider testingQueueProvider; + + @Before + public void initTestingQueueProvider() { + QueueProvider.startTestingMessenger(); + testingQueueProvider = (TestingQueueProvider) QueueProvider.getInstance(); + } + + @AfterClass + public static void tearDown() { + QueueProvider.clearInstance(); + } + + @Test + public void testQueuesEmptyWhenCreated() { + assertEquals(0, testingQueueProvider.getMessageHistory().length); + assertNull(testingQueueProvider.take()); + } + + @Test + public void testOffer() { + String expectedMsg = "Hello World!"; + testingQueueProvider.offer(expectedMsg); + String actualMsg = testingQueueProvider.getLastMessage(); + assertEquals(expectedMsg, actualMsg); + } + + @Test + public void testGetMessageHistory() { + String[] expectedMsgs = {"hello", "world", "!"}; + + for (String msg : expectedMsgs) { + testingQueueProvider.offer(msg); + } + + String[] actualMsgs = testingQueueProvider.getMessageHistory(); + assertArrayEquals(expectedMsgs, actualMsgs); + } + + @Test + public void testGetMessageHistoryAsString() { + String[] msgs = {"hello", "world", "!"}; + + for (String msg : msgs) { + testingQueueProvider.offer(msg); + } + + String expectedHistory = "hello\nworld\n!\n"; + String actualHistory = testingQueueProvider.getMessageHistoryAsString(); + assertEquals(expectedHistory, actualHistory); + } + + @Test + public void testInputQueue() { + String expectedMsg = "Hello World!"; + testingQueueProvider.offerToInputQueue(expectedMsg); + String actualMsg = testingQueueProvider.take(); + assertEquals(expectedMsg, actualMsg); + } +} \ No newline at end of file