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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. import com.fasterxml.jackson.core.JsonParseException;
  2. import com.fasterxml.jackson.core.JsonParser;
  3. import com.fasterxml.jackson.core.type.TypeReference;
  4. import com.fasterxml.jackson.databind.JsonMappingException;
  5. import com.fasterxml.jackson.databind.ObjectMapper;
  6. import java.io.BufferedReader;
  7. import java.io.DataOutputStream;
  8. import java.io.File;
  9. import java.io.FileNotFoundException;
  10. import java.io.FileReader;
  11. import java.io.IOException;
  12. import java.io.InputStreamReader;
  13. import java.net.URL;
  14. import java.util.ArrayList;
  15. import java.util.logging.Level;
  16. import java.util.logging.Logger;
  17. import java.net.HttpURLConnection;
  18. import java.util.Arrays;
  19. import java.util.Map;
  20. import java.util.Objects;
  21. public class Game {
  22. private ArrayList<Room> rooms = new ArrayList<>();
  23. private ArrayList<Item> inventory = new ArrayList<>();
  24. private ArrayList<String> story = new ArrayList<>();
  25. private ArrayList<Item> items = new ArrayList<>();
  26. private ArrayList<Puzzle> puzzles = new ArrayList<>();
  27. private boolean stoppFlag = false;
  28. private Map<String, Object> jsonMap = null;
  29. private String[] inputArray = null;
  30. private Integer id = null;
  31. private String itemName = null;
  32. private String intentName = null;
  33. private String puzzleName = null;
  34. private String input = null;
  35. private Room currentRoom = null;
  36. public Game() {
  37. try {
  38. setVariables();
  39. } catch (Exception ex) {
  40. Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
  41. }
  42. }
  43. public Game(Integer i) {
  44. try {
  45. id = i;
  46. setVariables();
  47. } catch (Exception ex) {
  48. Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
  49. }
  50. }
  51. public Map<String, Object> readJSON() throws IOException, Exception {
  52. //TODO: Define path!
  53. File file = new File("game.JSON");
  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, new TypeReference<Map<String, Object>>() {
  61. });
  62. } catch (JsonParseException e) {
  63. // TODO Auto-generated catch block
  64. } catch (JsonMappingException e) {
  65. // TODO Auto-generated catch block
  66. } catch (IOException e) {
  67. // TODO Auto-generated catch block
  68. }
  69. objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  70. String jsonStringItem = objectMapper.writeValueAsString(jsonMap.get("item"));
  71. String jsonStringStory = objectMapper.writeValueAsString(jsonMap.get("story"));
  72. String jsonStringPuzzle = objectMapper.writeValueAsString(jsonMap.get("puzzle"));
  73. String jsonStringRoom = objectMapper.writeValueAsString(jsonMap.get("room"));
  74. log("Story: " + jsonStringStory);
  75. String[] st = objectMapper.readValue(jsonStringStory, String[].class);
  76. log("Item: " + jsonStringItem);
  77. Item[] it = objectMapper.readValue(jsonStringItem, Item[].class);
  78. log("Puzzle: " + jsonStringPuzzle);
  79. Puzzle[] pu = objectMapper.readValue(jsonStringPuzzle, Puzzle[].class);
  80. log("Room: " + jsonStringRoom);
  81. Room[] ro = objectMapper.readValue(jsonStringRoom, Room[].class);
  82. rooms.addAll(Arrays.asList(ro));
  83. log("Rooms einlesen fertig");
  84. items.addAll(Arrays.asList(it));
  85. log("Items einlesen fertig");
  86. puzzles.addAll(Arrays.asList(pu));
  87. log("Puzzles einlesen fertig");
  88. story.addAll(Arrays.asList(st));
  89. log("Story einlesen fertig");
  90. return jsonMap;
  91. } catch (FileNotFoundException e1) {
  92. // TODO Auto-generated catch block
  93. }
  94. return null;
  95. }
  96. public void setVariables() throws Exception {
  97. readJSON();
  98. log("JSON einlesen beendet");
  99. currentRoom = rooms.get(0);
  100. log("Aktueller Raum: " + currentRoom.getName());
  101. stoppFlag = false;
  102. inventory = new ArrayList<>();
  103. }
  104. public String prepareInput(String s) {
  105. s = s.replace("ä", "ae");
  106. s = s.replace("ü", "ue");
  107. s = s.replace("ö", "oe");
  108. s = s.replace("ß", "ss");
  109. s = s.toLowerCase();
  110. return s;
  111. }
  112. public void play() throws Exception {
  113. log("play()");
  114. log("Input: " + input);
  115. input = prepareInput(input);
  116. if (input.contains(" ")) {
  117. inputArray = input.split(" ");
  118. for (String s : inputArray) {
  119. if (getItemByName(s) != null) {
  120. itemName = getItemByName(s).getName();
  121. log("itemName: " + itemName);
  122. } else if (getPuzzleByName(s) != null) {
  123. puzzleName = getPuzzleByName(s).getName();
  124. log("PuzzleName: " + puzzleName);
  125. } else {
  126. if (intentName == null) {
  127. intentName = s;
  128. log("intentName: " + intentName);
  129. }
  130. }
  131. }
  132. } else {
  133. intentName = input;
  134. log("intentName: " + intentName);
  135. }
  136. switch (intentName) {
  137. //intent
  138. case "lookaroundintent":
  139. log("Switch: LookAroundIntent");
  140. if (itemName == null && puzzleName == null) {
  141. lookaround();
  142. } else {
  143. say("ich kann mich nur in Räumen umschauen. Falls sie Gegenstände untersuchen wollen, sagen dessen Namen und untersuchen");
  144. }
  145. break;
  146. //intent
  147. case "inspectintent":
  148. log("Switch: InspectIntent");
  149. if (itemName != null) {
  150. inspect(getItemByName(itemName));
  151. } else if (puzzleName != null) {
  152. inspect(getPuzzleByName(puzzleName));
  153. }
  154. break;
  155. //intent
  156. case "examineintent":
  157. log("Switch: ExamineIntent");
  158. if (itemName == null && puzzleName == null) {
  159. examine();
  160. } else {
  161. say("Wenn ich meine Taschen durchsuchen soll dann sagen sie Taschen durchsuchen.");
  162. }
  163. break;
  164. //intent
  165. case "takeintent":
  166. log("Switch: TakeIntent");
  167. if (itemName != null) {
  168. take(getItemByName(itemName));
  169. } else {
  170. say("Ich kann diesen Gegenstand nicht finden");
  171. }
  172. break;
  173. //intent
  174. case "openintent":
  175. log("Switch: OpenIntent");
  176. if (puzzleName != null) {
  177. open(getPuzzleByName(puzzleName));
  178. } else {
  179. say("Könnten Sie das wiederholen? Ich habe das leider nicht verstanden.");
  180. }
  181. break;
  182. //intent
  183. case "resetintent":
  184. log("Switch: ResetIntent");
  185. if (itemName == null && puzzleName == null) {
  186. resetGame();
  187. } else {
  188. say("das habe ich leider nicht verstanden, wiederholen sie das bitte?");
  189. }
  190. break;
  191. //intent
  192. case "skipintent":
  193. log("Switch: SkipIntent");
  194. if (itemName == null && puzzleName == null) {
  195. resetGame();
  196. for (int i = 0; i < currentRoom.puzzles.size(); i++) {
  197. if (getPuzzleById(currentRoom.puzzles.get(i)).getNextRoom() != null) {
  198. setRoom(getRoomById(getPuzzleById(currentRoom.puzzles.get(i)).getNextRoom()));
  199. }
  200. }
  201. } else {
  202. say("leider habe ich das nicht verstanden.können sie das wiederholen?");
  203. }
  204. break;
  205. case "resumeintent":
  206. log("Switch: ResumeIntent");
  207. break;
  208. case "startintent":
  209. log("Switch: StartIntent");
  210. startGame();
  211. break;
  212. default:
  213. log("Switch: Intent nicht vorhanden");
  214. say("Das habe ich leider nicht verstanden, könnten Sie das wiederholen?");
  215. break;
  216. }
  217. itemName = null;
  218. intentName = null;
  219. puzzleName = null;
  220. if (stoppFlag == true) {
  221. endGame();
  222. }
  223. }
  224. public Item getItemByName(String s) throws Exception {
  225. for (int i = 0; i < currentRoom.items.size(); i++) {
  226. String n = getItemById(currentRoom.items.get(i)).getName().toLowerCase();
  227. if (n.equals(s.toLowerCase())) {
  228. return getItemById(currentRoom.items.get(i));
  229. }
  230. }
  231. return null;
  232. }
  233. public Puzzle getPuzzleByName(String s) throws Exception {
  234. for (int i = 0; i < currentRoom.puzzles.size(); i++) {
  235. String n = getPuzzleById(currentRoom.puzzles.get(i)).getName().toLowerCase();
  236. if (n.equals(s.toLowerCase())) {
  237. return getPuzzleById(currentRoom.puzzles.get(i));
  238. }
  239. }
  240. return null;
  241. }
  242. public Room getRoomById(Integer i) {
  243. for (int j = 0; j < rooms.size(); j++) {
  244. if (rooms.get(j).getId() == i) {
  245. return rooms.get(j);
  246. }
  247. }
  248. return null;
  249. }
  250. public Item getItemById(Integer i) {
  251. for (int j = 0; j < items.size(); j++) {
  252. if (items.get(j).getId() == i) {
  253. return items.get(j);
  254. }
  255. }
  256. return null;
  257. }
  258. public Puzzle getPuzzleById(Integer i) {
  259. for (int j = 0; j < puzzles.size(); j++) {
  260. if (puzzles.get(j).getId() == i) {
  261. return puzzles.get(j);
  262. }
  263. }
  264. return null;
  265. }
  266. public void log(String s) throws Exception {
  267. String url = "https://medinf.efi.th-nuernberg.de/tomcat/WebAdventure/Log";
  268. URL obj = new URL(url);
  269. HttpURLConnection httpConn = (HttpURLConnection) obj.openConnection();
  270. //add reuqest header
  271. httpConn.setRequestMethod("POST");
  272. httpConn.setRequestProperty("User-Agent", "Mozilla/5.0");
  273. httpConn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  274. // Send post request
  275. httpConn.setDoOutput(true);
  276. try (DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream())) {
  277. String urlParameters = "log=" + s;
  278. wr.writeBytes(urlParameters);
  279. wr.flush();
  280. }
  281. BufferedReader in = new BufferedReader(
  282. new InputStreamReader(httpConn.getInputStream()));
  283. String inputLine;
  284. StringBuffer response = new StringBuffer();
  285. while ((inputLine = in.readLine()) != null) {
  286. response.append(inputLine);
  287. }
  288. in.close();
  289. }
  290. public void lookaround() throws Exception {
  291. log("lookaround()");
  292. say(currentRoom.getDescription() + ".");
  293. }
  294. public Integer getId() {
  295. return id;
  296. }
  297. public void setId(Integer i) {
  298. id = i;
  299. }
  300. public void startGame() throws Exception {
  301. log("startGame()" + ".");
  302. say(story.get(0));
  303. }
  304. public void resetGame() throws Exception {
  305. log("resetGame()");
  306. setVariables();
  307. startGame();
  308. }
  309. public void inspect(Puzzle currentPuzzle) throws Exception {
  310. log("inspect(" + currentPuzzle.getName() + ")");
  311. for (int i = 0; i < currentRoom.getItems().size(); i++) {
  312. if (Objects.equals(currentRoom.getPuzzles().get(i), currentPuzzle.getId())) {
  313. say(currentPuzzle.getDescription() + ".");
  314. return;
  315. } else {
  316. say("");
  317. };
  318. }
  319. }
  320. public void inspect(Item currentItem) throws Exception {
  321. log("inspect(" + currentItem.getName() + ")");
  322. for (int i = 0; i < currentRoom.getItems().size(); i++) {
  323. if (Objects.equals(currentRoom.getItems().get(i), currentItem.getId())) {
  324. say(currentItem.getDescription());
  325. return;
  326. } else {
  327. say("");
  328. };
  329. }
  330. }
  331. public void endGame() throws Exception {
  332. log("endGame()");
  333. say("Glückwunsch der Durchlauf ist beendet! Das Spiel starte nun von vorne.");
  334. setVariables();
  335. }
  336. public void sendPost(String s) throws Exception {
  337. s = s.replace(" ", "%20");
  338. String url = "https://medinf.efi.th-nuernberg.de/tomcat/WebAdventure/IO";
  339. URL obj = new URL(url);
  340. HttpURLConnection httpConn = (HttpURLConnection) obj.openConnection();
  341. //add reuqest header
  342. httpConn.setRequestMethod("POST");
  343. httpConn.setRequestProperty("User-Agent", "Mozilla/5.0");
  344. httpConn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  345. // Send post request
  346. httpConn.setDoOutput(true);
  347. DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
  348. String urlParameters = "alexaText=" + s;
  349. wr.writeBytes(urlParameters);
  350. wr.flush();
  351. wr.close();
  352. BufferedReader in = new BufferedReader(
  353. new InputStreamReader(httpConn.getInputStream()));
  354. String inputLine;
  355. StringBuffer response = new StringBuffer();
  356. while ((inputLine = in.readLine()) != null) {
  357. response.append(inputLine);
  358. }
  359. in.close();
  360. }
  361. public void say(String s) throws Exception {
  362. log("say(" + s + ")");
  363. try {
  364. sendPost(s);
  365. } catch (Exception ex) {
  366. Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
  367. }
  368. }
  369. public void setInput(String s) throws Exception {
  370. log("setInput(" + s + ")");
  371. input = s;
  372. }
  373. public void setRoom(Room nextRoom) throws Exception {
  374. log("setRoom(" + nextRoom.getName() + ")");
  375. currentRoom = nextRoom;
  376. }
  377. public void examine() throws Exception {
  378. log("examine() : " + getInventory());
  379. if (getInventory().isEmpty()) {
  380. say("Deine Taschen sind leer.");
  381. } else if (inventory.size() >= 1) {
  382. say("In deinen Taschen befindet sich: ");
  383. }
  384. inventory.forEach((bag) -> {
  385. try {
  386. say(bag.getName() + ".");
  387. } catch (Exception ex) {
  388. Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
  389. }
  390. });
  391. }
  392. public void open(Puzzle currentPuzzle) throws Exception {
  393. log("open(" + currentPuzzle.getName() + ") ");
  394. log("Puzzle gelöst?: " + currentPuzzle.isSolved());
  395. if (currentPuzzle.isSolved()) // bereits gelöst
  396. {
  397. log("Bereits gelöst: " + currentPuzzle.isSolved());
  398. say(currentPuzzle.getName() + "ist bereits geöffnet.");
  399. if (currentPuzzle.getNextRoom() != null) // wenn es eine Tür ist die in den nächsten Raum führt
  400. {
  401. say("Sie betreten den nächsten Raum.");
  402. log("nächster Raum: " + currentPuzzle.getNextRoom());
  403. setRoom(getRoomById(currentPuzzle.getNextRoom())); // wechselt in den nächsten Raum
  404. lookaround();
  405. }
  406. return;
  407. }
  408. log(" " + checkDependency(currentPuzzle));
  409. if (!checkDependency(currentPuzzle)) // ist keine Abhängigkeit vorhanden oder aber die Abhängigkeit ist gelöst
  410. {
  411. log("Abhängigkeit: " + currentPuzzle.hasDependency());
  412. log("" + checkPuzzleItemsInInventory(currentPuzzle) + "");
  413. if (checkPuzzleItemsInInventory(currentPuzzle)) // keine Items zum lösen notwendig oder alle Items zum lösen befinden sich im Inventar
  414. {
  415. say(currentPuzzle.getSolvedText()); // Lösungstext
  416. currentPuzzle.setSolved(true); // auf gelöst setzen
  417. if (checkGameOver(currentPuzzle)) // Wenn es das letzte Rätsel im Spiel war oder man vom Angreifer erwischt wurde
  418. {
  419. log("Gameover");
  420. stoppFlag = true; // Spiel wird nun beendet
  421. }
  422. if (currentPuzzle.getNextRoom() != null) // wenn es eine Tür ist die in den nächsten Raum führt
  423. {
  424. setRoom(getRoomById(currentPuzzle.getNextRoom())); // wechselt in den nächsten Raum
  425. log(currentRoom.getName() + " " + currentRoom.getDescription());
  426. lookaround();
  427. }
  428. } else // Item zum lösen fehlt
  429. {
  430. say("das geht leider nicht, hier fehlt noch etwas.");
  431. }
  432. }
  433. if (getPuzzleById(currentPuzzle.getDependency()) != null) {
  434. if (!getPuzzleById(currentPuzzle.getDependency()).isSolved()) // Abhängigkeit nicht gelöst
  435. {
  436. say(currentPuzzle.getDependencyText() + ".");
  437. }
  438. }
  439. }
  440. public boolean checkDependency(Puzzle currentPuzzle) {
  441. if (currentPuzzle.hasDependency()) {
  442. return true;
  443. }
  444. if (getPuzzleById(currentPuzzle.getDependency()) != null) {
  445. if (getPuzzleById(currentPuzzle.getDependency()).isSolved()) {
  446. return true;
  447. }
  448. }
  449. return false;
  450. }
  451. public boolean checkGameOver(Puzzle currentPuzzle) {
  452. if (currentRoom.getGameoverFlag() == true) {
  453. return true;
  454. }
  455. if (currentPuzzle.getGameOverFlag() == true) {
  456. return true;
  457. }
  458. return false;
  459. }
  460. public void take(Item currentItem) throws Exception {
  461. log("take(" + currentItem.getName() + ") ");
  462. if ((!inventory.contains(currentItem)) && (currentItem.isPortableFlag() == true)) {
  463. inventory.add(currentItem);
  464. currentRoom.items.remove(currentItem.getId());
  465. say(currentItem.getName() + " wurde deiner Tasche hinzugefuegt.");
  466. } else if (currentItem.isPortableFlag() == false) {
  467. say("Das Item kann nicht mitgenommen werden.");
  468. } else if (inventory.contains(currentItem)) {
  469. say("Das Item befindet sich bereits in deiner Tasche!");
  470. }
  471. }
  472. public boolean checkPuzzleItemsInInventory(Puzzle currentPuzzle) { // checkt ob ob alle Items benötigten Items im Inventar sind oder ob Items gebraucht werden
  473. if (currentPuzzle.getItems().isEmpty()) { // keine Items zum lösen notwendig
  474. return true;
  475. } else { // durchsucht ob alle nötigen Items im Inventar sind
  476. for (int i = 0; i < currentPuzzle.getItems().size(); i++) {
  477. if (inventory.contains(getItemById(currentPuzzle.getItems().get(i)))) {
  478. } else {
  479. return false;
  480. }
  481. }
  482. return true;
  483. }
  484. }
  485. public ArrayList<Item> getInventory() {
  486. return inventory;
  487. }
  488. }