// Method that allows the user to create a new game in the database public void CreateGame( ScreenFrame frame, ServerConnection server, User currentUser, Parsers parser) { try { // Defining variables from typed values in the CreateScreen panel String gamename = frame.getCreate().getTfGameName().getText(); int mapSize = frame.getCreate().getTfMapSize(); String controls = frame.getCreate().getTfControls().getText(); // Checks whether the typed in values are legitimate // Strings controls and gamename can't be empty and the map size can't be 0 if (!controls.equals("") && mapSize != 0 && !gamename.equals("")) { // Creates objects of/instansialize Game and Gamer classes Game game = new Game(); Gamer gamer = new Gamer(); // Sets controls equal to the typed controls gamer.setControls(controls); // Sets id equal to the logged in user (the current user) gamer.setId(currentUser.getId()); // Sets the above defined id as the host of the game game.setHost(gamer); // Sets the gamename and mapsize equal to the typed values game.setName(gamename); game.setMapSize(mapSize); // All of the above setters are used to @post the variables into the database // String json = new Gson().toJson(game); String message = parser.createParser(server.post(json, "games/")); // Checks if the received list of games contains the newly created game // If so a confirmation will be shown to the user if (message.equals(game.getName())) { JOptionPane.showMessageDialog( frame, "Game was created!\nIt's called " + game.getName(), "Success!", JOptionPane.INFORMATION_MESSAGE); } } // Prints a stacktrace when catching an unforeseen error } catch (Exception e) { e.printStackTrace(); } }
@Override public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case "Cancel": screen.show("menu"); break; case "Create": Game startGame = new Game(); startGame.setName(screen.getStartGamePanel().getGameName()); startGame.setMapSize(25); Gamer opponent = new Gamer(); // For-loop kører brugerne igennem og viser dem i en comboBox // 1. if tjekker værdien af hvad der er valgt i comboBoxen og sammenligner med de brugere // som for-loopet kører igennem for (User u : users) { if (u.getUsername().equals(screen.getStartGamePanel().getSelectedUSer())) { opponent.setId(u.getId()); } } // If tjekker om hosten vil udfordre sig selv og giver fejlmeddelelse og ellers er spillet // oprettet. if (opponent.getId() == currentUser.getId()) { JOptionPane.showMessageDialog( screen, "Error: You need to choose a different opponent than yourself"); } else { Gamer host = new Gamer(); host.setId(currentUser.getId()); host.setControls(screen.getStartGamePanel().getControlsToSnake()); startGame.setHost(host); startGame.setOpponent(opponent); String message = api.createGame(startGame); JOptionPane.showMessageDialog(screen, message); screen.show("menu"); } break; } }