import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import java.net.HttpURLConnection; import java.util.Arrays; import java.util.Map; import java.util.Objects; public class Game { private ArrayList rooms = new ArrayList<>(); private ArrayList inventory = new ArrayList<>(); private ArrayList story = new ArrayList<>(); private ArrayList items = new ArrayList<>(); private ArrayList puzzles = new ArrayList<>(); private boolean stoppFlag = false; private Map jsonMap = null; private String[] inputArray = null; private Integer id = null; private String itemName = null; private String intentName = null; private String puzzleName = null; private String input = null; private Room currentRoom = null; public Game() { try { setVariables(); } catch (Exception ex) { Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex); } } public Game(Integer i) { try { id = i; setVariables(); } catch (Exception ex) { Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex); } } public Map readJSON() throws IOException, Exception { //TODO: Define path! File file = new File("game.JSON"); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String jsonObject = br.readLine(); log(jsonObject); ObjectMapper objectMapper = new ObjectMapper(); try { jsonMap = objectMapper.readValue(jsonObject, new TypeReference>() { }); } catch (JsonParseException e) { // TODO Auto-generated catch block } catch (JsonMappingException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); String jsonStringItem = objectMapper.writeValueAsString(jsonMap.get("item")); String jsonStringStory = objectMapper.writeValueAsString(jsonMap.get("story")); String jsonStringPuzzle = objectMapper.writeValueAsString(jsonMap.get("puzzle")); String jsonStringRoom = objectMapper.writeValueAsString(jsonMap.get("room")); log("Story: " + jsonStringStory); String[] st = objectMapper.readValue(jsonStringStory, String[].class); log("Story einlesen fertig"); log("Item: " + jsonStringItem); Item[] it = objectMapper.readValue(jsonStringItem, Item[].class); log("Items einlesen fertig"); log("Puzzle: " + jsonStringPuzzle); Puzzle[] pu = objectMapper.readValue(jsonStringPuzzle, Puzzle[].class); log("Puzzles einlesen fertig"); log("Room: " + jsonStringRoom); Room[] ro = objectMapper.readValue(jsonStringRoom, Room[].class); log("Rooms einlesen fertig"); story.addAll(Arrays.asList(st)); items.addAll(Arrays.asList(it)); rooms.addAll(Arrays.asList(ro)); puzzles.addAll(Arrays.asList(pu)); return jsonMap; } catch (FileNotFoundException e1) { // TODO Auto-generated catch block } return null; } public void setVariables() throws Exception { readJSON(); log("JSON einlesen beendet"); currentRoom = rooms.get(0); stoppFlag = false; inventory = new ArrayList<>(); } public String prepareInput(String s) { //s = s.replace("ä", "ae"); //s = s.replace("ü", "ue"); //s = s.replace("ö", "oe"); s = s.replace("ß", "ss"); s = s.toLowerCase(); return s; } public void play() throws Exception { log("play()"); log("Input: " + input); log("Aktueller Raum " + currentRoom.getName()); for (int i = 0; i < currentRoom.puzzles.size(); i++) { log("Puzzle: " + getPuzzleById(currentRoom.puzzles.get(i)).getName() + " ID: " + getPuzzleById(currentRoom.puzzles.get(i)).getId()); } for (int i = 0; i < currentRoom.items.size(); i++) { log("Item: " + getItemById(currentRoom.items.get(i)).getName() + " ID: " + getItemById(currentRoom.items.get(i)).getId()); } input = prepareInput(input); log("vor if"); if (input.contains(" ")) { log("if"); inputArray = input.split(" "); for (String s : inputArray) { if (getItemByName(s) != null) { itemName = getItemByName(s).getName(); log("itemName: " + itemName); } else if (getPuzzleByName(s) != null) { puzzleName = getPuzzleByName(s).getName(); log("PuzzleName: " + puzzleName); } else { if (intentName == null) { intentName = s; log("intentName: " + intentName); } } } } else { intentName = input; log("intentName: " + intentName); } log("vor switch"); switch (intentName) { //intent case "lookaroundintent": log("Switch: LookAroundIntent"); if (itemName == null && puzzleName == null) { lookaround(); } else { say("ich kann mich nur in Räumen umschauen. Falls sie Gegenstände untersuchen wollen, sagen dessen Namen und untersuchen"); } break; //intent case "inspectintent": log("Switch: InspectIntent"); if (itemName != null) { inspect(getItemByName(itemName)); } else if (puzzleName != null) { inspect(getPuzzleByName(puzzleName)); } break; //intent case "examineintent": log("Switch: ExamineIntent"); if (itemName == null && puzzleName == null) { examine(); } else { say("Wenn ich meine Taschen durchsuchen soll dann sagen sie Taschen durchsuchen."); } break; //intent case "takeintent": log("Switch: TakeIntent"); if (itemName != null) { take(getItemByName(itemName)); } else { say("Ich kann diesen Gegenstand nicht finden"); } break; //intent case "openintent": log("Switch: OpenIntent"); if (puzzleName != null) { open(getPuzzleByName(puzzleName)); } else { say("Könnten Sie das wiederholen? Ich habe das leider nicht verstanden."); } break; //intent case "resetintent": log("Switch: ResetIntent"); if (itemName == null && puzzleName == null) { resetGame(); } else { say("das habe ich leider nicht verstanden, wiederholen sie das bitte?"); } break; //intent case "skipintent": log("Switch: SkipIntent"); if (itemName == null && puzzleName == null) { resetGame(); for (int i = 0; i < currentRoom.puzzles.size(); i++) { if (getPuzzleById(currentRoom.puzzles.get(i)).getNextRoom() != null) { setRoom(getRoomById(getPuzzleById(currentRoom.puzzles.get(i)).getNextRoom())); } } } else { say("leider habe ich das nicht verstanden.können sie das wiederholen?"); } break; case "resumeintent": log("Switch: ResumeIntent"); break; case "startintent": log("Switch: StartIntent"); startGame(); break; default: log("Switch: Intent nicht vorhanden"); say("Das habe ich leider nicht verstanden, könnten Sie das wiederholen?"); break; } itemName = null; intentName = null; puzzleName = null; if (stoppFlag == true) { endGame(); } } public Item getItemByName(String s) throws Exception { for (int i = 0; i < currentRoom.items.size(); i++) { String n = getItemById(currentRoom.items.get(i)).getName().toLowerCase(); if (n.equals(s.toLowerCase())) { return getItemById(currentRoom.items.get(i)); } } return null; } public Puzzle getPuzzleByName(String s) throws Exception { for (int i = 0; i < currentRoom.puzzles.size(); i++) { String n = getPuzzleById(currentRoom.puzzles.get(i)).getName().toLowerCase(); if (n.equals(s.toLowerCase())) { return getPuzzleById(currentRoom.puzzles.get(i)); } } return null; } public Room getRoomById(Integer i) throws Exception { for (int j = 0; j < rooms.size(); j++) { if (Objects.equals(i, rooms.get(j).getId())) { return rooms.get(j); } } return null; } public Item getItemById(Integer i) throws Exception { for (int j = 0; j < items.size(); j++) { if (Objects.equals(items.get(j).getId(), i)) { return items.get(j); } } return null; } public Puzzle getPuzzleById(Integer i) throws Exception { for (int j = 0; j < puzzles.size(); j++) { if (Objects.equals(puzzles.get(j).getId(), i)) { return puzzles.get(j); } } return null; } public void log(String s) throws Exception { String url = "https://medinf.efi.th-nuernberg.de/tomcat/WebAdventure/Log"; URL obj = new URL(url); HttpURLConnection httpConn = (HttpURLConnection) obj.openConnection(); //add reuqest header httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("User-Agent", "Mozilla/5.0"); httpConn.setRequestProperty("Accept-Language", "de-DE,de;q=0.5"); // Send post request httpConn.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream())) { String urlParameters = "log=" + s; wr.writeBytes(urlParameters); wr.flush(); } BufferedReader in = new BufferedReader( new InputStreamReader(httpConn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } public void lookaround() throws Exception { log("lookaround()"); say(currentRoom.getDescription() + "."); } public Integer getId() { return id; } public void setId(Integer i) { id = i; } public void startGame() throws Exception { log("startGame()"); say(story.get(0)); } public void resetGame() throws Exception { log("resetGame()"); setVariables(); startGame(); } public void inspect(Puzzle currentPuzzle) throws Exception { log("inspect(" + currentPuzzle.getName() + ")"); for (int i = 0; i < currentRoom.getItems().size(); i++) { if (Objects.equals(currentRoom.getPuzzles().get(i), currentPuzzle.getId())) { say(currentPuzzle.getDescription() + "."); return; } else { log("Else Reset"); }; } } public void inspect(Item currentItem) throws Exception { log("inspect(" + currentItem.getName() + ")"); for (int i = 0; i < currentRoom.getItems().size(); i++) { if (Objects.equals(currentRoom.getItems().get(i), currentItem.getId())) { say(currentItem.getDescription()); return; } else { log("Else Inspect"); }; } } public void endGame() throws Exception { log("endGame()"); say("Glückwunsch der Durchlauf ist beendet! Das Spiel starte nun von vorne."); setVariables(); } public void sendPost(String s) throws Exception { s = s.replace(" ", "%20"); String url = "https://medinf.efi.th-nuernberg.de/tomcat/WebAdventure/IO"; URL obj = new URL(url); HttpURLConnection httpConn = (HttpURLConnection) obj.openConnection(); //add reuqest header httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("User-Agent", "Mozilla/5.0"); httpConn.setRequestProperty("Accept-Language", "de-DE,de;q=0.5"); // Send post request httpConn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream()); String urlParameters = "alexaText=" + s; wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader in = new BufferedReader( new InputStreamReader(httpConn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } public void say(String s) throws Exception { log("say(" + s + ")"); try { sendPost(s); } catch (Exception ex) { Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex); } } public void setInput(String s) throws Exception { log("setInput(" + s + ")"); input = s; } public void setRoom(Room nextRoom) throws Exception { log("setRoom(" + nextRoom.getName() + ")"); log(nextRoom.getDescription()); currentRoom = null; currentRoom = nextRoom; } public void examine() throws Exception { log("examine() : " + getInventory()); String s = "In deinen Taschen befindet sich: "; if (getInventory().isEmpty()) { say("Deine Taschen sind leer."); } else { for (int i = 0; i < inventory.size(); i++) { s = s + " " + inventory.get(i).getName(); } say(s); } } public void open(Puzzle currentPuzzle) throws Exception { log("open(" + currentPuzzle.getName() + ") "); log("Puzzle gelöst?: " + currentPuzzle.isSolved()); if (currentPuzzle.isSolved()) // bereits gelöst { log("Bereits gelöst: " + currentPuzzle.isSolved()); if (currentPuzzle.getNextRoom() != null) // wenn es eine Tür ist die in den nächsten Raum führt { say("das Räsel ist bereits gelöst. Sie betreten den nächsten Raum."); log("nächster Raum: " + currentPuzzle.getNextRoom()); setRoom(getRoomById(currentPuzzle.getNextRoom())); // wechselt in den nächsten Raum } } log(" " + checkDependency(currentPuzzle)); if (!checkDependency(currentPuzzle)) // ist keine Abhängigkeit vorhanden oder aber die Abhängigkeit ist gelöst { log("Abhängigkeit: " + currentPuzzle.hasDependency()); log("" + checkPuzzleItemsInInventory(currentPuzzle) + ""); if (checkPuzzleItemsInInventory(currentPuzzle)) // keine Items zum lösen notwendig oder alle Items zum lösen befinden sich im Inventar { say(currentPuzzle.getSolvedText()); // Lösungstext currentPuzzle.setSolved(true); // auf gelöst setzen if (checkGameOver(currentPuzzle)) // Wenn es das letzte Rätsel im Spiel war oder man vom Angreifer erwischt wurde { stoppFlag = true; // Spiel wird nun beendet log("Gameover"); } if (currentPuzzle.getNextRoom() != null) // wenn es eine Tür ist die in den nächsten Raum führt { log("Nächster Raum: " + getRoomById(currentPuzzle.getNextRoom()).getName()); log(currentPuzzle.getNextRoom() + ""); setRoom(getRoomById(currentPuzzle.getNextRoom())); // wechselt in den nächsten Raum } } else // Item zum lösen fehlt { say("das geht leider nicht, hier fehlt noch etwas."); } } if (getPuzzleById(currentPuzzle.getDependency()) != null) { if (!getPuzzleById(currentPuzzle.getDependency()).isSolved()) // Abhängigkeit nicht gelöst { say(currentPuzzle.getDependencyText() + "."); } } } public boolean checkDependency(Puzzle currentPuzzle) { if (currentPuzzle.hasDependency()) { return true; } try { if (getPuzzleById(currentPuzzle.getDependency()) != null) { if (getPuzzleById(currentPuzzle.getDependency()).isSolved()) { return true; } } } catch (Exception ex) { Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex); } return false; } public boolean checkGameOver(Puzzle currentPuzzle) { if (currentRoom.getGameoverFlag() == true) { return true; } if (currentPuzzle.getGameOverFlag() == true) { return true; } return false; } public void take(Item currentItem) throws Exception { log("take(" + currentItem.getName() + ") "); if ((!inventory.contains(currentItem)) && (currentItem.isPortableFlag() == true)) { inventory.add(currentItem); currentRoom.items.remove(currentItem.getId()); say(currentItem.getName() + " wurde deiner Tasche hinzugefuegt."); } else if (currentItem.isPortableFlag() == false) { say("Das Item kann nicht mitgenommen werden."); } else if (inventory.contains(currentItem)) { say("Das Item befindet sich bereits in deiner Tasche!"); } } public boolean checkPuzzleItemsInInventory(Puzzle currentPuzzle) throws Exception { // checkt ob ob alle Items benötigten Items im Inventar sind oder ob Items gebraucht werden if (currentPuzzle.getItems().isEmpty()) { // keine Items zum lösen notwendig return true; } else { // durchsucht ob alle nötigen Items im Inventar sind for (int i = 0; i < currentPuzzle.getItems().size(); i++) { if (inventory.contains(getItemById(currentPuzzle.getItems().get(i)))) { } else { return false; } } return true; } } public ArrayList getInventory() { return inventory; } }