Example #1
0
  public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ESCAPE && gamerunner.running) {

      Graphics gr = this.getGraphics();
      gr.setFont(new Font("TimesRoman", Font.PLAIN, 40));
      gr.drawString("PAUSE", (int) this.getWidth() / 2, this.getHeight() / 2);
      if (!online) {
        gamerunner.running = false;
      }
      if (soundan) {} // end of if
      Menu menu = new Menu(this);
      // volume.setValue(vol);
    } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
      gamerunner.running = true;
      if (soundan) {} // end of if
    } // end of if-else
    else if (e.getKeyCode() == KeyEvent.VK_R && !online) {
      restartGame();
    } else if (e.getKeyCode() == KeyEvent.VK_F11) {
      dispose();
      setUndecorated(true);
      String[] arguments = {"fullscreen"};
      new JavaGame(arguments);
    } else if (e.getKeyCode() == KeyEvent.VK_ENTER && online) {
      String message =
          JOptionPane.showInputDialog(null, "Chat", "Nachricht", JOptionPane.PLAIN_MESSAGE);
      try {
        if (!message.isEmpty()) {
          client.sendNewChatMessage(player[client.id].name, message);
        }
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
Example #2
0
  /** Setzt alle Spielparameter zurück und verteilt die Spieler entlang der Main-Ebene */
  public void restartGame() {
    for (int c = 1; c < player.length; c++) {
      if (player[c] != null) {
        player[c].x = (int) (Math.random() * (ebenen[0][1] - ebenen[0][0]) + ebenen[0][0]);
        player[c].y = 0;
        player[c].health = 100;
        player[c].jumpheigth = 200;
        player[c].speed = 5;
        player[c].sperrzeit = 40;
        player[c].freezeControls = false;
        gamerunner.neu = false;
        gamerunner.schonneu = true;
        player[c].amstartwarten = 42;
        player[c].perkzählerjump = -1;
        player[c].perkzählerrun = -1;
        player[c].perkzählershoot = -1;
        player[c].boomRight = 0;
        player[c].boomUp = 0;
        player[c].boomLeft = 0;
        gamerunner.wellenModus.wAnzeige = -1;
        gamerunner.wellenModus.wNeu = false;
        gamerunner.wellenModus.nNeu = false;
        gamerunner.storyModus.amanfang = true;
        gamerunner.wellenModus.amanfang = true;
      } // end of if
    } // end of for

    for (int c = 0; c < gamerunner.shot.length; c++) {
      gamerunner.shot[c] = null;
      DamageLogig.shot[c] = null;
    } // end of for
    DamageLogig.counter = 0;
  }
  public void levelUp() {
    try {
      int lastLevel = level;
      super.levelUp();
      if (lastLevel != level) {
        helth =
            (int) ((Math.pow(2.5, level - 1)) - Math.pow(2.0, level - 1) + (40 * level) + 40)
                - (maxHelth - helth);
        maxHelth =
            (int) ((Math.pow(2.5, level - 1)) - Math.pow(2.0, level - 1) + (40 * level) + 40);
        buildImages.clear();
        costs.clear();

        if (level >= 1) {
          MagicSpirit m = new MagicSpirit(null, null);
          m.level = level - 2;
          m.levelUp();
          buildImages.add(GameRunner.getMagicSpirit());
          costs.add(50);
          buildNames.add("Train " + m.firstName);

          Mage ma = new Mage(null, null);
          ma.level = level - 2;
          ma.levelUp();
          buildImages.add(GameRunner.getMage());
          costs.add(100);
          buildNames.add("Train " + ma.firstName);

          buildImages.add(ImageIO.read(new File("src/+1.png")));
          costs.add((int) (Math.pow(3.4, level) + (300 * level) + 196.6));
          buildNames.add("Level Up to gain better units");

          buildImages.add(GameRunner.getAutoMine());
          costs.add(0);
          buildNames.add("Automatically mine gold with any units that can this turn");
        }
        if (level >= 2) {
          Summoner s = new Summoner(null, null);
          buildImages.add(GameRunner.getSummoner());
          costs.add(100);
          buildNames.add("Train " + s.name + " to summon units into battle");
        }
        if (level >= 3) {
          ArchMage am = new ArchMage(null, null);
          am.level = level - 4;
          am.levelUp();
          buildImages.add(GameRunner.getArchMage());
          costs.add(300);
          buildNames.add("Train " + am.firstName);
        }
      }
    } catch (Exception e) {
      LogHandling.logError("Can't add image  " + e);
    }
  }
Example #4
0
 /** Get the root folder for the application */
 public static File getRootFolder() {
   // we know that the class file is in a directory one above the games root folder
   // so navigate up from the class file, and we have root.
   // find the url of our class
   final URL url = GameRunner2.class.getResource("GameRunner2.class");
   // we want to move up 1 directory for each
   // package
   final int moveUpCount = GameRunner2.class.getName().split("\\.").length + 1;
   String fileName = url.getFile();
   try {
     // deal with spaces in the file name which would be url encoded
     fileName = URLDecoder.decode(fileName, "UTF-8");
   } catch (final UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   final String tripleaJarName = "triplea.jar!";
   final String tripleaJarNameWithEngineVersion = getTripleaJarWithEngineVersionStringPath();
   // we are in a jar file
   if (fileName.indexOf(tripleaJarName) != -1) {
     final String subString =
         fileName.substring(
             "file:/".length() - (GameRunner.isWindows() ? 0 : 1),
             fileName.indexOf(tripleaJarName) - 1);
     final File f = new File(subString).getParentFile();
     if (!f.exists()) {
       throw new IllegalStateException("File not found:" + f);
     }
     return f;
   } else if (fileName.indexOf(tripleaJarNameWithEngineVersion) != -1) {
     final String subString =
         fileName.substring(
             "file:/".length() - (GameRunner.isWindows() ? 0 : 1),
             fileName.indexOf(tripleaJarNameWithEngineVersion) - 1);
     final File f = new File(subString).getParentFile();
     if (!f.exists()) {
       throw new IllegalStateException("File not found:" + f);
     }
     return f;
   } else {
     File f = new File(fileName);
     for (int i = 0; i < moveUpCount; i++) {
       f = f.getParentFile();
     }
     if (!f.exists()) {
       System.err.println("Could not find root folder, does  not exist:" + f);
       return new File(System.getProperties().getProperty("user.dir"));
     }
     return f;
   }
 }
 public void botBuild(int maxNum) {
   PlayerBot bot = (PlayerBot) GameRunner.getPlayerisTurn();
   boolean done = false;
   while (!done && maxNum > 0) {
     bot.setUnitNums();
     if (((float) bot.getUnitNums()[2]) < level) {
       if (level >= 2 && bot.gold >= costs.get(4)) {
         build(4);
       }
     }
     if (((float) bot.getUnitNums()[1]) / ((float) bot.getUnits().size())
         < (1.0f - bot.getAggressiveness())) {
       if (bot.gold >= costs.get(0)) {
         build(0);
       } else {
         done = true;
       }
     } else if (((float) bot.getUnitNums()[0]) / ((float) bot.getUnits().size())
         < bot.getAggressiveness()) {
       if (level >= 2 && bot.gold >= costs.get(4) && Math.random() <= .1f) {
         build(4);
       }
       if (level >= 3 && bot.gold >= costs.get(5) && Math.random() <= .7f) {
         build(5);
       } else if (bot.gold >= costs.get(1)) {
         build(1);
       } else {
         done = true;
       }
     }
     maxNum--;
   }
 }
 public static Unit load(ArrayList<String> data) {
   MagesTower m =
       new MagesTower(
           new Location(Integer.parseInt(data.get(4)), Integer.parseInt(data.get(5))),
           GameRunner.getMageTower());
   return m;
 }
Example #7
0
 /**
  * Our jar is named with engine number and we are in "old" folder.
  *
  * @return
  */
 public static boolean areWeOldExtraJar() {
   final URL url = GameRunner2.class.getResource("GameRunner2.class");
   String fileName = url.getFile();
   try {
     fileName = URLDecoder.decode(fileName, "UTF-8");
   } catch (final UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   final String tripleaJarNameWithEngineVersion = getTripleaJarWithEngineVersionStringPath();
   if (fileName.indexOf(tripleaJarNameWithEngineVersion) != -1) {
     final String subString =
         fileName.substring(
             "file:/".length() - (GameRunner.isWindows() ? 0 : 1),
             fileName.indexOf(tripleaJarNameWithEngineVersion) - 1);
     final File f = new File(subString);
     if (!f.exists()) {
       throw new IllegalStateException("File not found:" + f);
     }
     String path;
     try {
       path = f.getCanonicalPath();
     } catch (final IOException e) {
       path = f.getPath();
     }
     return path.indexOf("old") != -1;
   }
   return false;
 }
 @Test
 public void replaysUntilNo() {
   uiSpy.setMenuOptions("1", "3", "1", "3");
   uiSpy.setUserInputs(1, 4, 2, 5, 3, 1, 2, 3, 4, 5, 7, 6, 9, 8);
   uiSpy.setReplayAnswers(true, false);
   gameSetup.playGame(menu, playerCreator);
   assertTrue(uiSpy.replayWasCalled());
 }
 @Test
 public void printsWelcomeMessage() {
   uiSpy.setMenuOptions("1", "3");
   uiSpy.setUserInputs(1, 4, 2, 5, 3);
   uiSpy.setReplayAnswers(false);
   gameSetup.playGame(menu, playerCreator);
   assertTrue(uiSpy.printWelcomeMessageWasCalled());
 }
Example #10
0
 public static File getUserRootFolder() {
   final File userHome = new File(System.getProperties().getProperty("user.home"));
   // the default
   File rootDir;
   if (GameRunner.isMac()) rootDir = new File(new File(userHome, "Documents"), "triplea");
   else rootDir = new File(userHome, "triplea");
   return rootDir;
 }
Example #11
0
 /**
  * This calculateLocation method varies the location of the image and this occurs with the arrays;
  * the min.value and location are used.
  */
 public void calculateLocation() {
   try {
     if (location[3] != Integer.MIN_VALUE) {
       int[] frameLoc = GameRunner.getFrameLoc();
       location[2] = location[0] - frameLoc[0];
       location[3] = location[1] - frameLoc[1];
     }
   } catch (Exception e) {
     ErrorLogger.logError("Can't calculate object location " + e);
   }
 }
 @Override
 public void select() {
   super.select();
   // get autoMine amount
   int mineGold = 0;
   for (Unit u : GameRunner.getPlayerisTurn().getUnits()) {
     if (u.type.equals("Support Unit")) {
       mineGold += ((SupportUnit) u).getAutoMineGold();
     }
   }
   costs.set(3, -1 * mineGold);
 }
Example #13
0
  public Dialogue(Image speaker, String[] lines) {
    try {
      // name
      frame.setTitle(lines[0]);

      // size
      this.setPreferredSize(new Dimension(800, lines.length * 20));

      // location
      frame.setLocation(
          (int) ((GameRunner.getWidthHeight().getExactX() / 2) - 400),
          (int) ((GameRunner.getWidthHeight().getExactY() / 2) - lines.length * 20));

      this.image = speaker;
      this.lines = lines;
      frame.add(this);
      frame.setVisible(true);
      frame.pack();
      frame.repaint();
    } catch (Exception e) {
      LogHandling.logError("Can't show message..." + e);
    }
  }
Example #14
0
 public static String getDefaultLookAndFeel() {
   final Preferences pref = Preferences.userNodeForPackage(GameRunner2.class);
   String defaultLookAndFeel =
       "org.pushingpixels.substance.api.skin.SubstanceGraphiteLookAndFeel"; // substance 7.x
   // String defaultLookAndFeel = "org.jvnet.substance.skin.SubstanceRavenGraphiteLookAndFeel"; //
   // substance 5.x
   // macs are already beautiful
   if (GameRunner.isMac()) {
     defaultLookAndFeel = UIManager.getSystemLookAndFeelClassName();
   }
   final String userDefault = pref.get(LOOK_AND_FEEL_PREF, defaultLookAndFeel);
   final List<String> availableSkins = BasicGameMenuBar.getLookAndFeelAvailableList();
   if (!availableSkins.contains(userDefault)) {
     if (!availableSkins.contains(defaultLookAndFeel))
       return UIManager.getSystemLookAndFeelClassName();
     setDefaultLookAndFeel(defaultLookAndFeel);
     return defaultLookAndFeel;
   }
   return userDefault;
 }
  public void build(int build) {
    try {
      if (GameRunner.getPlayerisTurn().getGold() - costs.get(build) >= 0) {
        if (costs.get(build) > 0) GameRunner.getPlayerisTurn().addGold((-1) * costs.get(build));

        if (build == 0) {
          MagicSpirit s =
              new MagicSpirit(addLoc(location, false, true), GameRunner.getMagicSpirit());
          for (int i = 0; i < level - 1; i++) {
            s.levelUp();
          }
          GameRunner.getPlayerisTurn().addUnit(s);
        } else if (build == 1) {
          Mage s = new Mage(addLoc(location, false, true), GameRunner.getMage());
          for (int i = 0; i < level - 1; i++) {
            s.levelUp();
          }
          GameRunner.getPlayerisTurn().addUnit(s);
        } else if (build == 2) {
          GameRunner.getPlayerisTurn().levelUp();
          levelUp();
        } else if (build == 3) {
          for (Unit u : GameRunner.getPlayerisTurn().getUnits()) {
            if (u.type.equals("Support Unit")) {
              ((SupportUnit) u).autoMine();
            }
          }
        } else if (build == 4) {
          Summoner s = new Summoner(addLoc(location, false, true), GameRunner.getSummoner());
          GameRunner.getPlayerisTurn().addUnit(s);
        } else if (build == 5) {
          ArchMage n = new ArchMage(addLoc(location, false, true), GameRunner.getArchMage());
          for (int i = 0; i < level - 3; i++) {
            n.levelUp();
          }
          GameRunner.getPlayerisTurn().addUnit(n);
        }
      }
    } catch (Exception e) {
      LogHandling.logError("Can't add unit   " + e);
    }
  }
  public static void main(String[] args) throws IOException {
    double max_temp = 10.0; // The max temperature in the simulated annealing
    double cur_temp =
        max_temp; // The current temperature in the simulated annealing, initialized at the max temp
    // double step_size = .10;

    int sessions_at_cur_temp = 1; // The number of sessions to play at the current temperature.
    double stop_percent = 10; // The percentage value of the max_temp at which to stop.

    double heuristic_min = -100.0; //
    double heuristic_max = 100.0; // The max and min values passed to the AI constructor.

    GameRunner myRunner = new GameRunner(); // Initialize a GameRunner
    boolean Continue = true;

    int session_number = 0;

    FileWriter writer = new FileWriter("acceptance.csv");
    writer.write("Accepted\n");
    writer.flush();

    // BEGIN ANNEALING
    double[] current_heuristic = myRunner.generateParameters();
    double current_winrate = myRunner.playSession(current_heuristic);

    while (cur_temp > max_temp * stop_percent * 0.01
        && Continue) { // Stop the simulation when current temp is less than some percent of the
      // max_temp
      for (int i = 0; i < sessions_at_cur_temp; i++) { // For each session we play at current temp:
        double[] heuristic_prime =
            current_heuristic
                .clone(); // Clone the current heuristic into heuristic prime (before changing
        // heuristic prime)

        double[] shuffled_heuristic =
            heuristic_prime; // Shuffle the heuristic prime for fair iteration
        Collections.shuffle(Arrays.asList(shuffled_heuristic)); //

        for (int j = 0;
            j < shuffled_heuristic.length;
            j++) { // For each variable in the shuffled heuristic prime:
          System.out.print("Simulating with heuristic: ");
          for (int x = 0; x < heuristic_prime.length; x++) {
            System.out.printf("%.3f ", heuristic_prime[x]);
          }
          double old_value =
              shuffled_heuristic[j]; // Store the old value in case the new is not accepted
          shuffled_heuristic[j] = Math.random() * 2 * heuristic_max + heuristic_min;
          double winrate_prime =
              myRunner.playSession(
                  heuristic_prime); // Calculate the winrate with the heuristic prime
          System.out.printf("WR: %.2f", winrate_prime);
          if (winrate_prime
              > current_winrate) { // If the winrate prime is greater than the current winrate,
            System.out.println("... it was accepted as a higher winrate.");
            current_heuristic = heuristic_prime.clone(); // Take it immediately
            current_winrate = winrate_prime;
            writer.write("Accepted\n");
          } else if (Math.random()
              < Math.exp(
                  Math.abs(winrate_prime - current_winrate)
                      * -100
                      / (cur_temp))) { // Else, for some probability (decreasing with temperature)
            //													// Else,
            current_heuristic = heuristic_prime.clone(); // Take the winrate prime
            current_winrate = winrate_prime;
            System.out.printf(
                "... it was accepted with probability %f.\n",
                Math.exp(Math.abs(winrate_prime - current_winrate) * -100 / cur_temp));
            writer.write("Accepted\n");
          } else {
            shuffled_heuristic[j] = old_value;
            System.out.println("... it was not accepted.");
            writer.write("Dismissed\n");
          } // Otherwise, we don't accept the new heuristic

          if (current_winrate > 0.95) { // If your winrate is high, break
            Continue = false;
            break;
          }

          writer.flush();
        }
        cur_temp = cur_temp * 0.9; // Decrement the current temp and start again
        System.out.print("Completed session # ");
        System.out.print(session_number);
        System.out.print(" Temp: ");
        System.out.println(cur_temp);
        session_number++;
      }
    }
    writer.close();
    myRunner.close();
  }