Search in sources :

Example 1 with Game

use of mage.game.Game in project mage by magefree.

the class HumanPlayer method selectBlockers.

@Override
public void selectBlockers(Ability source, Game game, UUID defendingPlayerId) {
    if (gameInCheckPlayableState(game)) {
        return;
    }
    FilterCreatureForCombatBlock filter = filterCreatureForCombatBlock.copy();
    filter.add(new ControllerIdPredicate(defendingPlayerId));
    // stop skip on any/zero permanents available
    int possibleBlockersCount = game.getBattlefield().count(filter, null, playerId, game);
    boolean canStopOnAny = possibleBlockersCount != 0 && getControllingPlayersUserData(game).getUserSkipPrioritySteps().isStopOnDeclareBlockersWithAnyPermanents();
    boolean canStopOnZero = possibleBlockersCount == 0 && getControllingPlayersUserData(game).getUserSkipPrioritySteps().isStopOnDeclareBlockersWithZeroPermanents();
    // skip declare blocker step
    // as opposed to declare attacker - it can be skipped by ANY skip button TODO: make same for declare attackers and rework skip buttons (normal and forced)
    boolean skipButtonActivated = passedAllTurns || passedUntilEndStepBeforeMyTurn || passedTurn || passedUntilEndOfTurn || passedUntilNextMain;
    if (skipButtonActivated && !canStopOnAny && !canStopOnZero) {
        return;
    }
    while (canRespond()) {
        updateGameStatePriority("selectBlockers", game);
        prepareForResponse(game);
        if (!isExecutingMacro()) {
            Map<String, Serializable> options = new HashMap<>();
            java.util.List<UUID> possibleBlockers = game.getBattlefield().getActivePermanents(filter, playerId, game).stream().map(p -> p.getId()).collect(Collectors.toList());
            options.put(Constants.Option.POSSIBLE_BLOCKERS, (Serializable) possibleBlockers);
            game.fireSelectEvent(playerId, "Select blockers", options);
        }
        waitForResponse(game);
        UUID responseId = getFixedResponseUUID(game);
        if (response.getBoolean() != null) {
            return;
        } else if (response.getInteger() != null) {
            return;
        } else if (responseId != null) {
            Permanent blocker = game.getPermanent(responseId);
            if (blocker != null) {
                boolean removeBlocker = false;
                // does not block yet and can block or can block more attackers
                if (filter.match(blocker, null, playerId, game)) {
                    selectCombatGroup(defendingPlayerId, blocker.getId(), game);
                } else if (filterBlock.match(blocker, null, playerId, game) && game.getStack().isEmpty()) {
                    removeBlocker = true;
                }
                if (removeBlocker) {
                    game.getCombat().removeBlocker(blocker.getId(), game);
                }
            }
        }
    }
}
Also used : RequirementEffect(mage.abilities.effects.RequirementEffect) FilterBlockingCreature(mage.filter.common.FilterBlockingCreature) Match(mage.game.match.Match) REQUEST_AUTO_ANSWER_RESET_ALL(mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_RESET_ALL) Logger(org.apache.log4j.Logger) TapSourceCost(mage.abilities.costs.common.TapSourceCost) ManaCost(mage.abilities.costs.mana.ManaCost) mage.constants(mage.constants) Draft(mage.game.draft.Draft) mage.abilities(mage.abilities) Choice(mage.choices.Choice) ActivatedManaAbilityImpl(mage.abilities.mana.ActivatedManaAbilityImpl) StaticFilters(mage.filter.StaticFilters) GameLog(mage.util.GameLog) TargetAnyTarget(mage.target.common.TargetAnyTarget) mage.cards(mage.cards) FilterCreatureForCombatBlock(mage.filter.common.FilterCreatureForCombatBlock) CardUtil(mage.util.CardUtil) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) FilterCreatureForCombat(mage.filter.common.FilterCreatureForCombat) TargetDefender(mage.target.common.TargetDefender) List(java.util.List) Permanent(mage.game.permanent.Permanent) TargetAmount(mage.target.TargetAmount) Tournament(mage.game.tournament.Tournament) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Target(mage.target.Target) java.util(java.util) PlayerImpl(mage.players.PlayerImpl) ControllerIdPredicate(mage.filter.predicate.permanent.ControllerIdPredicate) PlayerList(mage.players.PlayerList) DeclareAttackerEvent(mage.game.events.DeclareAttackerEvent) Player(mage.players.Player) ManaUtil(mage.util.ManaUtil) TargetCard(mage.target.TargetCard) FilterAttackingCreature(mage.filter.common.FilterAttackingCreature) MageObject(mage.MageObject) CombatGroup(mage.game.combat.CombatGroup) Spell(mage.game.stack.Spell) SacrificeSourceCost(mage.abilities.costs.common.SacrificeSourceCost) Deck(mage.cards.decks.Deck) TRIGGER_AUTO_ORDER_RESET_ALL(mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_RESET_ALL) TargetAttackingCreature(mage.target.common.TargetAttackingCreature) java.awt(java.awt) VariableCost(mage.abilities.costs.VariableCost) ManaCostsImpl(mage.abilities.costs.mana.ManaCostsImpl) Game(mage.game.Game) ManaAbility(mage.abilities.mana.ManaAbility) ChoiceImpl(mage.choices.ChoiceImpl) GameImpl(mage.game.GameImpl) MessageToClient(mage.util.MessageToClient) HintUtils(mage.abilities.hint.HintUtils) TargetPermanent(mage.target.TargetPermanent) Serializable(java.io.Serializable) Permanent(mage.game.permanent.Permanent) TargetPermanent(mage.target.TargetPermanent) FilterCreatureForCombatBlock(mage.filter.common.FilterCreatureForCombatBlock) java.util(java.util) ControllerIdPredicate(mage.filter.predicate.permanent.ControllerIdPredicate)

Example 2 with Game

use of mage.game.Game in project mage by magefree.

the class ComputerPlayerMCTS method calculateActions.

protected void calculateActions(Game game, NextAction action) {
    if (root == null) {
        Game sim = createMCTSGame(game);
        MCTSPlayer player = (MCTSPlayer) sim.getPlayer(playerId);
        player.setNextAction(action);
        root = new MCTSNode(playerId, sim);
    }
    applyMCTS(game, action);
    root = root.bestChild();
    root.emancipate();
}
Also used : Game(mage.game.Game)

Example 3 with Game

use of mage.game.Game in project mage by magefree.

the class ComputerPlayerMCTS method applyMCTS.

protected void applyMCTS(final Game game, final NextAction action) {
    int thinkTime = calculateThinkTime(game, action);
    if (thinkTime > 0) {
        if (USE_MULTIPLE_THREADS) {
            ExecutorService pool = Executors.newFixedThreadPool(poolSize);
            List<MCTSExecutor> tasks = new ArrayList<>();
            for (int i = 0; i < poolSize; i++) {
                Game sim = createMCTSGame(game);
                MCTSPlayer player = (MCTSPlayer) sim.getPlayer(playerId);
                player.setNextAction(action);
                MCTSExecutor exec = new MCTSExecutor(sim, playerId, thinkTime);
                tasks.add(exec);
            }
            try {
                pool.invokeAll(tasks, thinkTime, TimeUnit.SECONDS);
                pool.awaitTermination(1, TimeUnit.SECONDS);
                pool.shutdownNow();
            } catch (InterruptedException | RejectedExecutionException ex) {
                logger.warn("applyMCTS interrupted");
            }
            int simCount = 0;
            for (MCTSExecutor task : tasks) {
                simCount += task.getSimCount();
                root.merge(task.getRoot());
                task.clear();
            }
            tasks.clear();
            totalThinkTime += thinkTime;
            totalSimulations += simCount;
            logger.info("Player: " + name + " Simulated " + simCount + " games in " + thinkTime + " seconds - nodes in tree: " + root.size());
            logger.info("Total: Simulated " + totalSimulations + " games in " + totalThinkTime + " seconds - Average: " + totalSimulations / totalThinkTime);
            MCTSNode.logHitMiss();
        } else {
            long startTime = System.nanoTime();
            long endTime = startTime + (thinkTime * 1000000000l);
            MCTSNode current;
            int simCount = 0;
            while (true) {
                long currentTime = System.nanoTime();
                if (currentTime > endTime)
                    break;
                current = root;
                // Selection
                while (!current.isLeaf()) {
                    current = current.select(this.playerId);
                }
                int result;
                if (!current.isTerminal()) {
                    // Expansion
                    current.expand();
                    // Simulation
                    current = current.select(this.playerId);
                    result = current.simulate(this.playerId);
                    simCount++;
                } else {
                    result = current.isWinner(this.playerId) ? 1 : -1;
                }
                // Backpropagation
                current.backpropagate(result);
            }
            logger.info("Simulated " + simCount + " games - nodes in tree: " + root.size());
        }
    // displayMemory();
    }
}
Also used : Game(mage.game.Game) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Example 4 with Game

use of mage.game.Game in project mage by magefree.

the class MCTSNode method createSimulation.

/**
 * Copies game and replaces all players in copy with simulated players
 * Shuffles each players library so that there is no knowledge of its order
 *
 * @param game
 * @return a new game object with simulated players
 */
protected Game createSimulation(Game game, UUID playerId) {
    Game sim = game.copy();
    for (Player oldPlayer : sim.getState().getPlayers().values()) {
        Player origPlayer = game.getState().getPlayers().get(oldPlayer.getId()).copy();
        SimulatedPlayerMCTS newPlayer = new SimulatedPlayerMCTS(oldPlayer, true);
        newPlayer.restore(origPlayer);
        sim.getState().getPlayers().put(oldPlayer.getId(), newPlayer);
    }
    randomizePlayers(sim, playerId);
    sim.setSimulation(true);
    return sim;
}
Also used : Player(mage.players.Player) Game(mage.game.Game)

Example 5 with Game

use of mage.game.Game in project mage by magefree.

the class ComputerPlayer2 method createSimulation.

/**
 * Copies game and replaces all players in copy with simulated players
 *
 * @param game
 * @return a new game object with simulated players
 */
protected Game createSimulation(Game game) {
    Game sim = game.copy();
    for (Player oldPlayer : sim.getState().getPlayers().values()) {
        Player origPlayer = game.getState().getPlayers().get(oldPlayer.getId()).copy();
        SimulatedPlayer newPlayer = new SimulatedPlayer(oldPlayer, oldPlayer.getId().equals(playerId), maxDepth);
        newPlayer.restore(origPlayer);
        sim.getState().getPlayers().put(oldPlayer.getId(), newPlayer);
    }
    sim.setSimulation(true);
    return sim;
}
Also used : Player(mage.players.Player) Game(mage.game.Game)

Aggregations

Game (mage.game.Game)212 Ability (mage.abilities.Ability)139 Player (mage.players.Player)126 UUID (java.util.UUID)117 OneShotEffect (mage.abilities.effects.OneShotEffect)104 CardSetInfo (mage.cards.CardSetInfo)102 CardImpl (mage.cards.CardImpl)100 CardType (mage.constants.CardType)82 Outcome (mage.constants.Outcome)78 Permanent (mage.game.permanent.Permanent)66 MageInt (mage.MageInt)60 mage.constants (mage.constants)47 Zone (mage.constants.Zone)46 GameEvent (mage.game.events.GameEvent)44 Objects (java.util.Objects)41 StaticFilters (mage.filter.StaticFilters)40 Collectors (java.util.stream.Collectors)35 SubType (mage.constants.SubType)34 Card (mage.cards.Card)32 MageObjectReference (mage.MageObjectReference)30