Advertisement
Guest User

Untitled

a guest
Mar 7th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 26.64 KB | None | 0 0
  1.  
  2. /* This is the driving engine of the program. It parses the command-line
  3.  * arguments and calls the appropriate methods in the other classes.
  4.  *
  5.  * You should edit this file in three ways:
  6.  * 1) Insert your database username and password in the proper places.
  7.  * 2) Implement the generation of the world by reading the world file.
  8.  * 3) Implement the three functions showPossibleMoves, showPlayerAssets
  9.  *    and showScores.
  10.  */
  11. import java.math.BigDecimal;
  12. import java.net.URL;
  13. import java.sql.*; // JDBC stuff.
  14. import java.util.Calendar;
  15. import java.util.Map;
  16. import java.util.Properties;
  17. import java.io.*;  // Reading user input.
  18. import java.util.ArrayList;
  19. import java.util.concurrent.Executor;
  20. import java.util.*;
  21.  
  22. public class GameCopy
  23. {
  24.     public class Player
  25.     {
  26.         String playername;
  27.         String personnummer;
  28.         String country;
  29.         private String startingArea;
  30.  
  31.         public Player (String name, String nr, String cntry, String startingArea) {
  32.             this.playername = name;
  33.             this.personnummer = nr;
  34.             this.country = cntry;
  35.             this.startingArea = startingArea;
  36.         }
  37.     }
  38.  
  39.     String USERNAME = "USERNAME";
  40.     String PASSWORD = "PASSWORD";
  41.  
  42.     /* Print command optionssetup.
  43.     * /!\ you don't need to change this function! */
  44.     public void optionssetup() {
  45.         System.out.println();
  46.         System.out.println("Setup-Options:");
  47.         System.out.println("        n[ew player] <player name> <personnummer> <country>");
  48.         System.out.println("        d[one]");
  49.         System.out.println();
  50.     }
  51.  
  52.     /* Print command options.
  53.     * /!\ you don't need to change this function! */
  54.     public void options() {
  55.         System.out.println("\nOptions:");
  56.         System.out.println("    n[ext moves] [area name] [area country]");
  57.         System.out.println("    l[ist properties] [player number] [player country]");
  58.         System.out.println("    s[cores]");
  59.         System.out.println("    r[efund] <area1 name> <area1 country> [area2 name] [area2 country]");
  60.         System.out.println("    b[uy] [name] <area1 name> <area1 country> [area2 name] [area2 country]");
  61.         System.out.println("    m[ove] <area1 name> <area1 country>");
  62.         System.out.println("    p[layers]");
  63.         System.out.println("    q[uit move]");
  64.         System.out.println("    [...] is optional\n");
  65.     }
  66.  
  67.     /* Given a town name, country and population, this function
  68.      * should try to insert an area and a town (and possibly also a country)
  69.      * for the given attributes.
  70.      */
  71.     void insertTown(Connection conn, String name, String country, String population) throws SQLException  {
  72.  
  73.    
  74.         /*  Check if the specified country exists in the "Countries"-table.
  75.             If it doesn't, insert it. Then insert the new area.
  76.         */ 
  77.         try {
  78.             String check = "select count(1) from Countries where name = '" + country + "'";
  79.             PreparedStatement ps = conn.prepareStatement(check);       
  80.             ResultSet rs = ps.executeQuery();
  81.             boolean recordFound = rs.next();
  82.            
  83.             //If the country didn't exist, insert it.
  84.             if  (!recordFound) {
  85.                 Statement st = conn.createStatement();
  86.                 st.executeUpdate("INSERT INTO Countries " +
  87.                     "VALUES ('"+country+"')");
  88.             }
  89.  
  90.             Statement st = conn.createStatement();
  91.             st.executeUpdate("INSERT INTO Areas " +
  92.                     "VALUES ('"+country+"', '"+name+"', '"+population+"')");
  93.            
  94.             st.executeUpdate("INSERT INTO Towns " +
  95.                     "VALUES ('"+country+"', '"+name+"')");
  96.  
  97.         } catch (Exception e) {
  98.             System.err.println("Got an exception in insertTown");
  99.             System.err.println(e.getMessage());
  100.  
  101.         }
  102.        
  103.     }
  104.  
  105.     /* Inserts a country */
  106.     void insertCountry(Connection conn, String country) throws SQLException {
  107.        
  108.  
  109.         /* Check that a specified country doesn't exists before inserting it */
  110.         int recordFound = 0;
  111.         try {
  112.             PreparedStatement ps = conn.prepareStatement("SELECT COUNT (name) FROM Countries WHERE name = (?);");
  113.             ps.setString(1, country);      
  114.             ResultSet rs = ps.executeQuery();
  115.            
  116.         while (rs.next()) {
  117.             recordFound = rs.getInt(1);
  118.             }
  119.         } catch  (SQLException se) {
  120.             System.err.println(se.getMessage());
  121.         }
  122.  
  123.         try {
  124.             if (recordFound < 1) {
  125.             PreparedStatement st = conn.prepareStatement("INSERT INTO Countries (name) VALUES (?);");  
  126.             st.setString(1, country);
  127.             st.executeUpdate();
  128.             }
  129.         } catch (SQLException se) {
  130.             System.out.println("Error in insertCountry");
  131.             System.out.println(se.getMessage());   
  132.         }
  133.     }
  134.  
  135.     /* Given a city name, country and population, this function
  136.      * should try to insert an area and a city (and possibly also a country)
  137.      * for the given attributes.
  138.      * The city visitbonus should be set to 0.
  139.      */
  140.     void insertCity(Connection conn, String name, String country, String population) throws SQLException {
  141.         /*  Check if the specified country exists in the "Countries"-table.
  142.             If it doesn't, insert it. Then insert the new area.
  143.         */
  144.         /* 
  145.         int recordFound = 0;
  146.         try {
  147.             String check = "select count(1) from Countries where name = '" + country + "'";
  148.             PreparedStatement ps = conn.prepareStatement(check);       
  149.             ResultSet rs = ps.executeQuery();
  150.            
  151.         while (rs.next()) {
  152.             recordFound = rs.getInt(1);
  153.             }
  154.         } catch  (SQLException se) {
  155.             System.err.println(recordFound);
  156.             System.err.println(se.getMessage());
  157.         }
  158.    
  159.         */
  160.  
  161.         try {
  162.             /*     
  163.             PreparedStatement st = conn.prepareStatement("INSERT INTO Countries (name) VALUES (?);");
  164.             st.setString(1, country);
  165.             st.executeUpdate();
  166.             */
  167.             insertCountry(conn, country);
  168.  
  169.         } catch (SQLException se) {
  170.                 System.err.println("Error inserting country in insertCity");
  171.                 System.err.println(se.getMessage());
  172.                 System.exit(2);
  173.         }
  174.  
  175.         try {
  176.             //Create a new area
  177.             Statement st = conn.createStatement();
  178.             st.executeUpdate("INSERT INTO Areas " +
  179.                     "VALUES ('"+country+"', '"+name+"', '"+population+"')");
  180.            
  181.             //Create a new city and set visitbonus to 0
  182.             st.executeUpdate("INSERT INTO Cities " +
  183.                     "VALUES ('"+country+"', '"+name+"', 0)");
  184.  
  185.         } catch (Exception e) {
  186.             System.err.println("Got an exception in insertCity");
  187.             System.err.println(e.getMessage());
  188.             System.exit(2);
  189.         }
  190.     }
  191.  
  192.     /* Given two areas, this function
  193.      * should try to insert a government owned road with tax 0
  194.      * between these two areas.
  195.      */
  196.     void insertRoad(Connection conn, String area1, String country1, String area2, String country2) throws SQLException {
  197.        
  198.         String emptyString = "";
  199.  
  200.         //ssn and name for the government is, as defined in the LabPM, "". 
  201.         try {
  202.             Statement st = conn.createStatement();
  203.             st.executeUpdate("INSERT INTO Roads " +
  204.                     "VALUES ('"+country1+"', '"+area1+"', '"+country2+"', '"+area2+"', '"+emptyString+"', '"+emptyString+"', 0)");
  205.  
  206.         } catch (Exception e) {
  207.             System.err.println("Got an exception in insertRoad");
  208.             System.err.println(e.getMessage());
  209.         }
  210.  
  211.     }
  212.  
  213.     /* Given a player, this function
  214.      * should return the area name of the player's current location.
  215.      */
  216.     String getCurrentArea(Connection conn, Player person) throws SQLException {
  217.         String name = person.playername;
  218.         Statement st = conn.createStatement();
  219.         ResultSet rs = st.executeQuery("SELECT locationArea FROM Persons WHERE name = '" + name + "'");
  220.         return rs.getString("name");
  221.     }
  222.  
  223.     /* Given a player, this function
  224.      * should return the country name of the player's current location.
  225.      */
  226.     String getCurrentCountry(Connection conn, Player person) throws SQLException {
  227.         String name = person.playername;
  228.         Statement st = conn.createStatement();
  229.         ResultSet rs = st.executeQuery("SELECT locationCountry FROM Persons WHERE name = '" + name + "'");
  230.         return rs.getString("name");
  231.     }
  232.  
  233.     /* Given a player, this function
  234.      * should try to insert a table entry in persons for this player
  235.      * and return 1 in case of a success and 0 otherwise.
  236.      * The location should be random and the budget should be 1000.
  237.      */
  238.     int createPlayer(Connection conn, Player person) throws SQLException {
  239.  
  240.         String name = person.playername;
  241.         String personNummer = person.personnummer;
  242.         String country = person.country;   
  243.         String startingArea = person.startingArea;
  244.  
  245.         Statement st = conn.createStatement(); 
  246.    
  247.         //Select a random country and area
  248.         String query = ("SELECT country, name FROM Areas ORDER BY RANDOM() LIMIT 1;");
  249.         ResultSet rs = st.executeQuery(query);
  250.    
  251.         String locationCountry = "", locationArea = "";
  252.    
  253.         while (rs.next()) {
  254.             locationCountry = rs.getString(1);
  255.             locationArea = rs.getString(2);
  256.         }
  257.            
  258.         /*Tries to insert the provided and randomized values in the database */
  259.         try {
  260.             Statement stmt = conn.createStatement();
  261.             stmt.executeUpdate("INSERT INTO Persons" +
  262.                     "VALUES ('"+country+"', '"+personNummer+"', '"+name+"', '"+locationCountry+"', '"+locationArea+"', '1000')");
  263.  
  264.         } catch (Exception e) {
  265.             System.err.println("Got an exception in insertRoad");
  266.             System.err.println(e.getMessage());
  267.             return 0;
  268.         }
  269.         return 1;
  270.  
  271.     }
  272.  
  273.     /* Given a player and an area name and country name, this function
  274.      * sould show all directly-reachable destinations for the player from the
  275.      * area from the arguments.
  276.      * The output should include area names, country names and the associated road-taxes
  277.      */
  278.     void getNextMoves(Connection conn, Player person, String area, String country) throws SQLException {
  279.         Statement st = conn.createStatement(); 
  280.        
  281.         String query = "SELECT tocountry, toarea, roadtax FROM Roads " +
  282.                         "WHERE fromcountry = '"+country+"' AND fromarea = '"+area+"'";
  283.         ResultSet rs = st.executeQuery(query); 
  284.        
  285.  
  286.         while(rs.next())
  287.         {
  288.             System.out.print("Reachable destinations - Area, Country, Roadtax ");
  289.             System.out.println("Area: " + (rs.getString(1)) + "Country: " +(rs.getString(2))+ " Roadtax: " +(rs.getString(3)) + ".");
  290.         }
  291.         rs.close();
  292.         st.close();
  293.     }
  294.  
  295.     /* Given a player, this function
  296.      * sould show all directly-reachable destinations for the player from
  297.      * the player's current location.
  298.      * The output should include area names, country names and the associated road-taxes
  299.      */
  300.     void getNextMoves(Connection conn, Player person) throws SQLException {
  301.         Statement st = conn.createStatement();
  302.  
  303.         /*Get the players location */
  304.         String pname = person.playername;
  305.         String nameQuery = "SELECT locationcountry, locationarea FROM Persons " +
  306.                             "WHERE name = '"+pname+"'";
  307.         ResultSet nameSet = st.executeQuery(nameQuery);
  308.         String locCountry = "";
  309.         String locArea = "";
  310.  
  311.         while(nameSet.next()) {
  312.             locCountry = nameSet.getString(1);
  313.             locArea    = nameSet.getString(2);
  314.         }
  315.         nameSet.close();
  316.  
  317.         /* Get that players reachable locations */
  318.         String locationQuery = "SELECT tocountry, toarea, roadtax FROM Roads " +
  319.                                 "WHERE fromcountry = '"+locCountry+"' " +
  320.                                 "AND fromarea = '"+locArea+"' ";
  321.         ResultSet locationSet = st.executeQuery(locationQuery);
  322.  
  323.         /* Print all reachable destinations */
  324.         while(locationSet.next()) {
  325.             System.out.println("Area: " + (locationSet.getString(1)) + "Country: " +(locationSet.getString(2))+ " Roadtax: " +(locationSet.getString(3)) + ".");
  326.         }
  327.         locationSet.close();
  328.         st.close();
  329.     }
  330.  
  331.     /* Given a personnummer and a country, this function
  332.      * should list all properties (roads and hotels) of the person
  333.      * that is identified by the tuple of personnummer and country.
  334.      */
  335.     void listProperties(Connection conn, String personnummer, String country) {
  336.  
  337.         try {
  338.             Statement st = conn.createStatement();
  339.    
  340.             /* Creates a string of the names of all hotels owned */
  341.             String hotelQuery = "SELECT name FROM Hotels WHERE ownercountry = '"+country+"' AND ownerpersonnummer = '"+personnummer+"'";
  342.             ResultSet hotelSet = st.executeQuery(hotelQuery);
  343.  
  344.             String ownedHotels = "";
  345.             while(hotelSet.next()) {
  346.                 ownedHotels = ownedHotels + "Owns hotel " + hotelSet.getString(1) + "\n";
  347.             }
  348.             hotelSet.close();
  349.    
  350.             /* Creates a string listing owned roads, identified by their start and endpoints */
  351.             String roadQuery = "SELECT fromcountry, fromarea, tocountry, toarea FROM Roads " +
  352.                                 "WHERE ownercountry = '"+country+"' AND ownerpersonnummer = '"+personnummer+"'";
  353.             ResultSet roadSet = st.executeQuery(roadQuery);
  354.             String ownedRoads = "";
  355.             while(roadSet.next()) {
  356.                 String fromCountry = roadSet.getString(1);
  357.                 String fromArea = roadSet.getString(2);
  358.                 String toCountry = roadSet.getString(3);
  359.                 String toArea = roadSet.getString(4);
  360.                 ownedRoads = ownedRoads + "Owns road between " + fromCountry + " , " + fromArea + " and " + toCountry + " , " + toArea + "\n";
  361.             }
  362.         } catch (Exception e) {
  363.             System.err.println("Got an exception in listProperties");
  364.         }
  365.     }
  366.  
  367.     /* Given a player, this function
  368.      * should list all properties of the player.
  369.      */
  370.     void listProperties(Connection conn, Player person) throws SQLException {
  371.         String ssn = person.personnummer;
  372.         String country = person.country;
  373.  
  374.         listProperties(conn, ssn, country);
  375.     }
  376.  
  377.     /* This function should print the budget, assets and refund values for all players.
  378.      */
  379.     void showScores(Connection conn) throws SQLException {
  380.            
  381.         Statement st = conn.createStatement();
  382.    
  383.         String query = "SELECT * FROM AssetSummary;";
  384.  
  385.         ResultSet rs = st.executeQuery(query); 
  386.         /* Print everything */
  387.         while (rs.next()) {
  388.             System.out.println(rs.getString(0) + " " + rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
  389.         }      
  390.        
  391.     }
  392.  
  393.     /* Given a player, a from area and a to area, this function
  394.      * should try to sell the road between these areas owned by the player
  395.      * and return 1 in case of a success and 0 otherwise.
  396.      */
  397.     int sellRoad(Connection conn, Player person, String area1, String country1, String area2, String country2) throws SQLException {
  398.    
  399.         String playerName = person.playername;
  400.         String SSN = person.personnummer;  
  401.         Statement st = conn.createStatement();     
  402.         /* Updates the given road, making the government the owner. */
  403.         String query = "UPDATE Roads " +
  404.             "SET ownerpersonnummer = ' ' , ownercountry = ' ' " +
  405.             "WHERE ownerpersonnummer = '"+SSN+"' AND fromcountry = '"+country1+"' " +
  406.             "AND fromarea = '"+area1+"' AND tocountry = '"+country2+"' " +
  407.             "AND toArea = '"+area2+"'; ";
  408.        
  409.         try {
  410.             st.executeUpdate(query);
  411.             }catch (SQLException se){
  412.                 return 0;
  413.             }  
  414.         return 1;
  415.     }
  416.  
  417.     /* Given a player and a city, this function
  418.      * should try to sell the hotel in this city owned by the player
  419.      * and return 1 in case of a success and 0 otherwise.
  420.      */
  421.     int sellHotel(Connection conn, Player person, String city, String country) throws SQLException {
  422.         String SSN = person.personnummer;
  423.         Statement st = conn.createStatement();
  424.  
  425.         /* "Destroys" the hotel, removing it from the table */
  426.         String query = "DELETE FROM Hotels WHERE "+
  427.                         "ownerpersonnummer = '"+SSN+"' AND locationcountry = '"+country+"' " +
  428.                         "AND locationname = '"+city+"';";
  429.        
  430.         try {
  431.             st.executeUpdate(query);
  432.         } catch (SQLException se) {
  433.             return 0;
  434.         }
  435.         return 1;
  436.     }
  437.  
  438.     /* Given a player, a from area and a to area, this function
  439.      * should try to buy a road between these areas owned by the player
  440.      * and return 1 in case of a success and 0 otherwise.
  441.      */
  442.     int buyRoad(Connection conn, Player person, String area1, String country1, String area2, String country2) throws SQLException {
  443.         /* Inserts a new road */
  444.         Statement st = conn.createStatement();
  445.         String ownercountry = person.country;
  446.         String ownerpersonnummer = person.personnummer;
  447.         String query = "INSERT INTO Roads VALUES ('"+country1+"', '"+area1+"', '"+country2+"', '"+area2+"', '"+country2+"', '"+ownercountry+"', '"+ownerpersonnummer+"', getval('roadtax'));";
  448.    
  449.         try {
  450.             st.executeUpdate(query);
  451.         } catch (SQLException se) {
  452.             System.out.println("Got an exception in buyRoad");
  453.             return 0;  
  454.         }
  455.         return 1;
  456.     }
  457.  
  458.     /* Given a player and a city, this function
  459.      * should try to buy a hotel in this city owned by the player
  460.      * and return 1 in case of a success and 0 otherwise.
  461.      */
  462.     int buyHotel(Connection conn, Player person, String name, String city, String country) throws SQLException {
  463.         Statement st = conn.createStatement();
  464.         String ownercountry = person.country;
  465.         String ownerpersonnummer = person.personnummer;
  466.        
  467.         String query = "INSERT INTO Hotels VALUES ( '"+name+"', '"+country+"', '"+city+"', '"+ownercountry+"', '"+ownerpersonnummer+"')";
  468.         /* Inserts a new hotel in a city */
  469.         try {
  470.             st.executeUpdate(query);
  471.         } catch (SQLException se) {
  472.             System.out.println("Got an exception in buyHotel");
  473.             return 0;
  474.         }
  475.         return 1;
  476.     }
  477.  
  478.     /* Given a player and a new location, this function
  479.      * should try to update the players location
  480.      * and return 1 in case of a success and 0 otherwise.
  481.      */
  482.     int changeLocation(Connection conn, Player person, String area, String country) throws SQLException {
  483.         String changeCountry = person.country;
  484.         String changePersonnummer = person.personnummer;
  485.  
  486.         Statement st = conn.createStatement();
  487.         String query = "UPDATE Persons SET locationcountry = '"+country+"', locationarea = '"+area+"' " +
  488.                         "WHERE personnummer = '"+changePersonnummer+"' AND country = '"+changeCountry+"';";
  489.  
  490.         try {
  491.             st.executeUpdate(query);
  492.  
  493.         } catch (SQLException se) {
  494.             System.out.println("Got an exception in changeLocation");
  495.             return 0;
  496.         }
  497.         return 1;
  498.     }
  499.  
  500.     /* This function should add the visitbonus of 1000 to a random city
  501.      */
  502.     void setVisitingBonus(Connection conn) throws SQLException {
  503.    
  504.         Statement st = conn.createStatement();
  505.         /*String query = "UPDATE Cities " +
  506.                         "SET visitbonus = 1000 " +
  507.                         "WHERE name = (SELECT name FROM CITIES " +
  508.                         "ORDER BY RANDOM()" +
  509.                         "LIMIT 1);"; */
  510.         String query = "(SELECT NAME FROM CITIES " +
  511.                         "ORDER BY RANDOM()" +
  512.                         "LIMIT 1);";
  513.  
  514.  
  515.         try {
  516.             st.executeQuery(query);
  517.         } catch (SQLException se) {
  518.             /* Terminate the session if an exception is thrown */
  519.             System.out.println(se.getMessage());
  520.             System.out.println("Got an exception in setVisitingBonus");
  521.             System.exit(0);
  522.         }
  523.     }
  524.  
  525.     /* This function should print the winner of the game based on the currently highest budget.
  526.      */
  527.     void announceWinner(Connection conn) throws SQLException {
  528.         Statement st = conn.createStatement();
  529.         String query = "SELECT * FROM Persons " +
  530.                         "WHERE name != ('The government') " +
  531.                         "ORDER BY budget DESC LIMIT (1);";
  532.  
  533.         try {
  534.             System.out.println("And the winner is.....");
  535.             st.executeQuery(query);
  536.         } catch (SQLException se) {
  537.             System.out.println("Got an exception in announceWinner");
  538.             System.exit(0);
  539.         }
  540.     }
  541.  
  542.     void play (String worldfile) throws IOException {
  543.  
  544.         // Read username and password from config.cfg
  545.         try {
  546.             BufferedReader nf = new BufferedReader(new FileReader("config.cfg"));
  547.             String line;
  548.             if ((line = nf.readLine()) != null) {
  549.                 USERNAME = line;
  550.             }
  551.             if ((line = nf.readLine()) != null) {
  552.                 PASSWORD = line;
  553.             }
  554.         } catch (Exception e) {
  555.             System.out.println(e.getMessage());
  556.         }
  557.  
  558.         if (USERNAME.equals("USERNAME") || PASSWORD.equals("PASSWORD")) {
  559.             System.out.println("CONFIG FILE HAS WRONG FORMAT");
  560.             return;
  561.         }
  562.  
  563.         try {
  564.             try {
  565.                 Class.forName("org.postgresql.Driver");
  566.             } catch (Exception e) {
  567.                 System.out.println(e.getMessage());
  568.             }
  569.             String url = "jdbc:postgresql://ate.ita.chalmers.se/";
  570.             Properties props = new Properties();
  571.             props.setProperty("user",USERNAME);
  572.             props.setProperty("password",PASSWORD);
  573.  
  574.             final Connection conn = DriverManager.getConnection(url, props);
  575.             System.out.println("Managed to connect");
  576.  
  577.             /* This block creates the government entry and the necessary
  578.              * country and area for that.
  579.              */
  580.             try {
  581.                 PreparedStatement statement = conn.prepareStatement("INSERT INTO Countries (name) VALUES (?)");
  582.                 statement.setString(1, "");
  583.                 statement.executeUpdate();
  584.                 statement = conn.prepareStatement("INSERT INTO Areas (country, name, population) VALUES (?, ?, cast(? as INT))");
  585.                 statement.setString(1, "");
  586.                 statement.setString(2, "");
  587.                 statement.setString(3, "1");
  588.                 statement.executeUpdate();
  589.                 statement = conn.prepareStatement("INSERT INTO Persons (country, personnummer, name, locationcountry, locationarea, budget) VALUES (?, ?, ?, ?, ?, cast(? as NUMERIC))");
  590.                 statement.setString(1, "");
  591.                 statement.setString(2, "");
  592.                 statement.setString(3, "Government");
  593.                 statement.setString(4, "");
  594.                 statement.setString(5, "");
  595.                 statement.setString(6, "0");
  596.                 statement.executeUpdate();
  597.             } catch (SQLException e) {
  598.                 System.out.println(e.getMessage());
  599.             }
  600.  
  601.             // Initialize the database from the worldfile
  602.             try {
  603.                 BufferedReader br = new BufferedReader(new FileReader(worldfile));
  604.                 String line;
  605.                 while ((line = br.readLine()) != null) {
  606.                 String[] cmd = line.split(" +");
  607.                     if ("ROAD".equals(cmd[0]) && (cmd.length == 5)) {
  608.                         insertRoad(conn, cmd[1], cmd[2], cmd[3], cmd[4]);
  609.                     } else if ("TOWN".equals(cmd[0]) && (cmd.length == 4)) {
  610.                         /* Create an area and a town entry in the database */
  611.                         insertTown(conn, cmd[1], cmd[2], cmd[3]);
  612.                     } else if ("CITY".equals(cmd[0]) && (cmd.length == 4)) {
  613.                         /* Create an area and a city entry in the database */
  614.                         insertCity(conn, cmd[1], cmd[2], cmd[3]);
  615.                     }
  616.                 }
  617.             } catch (Exception e) {
  618.                 System.out.println(e.getMessage());
  619.             }
  620.  
  621.             ArrayList<Player> players = new ArrayList<Player>();
  622.  
  623.             while(true) {
  624.                 optionssetup();
  625.                 String mode = readLine("? > ");
  626.                 String[] cmd = mode.split(" +");
  627.                 cmd[0] = cmd[0].toLowerCase();
  628.                 if ("new player".startsWith(cmd[0]) && (cmd.length == 5)) {
  629.                     Player nextplayer = new Player(cmd[1], cmd[2], cmd[3], cmd[4]);
  630.                     if (createPlayer(conn, nextplayer) == 1) {
  631.                         players.add(nextplayer);
  632.                     }
  633.                 } else if ("done".startsWith(cmd[0]) && (cmd.length == 1)) {
  634.                     break;
  635.                 } else {
  636.                     System.out.println("\nInvalid option.");
  637.                 }
  638.             }
  639.  
  640.             System.out.println("\nGL HF!");
  641.             int roundcounter = 1;
  642.             int maxrounds = 5;
  643.             while(roundcounter <= maxrounds) {
  644.                 System.out.println("\nWe are starting the " + roundcounter + ". round!!!");
  645.                 /* for each player from the playerlist */
  646.                 for (int i = 0; i < players.size(); ++i) {
  647.                     System.out.println("\nIt's your turn " + players.get(i).playername + "!");
  648.                     System.out.println("You are currently located in " + getCurrentArea(conn, players.get(i)) + " (" + getCurrentCountry(conn, players.get(i)) + ")");
  649.                     while (true) {
  650.                         options();
  651.                         String mode = readLine("? > ");
  652.                         String[] cmd = mode.split(" +");
  653.                         cmd[0] = cmd[0].toLowerCase();
  654.                         if ("next moves".startsWith(cmd[0]) && (cmd.length == 1 || cmd.length == 3)) {
  655.                             /* Show next moves from a location or current location. Turn continues. */
  656.                             if (cmd.length == 1) {
  657.                                 String area = getCurrentArea(conn, players.get(i));
  658.                                 String country = getCurrentCountry(conn, players.get(i));
  659.                                 getNextMoves(conn, players.get(i));
  660.                             } else {
  661.                                 getNextMoves(conn, players.get(i), cmd[1], cmd[2]);
  662.                             }
  663.                         } else if ("list properties".startsWith(cmd[0]) && (cmd.length == 1 || cmd.length == 3)) {
  664.                             /* List properties of a player. Can be a specified player
  665.                                or the player himself. Turn continues. */
  666.                             if (cmd.length == 1) {
  667.                                 listProperties(conn, players.get(i));
  668.                             } else {
  669.                                 listProperties(conn, cmd[1], cmd[2]);
  670.                             }
  671.                         } else if ("scores".startsWith(cmd[0]) && cmd.length == 1) {
  672.                             /* Show scores for all players. Turn continues. */
  673.                             showScores(conn);
  674.                         } else if ("players".startsWith(cmd[0]) && cmd.length == 1) {
  675.                             /* Show scores for all players. Turn continues. */
  676.                             System.out.println("\nPlayers:");
  677.                             for (int k = 0; k < players.size(); ++k) {
  678.                                 System.out.println("\t" + players.get(k).playername + ": " + players.get(k).personnummer + " (" + players.get(k).country + ") ");
  679.                             }
  680.                         } else if ("refund".startsWith(cmd[0]) && (cmd.length == 3 || cmd.length == 5)) {
  681.                             if (cmd.length == 5) {
  682.                                 /* Sell road from arguments. If no road was sold the turn
  683.                                    continues. Otherwise the turn ends. */
  684.                                 if (sellRoad(conn, players.get(i), cmd[1], cmd[2], cmd[3], cmd[4]) == 1) {
  685.                                     break;
  686.                                 } else {
  687.                                     System.out.println("\nTry something else.");
  688.                                 }
  689.                             } else {
  690.                                 /* Sell hotel from arguments. If no hotel was sold the turn
  691.                                    continues. Otherwise the turn ends. */
  692.                                 if (sellHotel(conn, players.get(i), cmd[1], cmd[2]) == 1) {
  693.                                     break;
  694.                                 } else {
  695.                                     System.out.println("\nTry something else.");
  696.                                 }
  697.                             }
  698.                         } else if ("buy".startsWith(cmd[0]) && (cmd.length == 4 || cmd.length == 5)) {
  699.                             if (cmd.length == 5) {
  700.                                 /* Buy road from arguments. If no road was bought the turn
  701.                                    continues. Otherwise the turn ends. */
  702.                                 if (buyRoad(conn, players.get(i), cmd[1], cmd[2], cmd[3], cmd[4]) == 1) {
  703.                                     break;
  704.                                 } else {
  705.                                     System.out.println("\nTry something else.");
  706.                                 }
  707.                             } else {
  708.                                 /* Buy hotel from arguments. If no hotel was bought the turn
  709.                                    continues. Otherwise the turn ends. */
  710.                                 if (buyHotel(conn, players.get(i), cmd[1], cmd[2], cmd[3]) == 1) {
  711.                                     break;
  712.                                 } else {
  713.                                     System.out.println("\nTry something else.");
  714.                                 }
  715.                             }
  716.                         } else if ("move".startsWith(cmd[0]) && cmd.length == 3) {
  717.                             /* Change the location of the player to the area from the arguments.
  718.                                If the move was legal the turn ends. Otherwise the turn continues. */
  719.                             if (changeLocation(conn, players.get(i), cmd[1], cmd[2]) == 1) {
  720.                                 break;
  721.                             } else {
  722.                                 System.out.println("\nTry something else.");
  723.                             }
  724.                         } else if ("quit".startsWith(cmd[0]) && cmd.length == 1) {
  725.                             /* End the move of the player without any action */
  726.                             break;
  727.                         } else {
  728.                             System.out.println("\nYou chose an invalid option. Try again.");
  729.                         }
  730.                     }
  731.                 }
  732.                 setVisitingBonus(conn);
  733.                 ++roundcounter;
  734.             }
  735.             announceWinner(conn);
  736.             System.out.println("\nGG!\n");
  737.  
  738.         } catch (SQLException e) {
  739.             System.err.println(e);
  740.             System.exit(2);
  741.         }
  742.     }
  743.  
  744.     private String readLine(String s) throws IOException {
  745.         System.out.print(s);
  746.         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
  747.         char c;
  748.         StringBuilder stringBuilder = new StringBuilder();
  749.         do {
  750.             c = (char) bufferedReader.read();
  751.             stringBuilder.append(c);
  752.         } while(String.valueOf(c).matches(".")); // Without the DOTALL switch, the dot in a java regex matches all characters except newlines
  753.  
  754.         System.out.println("");
  755.         stringBuilder.deleteCharAt(stringBuilder.length()-1);
  756.  
  757.         return stringBuilder.toString();
  758.     }
  759.  
  760.     /* main: parses the input commands.
  761.     * /!\ You don't need to change this function! */
  762.     public static void main(String[] args) throws Exception
  763.     {
  764.         String worldfile = args[0];
  765.         GameCopy g = new GameCopy();
  766.         g.play(worldfile);
  767.     }
  768. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement