You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Game.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. import com.fasterxml.jackson.core.JsonEncoding;
  2. import com.fasterxml.jackson.core.JsonGenerator;
  3. import com.fasterxml.jackson.core.JsonParseException;
  4. import com.fasterxml.jackson.core.JsonParser;
  5. import com.fasterxml.jackson.core.type.TypeReference;
  6. import com.fasterxml.jackson.databind.JsonMappingException;
  7. import com.fasterxml.jackson.databind.ObjectMapper;
  8. import java.io.BufferedReader;
  9. import java.io.DataOutputStream;
  10. import java.io.File;
  11. import java.io.FileNotFoundException;
  12. import java.io.FileReader;
  13. import java.io.IOException;
  14. import java.io.InputStreamReader;
  15. import java.io.PrintWriter;
  16. import java.net.URL;
  17. import java.util.ArrayList;
  18. import java.util.logging.Level;
  19. import java.util.logging.Logger;
  20. import java.net.HttpURLConnection;
  21. import java.util.Map;
  22. import java.util.Objects;
  23. import javax.json.stream.JsonGenerationException;
  24. public class Game {
  25. private static ArrayList<Room> rooms = new ArrayList<Room>();
  26. private static ArrayList<Item> inventory = new ArrayList<Item>();
  27. private static ArrayList<String> story = new ArrayList<String>();
  28. private static ArrayList<Item> items = new ArrayList<Item>();
  29. private static ArrayList<Puzzle> puzzles = new ArrayList<Puzzle>();
  30. private boolean stoppFlag = false;
  31. private Map<String, Object> jsonMap = null;
  32. private String[] inputArray = null;
  33. private String itemName = null;
  34. private String intentName = null;
  35. private String puzzleName = null;
  36. private String input = null;
  37. private Room currentRoom = null;
  38. public Game() {
  39. try {
  40. startGame();
  41. } catch (Exception ex) {
  42. Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
  43. }
  44. }
  45. public Map<String, Object> readJSON() throws IOException, Exception {
  46. //TODO: Define path!
  47. File file = new File("game.JSON");
  48. if(!file.exists())
  49. {
  50. PrintWriter writer = new PrintWriter("game.JSON", "UTF-8");
  51. writer.println("{\\nroom\\n:[{\\nid\\n:0,\\nname\\n:\\nIntro\\n,\\ndescription\\n:\\nHier ist das Intro von Kidnappd\\n,\\ngameoverFlag\\n:false,\\nitems\\n:[],\\npuzzles\\n:[0]},{\\nid\\n:1,\\nname\\n:\\nKeller\\n,\\ndescription\\n:\\nder kleine Mondschein, der zuvor den unbekannten Raum schwach beleuchtet hat, leuchtet viel gr��er und viel heller und du erkennst nun den gesamten Raum. Er ist klein und d�ster. überall h�ngen Spinnennetze und Staub sammelt sich am Betonboden. Du erkennst am anderen Ende des Raumes eine T�r\\n,\\ngameoverFlag\\n:false,\\nitems\\n:[0,1],\\npuzzles\\n:[1,2]}],\\npuzzle\\n:[{\\nid\\n:0,\\nname\\n:\\nDurchgang\\n,\\nitems\\n:[],\\ndescription\\n:\\nAusgang Intro Level\\n,\\nsolved\\n:false,\\nsolvedText\\n:\\nHurra, du hast es geschafft\\n,\\ngameOverFlag\\n:false,\\nnextRoom\\n:null,\\ndependencyText\\n:null,\\ndependency\\n:null},{\\nid\\n:1,\\nname\\n:\\nTuer\\n,\\nitems\\n:[1],\\ndescription\\n:\\nAusgang aus dem Keller\\n,\\nsolved\\n:false,\\nsolvedText\\n:\\nGeschafft! Die Tuer ist offen. Das Intro ist nun beendet\\n,\\ngameOverFlag\\n:true,\\nnextRoom\\n:null,\\ndependencyText\\n:null,\\ndependency\\n:null},{\\nid\\n:2,\\nname\\n:\\nSchloss\\n,\\nitems\\n:[0],\\ndescription\\n:\\nEs ist ein altes Schloss aus Metall, dass eine Einkerbung f�r einen Schl�ssel hat\\n,\\nsolved\\n:false,\\nsolvedText\\n:\\nJa, es hat funktioniert! Mit einem Knacksen geht das Schloss auf und du kannst dich von deiner Beinfessel befreien. \\n,\\ngameOverFlag\\n:false,\\nnextRoom\\n:null,\\ndependencyText\\n:null,\\ndependency\\n:null}],\\nitem\\n:[{\\nid\\n:1,\\nname\\n:\\nStahlschluessel\\n,\\nportableFlag\\n:true,\\nhiddenFlag\\n:false,\\ndescription\\n:\\nEin Stahlschlüssel\\n},{\\nid\\n:0,\\nname\\n:\\nSchluessel\\n,\\nportableFlag\\n:true,\\nhiddenFlag\\n:false,\\ndescription\\n:\\nDer Schlüssel ist kalt und klein. Vielleicht hast du Glück und er passt ins Schloss. Versuche es zu öffnen!\\n}],\\nstory\\n:[\\nDein ganzer K�rper schmerzt, du liegst auf Betonboden. Du f�ngst laut an zu husten und Staubklumpen fliegen aus deinem Mund. Du �ffnest langsam und nur schwer die Augen, doch es ist fast gar nichts zu sehen. Die einzige Lichtquelle ist ein kleines Fenster �ber dir, durch die ein schwacher Mondschein f�llt. Es ist also Nachts... Langsam versuchst du dich an die fast komplette Dunkelheit zu gew�hnen und erkennst, dass du dich in einem kleinen dir unbekannten Raum befindest. Dich packt die Angst! Was ist passiert, wo bist du und wie bist du hier gelandet?Du nimmst die Stahlkette in die Hand. Sie ist schwer und verrostet. Mit den H�nden tastest du dich voran bis an die Heizung, wo du ein Schloss an der Kette entdeckst.Das Mondlicht ist nur sehr schwach, um den Raum zu begutachten. Du gehst in die Knie und tastest mit deinem H�nden wild und in Panik am Betonboden. Pl�tzlich st��t du auf einen kleinen Gegenstand, der sich tats�chlich anf�hlt wie ein Schl�ssel. Du solltest ihn aufheben\\n]}");
  52. writer.close();
  53. }
  54. try {
  55. FileReader fr = new FileReader(file);
  56. BufferedReader br = new BufferedReader(fr);
  57. String jsonObject = br.readLine();
  58. ObjectMapper objectMapper = new ObjectMapper();
  59. try {
  60. jsonMap = objectMapper.readValue(jsonObject,
  61. new TypeReference<Map<String, Object>>() {
  62. });
  63. } catch (JsonParseException e) {
  64. // TODO Auto-generated catch block
  65. e.printStackTrace();
  66. } catch (JsonMappingException e) {
  67. // TODO Auto-generated catch block
  68. e.printStackTrace();
  69. } catch (IOException e) {
  70. // TODO Auto-generated catch block
  71. e.printStackTrace();
  72. }
  73. log("Keyset:" + jsonMap.keySet().toString());
  74. return jsonMap;
  75. } catch (FileNotFoundException e1) {
  76. // TODO Auto-generated catch block
  77. e1.printStackTrace();
  78. }
  79. return null;
  80. }
  81. public static String writeJSON(File f) throws IOException {
  82. ObjectMapper mapper = new ObjectMapper();
  83. String s = "";
  84. try (
  85. JsonGenerator jGenerator
  86. = mapper.getFactory().createGenerator(f,JsonEncoding.UTF8)) {
  87. jGenerator.writeStartObject();
  88. jGenerator.writeObjectField("room", rooms);
  89. jGenerator.writeObjectField("puzzle", puzzles);
  90. jGenerator.writeObjectField("item", items);
  91. jGenerator.writeObjectField("story", story);
  92. jGenerator.writeEndObject();
  93. jGenerator.close();
  94. } catch (JsonGenerationException e) {
  95. e.printStackTrace();
  96. } catch (JsonMappingException e) {
  97. e.printStackTrace();
  98. } catch (IOException e) {
  99. e.printStackTrace();
  100. }
  101. BufferedReader reader = null;
  102. try {
  103. reader = new BufferedReader(new FileReader("game.JSON"));
  104. } catch (FileNotFoundException ex) {
  105. Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
  106. }
  107. StringBuilder sb = new StringBuilder();
  108. String line;
  109. while ((line = reader.readLine()) != null) {
  110. s = s + (line + "\n");
  111. }
  112. return s;
  113. }
  114. public Item getItem(String s) {
  115. for (int i = 0; i < items.size(); i++) {
  116. if (items.get(i).getName().toLowerCase().equals(s.toLowerCase())) {
  117. if (currentRoom.getItems().contains(items.get(i).getId())) {
  118. return items.get(i);
  119. }
  120. }
  121. }
  122. return null;
  123. }
  124. public Puzzle getPuzzle(String s) {
  125. for (int i = 0; i < items.size(); i++) {
  126. if (items.get(i).getName().toLowerCase().equals(s.toLowerCase())) {
  127. if (currentRoom.getPuzzles().contains(puzzles.get(i).getId())) {
  128. return puzzles.get(i);
  129. }
  130. }
  131. }
  132. return null;
  133. }
  134. public void setVariables() throws Exception {
  135. readJSON();
  136. log(readJSON().toString());
  137. log("Readjson fertig");
  138. currentRoom = rooms.get(0);
  139. stoppFlag = false;
  140. inventory = new ArrayList<>();
  141. //log("JSON: " + writeJSON());
  142. ObjectMapper objectMapper = new ObjectMapper();
  143. objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  144. String jsonStringRoom = objectMapper.writeValueAsString(jsonMap.get("room"));
  145. String jsonStringItem = objectMapper.writeValueAsString(jsonMap.get("item"));
  146. String jsonStringPuzzle = objectMapper.writeValueAsString(jsonMap.get("puzzle"));
  147. String jsonStringStory = objectMapper.writeValueAsString(jsonMap.get("story"));
  148. log("Item: " + jsonStringItem);
  149. log("Room: " + jsonStringRoom);
  150. log("Story: " + jsonStringStory);
  151. log("Puzzle: " + jsonStringPuzzle);
  152. String[] st = objectMapper.readValue(jsonStringStory, String[].class);
  153. log("Story Array OK");
  154. Item[] it = objectMapper.readValue(jsonStringItem, Item[].class);
  155. log("Item Array OK");
  156. Puzzle[] pu = objectMapper.readValue(jsonStringPuzzle, Puzzle[].class);
  157. log("Puzzle Array OK");
  158. Room[] ro = objectMapper.readValue(jsonStringRoom, Room[].class);
  159. log("Room Array OK");
  160. for (Room ro1 : ro) {
  161. log("Room: " + ro1.getName());
  162. log("Description: " + ro1.getDescription());
  163. }
  164. for (Item it1 : it) {
  165. log("Item: " + it1.getName());
  166. log("Description: " + it1.getDescription());
  167. }
  168. for (Puzzle pu1 : pu) {
  169. log("Puzzle: " + pu1.getName());
  170. log("Description: " + pu1.getDescription());
  171. log("DependencyText: " + pu1.getDependencyText());
  172. }
  173. for (String st1 : st) {
  174. log("Story: " + st1);
  175. }
  176. }
  177. public void play() throws Exception {
  178. log("play()");
  179. log("Input: " + input);
  180. log("currentRoom: " + currentRoom.getName());
  181. for (int i = 0; i < currentRoom.getPuzzles().size(); i++) {
  182. log("Puzzle im Raum: " + currentRoom.getPuzzles().get(i)); //getPuzzles().get(i).getName());
  183. }
  184. for (int i = 0; i < currentRoom.getItems().size(); i++) {
  185. log("Item im Raum: " + currentRoom.getItems().get(i)); //getItems().get(i).getName());
  186. }
  187. input = input.replace("ä", "ae");
  188. input = input.replace("ü", "ue");
  189. input = input.replace("ö", "oe");
  190. input = input.replace("ß", "ss");
  191. if (input.contains(" ")) {
  192. inputArray = input.split(" ");
  193. for (String s : inputArray) {
  194. if (getItem(s) != null) {
  195. itemName = getItem(s).getName();
  196. log("itemName: " + itemName);
  197. } else if (getPuzzle(s) != null) {
  198. puzzleName = getPuzzle(s).getName();
  199. log("PuzzleName: " + puzzleName);
  200. } else {
  201. intentName = s;
  202. log("intentName: " + intentName);
  203. }
  204. }
  205. } else {
  206. intentName = input;
  207. log("intentName: " + intentName);
  208. }
  209. switch (intentName.toLowerCase()) {
  210. //intent
  211. case "lookaroundintent":
  212. log("Switch: LookAroundIntent");
  213. if (itemName == null && puzzleName == null) {
  214. lookaround();
  215. }
  216. break;
  217. //intent
  218. case "inspectintent":
  219. log("Switch: InspectIntent");
  220. if (getItem(itemName) != null) {
  221. inspect(getItem(itemName));
  222. } else if (getPuzzle(puzzleName) != null) {
  223. inspect(getPuzzle(puzzleName));
  224. }
  225. break;
  226. //intent
  227. case "examineintent":
  228. log("Switch: ExamineIntent");
  229. if (itemName == null && puzzleName == null) {
  230. examine();
  231. }
  232. break;
  233. //intent
  234. case "takeintent":
  235. log("Switch: TakeIntent");
  236. if (getItem(itemName) != null) {
  237. take(getItem(itemName));
  238. }
  239. break;
  240. //intent
  241. case "openintent":
  242. log("Switch: OpenIntent");
  243. if (getPuzzle(puzzleName) != null) {
  244. open(getPuzzle(puzzleName));
  245. }
  246. break;
  247. //intent
  248. case "resetintent":
  249. log("Switch: ResetIntent");
  250. if (itemName == null && puzzleName == null) {
  251. resetGame();
  252. }
  253. break;
  254. //intent
  255. case "skipintent":
  256. log("Switch: SkipIntent");
  257. if (itemName == null && puzzleName == null) {
  258. resetGame();
  259. for (int i = 0; i < currentRoom.puzzles.size(); i++) {
  260. if (getPuzzleById(currentRoom.puzzles.get(i)).getNextRoom() != null) {
  261. setRoom(getRoomById(getPuzzleById(currentRoom.puzzles.get(i)).getNextRoom()));
  262. }
  263. }
  264. }
  265. break;
  266. case "resumeintent":
  267. log("Switch: ResumeIntent");
  268. break;
  269. }
  270. itemName = null;
  271. intentName = null;
  272. puzzleName = null;
  273. log("stoppFlag: " + stoppFlag);
  274. if (stoppFlag == true) {
  275. endGame();
  276. }
  277. }
  278. public Room getRoomById(int i) {
  279. for (int j = 0; j < rooms.size(); j++) {
  280. if (rooms.get(j).getId() == i) {
  281. return rooms.get(j);
  282. }
  283. }
  284. return null;
  285. }
  286. public Item getItemById(int i) {
  287. for (int j = 0; j < items.size(); j++) {
  288. if (items.get(j).getId() == i) {
  289. return items.get(j);
  290. }
  291. }
  292. return null;
  293. }
  294. public Puzzle getPuzzleById(int i) {
  295. for (int j = 0; j < puzzles.size(); j++) {
  296. if (puzzles.get(j).getId() == i) {
  297. return puzzles.get(j);
  298. }
  299. }
  300. return null;
  301. }
  302. public void log(String s) throws Exception {
  303. String url = "https://medinf.efi.th-nuernberg.de/tomcat/WebAdventure/Log";
  304. URL obj = new URL(url);
  305. HttpURLConnection httpConn = (HttpURLConnection) obj.openConnection();
  306. //add reuqest header
  307. httpConn.setRequestMethod("POST");
  308. httpConn.setRequestProperty("User-Agent", "Mozilla/5.0");
  309. httpConn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  310. // Send post request
  311. httpConn.setDoOutput(true);
  312. try (DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream())) {
  313. String urlParameters = "log=" + s;
  314. wr.writeBytes(urlParameters);
  315. wr.flush();
  316. }
  317. BufferedReader in = new BufferedReader(
  318. new InputStreamReader(httpConn.getInputStream()));
  319. String inputLine;
  320. StringBuffer response = new StringBuffer();
  321. while ((inputLine = in.readLine()) != null) {
  322. response.append(inputLine);
  323. }
  324. in.close();
  325. }
  326. public void lookaround() throws Exception {
  327. log("lookaround()");
  328. say(currentRoom.getDescription());
  329. }
  330. public void startGame() throws Exception {
  331. log("startGame()");
  332. for (int i = 0; i < story.size(); i++) {
  333. say(story.get(i));
  334. }
  335. }
  336. public void resetGame() throws Exception {
  337. log("resetGame()");
  338. startGame();
  339. }
  340. public void inspect(Puzzle currentPuzzle) throws Exception {
  341. log("inspect(" + currentPuzzle.getName() + ")");
  342. for (int i = 0; i < currentRoom.getItems().size(); i++) {
  343. if (Objects.equals(currentRoom.getPuzzles().get(i), currentPuzzle.getId())) {
  344. say(currentPuzzle.getDescription());
  345. }
  346. }
  347. }
  348. public void inspect(Item currentItem) throws Exception {
  349. log("inspect(" + currentItem.getName() + ")");
  350. for (int i = 0; i < currentRoom.getItems().size(); i++) {
  351. if (Objects.equals(currentRoom.getItems().get(i), currentItem.getId())) {
  352. say(currentItem.getDescription());
  353. }
  354. }
  355. }
  356. public void endGame() throws Exception {
  357. log("endGame()");
  358. say("Glückwunsch das Spiel ist beendet!");
  359. setVariables();
  360. }
  361. public void sendPost(String s) throws Exception {
  362. s = s.replace(" ", "%20");
  363. String url = "https://medinf.efi.th-nuernberg.de/tomcat/WebAdventure/IO";
  364. URL obj = new URL(url);
  365. HttpURLConnection httpConn = (HttpURLConnection) obj.openConnection();
  366. //add reuqest header
  367. httpConn.setRequestMethod("POST");
  368. httpConn.setRequestProperty("User-Agent", "Mozilla/5.0");
  369. httpConn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  370. // Send post request
  371. httpConn.setDoOutput(true);
  372. DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
  373. String urlParameters = "alexaText=" + s;
  374. wr.writeBytes(urlParameters);
  375. wr.flush();
  376. wr.close();
  377. BufferedReader in = new BufferedReader(
  378. new InputStreamReader(httpConn.getInputStream()));
  379. String inputLine;
  380. StringBuffer response = new StringBuffer();
  381. while ((inputLine = in.readLine()) != null) {
  382. response.append(inputLine);
  383. }
  384. in.close();
  385. }
  386. public void say(String s) throws Exception {
  387. log("say(" + s + ")");
  388. try {
  389. sendPost(s);
  390. } catch (Exception ex) {
  391. Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
  392. }
  393. }
  394. public void setInput(String s) throws Exception {
  395. log("setInput(" + s + ")");
  396. input = s;
  397. }
  398. public void setRoom(Room nextRoom) throws Exception {
  399. log("setRoom(" + nextRoom.getName() + ")");
  400. currentRoom = nextRoom;
  401. say(currentRoom.getDescription());
  402. }
  403. public void examine() throws Exception {
  404. log("examine() : " + getInventory());
  405. if (getInventory().isEmpty()) {
  406. say("Deine Taschen sind leer");
  407. } else if (inventory.size() >= 1) {
  408. say("In deinen Taschen befindet sich: ");
  409. }
  410. inventory.forEach((bag) -> {
  411. try {
  412. say(bag.getName());
  413. } catch (Exception ex) {
  414. Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
  415. }
  416. });
  417. }
  418. public void open(Puzzle currentPuzzle) throws Exception {
  419. log("open(" + currentPuzzle.getName() + ") ");
  420. if (currentPuzzle.isSolved()) // bereits gelöst
  421. {
  422. say("ist bereits geöffnet");
  423. if (currentPuzzle.getNextRoom() != null) // wenn es eine Tür ist die in den nächsten Raum führt
  424. {
  425. setRoom(getRoomById(currentPuzzle.getNextRoom())); // wechselt in den nächsten Raum
  426. }
  427. return;
  428. }
  429. if (!currentPuzzle.hasDependency() || getPuzzleById(currentPuzzle.getDependency()).isSolved()) // ist keine Abhängigkeit vorhanden oder aber die Abhängigkeit ist gelöst
  430. {
  431. if (currentPuzzle.getItems().isEmpty() || checkPuzzleItemsInInventory(currentPuzzle.getId())) // keine Items zum lösen notwendig oder alle Items zum lösen befinden sich im Inventar
  432. {
  433. currentPuzzle.setSolved(true); // auf gelöst setzen
  434. say(currentPuzzle.getSolvedText()); // Lösungstext
  435. if (currentRoom.getGameoverFlag() || currentPuzzle.getGameOverFlag()) // Wenn es das letzte Rätsel im Spiel war oder man vom Angreifer erwischt wurde
  436. {
  437. stoppFlag = true; // Spiel wird nun beendet
  438. }
  439. if (currentPuzzle.getNextRoom() != null) // wenn es eine Tür ist die in den nächsten Raum führt
  440. {
  441. setRoom(getRoomById(currentPuzzle.getNextRoom())); // wechselt in den nächsten Raum
  442. }
  443. } else // Item zum lösen fehlt
  444. {
  445. say("das geht leider nicht, da fehlt noch etwas");
  446. }
  447. }
  448. if (!getPuzzleById(currentPuzzle.getDependency()).isSolved()) // Abhängigkeit nicht gelöst
  449. {
  450. say(currentPuzzle.getDependencyText());
  451. }
  452. }
  453. public void take(Item currentItem) throws Exception {
  454. log("take(" + currentItem.getName() + ") ");
  455. if ((!inventory.contains(currentItem)) && (currentItem.isPortableFlag() == true)) {
  456. inventory.add(currentItem);
  457. currentRoom.items.remove(currentItem);
  458. say(currentItem.getName() + " wurde deiner Tasche hinzugefuegt");
  459. } else if (currentItem.isPortableFlag() == false) {
  460. say("Das Item kann nicht mitgenommen werden");
  461. } else {
  462. say("Das Item befindet sich bereits in deiner Tasche!");
  463. }
  464. }
  465. public boolean checkPuzzleItemsInInventory(int puzzleId) {
  466. Puzzle p = getPuzzleById(puzzleId);
  467. for (int i = 0; i < p.getItems().size(); i++) {
  468. if (inventory.contains(getItemById(p.getItems().get(i)))) {
  469. } else {
  470. return false;
  471. }
  472. }
  473. return true;
  474. }
  475. public ArrayList<Item> getInventory() {
  476. return inventory;
  477. }
  478. }