/** * Even distirbution of the total cash by ship capacity in the convoy. */ private void updatePlayerByCapacityPercentage(IConvoy convoy, Map<IPlayer, Integer> capacityMap, long totalCash) { double totalCapacity = convoy.getCapacity(); for (Entry<IPlayer, Integer> entry : capacityMap.entrySet()) { double percentage = entry.getValue()/totalCapacity; long partialAmount = Math.round(totalCash*percentage); IPlayer player = entry.getKey(); if (player instanceof IHumanPlayer) { player.getCompany().updateCash(partialAmount); } else { player.getCompany().updateCashDirectly(partialAmount); } } }
@Override public void run() { int bounty = (int)(Math.abs(opponent.getCompany().getCash()/2000*rnd.nextDouble())); if (opponent instanceof IHumanPlayer) { opponent.getCompany().updateCash(-bounty); } else { opponent.getCompany().updateCashDirectly(-bounty); } DisplayMessage msg = new DisplayMessage("ch.sahits.game.graphic.event.task.BreakInAction.message", bounty, opponent.getLastName()); clientEventBus.post(msg); }
@Override public void run() { if (player instanceof IHumanPlayer) { player.getCompany().updateCash(tenant.getRentPerWeek()); } else { player.getCompany().updateCashDirectly(tenant.getRentPerWeek()); } } }
@Override public boolean execute() { clientEventBus.post(new DisplayMessage("ch.sahits.game.event.handler.impl.SinkConcurrentShipOrder.thankyou")); if (player instanceof IHumanPlayer) { player.getCompany().updateCash(premium); } else { player.getCompany().updateCashDirectly(premium); } if (reconciliation != null) { list.remove(reconciliation); } return true; }}
/** * Redistribute the cash between the players and the convoy owner. The amounts deduced in one place are added in the * other. */ private void updatePlayerByCapacityPercentageRedistribution(IPlayer player, IConvoy convoy, Map<IPlayer, Integer> capacityMap, long totalCash) { double totalCapacity = convoy.getCapacity(); ICompany company = player.getCompany(); for (Entry<IPlayer, Integer> entry : capacityMap.entrySet()) { double percentage = entry.getValue()/totalCapacity; long partialAmount = Math.round(totalCash*percentage); IPlayer player1 = entry.getKey(); ICompany company1 = player1.getCompany(); if (player1 instanceof IHumanPlayer) { company1.updateCash(partialAmount); } else { company1.updateCashDirectly(partialAmount); } if (player instanceof IHumanPlayer) { company.updateCash(-partialAmount); } else { company.updateCashDirectly(-partialAmount); } } }
/** * Calculate the entry fee for the guild based on the company value. * @param player for whom to calculate the entry fee * @return entry fee for the player. */ public int getEntryFee(IPlayer player) { long companyValue = player.getCompany().getCompanyValue(); int min = guildSettings.getMinEntryFee(); int max = guildSettings.getMaxEntryFee(); int span = max - min; if (companyValue <= MIN_COMPANY_VALUE) { return min; } if (companyValue >= MAX_COMPANY_VALUE) { return max; } double factor = companyValue * 1.0 / MAX_COMPANY_VALUE; double fee = min + span * factor; return (int)Math.rint(fee); }
/** * Create a standalone game * @param player identifing the human player UI */ public void startStandaloneGame(IPlayer player) { Preconditions.checkState(this.game != null, "The game has to be initialized first through startGame(IGame, int)"); // the client should be updated through communication channel. // Do we still need the client instance, as the model is created in the server and then replicated on the client? // create the player instances // initilaize the client // run this in the same thread as the user /* engine that handles the city events based on clock ticks */ CityEngine cityEngine = context.getBean(CityEngine.class); cityEngine.start(game); addEngine(cityEngine); createAndInitAIPlayers(numberOfPlayers - 1, player.getCompany().getCash()); AIPlayerEngine aiPlayerEngine = context.getBean(AIPlayerEngine.class); addEngine(aiPlayerEngine); addEngine(context.getBean(EventEngine.class)); logger.debug("Standalone Server created"); } /**
private boolean notEnoughMoney(IPlayer player) { ESocialRank rank = player.getRank(); ESocialRank nextRank = rank.getNextRank(); final ICompany company = player.getCompany(); long compValue = company.getCompanyValue(); return compValue < nextRank.getCompanyValue(); }
@Override public boolean execute(ICity city) { ((IShip)getShip()).setOccupiedSpace(((IShip)getShip()).getOccupiedSpace() - amount); IPlayer owner = (IPlayer) getShip().getOwner(); if (rnd.nextBoolean()) { int penalty = (int)(Math.abs(owner.getCompany().getCash()/200*rnd.nextDouble())); DisplayMessage msg = new DisplayMessage("ch.sahits.game.event.handler.impl.DeliverPackages.messageCaught", penalty); clientEventBus.post(msg); if (owner instanceof IHumanPlayer) { owner.getCompany().updateCash(-penalty); } else { owner.getCompany().updateCashDirectly(-penalty); } } else { if (owner instanceof IHumanPlayer) { owner.getCompany().updateCash(premium); } else { owner.getCompany().updateCashDirectly(premium); } DisplayMessage msg = new DisplayMessage("ch.sahits.game.event.handler.impl.DeliverPackages.messageSuccess"); clientEventBus.post(msg); } unregisterEventBus(); return false; } @Override
public void bindToPlayer(IPlayer player) { cashTxt.textProperty().bind(player.getCompany().cashProperty().asString()); }
/** * Sell <code>amount</code> of <code>ware</code> from the <code>office</code> to the <code>city</code>. * @param office where the ware is stored. * @param player owner of the office * @param city to which to sell to * @param ware to be sold * @param amount to be sold * @param minAvgPrice minimal avg price that has to be payed per item. If no value is passed the whole lot will be sold. * @return total price of all sold wares (always positiv) */ public int sellFromStorageToCity(ITradingOffice office, IPlayer player, ICity city, IWare ware, int amount, Optional<Integer> minAvgPrice) { int availableAmountCity = city.getWare(ware).getAmount(); int amountToBeSold = amount; if (minAvgPrice.isPresent()) { amountToBeSold = computablePrice.calculateSellAmount(ware, availableAmountCity, minAvgPrice.get(), amount); } final int avgPrice = computablePrice.sellPrice(ware, new SimpleIntegerProperty(availableAmountCity), new ConstantIntegerBinding(amountToBeSold)); city.move(ware, amountToBeSold, player); // The price here is irrelevant int sold = office.move(ware, -amountToBeSold, avgPrice); if (player instanceof IHumanPlayer) { player.getCompany().updateCash(avgPrice * sold); } else { player.getCompany().updateCashDirectly(avgPrice * sold); } return avgPrice * sold; }
if (auction.getOwner().isPresent() && auction.getOwner().get() instanceof IPlayer) { if (auction.getOwner().get() instanceof IHumanPlayer) { ((IPlayer) auction.getOwner().get()).getCompany().updateCash(amount); } else { ((IPlayer) auction.getOwner().get()).getCompany().updateCashDirectly(amount); newOwner.getCompany().updateCash(-amount); } else { newOwner.getCompany().updateCashDirectly(-amount);
private boolean isNextRankAchievable(IPlayer player){ ESocialRank rank = player.getRank(); if (rank==ESocialRank.PATRICIAN || rank==ESocialRank.MAYOR || rank==ESocialRank.ALDERMAN){ return false; } final ICompany company = player.getCompany(); ICity homeTown = player.getHometown(); long compValue = company.getCompanyValue(); ESocialRank nextRank = rank.getNextRank(); double remapedRep = repCalculator.remapReputation(homeTown, player); if (compValue>=nextRank.getCompanyValue() && remapedRep>=nextRank.getSocialRank()){ if (nextRank==ESocialRank.COUNCILMAN){ IGuild guild = guildList.findGuild(homeTown).get(); return guild.getMembers().contains(player); } return true; } return false; }
@Override public void run() { ICompany company = debitor.getCompany(); int requiredAmount = debt.getAmount(); int amount = (int) Math.min(requiredAmount, company.getCash()); if (debitor instanceof IHumanPlayer) { company.updateCash(-amount); } else { company.updateCashDirectly(-amount); } if (debt.getCreditor() instanceof IPlayer) { if (debt.getCreditor() instanceof IHumanPlayer) { ((IPlayer) debt.getCreditor()).getCompany().updateCash(amount); } else { ((IPlayer) debt.getCreditor()).getCompany().updateCashDirectly(amount); } if (debt.getCreditor() instanceof IHumanPlayer) { DisplayMessage msg = new DisplayMessage("ch.sahits.game.openpatrician.engine.land.city.LoanerEngine.paybackAfterWithoutAuction", new Object[]{debitor.getName(), debitor.getLastName(), amount}); TargetedEvent message = new TargetedEvent((IHumanPlayer) debt.getCreditor(), msg); clientServerEventBus.post(message); } } } }
@Override public boolean execute(ICity city) { Optional<ICity> nextCity = state.nextDestination(); if (!nextCity.isPresent()){ // last leg int premium = state.getPremium()+state.getNumberOfAttacks()*state.getBonusPerAttack(); if (player instanceof IHumanPlayer) { player.getCompany().updateCash(premium); } else { player.getCompany().updateCashDirectly(premium); } clientEventBus.post(new DisplayMessage("ch.sahits.game.event.handler.impl.NextPatrolStation.premium", premium)); clientServerEventBus.unregister(atackListener); unregisterEventBus(); clientServerEventBus.unregister(atackListener); } else { // next leg ICity next = nextCity.get(); state.removeFirstCity(); int minutes = rnd.nextInt(600); LocalDateTime postMessage = date.getCurrentDate().plusMinutes(minutes); taskFactory.getPostponedDisplayMessage(postMessage, "ch.sahits.game.event.handler.impl.NextCourierPatrolStation.nextStation", next.getName()); LocalDateTime deadline = date.getCurrentDate().plusDays(6); new NextPatrolStation((IShip) getShip(), state.nextDestination().get(), state, player, deadline, atackListener); } return true; }}
@VisibleForTesting Runnable createPawnRunnable(final IDebt debt, final ICity city) { return () -> { if (debt.getDebitor() instanceof IHumanPlayer) { pawnFromHumanDebitor(debt, city); // Add task for the following day to collect the money } else if (debt.getCreditor() instanceof IHumanPlayer){ int value = rnd.nextInt(debt.getAmount()/2) + debt.getAmount(); value = (int) Math.min(value, debt.getAmount()*debt.getInterest()); ((IPlayer)debt.getCreditor()).getCompany().updateCash(value); ICitizen debitor = debt.getDebitor(); DisplayMessage msg = new DisplayMessage("ch.sahits.game.openpatrician.engine.land.city.LoanerEngine.pawnMsg1", new Object[]{debitor.getName(), debitor.getLastName(), value}); TargetedEvent message = new TargetedEvent((IHumanPlayer) debt.getCreditor(), msg); clientServerEventBus.post(message); } }; } @VisibleForTesting
@Override public void run() { IHumanPlayer debitor = (IHumanPlayer) debt.getDebitor(); ICompany company = debitor.getCompany(); int requiredAmount = debt.getAmount(); int amount = (int) Math.min(requiredAmount, company.getCash()); company.updateCash(-amount); if (debt.getCreditor() instanceof IPlayer) { if (debt.getCreditor() instanceof IHumanPlayer) { ((IPlayer) debt.getCreditor()).getCompany().updateCash(amount); } else { ((IPlayer) debt.getCreditor()).getCompany().updateCashDirectly(amount); } if (debt.getCreditor() instanceof IHumanPlayer) { DisplayMessage msg = new DisplayMessage("ch.sahits.game.openpatrician.engine.land.city.LoanerEngine.paybackAfterShipAuction", new Object[]{debitor.getName(), debitor.getLastName(), amount}); TargetedEvent message = new TargetedEvent((IHumanPlayer) debt.getCreditor(), msg); clientServerEventBus.post(message); } } } }
@Override public void run() { int penalty = (int)(Math.abs(player.getCompany().getCash()/(200*rnd.nextDouble()))); DisplayMessage msg = new DisplayMessage("ch.sahits.game.graphic.event.task.DelayedCaughtAction.message", penalty); clientEventBus.post(msg); ILoaner loaner = loaners.getLoaner(city); IDebt debt = Debt.builder() .amount(penalty) .dueDate(date.getCurrentDate().plusMonths(1)) .interest(0) .loanTakeOut(date.getCurrentDate()) .debitor(player) .creditor(new CityCreditor()) .build(); loaner.addDebt(debt); } }
/** * Take out a loan. * @param loaner from which to take the loan * @param proposal selected loan * @param debitor who is taking the loan. */ public void takeOutLoan(ILoaner loaner, ILoanProposal proposal, IPlayer debitor, ICity city) { // TODO: andi 6/12/16 the proposol might be on that is offed by a player and not a citizen LocalDateTime now = date.getCurrentDate(); ESocialRank rank = ESocialRank.values()[rnd.nextInt(ESocialRank.values().length-2)]; // Exclude Mayor and Alderman ICreditor creditor = new Citizen(lastNameLoader.getRandomName(), firstNameLoader.getRandomName(), rank, city); LocalDateTime dueDate = now.plusWeeks(proposal.getDurationInWeeks()); Debt debt = Debt.builder() .creditor(creditor) .amount(proposal.getAmount()) .dueDate(dueDate) .interest(proposal.getInterest()) .debitor(debitor) .loanTakeOut(now) .build(); loaner.addDebt(debt); loaner.getLoanProposals().remove(proposal); if (debitor instanceof IHumanPlayer) { debitor.getCompany().updateCash(proposal.getAmount()); } else { debitor.getCompany().updateCashDirectly(proposal.getAmount()); } }
@Override public boolean execute(ICity city) { if (ignoreEventCity()) { // time has passed and passenger will leave. EDialogTemplateType templateType = resolveType(dialogTemplateType, false); DialogTemplate template = dialogTemplateFactory.createDialogTemplate(templateType, dialogParameterSupplier); DisplayTemplateMessage message = new DisplayTemplateMessage(getMessageBoardTitleKey(templateType), template, getMessageBoardTitleParameters(templateType, city)); TargetedEvent tagetDisplayMsg = new TargetedEvent((IHumanPlayer)shipsOwner, message); clientServerEventBus.post(tagetDisplayMsg); } else { // Successful arrival at destination if (shipsOwner instanceof IHumanPlayer) { shipsOwner.getCompany().updateCash(premiumCalculator.get()); } else { shipsOwner.getCompany().updateCashDirectly(premiumCalculator.get()); } EDialogTemplateType templateType = resolveType(dialogTemplateType, true); DialogTemplate template = dialogTemplateFactory.createDialogTemplate(templateType, dialogParameterSupplier); DisplayTemplateMessage message = new DisplayTemplateMessage(getMessageBoardTitleKey(templateType), template, getMessageBoardTitleParameters(templateType, city)); TargetedEvent tagetDisplayMsg = new TargetedEvent((IHumanPlayer)shipsOwner, message); clientServerEventBus.post(tagetDisplayMsg); } ((IShip) getShip()).leavePassenger(); unregisterEventBus(); return true; }