@Test
 public void testEquals() {
     Player p1 = new Player("Namegültig", 435, 243536);
     assertEquals(new Player("Namegültig", 435, 243536), p1);
     assertTrue(!p1.equals(new Player("Namegfültig", 435, 243536)));
     assertTrue(!p1.equals(new Player("Namegültig", 433, 243536)));
     assertTrue(!p1.equals(new Player("Namegültig", 435, 7456)));
 }
 @EventHandler
 void onPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
   if (event.getPlayer().hasMetadata("give-pet")) {
     if (event.getRightClicked() instanceof Tameable) {
       Tameable pet = (Tameable) event.getRightClicked();
       if (pet.isTamed() && pet.getOwner() instanceof Player) {
         Player player = (Player) pet.getOwner();
         if (player.equals(event.getPlayer())
             || event.getPlayer().hasPermission("omneity3.give-pet.override")) {
           OfflinePlayer reciever =
               plugin
                   .getServer()
                   .getOfflinePlayer(
                       (String) event.getPlayer().getMetadata("give-pet").get(0).value());
           pet.setOwner(reciever);
           event.getPlayer().removeMetadata("give-pet", plugin);
         } else {
           event.getPlayer().sendMessage("This pet is not yours to give");
           event.getPlayer().removeMetadata("give-pet", plugin);
         }
       } else {
         event.getPlayer().sendMessage("This pet is not tamed");
         event.getPlayer().removeMetadata("give-pet", plugin);
       }
     } else {
       event.getPlayer().sendMessage("That entity can not be a pet");
       event.getPlayer().removeMetadata("give-pet", plugin);
     }
   }
 }
Beispiel #3
0
 public void switchPlayer() {
   if (currentPlayer.equals(player1)) {
     currentPlayer = player2;
   } else {
     currentPlayer = player1;
   }
 }
    public GuardiansSpawner(NpcInstance npc, QuestState st, int _count) {
      NpcTemplate template = NpcHolder.getInstance().getTemplate(Soul_of_Tree_Guardian);
      if (template == null) return;
      try {
        _spawn = new SimpleSpawner(template);
      } catch (Exception e) {
        e.printStackTrace();
      }
      for (int i = 0; i < _count; i++) {
        _spawn.setLoc(Location.findPointToStay(npc, 50, 200));
        _spawn.setHeading(Rnd.get(0, 0xFFFF));
        _spawn.setAmount(1);
        _spawn.doSpawn(true);

        agressor = st.getPlayer().getName();
        if (st.getPlayer().getSummonList().getPet() != null)
          agressors_pet = st.getPlayer().getSummonList().getPet().getName();
        if (st.getPlayer().getParty() != null) {
          agressors_party = new ArrayList<String>();
          for (Player _member : st.getPlayer().getParty().getPartyMembers())
            if (!_member.equals(st.getPlayer())) agressors_party.add(_member.getName());
        }
      }
      _spawn.stopRespawn();
      updateAgression();
    }
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (obj == null) return false;
   if (getClass() != obj.getClass()) return false;
   Media other = (Media) obj;
   if (_bitrate != other._bitrate) return false;
   if (_copyright == null) {
     if (other._copyright != null) return false;
   } else if (!_copyright.equals(other._copyright)) return false;
   if (_duration != other._duration) return false;
   if (_format == null) {
     if (other._format != null) return false;
   } else if (!_format.equals(other._format)) return false;
   if (_height != other._height) return false;
   if (_persons == null) {
     if (other._persons != null) return false;
   } else if (!_persons.equals(other._persons)) return false;
   if (_player == null) {
     if (other._player != null) return false;
   } else if (!_player.equals(other._player)) return false;
   if (_size != other._size) return false;
   if (_title == null) {
     if (other._title != null) return false;
   } else if (!_title.equals(other._title)) return false;
   if (_uri == null) {
     if (other._uri != null) return false;
   } else if (!_uri.equals(other._uri)) return false;
   if (_width != other._width) return false;
   return true;
 }
Beispiel #6
0
  // returns playerId of a specific Player by comparing the ClientInterfaces
  // returns -1 when no such player is found
  public int getPlayerIdByInterfaceCheck(Player p1) {
    for (Player p2 : this.players) {
      if (p1.equals(p2)) {
        return p2.getId();
      }
    }

    return -1;
  }
Beispiel #7
0
  // checks whether a player is already in this lobby (by checking the
  // ClientInterface). returns true if player is already there, false if not
  public boolean containsPlayerIdByInterfaceCheck(Player p1) {
    for (Player p2 : this.players) {
      if (p1.equals(p2)) {
        return true;
      }
    }

    return false;
  }
    @EventHandler
    public void onProjectileHit(ProjectileHitEvent projectile) {
      Heroes.debug.startTask("HeroesSkillListener");

      if (!(projectile.getEntity() instanceof Arrow)) {
        Heroes.debug.stopTask("HeroesSkillListener");
        return;
      }

      Arrow arrow = (Arrow) projectile.getEntity();

      if (!(arrow.getShooter() instanceof Player)) {
        Heroes.debug.stopTask("HeroesSkillListener");
        return;
      }

      Player player = (Player) arrow.getShooter();
      Hero hero = SkillExplodingArrow.this.plugin.getCharacterManager().getHero(player);
      if (!hero.hasEffect("ExplodingArrowBuff")) {
        Heroes.debug.stopTask("HeroesSkillListener");
        return;
      }

      int radius =
          (int)
              Math.pow(
                  SkillConfigManager.getUseSetting(hero, this.skill, "radius", 5, false), 2.0D);

      float damage = SkillConfigManager.getUseSetting(hero, this.skill, "DAMAGE", 5, false);
      float blockdamage = damage;
      int block_dmg = SkillConfigManager.getUseSetting(hero, this.skill, "block-dmg", 0, false);

      if (block_dmg == 0) {
        blockdamage = 0.0F;

        for (Entity t_entity : player.getWorld().getEntities()) {
          if ((t_entity instanceof Player)) {
            Player heroes = (Player) t_entity;
            if ((heroes.equals(player))
                || (heroes.getLocation().distanceSquared(arrow.getLocation()) > radius)) continue;
            damageEntity(
                heroes, player, (int) damage, EntityDamageEvent.DamageCause.ENTITY_EXPLOSION);
          } else if ((t_entity instanceof Creature)) {
            Creature mob = (Creature) t_entity;
            if (t_entity.getLocation().distanceSquared(arrow.getLocation()) <= radius) {
              damageEntity(
                  mob, player, (int) damage, EntityDamageEvent.DamageCause.ENTITY_EXPLOSION);
            }
          }
        }
      }

      arrow.getWorld().createExplosion(arrow.getLocation(), blockdamage);

      Heroes.debug.stopTask("HeroesSkillListener");
    }
 public void showOnlyToPlayer(Player player) {
   this.spawn();
   try {
     for (Player non : etc.getServer().getPlayerList()) {
       if (!non.equals(player)) {
         hideNPCFrom(non);
       }
     }
   } catch (Exception ex) {
   }
 }
Beispiel #10
0
 private void checkCollisionWithOtherObjectForPlayer(Player player) {
   ArrayList<Player> playerArray = new ArrayList<>();
   playerArray.addAll(team0.getPlayers());
   playerArray.addAll(team1.getPlayers());
   for (Player otherPlayer : playerArray) {
     if (!player.equals(otherPlayer)) {
       player.checkCollisionWithObject(otherPlayer, endTurnStepTime);
     }
   }
   player.checkCollisionWithObject(puck, endTurnStepTime);
 }
Beispiel #11
0
  /**
   * Handles a pickup packet from the server. The level then gives the appropriate player the item
   * parsed in the packet.
   *
   * @param username - username of the player picking up the item
   * @param tileID - ID of the tile that the item was on
   * @param itemID - ID of the item to be picked up
   */
  public void handlePickUp(String username, int tileID, int itemID) {

    Player player = getPlayer(username);

    // We do not want to handle a pickup from the player on this computer
    if (player.equals(game.getPlayer())) return;

    Room currentRoom = player.getRoom();
    Tile tile = currentRoom.getTile(player, tileID);

    if (tile != null) tile.onEnter(player);
    else System.err.println("Tile is NULL");
  }
Beispiel #12
0
 @Override
 public void sendMove(Player player, Location from, Location to) {
   if (player.equals(this.player) && !this.finalizing) {
     if (!this.waiting) {
       if (iLoveYou.distance(from, this.herobrine.getLocation())
           > iLoveYou.distance(to, this.herobrine.getLocation())) {
         moveHerobrine();
         this.herobrine.showOnlyToPlayer(player);
       }
     } else {
       double d1 = this.herobrine.getX() - to.x;
       double d2 = this.herobrine.getZ() - to.z;
       double d3 = Math.toDegrees(Math.atan(Math.abs(d1 / d2)));
       double d4 =
           Math.asin(
                   (this.herobrine.getY() - to.y)
                       / iLoveYou.distance(
                           to,
                           new Location(
                               this.herobrine.getX(),
                               this.herobrine.getY(),
                               this.herobrine.getZ())))
               * 45.0D;
       if (d1 >= 0.0D) {
         if (d2 >= 0.0D) {
           d3 = 180.0D - d3;
         }
       } else if (d2 >= 0.0D) {
         d3 += 180.0D;
       } else {
         d3 = 360.0D - d3;
       }
       this.herobrine.teleportTo(
           this.herobrine.getX(),
           this.herobrine.getY(),
           this.herobrine.getZ(),
           (float) d3,
           (float) d4);
       this.herobrine.showOnlyToPlayer(player);
       this.herobrine.lookat(this.player);
       if (iLoveYou.distance(to, this.herobrine.getLocation()) < 3.0D) {
         this.finalizing = true;
         this.herobrine.sendMessage(player, getFarewell());
         server.addToServerQueue(new DiamondEvent.BlockRestorer(), 300L);
         this.herobrine.destroy();
       }
     }
   }
 }
Beispiel #13
0
  public Player getPlayer(String name) {
    // Player p = playerlist.get(name);
    // return p;
    /// *
    // playerlist.keySet()
    for (Player p : playerlist.values()) {
      if (p.equals(playerlist.get(name))) {
        return p;
      }
    }

    //    Player z = playerlist.values();
    return null;
    // */
  }
Beispiel #14
0
 private PlayerInfo buildPlayerInfo(final Player p) {
   final PlayerInfo info = new PlayerInfo();
   final Stich r = getCurrentStich();
   info.setAufspieler(r != null ? r.getStarter().getUsername() : "");
   info.setGeber(geber != null ? geber.getUsername() : "");
   info.setActive(p.equals(this.activePlayer));
   info.setKarten(buildCardInfo());
   info.setPlayerId(p.getId());
   info.setPosition(p.getPosition());
   info.setKleinesHolz(0);
   info.setGrossesHolz(0);
   info.setPunkte(sumPoints(p));
   info.setName(p.getUsername());
   info.setRunde(r == null ? 0 : r.getStichNr());
   info.setTrumpf(trumpfFarbe);
   return info;
 }
Beispiel #15
0
  /**
   * Handles an interact packet sent from the server. Interactions are then performed by the
   * appropriate player on the appropriate tile.
   *
   * @param username - username of the player interacting
   * @param ID - ID of the tile to interact with
   */
  public void handleInteract(String username, int ID) {

    Player player = getPlayer(username);

    // We do not want to handle an interact from the player on this computer
    if (player.equals(game.getPlayer())) return;

    Room currentRoom = player.getRoom();
    Tile tile = currentRoom.getTile(player, ID);

    if (tile != null) {
      // System.out.println(tile.getClass().getName());
      tile.onInteract(player);
    }

    for (Player p : players) {
      // System.out.println(p.getUsername() + " is in: "
      // + p.getRoom().getName());
    }
  }
Beispiel #16
0
 /**
  * A command method to attack a player. Tell the player that he can't attack himself and do
  * different stuff depending on weapon.
  *
  * @param p a reference to player is sent to all commands to refer to the player who used the
  *     command
  */
 @Command
 public void attack(Player p) {
   if (!p.equals(this)) {
     if (p.hasItem("sword")) {
       System.out.println(
           "You attack the "
               + this.getName()
               + " with your sword. The "
               + this.getName()
               + " dies.");
       p.getCurrentRoom().getInventory().removeObject(this);
       p.getCurrentRoom()
           .setDescription(
               "This is a small room with a passage to the east. Bloodstains and deep scratches \n(perhaps made by an axe) mar the walls.");
       p.getCurrentRoom().getExit("east").setLockedMessage("");
     } else if (p.hasItem("knife")) {
       System.out.println(
           "You attack the "
               + this.getName()
               + " with your knife. The "
               + this.getName()
               + " dies.");
       p.getCurrentRoom().getInventory().removeObject(this);
       p.getCurrentRoom()
           .setDescription(
               "This is a small room with a passage to the east. Bloodstains and deep scratches \n(perhaps made by an axe) mar the walls.");
       p.getCurrentRoom().getExit("east").setLockedMessage("");
     } else {
       System.out.println(
           "You attack the "
               + this.getName()
               + " with your bare hands. \nIt proves to be very inefficient and the "
               + this.getName()
               + "attacking you until you die.");
       p.die();
     }
   } else {
     System.out.println("You can't attack yourself. Are you stupid!?");
   }
 }
  /**
   * Returns the utility of the given State (assumed terminal) for the computer player.
   *
   * <p>You could move this method into the State class, but note that the utility depends on which
   * player is ``us.'' There are other ways you could handle that. For TTT, doing it here is ok and
   * also makes the code look more like the book's pseudocode.
   */
  protected int utility(State s) {

    if (true) ; // s.isTerminal())
    {
      // System.out.println("terminal");
      Player winner = s.getWinner();
      if (winner == null) {
        // Draw
        return 0;
      } else if (winner.equals(humanPlayer)) {
        // System.out.println("loss");
        // Lose
        return -10;
      } else {
        // Win
        return 10;
      }
    }
    /*else
    {
    	//System.out.println("not terminal");
    	for(int i = s.board.getSize()-1; i > 1 ; i--)
    	{
    		//int utility = (int) Math.pow(2,i);
    		//2 in a row gains have high priority
    		if(s.board.getNInARow(i) == humanPlayer)
    		{
    			//System.out.println("towards losing");
    			return -1*i;
    		}
    		else if(s.board.getNInARow(i) == null)
    		{int x = 0;}
    		else
    			return i;
    	}
    	return 0;
    }*/
  }
Beispiel #18
0
  public static void main(String[] args) {

    Boolean didUserWin = false;
    CardPile deck;

    ArrayList<Player> players = new ArrayList<Player>();
    players.add(new User("Human"));

    printGreeting();

    int numComps;
    if (DEBUG) {
      numComps = 3;
    } else {
      /*
       * ask for number of player
       */
      numComps = getNumComps();
    }
    /*
     * Create computer players
     */
    for (int i = 0; i < numComps; i++) {
      players.add(new Opponent("Comp " + String.valueOf(i + 1)));
    }

    /*
     * get our deck of cards
     */
    deck = new CardPile();

    Boolean isContinuePlay = true;

    while (isContinuePlay) {

      /*
       * randomizes position of cards within deck
       */
      deck.shuffle();

      System.out.println("Cards have been shuffled.  Let's play!");
      pause();

      System.out.println("Dealer is dealing cards to players...");
      pause();

      /*
       * draw cards for each player
       */
      if (DEBUG) {
        players.get(0).getHand().addCard(new Card(Suit.SPADES, Rank.ACE));
        players.get(0).getHand().addCard(new Card(Suit.HEARTS, Rank.TEN));
        players.get(0).getHand().addCard(new Card(Suit.HEARTS, Rank.TWO));
        players.get(0).getHand().addCard(new Card(Suit.SPADES, Rank.FIVE));
        players.get(0).getHand().addCard(new Card(Suit.CLUBS, Rank.FOUR));
        players.get(1).getHand().addCard(new Card(Suit.HEARTS, Rank.ACE));
        players.get(1).getHand().addCard(new Card(Suit.SPADES, Rank.NINE));
        players.get(1).getHand().addCard(new Card(Suit.SPADES, Rank.THREE));
        players.get(1).getHand().addCard(new Card(Suit.CLUBS, Rank.KING));
        players.get(1).getHand().addCard(new Card(Suit.SPADES, Rank.FOUR));
        players.get(2).getHand().addCard(new Card(Suit.SPADES, Rank.QUEEN));
        players.get(2).getHand().addCard(new Card(Suit.CLUBS, Rank.TEN));
        players.get(2).getHand().addCard(new Card(Suit.CLUBS, Rank.JACK));
        players.get(2).getHand().addCard(new Card(Suit.HEARTS, Rank.SIX));
        players.get(2).getHand().addCard(new Card(Suit.CLUBS, Rank.FOUR));
        players.get(3).getHand().addCard(new Card(Suit.DIAMONDS, Rank.TWO));
        players.get(3).getHand().addCard(new Card(Suit.SPADES, Rank.NINE));
        players.get(3).getHand().addCard(new Card(Suit.DIAMONDS, Rank.THREE));
        players.get(3).getHand().addCard(new Card(Suit.SPADES, Rank.TEN));
        players.get(3).getHand().addCard(new Card(Suit.HEARTS, Rank.FOUR));
      } else {
        for (int c = 1; c <= MAX_HAND_SIZE; c++) {
          for (Player player : players) {
            player.getHand().addCard(deck.drawCard());
          }
        }
      }
      /*
       * show user their hand in descending rank
       */
      showHand(players.get(USER_INDEX_POSITION), "The cards in your hand are: ");
      pause();

      System.out.println("It is time now to discard unwanted cards.");
      /*
       * get user's unwanted cards
       */
      ArrayList<Integer> discardIndices = getDiscardedCards(players.get(USER_INDEX_POSITION));

      /*
       * physically discard the user's cards
       */
      ArrayList<Card> discardCards = new ArrayList<Card>();
      for (int discardIndex : discardIndices) {
        Card card = players.get(USER_INDEX_POSITION).getHand().getCardAtIndex(discardIndex - 1);
        if (card != null) {
          discardCards.add(card);
        } else {
          System.out.println("Failed to get card at index " + discardIndex);
        }
      }
      for (Card discardCard : discardCards) {
        players.get(USER_INDEX_POSITION).getHand().discardCard(discardCard);
      }

      if (!DEBUG) {
        /*
         * opponents discard their non-valuable cards
         */
        for (int i = 0; i < players.size(); i++) {
          // we loop through all index values of array not assuming
          // which
          // index position user is at... if index is user, continue
          if (i == USER_INDEX_POSITION) continue;
          // now we are in index position related to opponent
          // Cast player as opponent
          Opponent opponent = (Opponent) players.get(i);
          opponent.discardCards();

          int discarded = MAX_HAND_SIZE - players.get(i).getHand().getCardCount();
          if (discarded > 0) {
            System.out.println(
                players.get(i).getName()
                    + " has discarded "
                    + discarded
                    + " card"
                    + (discarded > 1 ? "s" : ""));
          } else {
            System.out.println(players.get(i).getName() + " has chosen to keep their hand");
          }
        }
      }
      pause();

      /*
       * loop through each player and draw new cards
       */
      for (Player player : players) {
        int drawn = 0;
        for (int i = player.getHand().getCardCount() + 1; i <= MAX_HAND_SIZE; i++) {
          player.getHand().addCard(deck.drawCard());
          drawn++;
        }
        if (drawn > 0)
          System.out.println(
              player.getName() + " has drawn " + drawn + " card" + (drawn > 1 ? "s" : ""));
      }
      pause();

      /*
       * show everyone's hand and determine who has best
       */
      int highestScore = -1;
      for (Player player : players) {
        int playerScore = player.getHand().evalHand();
        if (highestScore < playerScore) {
          highestScore = playerScore;
        }

        System.out.println(player.getName() + " has a " + player.getHand().getHandHas());
        showHand(player, player.getName() + "'s hand: ");
        System.out.println();
      }
      // We need ArrayList of who has highest score in case of ties
      ArrayList<Player> winners = new ArrayList<Player>();
      for (Player player : players) {
        int playerScore = player.getHand().evalHand();
        if (highestScore == playerScore) {
          winners.add(player);
        }
      }

      System.out.println();
      if (winners.size() == 1) {
        System.out.println(
            winners.get(0).getName()
                + " wins this hand with a "
                + winners.get(0).getHand().getHandHas()
                + ".");
        didUserWin = (winners.get(0).getName() == players.get(USER_INDEX_POSITION).getName());
      } else {
        // we need to break ties
        for (int i = 0; i < winners.size() - 1; i++)
          for (int j = i + 1; j < winners.size(); j++) {
            Player player1 = winners.get(i);
            Player player2 = winners.get(j);
            if (player1.equals(player2)) continue;
            int result = player1.getHand().willBeat(player2.getHand());
            if (result == 1) {
              // player 2 lost this match, so remove from winners
              // list
              winners.remove(player2);
              j--;
            } else if (result == 0) {
              // player 1 lost this match, so remove from winners
              // list
              winners.remove(player1);
              j--;
            }
          }
        if (winners.size() == 1) {
          System.out.println(
              winners.get(0).getName()
                  + " wins this hand with a "
                  + winners.get(0).getHand().getHandHas()
                  + ".");
          didUserWin = (winners.get(0).getName() == players.get(USER_INDEX_POSITION).getName());
        } else {
          System.out.println("There was an unbreakable tie.");
        }
      }

      // Placeholder - hardcode to end game
      isContinuePlay = false;
    }

    if (didUserWin) System.out.println("Thanks for playing.  You rock!");
    else System.out.println("Thanks for playing.  Better luck next time.");
  }
Beispiel #19
0
  public MiniMaxTree miniMaxHelperWithGO2(
      MiniMaxTree gameTree,
      MiniMaxNode rootNode,
      Player currPlayer,
      int[] tempBoard,
      int tempDepth,
      int globalDepth,
      boolean checkParentsFt) {

    System.out.println();
    // System.out.println("In miniMaxHelperWithGO2 ");
    // TODO : CHECK THE DEPTH
    if (tempDepth >= globalDepth && !checkParentsFt) {
      return gameTree;
    }

    MiniMaxNode currParent = rootNode;

    if (!checkParentsFt) {
      if (currPlayer.equals(player1)) {
        currPlayer = player2;
      } else {
        currPlayer = player1;
      }
    }

    int startIndex = 0;
    int endIndex = mancalaBoard.getPitSize();
    if (currPlayer.playerNum == 2) {
      startIndex = mancalaBoard.getPitSize() + 1;
      endIndex = mancalaBoard.getBoardSize() - 1;
    }

    // boolean checkParentsFt = false;
    int i = startIndex;
    for (i = startIndex; i < endIndex; i++) {

      Move currMove = new Move(i);
      if (isIllegalMove(currMove, tempBoard)) {
        continue;
      } else {
        BoardFTCheck bft = makeTempMiniMaxMoveWithGO2(currMove, currPlayer, tempBoard);

        int mydepth = currParent.depth;
        if (mydepth == 0) {
          mydepth++;
        }

        if (!checkParentsFt) {
          mydepth++;
        }

        int evalFunc;
        // Odds are minimizers
        if (mydepth % 2 == 1) {
          evalFunc = Integer.MAX_VALUE;
        } else {
          evalFunc = Integer.MIN_VALUE;
        }

        // if we reached the leaf find the evaluation right away
        if (mydepth == globalDepth || bft.leadsToGameOver) {
          displayHelper(bft.tempBoard);

          // If I dont get a free turn at last level then only evaluate
          if (!bft.freeTurn) {
            evalFunc = getEvalFunc(currPlayer, bft.tempBoard);
          } else {
            // last level is already toggled
            if (evalFunc == Integer.MAX_VALUE) {
              evalFunc = Integer.MIN_VALUE;
            } else {
              evalFunc = Integer.MAX_VALUE;
            }
          }
        }

        MiniMaxNode newNode =
            new MiniMaxNode(
                bft.tempBoard,
                currPlayer.playerNum,
                mydepth,
                evalFunc,
                currParent,
                currMove,
                bft.freeTurn);

        // displayHelper(bft.tempBoard);
        /*System.out.println("Node to insert is ");
        displayHelper(newNode.nodeBoard);
        System.out.println("£££££££££££££££££££££££££££");
        System.out.println("In insert tree");
        System.out.println("£££££££££££££££££££££££££££");*/

        gameTree.insert(newNode, currParent);

        // gameTree.displayTree();

        /*System.out.println("return from insert tree");
        System.out.println();*/

        if (bft.freeTurn) {
          miniMaxHelperWithGO2(
              gameTree, newNode, currPlayer, bft.tempBoard, mydepth, globalDepth, true);
        } else {
          miniMaxHelperWithGO2(
              gameTree, newNode, currPlayer, bft.tempBoard, mydepth, globalDepth, false);
        }
      }
    }
    return gameTree;
  }
Beispiel #20
0
  /** Playing the game */
  public void playGame() {

    Player currPlayer = player1;
    int numOfTotalMoveplayer1 = 0;
    int numOfTotalMoveplayer2 = 0;

    while (true) {

      // System.out.println();
      /*System.out.println();
      System.out.println("##################################");

      System.out.println("Current Player is player " + currPlayer.playerNum);
      System.out.println();
      System.out.println();
      System.out.println("################################");
      System.out.println("          TURN CHANGED");
      System.out.println("################################"); */

      // Find the nextMove
      Move nextMove;
      if (!currPlayer.isHuman) {
        nextMove = getCompMove(mancalaBoard.getPitSize(), searchType, currPlayer);
      } else {
        nextMove = getHumanMove(mancalaBoard.getPitSize(), currPlayer);
      }

      // Play the move
      boolean gotFreeTurn = makeMove(nextMove, currPlayer);

      if (currPlayer.equals(player1)) {
        numOfTotalMoveplayer1++;
      } else {
        numOfTotalMoveplayer2++;
      }

      // Check for game over
      if (isGameOver(mancalaBoard.getBoard())) {
        mancalaBoard.setBoard(getAllStones(mancalaBoard.getBoard()));
        if (isGameDrawn()) {
          System.out.println("No winner : Game draw");
        } else {
          int winner = findWinner();
          System.out.println("Game over. Player " + winner + " won.");
          System.out.println("Scores are");
          System.out.println("Player 1: " + getScore(player1));
          System.out.println("Player 2: " + getScore(player2));
        }

        System.out.println("Player1 took : " + numOfTotalMoveplayer1 + "moves");
        System.out.println("Player2 took : " + numOfTotalMoveplayer2 + "moves");

        break;
      }

      // Toggle the turn if no free turn
      if (!gotFreeTurn) {
        if (currPlayer.equals(player1)) {
          currPlayer = player2;
        } else {
          currPlayer = player1;
        }
      }
    }
  }
Beispiel #21
0
  public synchronized boolean executeAction(Action a) {
    if (a.onUnite && !this.united) {
      this.actionOnUnite = a;
      this.united = true;
    }
    switch (a.action) {
      case HonorBoost:
        this.player.incrementHonor(a.magnitude);
        this.game.decrementHonor(a.magnitude);
        return true;
      case PowerBoost:
        this.power += a.magnitude;
        return true;
      case RuneBoost:
        this.rune += a.magnitude;
        return true;
      case DrawCard:
        player.playerDeck.drawNCards(a.magnitude);
        return true;
      case Discard:
        optionPane.showMessageDialog(
            game,
            String.format(game.descriptions.getString("SelectDeckDiscard"), a.magnitude),
            "",
            JOptionPane.PLAIN_MESSAGE);
        this.turnState = TurnState.Discard;
        this.turnStateMagnitude = a.magnitude;
        chill();
        return true;
      case OptionalDiscard:
        int za =
            optionPane.showConfirmDialog(
                game,
                String.format(game.descriptions.getString("OptionalHandDiscard"), a.magnitude),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (za == JOptionPane.YES_OPTION) {
          this.turnState = TurnState.Discard;
          this.turnStateMagnitude = a.magnitude;
          chill();
          return true;
        }
        return false;
      case ForcedDeckBanish:
        optionPane.showMessageDialog(
            game,
            String.format(game.descriptions.getString("ForcedBanish"), a.magnitude),
            "",
            JOptionPane.PLAIN_MESSAGE);
        this.turnState = TurnState.DeckBanish;
        this.turnStateMagnitude = a.magnitude;
        chill();
        return true;
      case CenterBanish:
        int m =
            optionPane.showConfirmDialog(
                game,
                String.format(game.descriptions.getString("OptionalCenterBanish"), a.magnitude),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (m == JOptionPane.YES_OPTION) {
          this.turnState = TurnState.CenterBanish;
          this.turnStateMagnitude = a.magnitude;
          chill();
          return true;
        }
        return false;
      case HandBanish:
        int z =
            optionPane.showConfirmDialog(
                game,
                String.format(game.descriptions.getString("OptionalHandBanish"), a.magnitude),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (z == JOptionPane.YES_OPTION) {
          this.turnState = TurnState.HandBanish;
          this.turnStateMagnitude = a.magnitude;
          chill();
          return true;
        }
        return false;
      case OptionalDeckBanish:
        if (player.playerDeck.hand.size() == 0) return false;
        int n =
            optionPane.showConfirmDialog(
                game,
                String.format(game.descriptions.getString("OptionalDeckBanish"), a.magnitude),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (n == JOptionPane.YES_OPTION) {
          this.turnState = TurnState.DeckBanish;
          this.turnStateMagnitude = a.magnitude;
          chill();
          return true;
        }
        return false;
      case HonorAndRuneBoost:
        this.rune += a.magnitude;
        this.player.incrementHonor(a.magnitude);
        this.game.decrementHonor(a.magnitude);
        return true;
      case ConstructRuneBoost:
        this.constructRune += a.magnitude;
        return true;
      case MechanaConstructRuneBoost:
        this.mechanaConstructRune += a.magnitude;
        return true;
      case EnterAiyanaState:
        this.AiyanaState = true;
        return true;
      case HeroRuneBoost:
        this.heroRune += a.magnitude;
        return true;
      case MonsterPowerBoost:
        this.monsterPower += a.magnitude;
        return true;
      case DefeatMonster:
        if (!this.game.gameDeck.canAMonsterBeDefeated(a.magnitude)) {
          this.player.incrementHonor(1);
          this.game.decrementHonor(1);
        } else {
          this.turnState = TurnState.DefeatMonster;
          this.turnStateMagnitude = a.magnitude;
        }
        return true;
      case EnterVoidMesmer:
        this.VoidMesmerState = true;
        return true;
      case FreeCard:
        optionPane.showMessageDialog(
            game, game.descriptions.getString("FreeCard"), "", JOptionPane.PLAIN_MESSAGE);
        this.turnState = TurnState.FreeCard;
        this.turnStateMagnitude = a.magnitude;
      case HeavyOrMystic:
        Object objects[] = {"Mystic", "Heavy Infantry"};
        int heavyOrMysticChoice =
            optionPane.showOptionDialog(
                game,
                game.descriptions.getString("HeavyOrMystic"),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                objects);
        if (heavyOrMysticChoice == JOptionPane.YES_OPTION) {
          this.player.playerDeck.hand.add(new Card(Main.getMystic()));
          this.player.playerDeck.deckRend.resetHandLocation();
        } else {
          this.player.playerDeck.hand.add(new Card(Main.getHeavyInfantry()));
          this.player.playerDeck.deckRend.resetHandLocation();
        }
        return true;
      case LunarStag:
        Object objects2[] = {
          game.descriptions.getString("2Rune"), game.descriptions.getString("2Honor")
        };
        int lunarStagChoice =
            optionPane.showOptionDialog(
                game,
                game.descriptions.getString("LunarStag"),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                objects2);
        if (lunarStagChoice == JOptionPane.YES_OPTION) {
          this.rune += 2;
        } else {
          this.player.incrementHonor(2);
          this.game.decrementHonor(2);
        }
        return true;
      case AskaraOfFate:
        this.player.playerDeck.drawCard();
        for (Player p : this.game.players) {
          p.playerDeck.drawCard();
        }
        return true;
      case AskaraCenterBanish:
        int num1 =
            optionPane.showConfirmDialog(
                game,
                String.format(game.descriptions.getString("OptionalCenterBanish"), 1),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (num1 == JOptionPane.YES_OPTION) {
          this.turnState = TurnState.AskaraCenterBanish;
          this.turnStateMagnitude = 1;
          chill();
          return true;
        }
        return false;
      case NookHound:
        this.player.playerDeck.drawCard();
        Card nookHoundCard =
            this.player.playerDeck.hand.get(this.player.playerDeck.hand.size() - 1);
        int nookHoundNumber =
            optionPane.showConfirmDialog(
                game,
                String.format(
                    game.descriptions.getString("OptionalDiscardDeShiz"), nookHoundCard.getName()),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (nookHoundNumber == JOptionPane.YES_OPTION) {
          this.player.playerDeck.hand.remove(this.player.playerDeck.hand.size() - 1);
          this.player.playerDeck.discard.add(nookHoundCard);
          this.player.playerDeck.drawCard();
        }
        return true;
      case AskaraDiscard:
        optionPane.showMessageDialog(
            game, game.descriptions.getString("DiscardDerpDeDerp"), "", JOptionPane.PLAIN_MESSAGE);
        this.turnState = TurnState.AskaraDiscard;
        this.turnStateMagnitude = 2;
        chill();
        return true;

      case TwofoldAskaraPlayed:
        if (this.player.playerDeck.checkForHeroInPlayedforTwoFold()) {
          optionPane.showMessageDialog(
              game, game.descriptions.getString("PickAndShit"), "", JOptionPane.PLAIN_MESSAGE);
          this.turnState = TurnState.TwofoldAskara;
          chill();

        } else {
          optionPane.showMessageDialog(
              game, game.descriptions.getString("NoHero"), "", JOptionPane.PLAIN_MESSAGE);
        }

        return true;
      case RajAction:
        optionPane.showMessageDialog(
            game, game.descriptions.getString("FryRy"), "", JOptionPane.PLAIN_MESSAGE);
        this.turnState = TurnState.RajTurnState;
        this.turnStateMagnitude = 1;
        chill();

        return true;
      case SeaTyrantAction:
        this.player.incrementHonor(5);
        this.game.decrementHonor(5);
        for (Player p : this.game.players) {
          if (!(p.equals(this.player))) {
            p.flipTyrantConstructsBool();
          }
        }
        return true;
      case CetraAction:
        if (this.game.gameDeck.checkForHeroInCenter()) {
          optionPane.showMessageDialog(
              game, game.descriptions.getString("CenterRowsShiz"), "", JOptionPane.PLAIN_MESSAGE);
          this.turnState = TurnState.FreeCardHero;
          chill();
        } else {
          optionPane.showMessageDialog(
              game, game.descriptions.getString("NoHeroToBuy"), "", JOptionPane.PLAIN_MESSAGE);
        }
        return true;

      case CorrosiveWidowAction:
        this.player.incrementHonor(3);
        this.game.decrementHonor(3);
        for (Player p : this.game.players) {
          if (!p.equals(this.player)) {
            p.flipWidowConstructsBool();
          }
        }
        return true;

      case TabletOfTimesDawn:
        int tabletOptionChoice =
            optionPane.showConfirmDialog(
                game,
                game.descriptions.getString("ZaBannishtheThings"),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (tabletOptionChoice == JOptionPane.YES_OPTION) {
          this.game.extraTurn = true;
          for (int i = 0; i < this.player.playerDeck.constructs.size(); i++) {
            if (this.player.playerDeck.constructs.get(i).getName().equals("Tablet_of_Times_Dawn")) {
              this.player.playerDeck.constructs.remove(i);
            }
          }
          return true;
        }
        return false;

      case YggdrasilStaff:
        this.power += 1;
        if (this.rune >= 4) {
          int yggdrasilStaffChoice =
              optionPane.showConfirmDialog(
                  game,
                  game.descriptions.getString("WouldZaThings"),
                  "",
                  JOptionPane.YES_NO_OPTION,
                  JOptionPane.QUESTION_MESSAGE);
          if (yggdrasilStaffChoice == JOptionPane.YES_OPTION) {
            this.rune -= 4;
            this.player.incrementHonor(3);
            this.game.decrementHonor(3);
            return true;
          }
        }
        return true;

      case AvatarGolem:
        this.power += 2;
        boolean mechanaConstructHonor = false;
        boolean lifeboundConstructHonor = false;
        boolean voidConstructHonor = false;
        boolean enlightenedConstructHonor = false;
        for (Card c : this.player.playerDeck.constructs) {
          if (this.testForMechana(c) && !mechanaConstructHonor) {
            this.player.incrementHonor(1);
            this.game.decrementHonor(1);
            mechanaConstructHonor = true;
          } else if (c.getFaction() == Card.Faction.Lifebound && !lifeboundConstructHonor) {
            this.player.incrementHonor(1);
            this.game.decrementHonor(1);
            lifeboundConstructHonor = true;
          } else if (c.getFaction() == Card.Faction.Void && !voidConstructHonor) {
            this.player.incrementHonor(1);
            this.game.decrementHonor(1);
            voidConstructHonor = true;
          } else if (c.getFaction() == Card.Faction.Enlightened && !enlightenedConstructHonor) {
            this.player.incrementHonor(1);
            this.game.decrementHonor(1);
            enlightenedConstructHonor = true;
          }
        }
        return true;

      case KorAction:
        this.power += 2;
        if (this.player.playerDeck.constructs.size() >= 2) {
          player.playerDeck.drawNCards(1);
        }
        return true;

      case MechanaInitiate:
        Object mechanaInitiateOptions[] = {"1 Rune", "1 Power"};
        int mechanaInitiateChoice =
            optionPane.showOptionDialog(
                game,
                game.descriptions.getString("GainAllTheThings"),
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                mechanaInitiateOptions);
        if (mechanaInitiateChoice == JOptionPane.YES_OPTION) {
          this.rune += 1;
        } else {
          this.power += 1;
        }
        return true;

      case HedronCannon:
        for (Card c : this.player.playerDeck.constructs) {
          if (this.testForMechana(c)) {
            this.power += 1;
          }
        }
        return true;

      case Voidthirster:
        this.power += 1;
        this.VoidthirsterState = true;
        return true;

      case XeronAction:
        this.player.incrementHonor(3);
        this.game.decrementHonor(3);
        for (int i = 0; i < this.game.players.size(); i++) {
          if (!this.game.players.get(i).equals(this.player)) {
            Card xeronTemp = this.game.players.get(i).playerDeck.stealCard();
            if (xeronTemp != null) {
              this.player.playerDeck.hand.add(xeronTemp);
              this.player.playerDeck.resetHandLocation();
            }
          }
        }
        return true;

      case RocketCourier:
        this.RocketCourierState++;
        return true;

      case HedronLinkDevice:
        this.HedronLinkDeviceState = true;
        return true;
      case HeroTopOfDeck:
        this.HeroTopOfDeckState = true;
        return true;
    }
    return false;
  }
Beispiel #22
0
  /**
   * Go through each player and check what action they are doing. Also, go through each tile and
   * update it.
   */
  public void tick() {

    // System.out.println(game.getPlayer().getUsername() + "'s game");

    // for (Player p : players)
    // System.out.println(p.getUsername() + "is in: " +
    // p.getRoom().getName());
    // Go through players
    for (Player p : players) {
      if (!p.isAlive()) {
        game.r_removeModel(p.getUsername());
      }

      // Only render the player if they are alive
      if (readyToRender && p.isAlive()) {

        // If the player is in the same room as the player on this
        // computer, add them to the renderer
        if (p.getRoom().equals(game.getPlayer().getRoom())) {
          if (game.r_addModel(p.getModel())) {
            // System.out.println("Adding " + p.getUsername()
            //		+ "'s model in "
            //		+ game.getPlayer().getUsername() + "'s game");
          }
        }

        // If the player is not in the same room as the
        // player on this computer, remove them from the
        // renderer
        else if (!p.getRoom().equals(game.getPlayer().getRoom())) {
          game.r_removeModel(p.getUsername());
        }

        // Update the room
        if (!p.isRoomLoaded() && p.equals(game.getPlayer())) {

          if (p.getOldRoom() != null) p.getOldRoom().removeTiles(game.getRenderer());

          p.getRoom().initTiles(game.getRenderer());
          p.setRoomLoaded(true);
        }

        // Update player
        p.tick();

        // Packet to be sent to the server
        Packet packet = null;

        // Player shooting
        if (p.isShooting()) {
          packet = new Packet03Engage(p.getUsername());
          // packet.writeData(game.getClient());
        }

        // Player interacting
        // Check if player is interacting with a tile
        if (p.isInteracting()
            && p.getRoom() != null
            && p.equals(game.getPlayer())
            && p.getRoom().validPosition(p, p.getX(), p.getY())) {
          Tile tile = p.getRoom().getTile(p, p.getX(), p.getY());
          // isInteracting = false;
          // tile.onInteract(p);

          // Find the type of interaction
          switch (p.getInteraction()) {
            case CHEST:
            case DOOR:
            case TERMINAL:
              packet = new Packet06Interact(p.getUsername(), tile.getID());
              break;

            case NONE:
            default:
              break;
          }

          // Interact with the tile
          tile.onInteract(p);

          // Reset the interaction back to NONE
          p.resetInteraction();

          p.setInteracting(false);

          if (packet != null) packet.writeData(game.getClient());
        }

        // Check health
        if (!p.getUsername().equals(game.getPlayer().getUsername())) {
          Player pl = getPlayer(game.getPlayer().getUsername());

          if (pl.getRoom().equals(p.getRoom())
              && pl.getSide() == Team.GUARD
              && p.getSide() == Team.SPY
              && pl.inRange(p.getX(), p.getY())) {
            // getPlayer(game.getPlayer().getUsername())
            // .takeDamage(0.1);
            packet = new Packet04Damage(p.getUsername(), p.getUsername(), 0.5);
            packet.writeData(game.getClient());
          }
        }

        // Player moving
        if (p.isMoving()) {
          packet =
              new Packet02Move(
                  p.getUsername(),
                  ((PlayerMP) p).getID(),
                  p.getX(),
                  p.getY(),
                  p.getZ(),
                  true,
                  p.getRotation());
          packet.writeData(game.getClient());
        }

        // Player picking up item
        if (p.itemPickedUp()) {
          Tile tile = p.getRoom().getTile(p, p.getX(), p.getY());
          Item last = p.getLastItem();
          p.setItemPickedUp(false);
          packet = new Packet10Pickup(p.getUsername(), tile.getID(), last.getID());
          packet.writeData(game.getClient());
        }

        // Finally tick through the room that the player is in
        p.getRoom().tick(game.getRenderer(), game.getPlayer());
      }
    }
  }
Beispiel #23
0
 @Override
 public void sendTeleport(Player player, Location from, Location to) {
   if (player.equals(this.player) && iLoveYou.distance(from, to) > 10.0D) {
     delete();
   }
 }
Beispiel #24
0
  public void playCard() {
    boolean fujaba__Success = false;
    Player player2 = null;
    Iterator fujaba__IterPlayer2ToCard2 = null;
    Card card2 = null;

    // story pattern successor
    try {
      fujaba__Success = false;

      // check object card1 is really bound
      JavaSDM.ensure(card1 != null);
      // check object cardsInPlay is really bound
      JavaSDM.ensure(cardsInPlay != null);
      // check object player1 is really bound
      JavaSDM.ensure(player1 != null);
      // check object turn is really bound
      JavaSDM.ensure(turn != null);
      // check link contain from card1 to cardsInPlay
      JavaSDM.ensure(cardsInPlay.equals(card1.getCardsInPlay()));

      // check link has from turn to player1
      JavaSDM.ensure(player1.equals(turn.getPlayer()));

      // search to-one link before from player1 to player2
      player2 = player1.getNext();

      // check object player2 is really bound
      JavaSDM.ensure(player2 != null);

      // check isomorphic binding between objects player2 and player1
      JavaSDM.ensure(!player2.equals(player1));

      // check link has from card1 to player1
      JavaSDM.ensure(card1.hasInPlayer(player1));

      // attribute condition suit == J
      JavaSDM.ensure(JavaSDM.stringCompare((String) card1.getSuit(), J) == 0);

      // attribute condition suit == card.getSuit()
      JavaSDM.ensure(JavaSDM.stringCompare((String) turn.getSuit(), card.getSuit()) == 0);

      // destroy link has from card1 to player1
      card1.removeFromPlayer(player1);
      fujaba__Success = true;
    } catch (JavaSDMException fujaba__InternalException) {
      fujaba__Success = false;
    }

    // story pattern Successor of successor
    try {
      fujaba__Success = false;

      // check object card1 is really bound
      JavaSDM.ensure(card1 != null);
      // check object cardsInPlay is really bound
      JavaSDM.ensure(cardsInPlay != null);
      // check object player1 is really bound
      JavaSDM.ensure(player1 != null);
      // check object player2 is really bound
      JavaSDM.ensure(player2 != null);
      // check object turn is really bound
      JavaSDM.ensure(turn != null);
      // check isomorphic binding between objects player2 and player1
      JavaSDM.ensure(!player2.equals(player1));

      // check link before from player2 to player1
      JavaSDM.ensure(player1.equals(player2.getFirst()));

      // check link contain from card1 to cardsInPlay
      JavaSDM.ensure(cardsInPlay.equals(card1.getCardsInPlay()));

      // check link has from turn to player1
      JavaSDM.ensure(player1.equals(turn.getPlayer()));

      // iterate to-many link has from player2 to card2
      fujaba__Success = false;
      fujaba__IterPlayer2ToCard2 = player2.iteratorOfCard();

      while (!(fujaba__Success) && fujaba__IterPlayer2ToCard2.hasNext()) {
        try {
          card2 = (Card) fujaba__IterPlayer2ToCard2.next();

          // check object card2 is really bound
          JavaSDM.ensure(card2 != null);
          // check isomorphic binding between objects card2 and card1
          JavaSDM.ensure(!card2.equals(card1));

          fujaba__Success = true;
        } catch (JavaSDMException fujaba__InternalException) {
          fujaba__Success = false;
        }
      }
      JavaSDM.ensure(fujaba__Success);
      // attribute condition suit != card.getSuit()
      JavaSDM.ensure(JavaSDM.stringCompare((String) turn.getSuit(), card.getSuit()) != 0);

      // attribute condition suit == J
      JavaSDM.ensure(JavaSDM.stringCompare((String) card1.getSuit(), J) == 0);

      // destroy link has from turn to player1
      turn.setPlayer(null);
      // create link has from turn to player2
      turn.setPlayer(player2);

      // create link contain from card2 to cardsInPlay
      card2.setCardsInPlay(cardsInPlay);

      fujaba__Success = true;
    } catch (JavaSDMException fujaba__InternalException) {
      fujaba__Success = false;
    }

    return;
  }