public void hitResponse(String response) {
   StringTokenizer st = new StringTokenizer(response);
   int k = 0;
   String side = null;
   int x = -1;
   int y = -1;
   while (st.hasMoreTokens()) {
     if (k == 0) st.nextToken();
     if (k == 1) side = st.nextToken();
     if (k == 2) x = Integer.parseInt(st.nextToken());
     if (k == 3) y = Integer.parseInt(st.nextToken());
     k++;
   }
   System.out.println(gameData.getPlayerSide());
   System.out.println(side);
   if (gameData.getPlayerSide().equals(side)) {
     System.out.println("player field hit");
     gameData.shootAtField(side, x, y, 3, false, null, null, -1, -1);
     mw.v.enqueEvent(new CustomEvent(CustomEvent.PLAYER_FIELD_HIT, x, y));
   } else {
     System.out.println("enemy field hit");
     gameData.shootAtField(side, x, y, 3, false, null, null, -1, -1);
     mw.v.enqueEvent(new CustomEvent(CustomEvent.OPPONENT_FIELD_HIT, x, y));
   }
 }
Exemplo n.º 2
0
  /* Create and show the graphical user interface. */
  private static void createAndShowGUI() {
    JFrame frame = new JFrame("My Collapsing Puzzle");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Game game = new Game();
    frame.setJMenuBar(game.createMenuBar());
    frame.setContentPane(game.createContentPane());
    frame.setSize(game.getGameSize());

    frame.setVisible(true);
  }
Exemplo n.º 3
0
  /**
   * Test load simple gnugo.
   *
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public void testLoadSimpleGnugo() throws IOException {

    Game game = Game.loadFromFile(new File("sgf/testing/simpleGnuGo.sgf"));
    Iterator<Move> i = game.getMoves();
    Move move = null;
    BoardI board = new SmallerBoard(game.getSize());
    while (i.hasNext()) {
      move = i.next();
      assertNotNull(move);
      board = board.newBoard(move);
    }
    // System.err.println(g);
  }
Exemplo n.º 4
0
  /**
   * Test load all sg ffiles.
   *
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public void testLoadAllSGFfiles() throws IOException {
    Stack<String> files = new Stack<String>();
    files.push("sgf/2004-12");
    int count = 0;

    while (files.size() > 0 && count <= 10) {
      String filename = files.pop();
      File file = new File(filename);
      count++;
      if (DEBUG) System.err.println("examining \"" + filename + "\"");
      if (file.exists()) {
        if (!file.isDirectory()) {
          // System.err.println("\"" + filename + "\" is not a
          // directory, parsing as an SGF file");

          Game game = Game.loadFromFile(file);
          if (game.getSize() == 19) {
            Iterator<Move> i = game.getMoves();
            Move move = null;
            BoardI board = new SmallerBoard(game.getSize());
            // System.err.println("board size is: \"" +
            // goGame.getSize()
            // + "\"");
            while (i.hasNext()) {
              move = i.next();
              assertNotNull(move);
              // System.err.print("move: \"" + move + "\"");
              // assertTrue("" + board + "\n" +
              // move.toString(),board.isLegalMove(move));
              board = board.newBoard(move);
              // System.err.println(" board size is: \"" +
              // board.getSize() + "\"");
            }
            // System.err.println();

          }
        } else {
          if (DEBUG) System.err.println("\"" + filename + "\" is a directory");
          if (!file.getName().contains(".svn")) {
            String[] children = file.list();
            for (int i = 0; i < children.length; i++) {
              // System.err.println("pushing \"" + children[i] +
              // "\"");
              files.push(filename + "/" + children[i]);
            }
          }
        }
      }
    }
  }
Exemplo n.º 5
0
 // --------------------------------createAndShowGUI-----------------------------
 public static void createAndShowGUI() {
   Game thisGame = new Game();
   try {
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
   } catch (Exception e) {
   }
   JFrame.setDefaultLookAndFeelDecorated(true);
   thisGame.frame = new JFrame("Tactics");
   thisGame.oConn = new SocketManager();
   thisGame.scrBounds = thisGame.frame.getGraphicsConfiguration().getBounds();
   thisGame.frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
   thisGame.frame.setDefaultLookAndFeelDecorated(true);
   thisGame.frame.addWindowListener(thisGame);
   thisGame.frame.setVisible(true);
 }
Exemplo n.º 6
0
 /** Rewrite this method for your game */
 protected void update(int deltaTime) {
   if (execute == false && click == true) {
     String[] args = {};
     Game.main(args);
     execute = true;
   }
 }
Exemplo n.º 7
0
  public void loadTerrain() {
    try {
      long start = System.currentTimeMillis();
      // remove the existing terrain and detach it from the root node.
      if (terrain != null) {
        Node existingTerrain = (Node) terrain;
        existingTerrain.removeFromParent();
        existingTerrain.removeControl(TerrainLodControl.class);
        existingTerrain.detachAllChildren();
        terrain = null;
      }

      InputStream fis =
          game.getGameApplication()
              .getAssetManager()
              .locateAsset(new AssetKey("Scenes/" + map + "/terrainsave.jme"))
              .openStream();
      BinaryImporter imp = BinaryImporter.getInstance();
      imp.setAssetManager(assetManager);

      terrain = (TerrainQuad) imp.load(new BufferedInputStream(fis));
      terrain.setShadowMode(ShadowMode.CastAndReceive);

      clickableNode.attachChild((Node) terrain);

      float duration = (System.currentTimeMillis() - start) / 1000.0f;
      System.out.println("Load took " + duration + " seconds");
    } catch (Exception e) {
    }
  }
Exemplo n.º 8
0
  public void loadDoodads() {
    InputStream fis =
        game.getGameApplication()
            .getAssetManager()
            .locateAsset(new AssetKey("Scenes/" + map + "/doodads.jme"))
            .openStream();
    BinaryImporter importer = BinaryImporter.getInstance();
    importer.setAssetManager(assetManager);

    try {
      doodadNode = (Node) importer.load(new BufferedInputStream(fis));

      // this node is for buildings in fog (unsauber usw.....)
      doodadNode.attachChild(new Node());

      /*
      Node test =new Node();

      List list =doodadNode.getChildren();
        for(int i=0;i<list.size();i++)
        {
            BatchNode batch = new BatchNode();
            batch.attachChild((Node)list.get(i));
            batch.batch();
            test.attachChild(batch);
        }
      rootNode.attachChild(test);
       *
       */

      reflectNode.attachChild(doodadNode);
    } catch (IOException ex) {
      //  Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "No saved node loaded.", ex);
    }
  }
Exemplo n.º 9
0
  public void loseGame() {
    final GameBoard boardView = (GameBoard) this.findViewById(R.id.gameBoard);

    game.reInitGame();

    boardView.setGame(game);
    boardView.invalidate();
  }
Exemplo n.º 10
0
  public static void main(String[] args) {
    try {
      if (args.length != 2) {
        System.err.println("USAGE: java RenderMap map.txt image.png");
        System.exit(1);
      }
      Game game = new Game(args[0], 100, 0);
      if (game.Init() == 0) {
        System.err.println("Error while loading map " + args[0]);
        System.exit(1);
      }

      ArrayList<Color> colors = new ArrayList<Color>();
      colors.add(new Color(106, 74, 60));
      colors.add(new Color(74, 166, 60));
      colors.add(new Color(204, 51, 63));
      colors.add(new Color(235, 104, 65));
      colors.add(new Color(237, 201, 81));
      Color bgColor = new Color(188, 189, 172);
      Color textColor = Color.BLACK;
      Font planetFont = new Font("Sans Serif", Font.BOLD, 11);
      Font fleetFont = new Font("Sans serif", Font.PLAIN, 7);

      GraphicsConfiguration gc =
          GraphicsEnvironment.getLocalGraphicsEnvironment()
              .getDefaultScreenDevice()
              .getDefaultConfiguration();

      BufferedImage image = gc.createCompatibleImage(640, 480);

      Graphics2D _g = (Graphics2D) image.createGraphics();

      // Turn on AA/Speed
      _g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      _g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
      _g.setRenderingHint(
          RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

      game.Render(640, 480, 0.0, null, colors, bgColor, textColor, planetFont, fleetFont, _g);

      File file = new File(args[1]);
      ImageIO.write(image, "png", file);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
Exemplo n.º 11
0
  @Override
  public void simpleUpdate(float tpf) {
    if (loading) {
      if (loading_frames == 0) {
        if (game.isMultiplayer() && client.allConnected() == false) {
          return;
        }
      }

      if (loading_frames == 5) {
        if (game.isMultiplayer() && client.allLoaded() == false) {
          return;
        }
      }

      loading(loading_frames);
      loading_frames++;
    } else {

      loops = 0;

      while (System.currentTimeMillis() > next_game_tick
          && loops < MAX_FRAMESKIP
          && (game.isMultiplayer() == false || client.canContinue())) {

        if (game.isMultiplayer()) {
          client.update();
        }

        Timer.update(GAME_TPF);
        game.update(GAME_TPF);

        next_game_tick += SKIP_TICKS;
        loops++;
      }

      camera.update(tpf);
      listener.setLocation(cam.getLocation());
      listener.setRotation(cam.getRotation());
      gui.update(tpf); // nur wegen Kamera auf Minimap
    }
  }
 public void shoot(int x, int y) {
   if (!isServer)
     requestToServer.println(
         "fire "
             + gameData.getPlayerSide()
             + " "
             + new Integer(x).toString()
             + " "
             + new Integer(y).toString());
   if (isServer) elaborateShootRequest(x, y, "host");
 }
 public void shipPlacedResponse(String response) {
   int i = 0;
   StringTokenizer st = new StringTokenizer(response);
   String field = null;
   String alignment = null;
   String shipName = null;
   int xStartCoordinate = -1;
   int yStartCoordinate = -1;
   while (st.hasMoreTokens()) {
     if (i == 0) st.nextToken();
     if (i == 1) field = st.nextToken();
     if (i == 2) alignment = st.nextToken();
     if (i == 3) shipName = st.nextToken();
     if (i == 4) xStartCoordinate = Integer.parseInt(st.nextToken());
     if (i == 5) yStartCoordinate = Integer.parseInt(st.nextToken());
     i++;
   }
   if (field.equals(gameData.getPlayerSide()))
     gameData.placeShipsOnField(alignment, shipName, xStartCoordinate, yStartCoordinate);
 }
 public boolean placeShipsOnField(
     String field, String alignment, String shipName, int xStartCoordinate, int yStartCoordinate) {
   if (!gameData.shipAlreadyPlaced(shipName, alignment, xStartCoordinate, yStartCoordinate)) {
     if (!isServer) {
       requestToServer.println(
           "placeShip "
               + field
               + " "
               + alignment
               + " "
               + shipName
               + " "
               + xStartCoordinate
               + " "
               + yStartCoordinate);
       return true;
     }
     if (isServer) {
       boolean controllerQuery =
           cont.addShip(shipName, alignment, field, xStartCoordinate, yStartCoordinate);
       if (controllerQuery) {
         gameData.placeShipsOnField(alignment, shipName, xStartCoordinate, yStartCoordinate);
         for (ServerService s : services) {
           s.sendMessageToClients(
               "placeShip "
                   + field
                   + " "
                   + alignment
                   + " "
                   + shipName
                   + " "
                   + xStartCoordinate
                   + " "
                   + yStartCoordinate);
         }
         return true;
       }
     }
   }
   return false;
 }
 public void allShipsDestroyed(String response) {
   StringTokenizer st = new StringTokenizer(response);
   st.nextToken();
   String result;
   if ((st.nextToken().equals(gameData.getPlayerSide()))) result = "You Lose";
   else result = "You Win!";
   mw.v.enqueEvent(new CustomEvent(CustomEvent.GAME_OVER, result));
   try {
     Thread.sleep(10000);
   } catch (InterruptedException e) {
   }
   System.exit(0);
 }
Exemplo n.º 16
0
  @Override
  public void run() {
    System.out.println("Starting Listener");
    int character;
    try {
      socket1 = new ServerSocket(port);
      game.gui.lock("Waiting for other player");
      connection = socket1.accept();

      bis = new BufferedInputStream(connection.getInputStream());
      isr = new InputStreamReader(bis);

      while ((character = isr.read()) != 13) {
        strb.append((char) character);
      }

      // if received CLOSEMESSAGE -> end listening and do something
      if (strb.toString().equals(Online.CLOSEMESSAGE)) {
        System.out.println("Looks like we have ended...");
      }

      // check incoming message
      System.out.println(strb);

      Figure f = game.parseFigure(strb.toString());
      Position p = game.parsePosition(strb.toString());
      game.playerPlay(f, p);

      game.switchPlayers();
      game.gui.unlock();
      connection.close();
      System.out.println("moved, your turn!");
      socket1.close();

    } catch (IOException e) {
      System.out.println("Unexpected exception on server side" + e);
    }
  }
Exemplo n.º 17
0
  @Override
  public void destroy() {
    super.destroy();

    if (client != null) {
      client.close();
    }

    if (server != null) {
      server.close();
    }

    game.getFogOfWar().destroy();
  }
Exemplo n.º 18
0
  @Override
  protected void onStop() {
    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    editor.putInt("level", this.level);
    editor.putString("map", game.getLabyrinth().getJsonMap());
    editor.putString("howdy", game.getJsonHowdy());

    String allDoneLevelsString = "";

    for (String s : allDoneLevels) {
      allDoneLevelsString += s + ",";
    }

    if (allDoneLevelsString.length() > 0) {
      editor.putString(
          "doneLevels", allDoneLevelsString.substring(0, allDoneLevelsString.length() - 1));
    }

    editor.commit();

    super.onStop();
  }
 public void waterResponse(String response) {
   StringTokenizer st = new StringTokenizer(response);
   String side = null;
   int k = 0;
   int x = -1;
   int y = -1;
   while (st.hasMoreTokens()) {
     if (k == 0) st.nextToken();
     if (k == 1) side = st.nextToken();
     if (k == 2) x = Integer.parseInt(st.nextToken());
     if (k == 3) y = Integer.parseInt(st.nextToken());
     k++;
   }
   gameData.shootAtField(side, x, y, 2, false, null, null, -1, -1);
 }
 public void parseChatMessage(String response) {
   int counter = 0;
   String side = null;
   String playerName = null;
   String chatMessage = null;
   response = response.substring(5);
   StringTokenizer st = new StringTokenizer(response);
   while (st.hasMoreElements()) {
     if (counter > 1) break;
     if (counter == 0) playerName = st.nextToken();
     if (counter == 1) side = st.nextToken();
     counter++;
   }
   chatMessage = response.substring(playerName.length() + side.length() + 2);
   if (playerName.equals(gameData.getPlayerName())) playerName = "Me";
   String finalString = playerName + " (" + side + ") says: " + chatMessage;
   mw.v.enqueEvent(new CustomEvent(CustomEvent.CHAT_MESSAGE, finalString));
 }
 public void chat(String message) {
   message = message.substring(5);
   if (isServer) {
     for (ServerService s : services)
       s.sendMessageToClients(
           "chat " + gameData.getPlayerName() + " " + gameData.getPlayerSide() + " " + message);
     parseChatMessage(
         "chat " + gameData.getPlayerName() + " " + gameData.getPlayerSide() + " " + message);
   }
   if (!isServer)
     requestToServer.println(
         "chat " + gameData.getPlayerName() + " " + gameData.getPlayerSide() + " " + message);
 }
Exemplo n.º 22
0
  @Override
  public void startTheGame() {

    gameType = "";

    try {
      // receive ping from server
      gameType = mainServer.readLine();
    } catch (IOException ex) {
      System.err.println("Could not communicate with server: " + ex);
      Global.onException();
    }

    super.startTheGame();

    for (FixedTimer timer : timers) timer.start();

    startMarquee(getGameType(), 1000);
    startMarquee("3");
    startMarquee("2");
    startMarquee("1");

    // receive ping that the game is starting

    try {
      // ping back that client is ready
      mainServer.println();
      mainServer.flush();
      // wait for if server is ready
      mainServer.readLine();
    } catch (IOException ex) {
      System.err.println("Could not communicate with server: " + ex);
      Global.onException();
    }

    turnOnEndGameReceiver();
    startMarquee("START!");
  }
 public void destroyedResponse(String response) {
   StringTokenizer st = new StringTokenizer(response);
   String side = null;
   String shipName = null;
   String alignment = null;
   int size = 0;
   int k = 0;
   int xStartCoord = -1;
   int yStartCoord = -1;
   int hostPoints = -1;
   int guestPoints = -1;
   int x = -1;
   int y = -1;
   while (st.hasMoreTokens()) {
     if (k == 0) st.nextToken();
     if (k == 1) side = st.nextToken();
     if (k == 2) shipName = st.nextToken();
     if (k == 3) alignment = st.nextToken();
     if (k == 4) xStartCoord = Integer.parseInt(st.nextToken());
     if (k == 5) yStartCoord = Integer.parseInt(st.nextToken());
     if (k == 6) hostPoints = Integer.parseInt(st.nextToken());
     if (k == 7) guestPoints = Integer.parseInt(st.nextToken());
     if (k == 8) x = Integer.parseInt(st.nextToken());
     if (k == 9) y = Integer.parseInt(st.nextToken());
     k++;
   }
   if (shipName.equals("aircraft")) size = 5;
   if (shipName.equals("battleship")) size = 4;
   if (shipName.equals("destroyer")) size = 3;
   if (shipName.equals("submarine")) size = 2;
   if (gameData.getPlayerSide().equals("guest")) {
     gameData.setMyPoints(guestPoints);
     gameData.setEnemyPoints(hostPoints);
   } else {
     gameData.setMyPoints(hostPoints);
     gameData.setEnemyPoints(guestPoints);
   }
   gameData.shootAtField(side, x, y, 3, true, shipName, alignment, xStartCoord, yStartCoord);
   mw.v.enqueEvent(
       new CustomEvent(CustomEvent.SHIP_EXPLODE, xStartCoord, yStartCoord, size, alignment, side));
 }
Exemplo n.º 24
0
  public void simulate(int x) {
    // Bracket winners write to simfirst arraylist and move to next array in tournTeams to process.
    ArrayList<String> simfirst = new ArrayList<String>();
    tournTeams = new Team[4][16]; // to reset the wins for new simulation
    nRegion = new Region[4];
    winners = new Team[64];
    ReadNCAA();
    for (int l = 0; l < x; l++) {
      // loop for simulations

      roundOf32 = new Team[4][8];
      sweet16 = new Team[4][4];
      elite8 = new Team[4][2];
      final4 = new Team[4][1];
      theFinals = new Team[2];

      simfirst = new ArrayList<String>();
      // Round of 32

      simfirst.add("Winner Bracket " + Integer.toString(1) + "  on to Round of 32");

      for (int j = 0; j < (tournTeams.length); j++) {
        // loop for teams in round
        int countNextb = 0;
        simfirst.add("  Region: " + nRegion[j].name());
        // System.out.println("Region: " + nRegion[j].name());
        for (int i = 0; i < tournTeams[j].length - 1; i += 2) {
          myGame = new Game(tournTeams[j][i], tournTeams[j][i + 1]);
          if (myGame.winnerIndex() == 1) {
            simfirst.add(
                "    Team " + tournTeams[j][i].name() + " Wins " + (tournTeams[j][i].wins() + 1));
            //	System.out.println(" Team "+ tournTeams[k][j][i].name() + " Wins " +
            // tournTeams[k][j][i].wins());
            roundOf32[j][countNextb] =
                new Team(tournTeams[j][i].name(), tournTeams[j][i].seed(), tournTeams[j][i].wp());
            roundOf32[j][countNextb].win();
            //	 System.out.println("k+1="+(k+1)+" j =" + j +" countNextb= "+countNextb + " Team " +
            // tournTeams[k+1][j][countNextb].name());
          } else {
            simfirst.add(
                "    Team "
                    + tournTeams[j][i + 1].name()
                    + " Wins "
                    + (tournTeams[j][i + 1].wins() + 1));
            //	System.out.println(" Team "+ tournTeams[k][j][i+1].name() + " Wins " +
            // tournTeams[k][j][i+1].wins());
            roundOf32[j][countNextb] =
                new Team(
                    tournTeams[j][i + 1].name(),
                    tournTeams[j][i + 1].seed(),
                    tournTeams[j][i + 1].wp());
            roundOf32[j][countNextb].win();
            // System.out.println("k+1="+(k+1)+" j =" + j +" countNextb= "+countNextb + " Team " +
            // tournTeams[k+1][j][countNextb].name());
          }
          countNextb++;
        }
      }

      //  Sweet 16
      simfirst.add("Winner Bracket " + Integer.toString(2) + " on to Sweet 16");
      for (int j = 0; j < (roundOf32.length); j++) {
        // loop for teams in round
        int countNextb = 0;
        simfirst.add("  Region: " + nRegion[j].name());
        // System.out.println("Region: " + nRegion[j].name());
        for (int i = 0; i < roundOf32[j].length - 1; i += 2) {
          myGame = new Game(roundOf32[j][i], roundOf32[j][i + 1]);
          if (myGame.winnerIndex() == 1) {
            simfirst.add(
                "    Team " + roundOf32[j][i].name() + " Wins " + (roundOf32[j][i].wins() + 1));
            sweet16[j][countNextb] = roundOf32[j][i];
            sweet16[j][countNextb].win();
          } else {
            simfirst.add(
                "    Team "
                    + roundOf32[j][i + 1].name()
                    + " Wins "
                    + (roundOf32[j][i + 1].wins() + 1));
            sweet16[j][countNextb] = roundOf32[j][i + 1];
            sweet16[j][countNextb].win();
          }
          countNextb++;
        }
      }
      //  Elite 8
      simfirst.add("Winner Bracket " + Integer.toString(3) + " on to Elite 8");
      for (int j = 0; j < (sweet16.length); j++) {
        // loop for teams in round
        int countNextb = 0;
        simfirst.add("  Region: " + nRegion[j].name());
        // System.out.println("Region: " + nRegion[j].name());
        for (int i = 0; i < sweet16[j].length - 1; i += 2) {
          myGame = new Game(sweet16[j][i], sweet16[j][i + 1]);
          if (myGame.winnerIndex() == 1) {
            simfirst.add(
                "    Team " + sweet16[j][i].name() + " Wins " + (sweet16[j][i].wins() + 1));
            elite8[j][countNextb] = sweet16[j][i];
            elite8[j][countNextb].win();
          } else {
            simfirst.add(
                "    Team " + sweet16[j][i + 1].name() + " Wins " + (sweet16[j][i + 1].wins() + 1));
            elite8[j][countNextb] = sweet16[j][i + 1];
            elite8[j][countNextb].win();
          }
          countNextb++;
        }
      }
      //  Final 4
      simfirst.add("Winner Bracket " + Integer.toString(4) + " on to Final 4");
      for (int j = 0; j < (elite8.length); j++) {
        // loop for teams in round

        simfirst.add("  Region: " + nRegion[j].name());
        // System.out.println("Region: " + nRegion[j].name());
        for (int i = 0; i < elite8[j].length - 1; i += 2) {
          myGame = new Game(elite8[j][i], elite8[j][i + 1]);
          if (myGame.winnerIndex() == 1) {
            simfirst.add("    Team " + elite8[j][i].name() + " Wins " + (elite8[j][i].wins() + 1));
            final4[j][0] = elite8[j][i];
            final4[j][0].win();
          } else {
            simfirst.add(
                "    Team " + elite8[j][i + 1].name() + " Wins " + (elite8[j][i + 1].wins() + 1));
            final4[j][0] = elite8[j][i + 1];
            final4[j][0].win();
          }
        }
      }
      //  Final 2
      simfirst.add("Winner Bracket " + Integer.toString(5) + " on to Finals");
      // loop for teams in round
      // System.out.println("Region: " + nRegion[j].name());
      myGame = new Game(final4[0][0], final4[1][0]);
      if (myGame.winnerIndex() == 1) {
        simfirst.add("  Region: " + getRegionTeam(final4[0][0].name()));
        simfirst.add("    Team " + final4[0][0].name() + " Wins " + (final4[0][0].wins() + 1));
        theFinals[0] = final4[0][0];
        theFinals[0].win();
      } else {
        simfirst.add("  Region: " + getRegionTeam(final4[1][0].name()));
        simfirst.add("    Team " + final4[1][0].name() + " Wins " + (final4[1][0].wins() + 1));
        theFinals[0] = final4[1][0];
        theFinals[0].win();
      }
      myGame = new Game(final4[2][0], final4[3][0]);
      if (myGame.winnerIndex() == 1) {
        simfirst.add("  Region: " + getRegionTeam(final4[2][0].name()));
        simfirst.add("    Team " + final4[2][0].name() + " Wins " + (final4[2][0].wins() + 1));
        theFinals[1] = final4[2][0];
        theFinals[1].win();
      } else {
        simfirst.add("  Region: " + getRegionTeam(final4[3][0].name()));
        simfirst.add("    Team " + final4[3][0].name() + " Wins " + (final4[3][0].wins() + 1));
        theFinals[1] = final4[3][0];
        theFinals[1].win();
      }

      // The Winner
      simfirst.add("Winner Bracket " + Integer.toString(6) + " on to The Finals");
      myGame = new Game(theFinals[0], theFinals[1]);
      if (myGame.winnerIndex() == 1) {
        simfirst.add("  Region: " + getRegionTeam(theFinals[0].name()));
        simfirst.add("    Team " + theFinals[0].name() + " Wins " + (theFinals[0].wins() + 1));
        for (int k = 0; k < winners.length; k++) {
          if (winners[k].name().equals(theFinals[0].name())) winners[k].win();
        }
      } else {
        simfirst.add("  Region: " + getRegionTeam(theFinals[1].name()));
        simfirst.add("    Team " + theFinals[1].name() + " Wins " + (theFinals[1].wins() + 1));
        for (int k = 0; k < winners.length; k++) {
          if (winners[k].name().equals(theFinals[0].name())) winners[k].win();
        }
      }

      totalSim.add(simfirst);
      // arraylist of the winner array list - all simulations stored together
    }
  }
Exemplo n.º 25
0
  private void gamesCsv(Round round) {
    File gamesCSV = new File(names[2]);

    if (gamesCSV.isFile() && gamesCSV.canRead()) {
      gamesCSV.delete();
    }

    if (round.getSize() == 0) {
      return;
    }

    try {
      gamesCSV.createNewFile();

      FileWriter fw = new FileWriter(gamesCSV.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);

      bw.write(
          "gameId;gameName;status;gameSize;gameLength;lastTick;"
              + "weatherLocation;weatherDate;logUrl;brokerId;brokerBalance;"
              + separator);

      String tourneyUrl = properties.getProperty("tourneyUrl");
      String baseUrl = properties.getProperty("actionIndex.logUrl", "download?game=%d");
      for (Game game : round.getGameMap().values()) {
        String logUrl = "";
        if (game.isComplete()) {
          if (baseUrl.startsWith("http://")) {
            logUrl = String.format(baseUrl, game.getGameId());
          } else {
            logUrl = tourneyUrl + String.format(baseUrl, game.getGameId());
          }
        }

        String content =
            String.format(
                "%d;%s;%s;%d;%d;%d;%s;%s;%s;",
                game.getGameId(),
                game.getGameName(),
                game.getState(),
                game.getSize(),
                game.getGameLength(),
                game.getLastTick(),
                game.getLocation(),
                game.getSimStartTime(),
                logUrl);
        for (Agent agent : game.getAgentMap().values()) {
          content = String.format("%s%d;%f;", content, agent.getBrokerId(), agent.getBalance());
        }

        bw.write(content + separator);
      }

      bw.close();

      copyFile(gamesCSV, names[3]);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 26
0
 /*
  *PlayerBeingAddedMessages are bodiless, containing nothing
  *beyond their prefix.
  *The response is to freeze the manipulator while the player
  *is being added, and display
  *a message about it.
  */
 public byte[] handleMessage(InputStream str) {
   Game.getLocalPlayer().getManipulator().setFrozen(true);
   JOptionPane.showMessageDialog(null, "A player is being added; stand by.");
   return new byte[0];
 }
Exemplo n.º 27
0
  public void loading(int pos) {
    if (pos == 0) {
      camera = new RTSCamera(getCamera());
      camera.registerWithInput(inputManager);

      loadingScreen.setProgress(0.1f, "Making Light");
    } else if (pos == 1) {

      loadShadow();
      loadLight();

      loadingScreen.setProgress(0.2f, "Loading Terrain");

    } else if (pos == 2) {
      reflectNode = new Node("reflect");
      rootNode.attachChild(reflectNode);
      nonreflectNode = new Node("non reflect");
      rootNode.attachChild(nonreflectNode);

      clickableNode = new Node("clickable");
      reflectNode.attachChild(clickableNode);
      //  clickableNode.attachChild(createTerrain());
      loadTerrain();
      loadWater();

      camera.addTerrain(terrain);
      camera.addWater(water);

      loadingScreen.setProgress(0.6f, "Loading Doodads");
    } else if (pos == 3) {
      loadDoodads();
      loadingScreen.setProgress(0.8f, "Init Game");
    } else if (pos == 4) {

      game.init();

      // gui=new GUI(game);

      game.getMyGame().init(game);

      if (game.isMultiplayer()) {
        client.finishedLoading();
      }

      loadingScreen.setProgress(1f, "Finished Loading");
    } else if (pos == 5) {
      loadingScreen.clear();
      camera.enable();

      gui = new GUI(game);
      gui.init();

      playerInput = new PlayerInput(game);
      // important input after nifty

      next_game_tick = System.currentTimeMillis();

      Timer.init();
      loading = false;
    }
  }
Exemplo n.º 28
0
  public static void main(String[] args) throws Exception {

    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

    Dice d1 = new Dice();
    Dice d2 = new Dice();
    Dice d3 = new Dice();

    Player player = new Player("Fred", 100);
    Game game = new Game(d1, d2, d3);
    List<DiceValue> cdv = game.getDiceValues();

    int totalWins = 0;
    int totalLosses = 0;

    while (true) {
      int winCount = 0;
      int loseCount = 0;

      for (int i = 0; i < 1; i++) {
        String name = "Fred";
        int balance = 10;
        int limit = 0;
        player = new Player(name, balance);
        player.setLimit(limit);
        int bet = 5;

        System.out.println(String.format("Start Game %d: ", i));
        System.out.println(
            String.format(
                "%s starts with balance %d, limit %d",
                player.getName(), player.getBalance(), player.getLimit()));

        int turn = 0;
        while (player.balanceExceedsLimitBy(bet) && player.getBalance() < 200) {
          turn++;
          DiceValue pick = DiceValue.getRandom();

          System.out.printf("Turn %d: %s bet %d on %s\n", turn, player.getName(), bet, pick);

          int winnings = game.playRound(player, pick, bet);
          cdv = game.getDiceValues();

          System.out.printf("Rolled %s, %s, %s\n", cdv.get(0), cdv.get(1), cdv.get(2));

          if (winnings > 0) {
            System.out.printf(
                "%s won %d, balance now %d\n\n", player.getName(), winnings, player.getBalance());
            winCount++;
          } else {
            System.out.printf("%s lost, balance now %d\n\n", player.getName(), player.getBalance());
            loseCount++;
          }
        } // while

        System.out.print(String.format("%d turns later.\nEnd Game %d: ", turn, i));
        System.out.println(
            String.format("%s now has balance %d\n", player.getName(), player.getBalance()));
      } // for

      System.out.println(
          String.format(
              "Win count = %d, Lose Count = %d, %.2f",
              winCount, loseCount, (float) winCount / (winCount + loseCount)));
      totalWins += winCount;
      totalLosses += loseCount;

      String ans = console.readLine();
      if (ans.equals("q")) break;
    } // while true

    System.out.println(
        String.format(
            "Overall win rate = %.1f%%", (float) (totalWins * 100) / (totalWins + totalLosses)));
  }
Exemplo n.º 29
0
  public void nextLevel() {
    boolean loaded = false;
    final GameBoard boardView = (GameBoard) this.findViewById(R.id.gameBoard);
    this.level++;

    AssetManager am = getResources().getAssets();

    try {
      List<String> allTutoLevels =
          new LinkedList<String>(Arrays.asList(am.list("levels/tutorial")));

      // if(addMsg){
      //    allTutoLevels.addAll(Arrays.asList(am.list("msg")));
      // }

      Log.d(TAG, allTutoLevels.toString());

      for (String name : allTutoLevels) {
        if (name.startsWith(this.level + ".")) {
          BufferedReader br =
              new BufferedReader(new InputStreamReader(am.open("levels/tutorial/" + name)));
          String line;
          String levelJSON = "";

          while ((line = br.readLine()) != null) {
            levelJSON += line + "\n";
          }

          br.close();

          game.initGame(
              levelJSON, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60);
          loaded = true;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (!loaded) {
      Random r = new Random();

      List<String> allLevels = new ArrayList<>();

      try {
        allLevels = Arrays.asList(am.list("levels"));
      } catch (IOException e) {
      }

      if (r.nextBoolean() && !allLevels.isEmpty() && allLevels.size() != allDoneLevels.size()) {
        try {
          int nLevel;
          do {
            nLevel = r.nextInt(allLevels.size());
          } while (allDoneLevels.contains(allLevels.get(nLevel)));

          String name = allLevels.get(nLevel);
          BufferedReader br = new BufferedReader(new InputStreamReader(am.open("levels/" + name)));

          String line;
          String levelJSON = "";

          while ((line = br.readLine()) != null) {
            levelJSON += line + "\n";
          }

          br.close();

          allDoneLevels.add(name);

          game.initGame(
              levelJSON, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60);
        } catch (IOException e) {
          this.game.initGame(
              level, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60);
        }
      } else {
        this.game.initGame(
            level, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60);
      }
    }

    // am.close();

    boardView.setGame(this.game);
    boardView.invalidate();
    boardView.getHowdyShadeView().invalidate();

    Toast.makeText(this, this.level + "", Toast.LENGTH_SHORT).show();

    Log.i(
        TAG,
        "Max tiles : "
            + (boardView.getMeasuredWidth() / 60) * (boardView.getMeasuredHeight() / 60));
  }
Exemplo n.º 30
0
 /**
  * Returns whether two games are equal. This is the case if they contain exactly the same lines.
  * The header does not matter.
  *
  * @return the hash code
  */
 public boolean equals(Object obj) {
   if (obj == this) return true; // =====>
   if (!(obj instanceof Game)) return false; // =====>
   Game game = (Game) obj;
   return game.getModel().equals(getModel());
 }