示例#1
1
  @Override
  public void onSensorChanged(SensorEvent e) {
    // make sure all players have the same speed
    long now = System.currentTimeMillis();
    if ((now - lastSensorEvent) < SENSOR_REFRESH_LIMIT) {
      return;
    }

    lastSensorEvent = now;

    float x = e.values[0];
    float y = e.values[1];
    float z = e.values[2];

    // http://www.anddev.org/code-snippets-for-android-f33/convert-android-accelerometer-values-and-get-tilt-from-accel-t6595.html
    // http://www.hobbytronics.co.uk/accelerometer-info

    double accX = -x / SensorManager.GRAVITY_EARTH;
    double accY = -y / SensorManager.GRAVITY_EARTH;
    double accZ = z / SensorManager.GRAVITY_EARTH;
    double totAcc = Math.sqrt((accX * accX) + (accY * accY) + (accZ * accZ));
    // tiltXYZ: returned angle is in the range -pi/2 through pi/2
    double tiltX = Math.asin(accX / totAcc);
    double tiltY = Math.asin(accY / totAcc);
    // double tiltZ = Math.asin(accZ / totAcc);

    // TODO [veny] there should be Strategy design pattern to calculate the speed of movement
    // (int)(tiltX * 2 / Math.PI) -  is increment (-1 to 1, 0 is no move)
    double speedX = (tiltX * 2 / Math.PI);
    double speedY = (-tiltY * 2 / Math.PI);
    if (0 != speedX || 0 != speedY) {
      Game.getInstance().moveMe(speedX, speedY);
    }
  }
示例#2
0
  public static void main(String[] args) {
    Game game = Game.getInstance();
    game.addPlayer(new Player("Juancito"));
    game.addPlayer(new Player("Pedrito"));

    System.out.println(Game.getInstance().getPlayers());
  }
示例#3
0
  @Override
  protected void onStart() {
    super.onStart();
    // register itself as game observer
    Game.getInstance().registerEventObserver(this);
    // start the game
    Bundle extras = getIntent().getExtras();
    String babaName = extras.getString(PlayingFieldActivity.BABANAME);

    Game.getInstance().start(babaName);
  }
示例#4
0
  public void offerNewGame() {
    GameOpt gameOpt;
    if (Game.hasInstance()) {
      // Copy the game options of the active instance.
      gameOpt = new GameOpt(Game.getInstance().getOpt());
      gameOpt.setRules(Rules.REPLAY);
    } else {
      // Start with the default game options.
      gameOpt = new GameOpt();
    }

    final int maxHands = ParmBox3.HANDS_DEALT_MAX;
    final HandOpt handOpts[] = new HandOpt[maxHands];
    for (int iHand = 0; iHand < maxHands; iHand++) {
      HandOpt handOpt;
      if (Game.hasInstance() && iHand < gameOpt.getHandsDealt()) {
        final ReadHand hand = Game.getInstance().getHand(iHand);
        handOpt = new HandOpt(hand.getOpt());
      } else {
        handOpt = new HandOpt("User");
      }
      handOpts[iHand] = handOpt;
    }

    final Wizard wizard = new Wizard(frame);

    final ParmBox1 parmBox1 = new ParmBox1(wizard);
    wizard.addCard(parmBox1);

    final WizardCard parmBox2 = new ParmBox2(wizard);
    wizard.addCard(parmBox2);

    final WizardCard parmBox3 = new ParmBox3(wizard);
    wizard.addCard(parmBox3);

    final WizardCard handBox = new HandBox(wizard);
    wizard.addCard(handBox);

    // pack and go
    final boolean completed = wizard.run(parmBox1, gameOpt, handOpts);

    if (!completed) {
      Console.print("New game aborted.\n");
      return;
    }

    final GameView view = GameView.getInstance();
    view.saveHand();
    final GameStyle oldStyle = Game.getStyle();
    new Game(gameOpt, handOpts);
    view.newGame(oldStyle);
  }
示例#5
0
  private void handleReleaseView(Point point) {
    assert point != null;
    assert mouseLast != null;
    assert Game.hasInstance();
    assert !Game.getInstance().isPaused();

    final int dx = point.x - mouseLast.x;
    final int dy = point.y - mouseLast.y;
    final GameView view = GameView.getInstance();
    if (view.hasActiveTile()) {
      assert !dragBoard;
      deactivateOnRelease = view.dropActiveTile(point, deactivateOnRelease);
      repaint();

    } else if (dragBoard) {
      view.translate(dx, dy);
      dragBoardPixelCount += Math.abs(dx) + Math.abs(dy);

      if (dragBoardPixelCount < DRAG_THRESHOLD) {
        /*
         * Board drags shorter than six pixels (clicks, basically)
         * also serve to alter or un-target the target cell.
         */
        view.toggleTargetCell(point);
      }

      // done dragging the board
      dragBoard = false;
      setCursor(Cursor.getDefaultCursor());
      repaint();
    }
  }
示例#6
0
  @Override
  public void onGameEvent(Game.GameEvent event) {
    switch (event.action) {
      case MOVE:

        // when player moved, invalidate view - render new position
        boardView.invalidate();
        break;

      case BABA:
        String caught = event.params[0];
        Toast.makeText(this, "BABA! The looser is: " + caught, Toast.LENGTH_SHORT).show();

        // refresh baba counter - show your baba-size ;)
        caughtCounterView.setText(
            this.babatextBase + String.valueOf(Game.getInstance().getMe().getCaughtCounter()));

        break;
      case QUIT:
        // String quitName = event.params[0];
        // Toast.makeText(this, "Player " + quitName + " left the game", Toast.LENGTH_SHORT).show();

        break;
      case END_GAME:
        Toast.makeText(this, "Game finished", Toast.LENGTH_LONG).show();
        stopGameOnClient(); // go back to Host/JoinGame -> onStart -> Game#reset()
        break;
    }
  }
示例#7
0
  private void leftButtonPress(Point point) {
    assert point != null;

    final ReadGame game = Game.getInstance();
    if (game != null && !game.isPaused()) {
      handleClickView(point);
    }
    leftButtonDown = true;
    mouseLast = point;
  }
示例#8
0
  public Camera(float x, float y) {
    this.x = x;
    this.y = y;

    for (CoreObject obj : Game.getInstance().getController().getObjects()) {
      if (obj.getId() == Identities.PLAYER) {
        player = (Player) obj;
      }
    }
  }
示例#9
0
  @Override
  public void mouseDragged(MouseEvent event) {
    assert event != null;

    final Point point = event.getPoint();
    if (leftButtonDown) {
      assert mouseLast != null;

      final ReadGame game = Game.getInstance();
      if (game != null && !game.isPaused()) {
        handleDragView(point);
      }
      mouseLast = point;
    }
  }
示例#10
0
  private void leftButtonRelease(Point point) {
    assert point != null;
    assert GameView.hasInstance();
    assert mouseLast != null;

    final Game game = Game.getInstance();
    if (game != null) {
      if (game.isPaused()) {
        GameView.getInstance().startClock();
      } else {
        handleReleaseView(point);
      }
    }
    leftButtonDown = false;
    mouseLast = point;
  }
示例#11
0
  private void handleDragView(Point point) {
    assert point != null;
    assert Game.hasInstance();
    assert !Game.getInstance().isPaused();
    assert GameView.hasInstance();

    if (GameView.getInstance().hasActiveTile()) {
      assert !dragBoard;
      repaint();

    } else if (dragBoard) {
      final int dx = point.x - mouseLast.x;
      final int dy = point.y - mouseLast.y;
      GameView.getInstance().translate(dx, dy);
      dragBoardPixelCount += Math.abs(dx) + Math.abs(dy);
      repaint();
    }
  }
示例#12
0
  // tests the game class
  @Test
  public void GameTest() throws Exception {
    Game game = Game.getInstance();
    game.setFields(null, 0, null, null, null, null, null, null, null, null, null, null, null);
    assert game.context == null;
    assert game.numCells1side == 0;
    assert game.textViewGameStage == null;
    assert game.textViewMessage == null;
    assert game.buttonAttack == null;
    assert game.buttonUpgrade == null;
    assert game.buttonRestart == null;
    assert game.gridViewBoard1 == null;
    assert game.gridViewBoard2 == null;
    assert game.adapterBoard1 == null;
    assert game.adapterBoard2 == null;
    assert game.player1 == null;
    assert game.player2 == null;

    // Can't test this without Espresso
    // game.initialize();
    // assert game.
  }
示例#13
0
  private void handleClickView(Point point) {
    assert point != null;
    assert Game.hasInstance();
    assert !Game.getInstance().isPaused();
    assert GameView.hasInstance();
    assert !dragBoard;

    final GameView view = GameView.getInstance();

    if (view.hasActiveTile()) {
      // Continue moving the active tile.
      assert mouseLast != null;
      assert deactivateOnRelease;
      repaint();
      return;
    }

    final Tile tile = view.findPlayableTile(point);
    if (tile != null) {
      /*
       * The local user clicked on a playable tile.
       * Activate the tile and start dragging it around.
       */
      view.activate(tile);
      deactivateOnRelease = false;
      repaint();

    } else if (!view.isInHandRect(point) && !view.isInSwapRect(point)) {
      // Start dragging the board around.
      dragBoard = true;
      view.deactivate();
      dragBoardPixelCount = 0;
      setCursor(DRAG_CURSOR);
      repaint();
    }
  }
public class PlayerFieldPanel extends FieldPanel {
  private int selected = 0;
  private JLabel shipsToPlaceInfo;
  private Game game = Game.getInstance();
  private JLabel shipSunk;

  /**
   * Creates things specific to the players field, like how many ships left and reporting
   * hits/misses
   */
  public PlayerFieldPanel() {
    super();

    // Notify how many ships (or, rather, modules) are placed
    shipsToPlaceInfo = new JLabel("Ships placed: 0 / 18");
    shipsToPlaceInfo.setBounds(200, 350, 120, 30);

    // To notify if the opponent sunk a ship of ours
    shipSunk = new JLabel("");
    shipSunk.setBounds(200, 370, 300, 30);

    this.add(shipSunk);
    this.add(shipsToPlaceInfo);

    // For each checkbox, add an event listener that checks for when checkboxes are
    // selected/unselected
    for (JCheckBox[] x : checkboxes) {
      for (JCheckBox y : x) {
        y.addItemListener(
            new ItemListener() {

              @Override
              public void itemStateChanged(ItemEvent e) {
                // Check what the event was. 1 is selected, 2 is unselected
                if (e.getStateChange() == 1) {
                  // If we are below the amount of ships that can be selected, proceed
                  // Otherwise, don't allow it
                  if (selected < 18) {
                    selected++;
                  } else {
                    JCheckBox src = (JCheckBox) e.getSource();
                    selected++; // It will be decreased with as many as it increased with when the
                                // unselected event is called.
                    src.setSelected(false);
                  }
                  shipsToPlaceInfo.setText("Ships placed: " + selected + " / 18");
                } else if (e.getStateChange() == 2) {
                  selected--;
                  shipsToPlaceInfo.setText("Ships placed: " + selected + " / 18");
                }
              }
            });
      }
    }
  }

  /**
   * Get the amount selected
   *
   * @return
   */
  public int getSelectedCount() {
    return selected;
  }

  /**
   * Set the status of sunken ships
   *
   * @param str the status to be set
   */
  public void setSunkText(String str) {
    shipSunk.setText(str);
  }

  /**
   * Check if it was a hit or not. If it's a hit, a hit icon is set, checkbox is disabled. A miss
   * leads to a missed icon 4 is sent to the opponent if it's a hit, 5 if it's a miss
   *
   * @param x the x-coordinate
   * @param y the y-coordinate
   * @return 4 if a hit, 5 if miss
   */
  public int checkHit(int x, int y) {
    if (checkboxes[x][y].isSelected()) {
      checkboxes[x][y].setDisabledSelectedIcon(
          new ImageIcon(getClass().getResource("/resources/hit.png")));
      selected--;
      shipsToPlaceInfo.setText("Ships placed: " + selected + " / 18");

      // If there is no more checkboxes, the game is over and we have lost
      if (selected == 0) {
        game.over();
      }
      return 4;
    } else {
      checkboxes[x][y].setDisabledIcon(
          new ImageIcon(getClass().getResource("/resources/miss.png")));
      return 5;
    }
  }

  /**
   * Selects a single checkbox, or deselects if reverse is true
   *
   * @param x the x-coordinate
   * @param y the y-coordinate
   * @param reverse If it should be reversed or not
   */
  public void select(int x, int y, boolean reverse) {

    if (!reverse) {
      checkboxes[x][y].setSelected(true);
    } else {
      checkboxes[x][y].setSelected(false);
    }
  }

  /**
   * Check if the ship to be placed is colliding with another ship. The rules are that a ship cannot
   * be placed on top of each other and not at the direct neighbor of another ship.
   *
   * @param fromX the x-coordinate the ship starts on
   * @param toX the x-coordinate the ship ends on
   * @param fromY the y-coordinate the ship starts on
   * @param toY the y-coordinate the ship ends on
   * @return true if collifing, false if not
   */
  public boolean isColliding(int fromX, int toX, int fromY, int toY) {

    // Expand the area of the ship to check all checkboxes next to it
    fromX--;
    toX++;

    fromY--;
    toY++;

    // We don't wanna check outside of the field (and the array) so make sure we don't
    if (fromX < 0) fromX = 0;
    if (toX > 9) toX = 9;

    if (fromY < 0) fromY = 0;
    if (toY > 9) toY = 9;

    // Loop through all coordinates around and inside the ship, and if a checkbox already is
    // selected, it's a collision
    for (int y = fromY; y <= toY; y++) {
      for (int x = fromX; x <= toX; x++) {
        if (checkboxes[x][y].isSelected()) {
          return true;
        }
      }
    }

    // If we reach here no collision was made
    return false;
  }

  /** Resets the panel */
  @Override
  public void reset() {
    super.reset();
    selected = 0;
  }
}
示例#15
0
  @Override
  public void OnPlayersUpdated(Integer num) {

    if (isCooldown()) {
      return;
    }

    // Interactions check
    for (final Player plr : Game.getInstance().players.values()) {
      if (plr.isCooldown()) {
        continue;
      }
      boolean targetInvuln = plr.isInvoln();
      double dist = LatLonDist(plr.latitude, latitude, plr.longitude, longitude);
      if (dist < Game.INTERACTION_RANGE
          && PlayerType.CanInteract(type, isInvoln(), plr.type, targetInvuln)) {
        WakkaWebClient.getInstance()
            .Interact(
                plr.devid,
                new Response.Listener<String>() {
                  @Override
                  public void onResponse(String response) {
                    // Notify Interact success
                    if (!response.equals("COOLDOWN")) {
                      EventBus.NOTIFICATION_EVENTBUS.broadcast(
                          new NotificationEvent.NotificationInfo(
                              type,
                              "You ate "
                                  + plr.name
                                  + " the "
                                  + PlayerType.getTypeString(plr.type)
                                  + "!"));
                    }
                  }
                },
                new Response.ErrorListener() {
                  @Override
                  public void onErrorResponse(VolleyError error) {
                    Log.e("VolleyError", "Could not interact with " + plr.devid);
                    Toast.makeText(
                        Game.getAppContext(),
                        "A network error occured - could not interact.",
                        Toast.LENGTH_SHORT);
                  }
                });
      } else if (dist < Game.THREAT_RANGE
          && PlayerType.CanInteract(plr.type, targetInvuln, type, isInvoln())) {
        // Notify of threat
        // Notify(plr.type, plr.name + " the " + PlayerType.getTypeString(plr.type) + " is nearby,
        // and can eat you!");
        if (plr.presenceAck != 1) {
          plr.presenceAck = 1;
          EventBus.NOTIFICATION_EVENTBUS.broadcast(
              new NotificationEvent.NotificationInfo(
                  plr.type,
                  plr.name
                      + " the "
                      + PlayerType.getTypeString(plr.type)
                      + " is nearby, and can eat you!"));
        }

      } else {
        plr.presenceAck = 0;
      }
    }
  }
示例#16
0
 @Override
 protected void onStop() {
   super.onStop();
   // remove itself as game observer
   Game.getInstance().removeEventObserver(this);
 }