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

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