diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/config/AIMinimax.properties b/Mage.Server.Plugins/Mage.Player.AI.MA/config/AIMinimax.properties new file mode 100644 index 0000000000..96b5480294 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/config/AIMinimax.properties @@ -0,0 +1,7 @@ +maxDepth=10 +maxNodes=5000 +evaluatorLifeFactor=2 +evaluatorPermanentFactor=1 +evaluatorCreatureFactor=1 +evaluatorHandFactor=1 +maxThinkSeconds=30 \ No newline at end of file diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml b/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml new file mode 100644 index 0000000000..a4671e0e52 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml @@ -0,0 +1,56 @@ + + + + 4.0.0 + + + org.mage + mage-root + 0.6 + + + Mage-Player-AI-MA + jar + Mage Player AI.MA + + + + ${project.groupId} + Mage + ${project.version} + + + ${project.groupId} + Mage-Player-AI + ${project.version} + + + + + src + + + org.apache.maven.plugins + maven-compiler-plugin + 2.0.2 + + 1.6 + 1.6 + + + + maven-resources-plugin + + UTF-8 + + + + + + mage-player-ai-ma + + + + + diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/Attackers.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/Attackers.java new file mode 100644 index 0000000000..51da223cc9 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/Attackers.java @@ -0,0 +1,52 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ + +package mage.player.ai; + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeMap; +import mage.game.permanent.Permanent; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class Attackers extends TreeMap> { + + public List getAttackers() { + List attackers = new ArrayList(); + for (List l: this.values()) { + for (Permanent permanent: l) { + attackers.add(permanent); + } + } + return attackers; + } + +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer2.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer2.java new file mode 100644 index 0000000000..a3c3008bb0 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer2.java @@ -0,0 +1,651 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ + +package mage.player.ai; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.logging.Level; +import java.util.logging.Logger; +import mage.Constants.Outcome; +import mage.Constants.PhaseStep; +import mage.Constants.RangeOfInfluence; +import mage.abilities.Ability; +import mage.abilities.ActivatedAbility; +import mage.abilities.effects.Effect; +import mage.abilities.effects.SearchEffect; +import mage.cards.Cards; +import mage.cards.decks.Deck; +import mage.choices.Choice; +import mage.filter.FilterAbility; +import mage.game.Game; +import mage.game.combat.Combat; +import mage.game.combat.CombatGroup; +import mage.game.events.GameEvent; +import mage.game.stack.StackAbility; +import mage.game.stack.StackObject; +import mage.game.turn.BeginCombatStep; +import mage.game.turn.BeginningPhase; +import mage.game.turn.CleanupStep; +import mage.game.turn.CombatDamageStep; +import mage.game.turn.CombatPhase; +import mage.game.turn.DeclareAttackersStep; +import mage.game.turn.DeclareBlockersStep; +import mage.game.turn.DrawStep; +import mage.game.turn.EndOfCombatStep; +import mage.game.turn.EndPhase; +import mage.game.turn.EndStep; +import mage.game.turn.Phase; +import mage.game.turn.PostCombatMainPhase; +import mage.game.turn.PostCombatMainStep; +import mage.game.turn.PreCombatMainPhase; +import mage.game.turn.PreCombatMainStep; +import mage.game.turn.UntapStep; +import mage.game.turn.UpkeepStep; +import mage.players.Player; +import mage.target.Target; +import mage.target.TargetCard; +import mage.util.Logging; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class ComputerPlayer2 extends ComputerPlayer implements Player { + + private static final transient Logger logger = Logging.getLogger(ComputerPlayer2.class.getName()); + private static final ExecutorService pool = Executors.newFixedThreadPool(1); + + protected int maxDepth; + protected int maxNodes; + protected LinkedList actions = new LinkedList(); + protected List targets = new ArrayList(); + protected List choices = new ArrayList(); + protected Combat combat; + protected int currentScore; + protected SimulationNode root; + + public ComputerPlayer2(String name, RangeOfInfluence range) { + super(name, range); + maxDepth = Config.maxDepth; + maxNodes = Config.maxNodes; + } + + public ComputerPlayer2(final ComputerPlayer2 player) { + super(player); + this.maxDepth = player.maxDepth; + this.currentScore = player.currentScore; + if (player.combat != null) + this.combat = player.combat.copy(); + for (Ability ability: player.actions) { + actions.add(ability); + } + for (UUID targetId: player.targets) { + targets.add(targetId); + } + for (String choice: player.choices) { + choices.add(choice); + } + } + + @Override + public ComputerPlayer2 copy() { + return new ComputerPlayer2(this); + } + + @Override + public void priority(Game game) { + logState(game); + game.firePriorityEvent(playerId); + switch (game.getTurn().getStepType()) { + case UPKEEP: + case DRAW: + pass(); + break; + case PRECOMBAT_MAIN: + case BEGIN_COMBAT: + case DECLARE_ATTACKERS: + case DECLARE_BLOCKERS: + case COMBAT_DAMAGE: + case END_COMBAT: + case POSTCOMBAT_MAIN: + if (actions.size() == 0) { + calculateActions(game); + } + act(game); + break; + case END_TURN: + case CLEANUP: + pass(); + break; + } + } + + protected void act(Game game) { + if (actions == null || actions.size() == 0) + pass(); + else { + boolean usedStack = false; + while (actions.peek() != null) { + Ability ability = actions.poll(); + this.activateAbility((ActivatedAbility) ability, game); + if (ability.isUsesStack()) + usedStack = true; + } + if (usedStack) + pass(); + } + } + + protected void calculateActions(Game game) { + currentScore = GameStateEvaluator.evaluate(playerId, game); + if (!getNextAction(game)) { + Game sim = createSimulation(game); + SimulationNode.resetCount(); + root = new SimulationNode(sim, maxDepth, playerId); + logger.fine("simulating actions"); + addActionsTimed(new FilterAbility()); + if (root.children.size() > 0) { + root = root.children.get(0); + actions = new LinkedList(root.abilities); + combat = root.combat; + } + } + } + + protected boolean getNextAction(Game game) { + if (root != null && root.children.size() > 0) { + SimulationNode test = root; + root = root.children.get(0); + while (root.children.size() > 0 && !root.playerId.equals(playerId)) { + test = root; + root = root.children.get(0); + } + logger.fine("simlating -- game value:" + game.getState().getValue() + " test value:" + test.gameValue); + if (root.playerId.equals(playerId) && root.abilities != null && game.getState().getValue() == test.gameValue) { + logger.fine("simulating -- continuing previous action chain"); + actions = new LinkedList(root.abilities); + combat = root.combat; + return true; + } + else { + return false; + } + } + return false; + } + + protected int minimaxAB(SimulationNode node, FilterAbility filter, int depth, int alpha, int beta) { + UUID currentPlayerId = node.getGame().getPlayerList().get(); + SimulationNode bestChild = null; + for (SimulationNode child: node.getChildren()) { + if (alpha >= beta) { + logger.fine("alpha beta pruning"); + break; + } + if (SimulationNode.nodeCount > maxNodes) { + logger.fine("simulating -- reached end-state"); + break; + } + int val = addActions(child, filter, depth-1, alpha, beta); + if (!currentPlayerId.equals(playerId)) { + if (val < beta) { + beta = val; + bestChild = child; + if (node.getCombat() == null) + node.setCombat(child.getCombat()); + } + } + else { + if (val > alpha) { + alpha = val; + bestChild = child; + if (node.getCombat() == null) + node.setCombat(child.getCombat()); + } + } + } + node.children.clear(); + if (bestChild != null) + node.children.add(bestChild); + if (!currentPlayerId.equals(playerId)) { + logger.fine("returning minimax beta: " + beta); + return beta; + } + else { + logger.fine("returning minimax alpha: " + alpha); + return alpha; + } + } + + protected SearchEffect getSearchEffect(StackAbility ability) { + for (Effect effect: ability.getEffects()) { + if (effect instanceof SearchEffect) { + return (SearchEffect) effect; + } + } + return null; + } + + protected void resolve(SimulationNode node, int depth, Game game) { + StackObject ability = game.getStack().pop(); + if (ability instanceof StackAbility) { + SearchEffect effect = getSearchEffect((StackAbility) ability); + if (effect != null && ability.getControllerId().equals(playerId)) { + Target target = effect.getTarget(); + if (!target.doneChosing()) { + for (UUID targetId: target.possibleTargets(ability.getSourceId(), ability.getControllerId(), game)) { + Game sim = game.copy(); + StackAbility newAbility = (StackAbility) ability.copy(); + SearchEffect newEffect = getSearchEffect((StackAbility) newAbility); + newEffect.getTarget().addTarget(targetId, newAbility, sim); + sim.getStack().push(newAbility); + SimulationNode newNode = new SimulationNode(sim, depth, ability.getControllerId()); + node.children.add(newNode); + newNode.getTargets().add(targetId); + logger.fine("simulating search -- node#: " + SimulationNode.getCount() + "for player: " + sim.getPlayer(ability.getControllerId()).getName()); + } + return; + } + } + } + logger.fine("simulating resolve "); + ability.resolve(game); + game.applyEffects(); + game.getPlayers().resetPassed(); + game.getPlayerList().setCurrent(game.getActivePlayerId()); + } + + protected void addActionsTimed(final FilterAbility filter) { + FutureTask task = new FutureTask(new Callable() { + public Integer call() throws Exception + { + return addActions(root, filter, maxDepth, Integer.MIN_VALUE, Integer.MAX_VALUE); + } + }); + pool.execute(task); + try { + task.get(Config.maxThinkSeconds, TimeUnit.SECONDS); + } catch (TimeoutException e) { + logger.fine("simulating - timed out"); + task.cancel(true); + } catch (ExecutionException e) { + + } catch (InterruptedException e) { + + } + } + + protected int addActions(SimulationNode node, FilterAbility filter, int depth, int alpha, int beta) { + Game game = node.getGame(); + int val; + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return GameStateEvaluator.evaluate(playerId, game); + } + if (depth <= 0 || SimulationNode.nodeCount > maxNodes || game.isGameOver()) { + logger.fine("simulating -- reached end state"); + val = GameStateEvaluator.evaluate(playerId, game); + } + else if (node.getChildren().size() > 0) { + logger.fine("simulating -- somthing added children:" + node.getChildren().size()); + val = minimaxAB(node, filter, depth-1, alpha, beta); + } + else { + if (logger.isLoggable(Level.FINE)) + logger.fine("simulating -- alpha: " + alpha + " beta: " + beta + " depth:" + depth + " step:" + game.getTurn().getStepType() + " for player:" + (node.getPlayerId().equals(playerId)?"yes":"no")); + if (allPassed(game)) { + if (!game.getStack().isEmpty()) { + resolve(node, depth, game); + } + else { +// int testScore = GameStateEvaluator.evaluate(playerId, game); +// if (testScore < currentScore) { +// // if score at end of step is worse than original score don't check any further +// logger.fine("simulating -- abandoning current check, no immediate benefit"); +// return testScore; +// } + game.getPlayers().resetPassed(); + playNext(game, game.getActivePlayerId(), node); + } + } + + if (game.isGameOver()) { + val = GameStateEvaluator.evaluate(playerId, game); + } + else if (node.getChildren().size() > 0) { + //declared attackers or blockers or triggered abilities + logger.fine("simulating -- attack/block/trigger added children:" + node.getChildren().size()); + val = minimaxAB(node, filter, depth-1, alpha, beta); + } + else { + val = simulatePriority(node, game, filter, depth, alpha, beta); + } + } + + if (logger.isLoggable(Level.FINE)) + logger.fine("returning -- score: " + val + " depth:" + depth + " step:" + game.getTurn().getStepType() + " for player:" + game.getPlayer(node.getPlayerId()).getName()); + return val; + + } + + protected int simulatePriority(SimulationNode node, Game game, FilterAbility filter, int depth, int alpha, int beta) { + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return GameStateEvaluator.evaluate(playerId, game); + } + node.setGameValue(game.getState().getValue()); + SimulatedPlayer currentPlayer = (SimulatedPlayer) game.getPlayer(game.getPlayerList().get()); + logger.fine("simulating -- player " + currentPlayer.getName()); + SimulationNode bestNode = null; + List allActions = currentPlayer.simulatePriority(game, filter); + if (logger.isLoggable(Level.FINE)) + logger.fine("simulating -- adding " + allActions.size() + " children:" + allActions); + for (Ability action: allActions) { + Game sim = game.copy(); + if (sim.getPlayer(currentPlayer.getId()).activateAbility((ActivatedAbility) action.copy(), sim)) { + sim.applyEffects(); + if (!sim.isGameOver() && action.isUsesStack()) { + // only pass if the last action uses the stack + sim.getPlayer(currentPlayer.getId()).pass(); + sim.getPlayerList().getNext(); + } + SimulationNode newNode = new SimulationNode(sim, action, depth, currentPlayer.getId()); + if (logger.isLoggable(Level.FINE)) + logger.fine("simulating -- node #:" + SimulationNode.getCount() + " actions:" + action); + sim.checkStateAndTriggered(); + int val = addActions(newNode, filter, depth-1, alpha, beta); + if (!currentPlayer.getId().equals(playerId)) { + if (val < beta) { + beta = val; + bestNode = newNode; + node.setCombat(newNode.getCombat()); + } + } + else { + if (val > alpha) { + alpha = val; + bestNode = newNode; + node.setCombat(newNode.getCombat()); + if (node.getTargets().size() > 0) + targets = node.getTargets(); + if (node.getChoices().size() > 0) + choices = node.getChoices(); + } + } + if (alpha >= beta) { + logger.fine("simulating -- pruning"); + break; + } + if (SimulationNode.nodeCount > maxNodes) { + logger.fine("simulating -- reached end-state"); + break; + } + } + } + if (bestNode != null) { + node.children.clear(); + node.children.add(bestNode); + } + if (!currentPlayer.getId().equals(playerId)) { + logger.fine("returning priority beta: " + beta); + return beta; + } + else { + logger.fine("returning priority alpha: " + alpha); + return alpha; + } + } + + protected boolean allPassed(Game game) { + for (Player player: game.getPlayers().values()) { + if (!player.isPassed() && !player.hasLost() && !player.hasLeft()) + return false; + } + return true; + } + + @Override + public boolean choose(Outcome outcome, Choice choice, Game game) { + if (choices.size() == 0) + return super.choose(outcome, choice, game); + if (!choice.isChosen()) { + for (String achoice: choices) { + choice.setChoice(achoice); + if (choice.isChosen()) { + choices.clear(); + return true; + } + } + return false; + } + return true; + } + + @Override + public boolean chooseTarget(Cards cards, TargetCard target, Ability source, Game game) { + if (targets.size() == 0) + return super.chooseTarget(cards, target, source, game); + if (!target.doneChosing()) { + for (UUID targetId: targets) { + target.addTarget(targetId, source, game); + if (target.doneChosing()) { + targets.clear(); + return true; + } + } + return false; + } + return true; + } + + @Override + public boolean choose(Cards cards, TargetCard target, Game game) { + if (targets.size() == 0) + return super.choose(cards, target, game); + if (!target.doneChosing()) { + for (UUID targetId: targets) { + target.add(targetId, game); + if (target.doneChosing()) { + targets.clear(); + return true; + } + } + return false; + } + return true; + } + + public void playNext(Game game, UUID activePlayerId, SimulationNode node) { + boolean skip = false; + while (true) { + Phase currentPhase = game.getPhase(); + if (!skip) + currentPhase.getStep().endStep(game, activePlayerId); + game.applyEffects(); + switch (currentPhase.getStep().getType()) { + case UNTAP: + game.getPhase().setStep(new UpkeepStep()); + break; + case UPKEEP: + game.getPhase().setStep(new DrawStep()); + break; + case DRAW: + game.getTurn().setPhase(new PreCombatMainPhase()); + game.getPhase().setStep(new PreCombatMainStep()); + break; + case PRECOMBAT_MAIN: + game.getTurn().setPhase(new CombatPhase()); + game.getPhase().setStep(new BeginCombatStep()); + break; + case BEGIN_COMBAT: + game.getPhase().setStep(new DeclareAttackersStep()); + break; + case DECLARE_ATTACKERS: + game.getPhase().setStep(new DeclareBlockersStep()); + break; + case DECLARE_BLOCKERS: + game.getPhase().setStep(new CombatDamageStep(true)); + break; + case COMBAT_DAMAGE: + if (((CombatDamageStep)currentPhase.getStep()).getFirst()) + game.getPhase().setStep(new CombatDamageStep(false)); + else + game.getPhase().setStep(new EndOfCombatStep()); + break; + case END_COMBAT: + game.getTurn().setPhase(new PostCombatMainPhase()); + game.getPhase().setStep(new PostCombatMainStep()); + break; + case POSTCOMBAT_MAIN: + game.getTurn().setPhase(new EndPhase()); + game.getPhase().setStep(new EndStep()); + break; + case END_TURN: + game.getPhase().setStep(new CleanupStep()); + break; + case CLEANUP: + game.getPhase().getStep().beginStep(game, activePlayerId); + if (!game.checkStateAndTriggered() && !game.isGameOver()) { + game.getState().setActivePlayerId(game.getState().getPlayerList(game.getActivePlayerId()).getNext()); + game.getTurn().setPhase(new BeginningPhase()); + game.getPhase().setStep(new UntapStep()); + } + } + if (!game.getStep().skipStep(game, game.getActivePlayerId())) { + if (game.getTurn().getStepType() == PhaseStep.DECLARE_ATTACKERS) { + game.fireEvent(new GameEvent(GameEvent.EventType.DECLARE_ATTACKERS_STEP_PRE, null, null, activePlayerId)); + if (!game.replaceEvent(GameEvent.getEvent(GameEvent.EventType.DECLARING_ATTACKERS, activePlayerId, activePlayerId))) { + for (Combat engagement: ((SimulatedPlayer)game.getPlayer(activePlayerId)).addAttackers(game)) { + Game sim = game.copy(); + UUID defenderId = game.getOpponents(playerId).iterator().next(); + for (CombatGroup group: engagement.getGroups()) { + for (UUID attackerId: group.getAttackers()) { + sim.getPlayer(activePlayerId).declareAttacker(attackerId, defenderId, sim); + } + } + sim.fireEvent(GameEvent.getEvent(GameEvent.EventType.DECLARED_ATTACKERS, playerId, playerId)); + SimulationNode newNode = new SimulationNode(sim, node.getDepth()-1, activePlayerId); + logger.fine("simulating -- node #:" + SimulationNode.getCount() + " declare attakers"); + newNode.setCombat(sim.getCombat()); + node.children.add(newNode); + } + } + } + else if (game.getTurn().getStepType() == PhaseStep.DECLARE_BLOCKERS) { + game.fireEvent(new GameEvent(GameEvent.EventType.DECLARE_BLOCKERS_STEP_PRE, null, null, activePlayerId)); + if (!game.replaceEvent(GameEvent.getEvent(GameEvent.EventType.DECLARING_BLOCKERS, activePlayerId, activePlayerId))) { + for (UUID defenderId: game.getCombat().getDefenders()) { + //check if defender is being attacked + if (game.getCombat().isAttacked(defenderId, game)) { + for (Combat engagement: ((SimulatedPlayer)game.getPlayer(defenderId)).addBlockers(game)) { + Game sim = game.copy(); + for (CombatGroup group: engagement.getGroups()) { + for (UUID blockerId: group.getBlockers()) { + group.addBlocker(blockerId, defenderId, sim); + } + } + sim.fireEvent(GameEvent.getEvent(GameEvent.EventType.DECLARED_BLOCKERS, playerId, playerId)); + SimulationNode newNode = new SimulationNode(sim, node.getDepth()-1, defenderId); + logger.fine("simulating -- node #:" + SimulationNode.getCount() + " declare blockers"); + newNode.setCombat(sim.getCombat()); + node.children.add(newNode); + } + } + } + } + } + else { + game.getStep().beginStep(game, activePlayerId); + } + if (game.getStep().getHasPriority()) + break; + } + else { + skip = true; + } + } + game.checkStateAndTriggered(); + } + + @Override + public void selectAttackers(Game game) { + logger.fine("selectAttackers"); + if (combat != null) { + UUID opponentId = game.getCombat().getDefenders().iterator().next(); + for (UUID attackerId: combat.getAttackers()) { + this.declareAttacker(attackerId, opponentId, game); + } + } + } + + @Override + public void selectBlockers(Game game) { + logger.fine("selectBlockers"); + if (combat != null && combat.getGroups().size() > 0) { + List groups = game.getCombat().getGroups(); + for (int i = 0; i < groups.size(); i++) { + if (i < combat.getGroups().size()) { + for (UUID blockerId: combat.getGroups().get(i).getBlockers()) { + this.declareBlocker(blockerId, groups.get(i).getAttackers().get(0), game); + } + } + } + } + } + + /** + * 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 copyPlayer: sim.getState().getPlayers().values()) { + Player origPlayer = game.getState().getPlayers().get(copyPlayer.getId()); + SimulatedPlayer newPlayer = new SimulatedPlayer(copyPlayer.getId(), copyPlayer.getId().equals(playerId)); + newPlayer.restore(origPlayer); + sim.getState().getPlayers().put(copyPlayer.getId(), newPlayer); + } + return sim; + } + +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer3.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer3.java new file mode 100644 index 0000000000..b3f4134527 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer3.java @@ -0,0 +1,536 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ + +package mage.player.ai; + +import java.util.LinkedList; +import java.util.UUID; +import java.util.logging.Level; +import java.util.logging.Logger; +import mage.Constants.AbilityType; +import mage.Constants.PhaseStep; +import mage.Constants.RangeOfInfluence; +import mage.Constants.Zone; +import mage.abilities.Ability; +import mage.cards.decks.Deck; +import mage.filter.FilterAbility; +import mage.game.Game; +import mage.game.combat.Combat; +import mage.game.combat.CombatGroup; +import mage.game.events.GameEvent; +import mage.game.turn.BeginCombatStep; +import mage.game.turn.BeginningPhase; +import mage.game.turn.CleanupStep; +import mage.game.turn.CombatDamageStep; +import mage.game.turn.CombatPhase; +import mage.game.turn.DeclareAttackersStep; +import mage.game.turn.DeclareBlockersStep; +import mage.game.turn.DrawStep; +import mage.game.turn.EndOfCombatStep; +import mage.game.turn.EndPhase; +import mage.game.turn.EndStep; +import mage.game.turn.PostCombatMainPhase; +import mage.game.turn.PostCombatMainStep; +import mage.game.turn.Step; +import mage.game.turn.UntapStep; +import mage.game.turn.UpkeepStep; +import mage.players.Player; +import mage.util.Logging; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class ComputerPlayer3 extends ComputerPlayer2 implements Player { + + private static final transient Logger logger = Logging.getLogger(ComputerPlayer3.class.getName()); + + private static FilterAbility filterLand = new FilterAbility(); + private static FilterAbility filterNotLand = new FilterAbility(); + + static { + filterLand.getTypes().add(AbilityType.PLAY_LAND); + filterLand.setZone(Zone.HAND); + + filterNotLand.getTypes().add(AbilityType.PLAY_LAND); + filterNotLand.setZone(Zone.HAND); + filterNotLand.setNotFilter(true); + + } + + public ComputerPlayer3(String name, RangeOfInfluence range) { + super(name, range); + maxDepth = Config.maxDepth; + maxNodes = Config.maxNodes; + } + + public ComputerPlayer3(final ComputerPlayer3 player) { + super(player); + } + + @Override + public ComputerPlayer3 copy() { + return new ComputerPlayer3(this); + } + + @Override + public void priority(Game game) { + logState(game); + game.firePriorityEvent(playerId); + switch (game.getTurn().getStepType()) { + case UPKEEP: + case DRAW: + pass(); + break; + case PRECOMBAT_MAIN: + if (game.getActivePlayerId().equals(playerId)) { + if (actions.size() == 0) { + calculatePreCombatActions(game); + } + act(game); + } + else + pass(); + break; + case BEGIN_COMBAT: + pass(); + break; + case DECLARE_ATTACKERS: + if (!game.getActivePlayerId().equals(playerId)) { + if (actions.size() == 0) { + calculatePreCombatActions(game); + } + act(game); + } + else + pass(); + break; + case DECLARE_BLOCKERS: + case COMBAT_DAMAGE: + case END_COMBAT: + pass(); + break; + case POSTCOMBAT_MAIN: + if (game.getActivePlayerId().equals(playerId)) { + if (actions.size() == 0) { + calculatePostCombatActions(game); + } + act(game); + } + else + pass(); + break; + case END_TURN: + case CLEANUP: + pass(); + break; + } + } + + protected void calculatePreCombatActions(Game game) { + if (!getNextAction(game)) { + currentScore = GameStateEvaluator.evaluate(playerId, game); + Game sim = createSimulation(game); + SimulationNode.resetCount(); + root = new SimulationNode(sim, maxDepth, playerId); + logger.fine("simulating pre combat actions -----------------------------------------------------------------------------------------"); + + addActionsTimed(new FilterAbility()); + if (root.children.size() > 0) { + root = root.children.get(0); + actions = new LinkedList(root.abilities); + combat = root.combat; + } + } + } + + protected void calculatePostCombatActions(Game game) { + if (!getNextAction(game)) { + currentScore = GameStateEvaluator.evaluate(playerId, game); + Game sim = createSimulation(game); + SimulationNode.resetCount(); + root = new SimulationNode(sim, maxDepth, playerId); + logger.fine("simulating post combat actions ----------------------------------------------------------------------------------------"); + addActionsTimed(new FilterAbility()); + if (root.children.size() > 0) { + root = root.children.get(0); + actions = new LinkedList(root.abilities); + combat = root.combat; + } + } + } + + @Override + protected int addActions(SimulationNode node, FilterAbility filter, int depth, int alpha, int beta) { + boolean stepFinished = false; + int val; + Game game = node.getGame(); + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return GameStateEvaluator.evaluate(playerId, game); + } + if (depth <= 0 || SimulationNode.nodeCount > maxNodes || game.isGameOver()) { + logger.fine("simulating -- reached end state"); + val = GameStateEvaluator.evaluate(playerId, game); + } + else if (node.getChildren().size() > 0) { + logger.fine("simulating -- somthing added children:" + node.getChildren().size()); + val = minimaxAB(node, filter, depth-1, alpha, beta); + } + else { + if (logger.isLoggable(Level.FINE)) + logger.fine("simulating -- alpha: " + alpha + " beta: " + beta + " depth:" + depth + " step:" + game.getTurn().getStepType() + " for player:" + game.getPlayer(game.getPlayerList().get()).getName()); + if (allPassed(game)) { + if (!game.getStack().isEmpty()) { + resolve(node, depth, game); + } + else { + stepFinished = true; + } + } + + if (game.isGameOver()) { + val = GameStateEvaluator.evaluate(playerId, game); + } + else if (stepFinished) { + logger.fine("step finished"); + int testScore = GameStateEvaluator.evaluate(playerId, game); + if (game.getActivePlayerId().equals(playerId)) { + if (testScore < currentScore) { + // if score at end of step is worse than original score don't check further + logger.fine("simulating -- abandoning check, no immediate benefit"); + val = testScore; + } + else { + switch (game.getTurn().getStepType()) { + case PRECOMBAT_MAIN: + val = -simulateCombat(game, node, depth-1, alpha, beta, false); + break; + case POSTCOMBAT_MAIN: + val = -simulateCounterAttack(game, node, depth-1, alpha, beta); + break; + default: + val = -GameStateEvaluator.evaluate(playerId, game); + break; + } + } + } + else { + if (game.getTurn().getStepType() == PhaseStep.DECLARE_ATTACKERS) + val = simulateBlockers(game, node, playerId, depth-1, alpha, beta, true); + else + val = GameStateEvaluator.evaluate(playerId, game); + } + } + else if (node.getChildren().size() > 0) { + logger.fine("simulating -- trigger added children:" + node.getChildren().size()); + val = minimaxAB(node, filter, depth, alpha, beta); + } + else { + val = simulatePriority(node, game, filter, depth, alpha, beta); + } + } + + if (logger.isLoggable(Level.FINE)) + logger.fine("returning -- score: " + val + " depth:" + depth + " step:" + game.getTurn().getStepType() + " for player:" + game.getPlayer(node.getPlayerId()).getName()); + return val; + + } + + protected int simulateCombat(Game game, SimulationNode node, int depth, int alpha, int beta, boolean counter) { + Integer val = null; + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return GameStateEvaluator.evaluate(playerId, game); + } + if (game.getTurn().getStepType() != PhaseStep.DECLARE_BLOCKERS) { + game.getTurn().setPhase(new CombatPhase()); + if (game.getPhase().beginPhase(game, game.getActivePlayerId())) { + simulateStep(game, new BeginCombatStep()); + game.getPhase().setStep(new DeclareAttackersStep()); + if (!game.getStep().skipStep(game, game.getActivePlayerId())) { + game.fireEvent(new GameEvent(GameEvent.EventType.DECLARE_ATTACKERS_STEP_PRE, null, null, game.getActivePlayerId())); + if (!game.replaceEvent(GameEvent.getEvent(GameEvent.EventType.DECLARING_ATTACKERS, game.getActivePlayerId(), game.getActivePlayerId()))) { + val = simulateAttackers(game, node, game.getActivePlayerId(), depth, alpha, beta, counter); + } + } + else if (!counter) { + simulateToEnd(game); + val = simulatePostCombatMain(game, node, depth, alpha, beta); + } + } + } + else { + if (!game.getStep().skipStep(game, game.getActivePlayerId())) { + game.fireEvent(new GameEvent(GameEvent.EventType.DECLARE_BLOCKERS_STEP_PRE, null, null, game.getActivePlayerId())); + if (!game.replaceEvent(GameEvent.getEvent(GameEvent.EventType.DECLARING_BLOCKERS, game.getActivePlayerId(), game.getActivePlayerId()))) { + //only suitable for two player games - only simulates blocks for 1st defender + val = simulateBlockers(game, node, game.getCombat().getDefenders().iterator().next(), depth, alpha, beta, counter); + } + } + else if (!counter) { + finishCombat(game); + val = GameStateEvaluator.evaluate(playerId, game); +// val = simulateCounterAttack(game, node, depth, alpha, beta); + } + } + if (val == null) + val = GameStateEvaluator.evaluate(playerId, game); + if (logger.isLoggable(Level.FINE)) + logger.fine("returning -- combat score: " + val + " depth:" + depth + " for player:" + game.getPlayer(node.getPlayerId()).getName()); + return val; + } + + + protected int simulateAttackers(Game game, SimulationNode node, UUID attackerId, int depth, int alpha, int beta, boolean counter) { + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return GameStateEvaluator.evaluate(playerId, game); + } + Integer val = null; + SimulationNode bestNode = null; + SimulatedPlayer attacker = (SimulatedPlayer) game.getPlayer(attackerId); + + for (Combat engagement: attacker.addAttackers(game)) { + if (alpha >= beta) { + logger.fine("simulating -- pruning attackers"); + break; + } + Game sim = game.copy(); + UUID defenderId = game.getOpponents(playerId).iterator().next(); + for (CombatGroup group: engagement.getGroups()) { + for (UUID attackId: group.getAttackers()) { + sim.getPlayer(attackerId).declareAttacker(attackId, defenderId, sim); + } + } + sim.fireEvent(GameEvent.getEvent(GameEvent.EventType.DECLARED_ATTACKERS, playerId, playerId)); + SimulationNode newNode = new SimulationNode(sim, depth, game.getActivePlayerId()); + if (logger.isLoggable(Level.FINE)) + logger.fine("simulating attack -- node#: " + SimulationNode.getCount()); + sim.checkStateAndTriggered(); + while (!sim.getStack().isEmpty()) { + sim.getStack().resolve(sim); + logger.fine("resolving triggered abilities"); + sim.applyEffects(); + } + sim.fireEvent(GameEvent.getEvent(GameEvent.EventType.DECLARE_ATTACKERS_STEP_POST, sim.getActivePlayerId(), sim.getActivePlayerId())); + Combat simCombat = sim.getCombat().copy(); + sim.getPhase().setStep(new DeclareBlockersStep()); + val = simulateCombat(sim, newNode, depth-1, alpha, beta, counter); + if (!attackerId.equals(playerId)) { + if (val < beta) { + beta = val; + bestNode = newNode; + node.setCombat(simCombat); + } + } + else { + if (val > alpha) { + alpha = val; + bestNode = newNode; + node.setCombat(simCombat); + } + } + } + if (val == null) + val = GameStateEvaluator.evaluate(playerId, game); + if (bestNode != null) { + node.children.clear(); + node.children.add(bestNode); + } + if (logger.isLoggable(Level.FINE)) + logger.fine("returning -- combat attacker score: " + val + " depth:" + depth + " for player:" + game.getPlayer(node.getPlayerId()).getName()); + return val; + } + + protected int simulateBlockers(Game game, SimulationNode node, UUID defenderId, int depth, int alpha, int beta, boolean counter) { + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return GameStateEvaluator.evaluate(playerId, game); + } + Integer val = null; + SimulationNode bestNode = null; + //check if defender is being attacked + if (game.getCombat().isAttacked(defenderId, game)) { + SimulatedPlayer defender = (SimulatedPlayer) game.getPlayer(defenderId); + for (Combat engagement: defender.addBlockers(game)) { + if (alpha >= beta) { + logger.fine("simulating -- pruning blockers"); + break; + } + Game sim = game.copy(); + for (CombatGroup group: engagement.getGroups()) { + UUID attackerId = group.getAttackers().get(0); + for (UUID blockerId: group.getBlockers()) { + sim.getPlayer(defenderId).declareBlocker(blockerId, attackerId, sim); + } + } + sim.fireEvent(GameEvent.getEvent(GameEvent.EventType.DECLARED_BLOCKERS, playerId, playerId)); + SimulationNode newNode = new SimulationNode(sim, depth, defenderId); + if (logger.isLoggable(Level.FINE)) + logger.fine("simulating block -- node#: " + SimulationNode.getCount()); + sim.checkStateAndTriggered(); + while (!sim.getStack().isEmpty()) { + sim.getStack().resolve(sim); + logger.fine("resolving triggered abilities"); + sim.applyEffects(); + } + sim.fireEvent(GameEvent.getEvent(GameEvent.EventType.DECLARE_BLOCKERS_STEP_POST, sim.getActivePlayerId(), sim.getActivePlayerId())); + Combat simCombat = sim.getCombat().copy(); + finishCombat(sim); + if (sim.isGameOver()) { + val = GameStateEvaluator.evaluate(playerId, sim); + } + else if (!counter) { + val = simulatePostCombatMain(sim, newNode, depth-1, alpha, beta); + } + else + val = GameStateEvaluator.evaluate(playerId, sim); + if (!defenderId.equals(playerId)) { + if (val < beta) { + beta = val; + bestNode = newNode; + node.setCombat(simCombat); + } + } + else { + if (val > alpha) { + alpha = val; + bestNode = newNode; + node.setCombat(simCombat); + } + } + } + } + if (val == null) + val = GameStateEvaluator.evaluate(playerId, game); + if (bestNode != null) { + node.children.clear(); + node.children.add(bestNode); + } + if (logger.isLoggable(Level.FINE)) + logger.fine("returning -- combat blocker score: " + val + " depth:" + depth + " for player:" + game.getPlayer(node.getPlayerId()).getName()); + return val; + } + + protected int simulateCounterAttack(Game game, SimulationNode node, int depth, int alpha, int beta) { + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return GameStateEvaluator.evaluate(playerId, game); + } + Integer val = null; + if (!game.isGameOver()) { + logger.fine("simulating -- counter attack"); + simulateToEnd(game); + game.getState().setActivePlayerId(game.getState().getPlayerList(game.getActivePlayerId()).getNext()); + game.getTurn().setPhase(new BeginningPhase()); + if (game.getPhase().beginPhase(game, game.getActivePlayerId())) { + simulateStep(game, new UntapStep()); + simulateStep(game, new UpkeepStep()); + simulateStep(game, new DrawStep()); + game.getPhase().endPhase(game, game.getActivePlayerId()); + } + val = simulateCombat(game, node, depth-1, alpha, beta, true); + if (logger.isLoggable(Level.FINE)) + logger.fine("returning -- counter attack score: " + val + " depth:" + depth + " for player:" + game.getPlayer(node.getPlayerId()).getName()); + } + if (val == null) + val = GameStateEvaluator.evaluate(playerId, game); + return val; + } + + protected void simulateStep(Game game, Step step) { + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return; + } + if (!game.isGameOver()) { + game.getPhase().setStep(step); + if (!step.skipStep(game, game.getActivePlayerId())) { + step.beginStep(game, game.getActivePlayerId()); + game.checkStateAndTriggered(); + while (!game.getStack().isEmpty()) { + game.getStack().resolve(game); + game.applyEffects(); + } + step.endStep(game, game.getActivePlayerId()); + } + } + } + + protected void finishCombat(Game game) { + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return; + } + simulateStep(game, new CombatDamageStep(true)); + simulateStep(game, new CombatDamageStep(false)); + simulateStep(game, new EndOfCombatStep()); + } + + protected int simulatePostCombatMain(Game game, SimulationNode node, int depth, int alpha, int beta) { + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return GameStateEvaluator.evaluate(playerId, game); + } + logger.fine("simulating -- post combat main"); + game.getTurn().setPhase(new PostCombatMainPhase()); + if (game.getPhase().beginPhase(game, game.getActivePlayerId())) { + game.getPhase().setStep(new PostCombatMainStep()); + game.getStep().beginStep(game, playerId); + game.getPlayers().resetPassed(); + return addActions(node, new FilterAbility(), depth, alpha, beta); + } + return simulateCounterAttack(game, node, depth, alpha, beta); + } + + protected void simulateToEnd(Game game) { + if (Thread.interrupted()) { + Thread.currentThread().interrupt(); + logger.fine("interrupted"); + return; + } + if (!game.isGameOver()) { + game.getTurn().getPhase().endPhase(game, game.getActivePlayerId()); + game.getTurn().setPhase(new EndPhase()); + if (game.getTurn().getPhase().beginPhase(game, game.getActivePlayerId())) { + simulateStep(game, new EndStep()); + simulateStep(game, new CleanupStep()); + } + } + } + +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/Config.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/Config.java new file mode 100644 index 0000000000..c0854286f4 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/Config.java @@ -0,0 +1,75 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ + +package mage.player.ai; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import mage.util.Logging; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class Config { + + private final static Logger logger = Logging.getLogger(Config.class.getName()); + + public static final int maxDepth; + public static final int maxNodes; + public static final int evaluatorLifeFactor; + public static final int evaluatorPermanentFactor; + public static final int evaluatorCreatureFactor; + public static final int evaluatorHandFactor; + public static final int maxThinkSeconds; + + static { + Properties p = new Properties(); + try { + File file = new File(Config.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); + p.load(new FileInputStream(new File(file.getParent() + File.separator + "AIMinimax.properties"))); + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + } catch (URISyntaxException ex) { + Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex); + } + maxDepth = Integer.parseInt(p.getProperty("maxDepth")); + maxNodes = Integer.parseInt(p.getProperty("maxNodes")); + evaluatorLifeFactor = Integer.parseInt(p.getProperty("evaluatorLifeFactor")); + evaluatorPermanentFactor = Integer.parseInt(p.getProperty("evaluatorPermanentFactor")); + evaluatorCreatureFactor = Integer.parseInt(p.getProperty("evaluatorCreatureFactor")); + evaluatorHandFactor = Integer.parseInt(p.getProperty("evaluatorHandFactor")); + maxThinkSeconds = Integer.parseInt(p.getProperty("maxThinkSeconds")); + } + +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/GameStateEvaluator.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/GameStateEvaluator.java new file mode 100644 index 0000000000..26d0c69f07 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/GameStateEvaluator.java @@ -0,0 +1,131 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package mage.player.ai; + +import java.util.UUID; +import java.util.logging.Level; +import java.util.logging.Logger; +import mage.Constants.CardType; +import mage.Constants.Zone; +import mage.abilities.ActivatedAbility; +import mage.abilities.keyword.DoubleStrikeAbility; +import mage.abilities.keyword.FirstStrikeAbility; +import mage.abilities.keyword.TrampleAbility; +import mage.abilities.mana.ManaAbility; +import mage.game.Game; +import mage.game.permanent.Permanent; +import mage.player.ai.ma.ArtificialScoringSystem; +import mage.players.Player; +import mage.util.Logging; + +/** + * + * @author nantuko + * + * this evaluator is only good for two player games + * + */ +public class GameStateEvaluator { + + private final static transient Logger logger = Logging.getLogger(GameStateEvaluator.class.getName()); + + static { + logger.setLevel(Level.ALL); + } + + public static final int WIN_GAME_SCORE = 100000000; + public static final int LOSE_GAME_SCORE = -WIN_GAME_SCORE; + + + private static final int LIFE_FACTOR = Config.evaluatorLifeFactor; + private static final int PERMANENT_FACTOR = Config.evaluatorPermanentFactor; + private static final int CREATURE_FACTOR = Config.evaluatorCreatureFactor; + private static final int HAND_FACTOR = Config.evaluatorHandFactor; + + public static int evaluate(UUID playerId, Game game) { + Player player = game.getPlayer(playerId); + Player opponent = game.getPlayer(game.getOpponents(playerId).iterator().next()); + if (game.isGameOver()) { + if (player.hasLost() || opponent.hasWon()) + return Integer.MIN_VALUE; + if (opponent.hasLost() || player.hasWon()) + return Integer.MAX_VALUE; + } + //int lifeScore = (player.getLife() - opponent.getLife()) * LIFE_FACTOR; + + //int lifeScore = (ArtificialScoringSystem.getLifeScore(player.getLife()) - opponent.getLife()) * LIFE_FACTOR; + int lifeScore = 0; + if (player.getLife() <= 0) { // we don't want a tie + lifeScore = ArtificialScoringSystem.LOSE_GAME_SCORE; + } else if (opponent.getLife() <= 0) { + lifeScore = ArtificialScoringSystem.WIN_GAME_SCORE; + } else { + lifeScore = ArtificialScoringSystem.getLifeScore(player.getLife()) - ArtificialScoringSystem.getLifeScore(opponent.getLife()); + } + + int permanentScore = 0; + for (Permanent permanent: game.getBattlefield().getAllActivePermanents(playerId)) { + permanentScore += evaluatePermanent(permanent, game); + } + for (Permanent permanent: game.getBattlefield().getAllActivePermanents(opponent.getId())) { + permanentScore -= evaluatePermanent(permanent, game); + } + //permanentScore *= PERMANENT_FACTOR; + + /*int handScore = 0; + handScore = 7 - opponent.getHand().size(); + handScore += Math.min(7, player.getHand().size()); + handScore *= HAND_FACTOR;*/ + + int score = lifeScore + permanentScore /*+ handScore*/; + //if (logger.isLoggable(Level.FINE)) + logger.fine("game state evaluated to- lifeScore:" + lifeScore + " permanentScore:" + permanentScore /*+ " handScore:" + handScore*/ + "total:" + score); + return score; + } + + public static int evaluatePermanent(Permanent permanent, Game game) { + /*int value = permanent.isTapped()?4:5; + if (permanent.getCardType().contains(CardType.CREATURE)) { + value += evaluateCreature(permanent, game) * CREATURE_FACTOR; + } + value += permanent.getAbilities().getManaAbilities(Zone.BATTLEFIELD).size(); + for (ActivatedAbility ability: permanent.getAbilities().getActivatedAbilities(Zone.BATTLEFIELD)) { + if (!(ability instanceof ManaAbility) && ability.canActivate(ability.getControllerId(), game)) + value += ability.getEffects().size(); + } + value += permanent.getAbilities().getStaticAbilities(Zone.BATTLEFIELD).size(); + value += permanent.getAbilities().getTriggeredAbilities(Zone.BATTLEFIELD).size(); + value += permanent.getManaCost().convertedManaCost(); + */ + + int value = ArtificialScoringSystem.getFixedPermanentScore(game, permanent) + + ArtificialScoringSystem.getVariablePermanentScore(game, permanent); + + //TODO: add a difficulty to calculation to ManaCost - sort permanents by difficulty for casting when evaluating game states + return value; + } + + public static int evaluateCreature(Permanent creature, Game game) { + int value = ArtificialScoringSystem.getFixedPermanentScore(game, creature) + + ArtificialScoringSystem.getVariablePermanentScore(game, creature); + + /*int value = 0; + value += creature.getPower().getValue(); + value += creature.getToughness().getValue(); +// if (creature.canAttack(game)) +// value += creature.getPower().getValue(); +// if (!creature.isTapped()) +// value += 2; + value += creature.getAbilities().getEvasionAbilities().size(); + value += creature.getAbilities().getProtectionAbilities().size(); + value += creature.getAbilities().containsKey(FirstStrikeAbility.getInstance().getId())?1:0; + value += creature.getAbilities().containsKey(DoubleStrikeAbility.getInstance().getId())?2:0; + value += creature.getAbilities().containsKey(TrampleAbility.getInstance().getId())?1:0;*/ + + return value; + } + +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulateBlockWorker.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulateBlockWorker.java new file mode 100644 index 0000000000..66a27c3c1c --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulateBlockWorker.java @@ -0,0 +1,62 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ + +package mage.player.ai; + +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.logging.Logger; +import mage.game.Game; +import mage.util.Logging; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class SimulateBlockWorker implements Callable { + + private final static Logger logger = Logging.getLogger(SimulationWorker.class.getName()); + + private SimulationNode node; + private ComputerPlayer3 player; + + public SimulateBlockWorker(ComputerPlayer3 player, SimulationNode node) { + this.player = player; + this.node = node; + } + + @Override + public Object call() { + try { +// player.simulateBlock(node); + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + return null; + } +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulatedAction.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulatedAction.java new file mode 100644 index 0000000000..ab82ee8096 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulatedAction.java @@ -0,0 +1,68 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ + +package mage.player.ai; + +import java.util.List; +import mage.abilities.Ability; +import mage.game.Game; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class SimulatedAction { + + private Game game; + private List abilities; + + public SimulatedAction(Game game, List abilities) { + this.game = game; + this.abilities = abilities; + } + + public Game getGame() { + return this.game; + } + + public List getAbilities() { + return this.abilities; + } + + @Override + public String toString() { + return this.abilities.toString(); + } + + public boolean usesStack() { + if (abilities != null && abilities.size() > 0) { + return abilities.get(abilities.size() -1).isUsesStack(); + } + return true; + } +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulatedPlayer.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulatedPlayer.java new file mode 100644 index 0000000000..be3b0c762c --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulatedPlayer.java @@ -0,0 +1,250 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ + +package mage.player.ai; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.logging.Level; +import java.util.logging.Logger; +import mage.abilities.Ability; +import mage.abilities.ActivatedAbility; +import mage.abilities.TriggeredAbility; +import mage.abilities.common.PassAbility; +import mage.abilities.mana.ManaOptions; +import mage.choices.Choice; +import mage.filter.FilterAbility; +import mage.game.Game; +import mage.game.combat.Combat; +import mage.game.events.GameEvent; +import mage.game.permanent.Permanent; +import mage.game.stack.StackAbility; +import mage.target.Target; +import mage.util.Copier; +import mage.util.Logging; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class SimulatedPlayer extends ComputerPlayer { + + private final static transient Logger logger = Logging.getLogger(SimulatedPlayer.class.getName()); + private boolean isSimulatedPlayer; + private FilterAbility filter; + private transient ConcurrentLinkedQueue allActions; + private static PassAbility pass = new PassAbility(); + + public SimulatedPlayer(UUID id, boolean isSimulatedPlayer) { + super(id); + pass.setControllerId(playerId); + this.isSimulatedPlayer = isSimulatedPlayer; + } + + public SimulatedPlayer(final SimulatedPlayer player) { + super(player); + this.isSimulatedPlayer = player.isSimulatedPlayer; + if (player.filter != null) + this.filter = player.filter.copy(); + } + + @Override + public SimulatedPlayer copy() { + return new SimulatedPlayer(this); + } + + public List simulatePriority(Game game, FilterAbility filter) { + allActions = new ConcurrentLinkedQueue(); + Game sim = game.copy(); + this.filter = filter; + + simulateOptions(sim, pass); + + ArrayList list = new ArrayList(allActions); + Collections.reverse(list); + return list; + } + + protected void simulateOptions(Game game, Ability previousActions) { + allActions.add(previousActions); + ManaOptions available = getManaAvailable(game); + available.addMana(manaPool.getMana()); + List playables = game.getPlayer(playerId).getPlayable(game, filter, available, isSimulatedPlayer); + for (Ability ability: playables) { + List options = game.getPlayer(playerId).getPlayableOptions(ability, game); + if (options.size() == 0) { + allActions.add(ability); +// simulateAction(game, previousActions, ability); + } + else { +// ExecutorService simulationExecutor = Executors.newFixedThreadPool(4); + for (Ability option: options) { + allActions.add(option); +// SimulationWorker worker = new SimulationWorker(game, this, previousActions, option); +// simulationExecutor.submit(worker); + } +// simulationExecutor.shutdown(); +// while(!simulationExecutor.isTerminated()) {} + } + } + } + +// protected void simulateAction(Game game, SimulatedAction previousActions, Ability action) { +// List actions = new ArrayList(previousActions.getAbilities()); +// actions.add(action); +// Game sim = game.copy(); +// if (sim.getPlayer(playerId).activateAbility((ActivatedAbility) action.copy(), sim)) { +// sim.applyEffects(); +// sim.getPlayers().resetPassed(); +// allActions.add(new SimulatedAction(sim, actions)); +// } +// } + + public List addAttackers(Game game) { + Map engagements = new HashMap(); + //useful only for two player games - will only attack first opponent + UUID defenderId = game.getOpponents(playerId).iterator().next(); + List attackersList = super.getAvailableAttackers(game); + //use binary digits to calculate powerset of attackers + int powerElements = (int) Math.pow(2, attackersList.size()); + StringBuilder binary = new StringBuilder(); + for (int i = powerElements - 1; i >= 0; i--) { + Game sim = game.copy(); + binary.setLength(0); + binary.append(Integer.toBinaryString(i)); + while (binary.length() < attackersList.size()) { + binary.insert(0, "0"); + } + for (int j = 0; j < attackersList.size(); j++) { + if (binary.charAt(j) == '1') + sim.getCombat().declareAttacker(attackersList.get(j).getId(), defenderId, sim); + } + if (engagements.put(sim.getCombat().getValue(sim), sim.getCombat()) != null) { + logger.fine("simulating -- found redundant attack combination"); + } + else if (logger.isLoggable(Level.FINE)) { + logger.fine("simulating -- attack:" + sim.getCombat().getGroups().size()); + } + } + return new ArrayList(engagements.values()); + } + + public List addBlockers(Game game) { + Map engagements = new HashMap(); + int numGroups = game.getCombat().getGroups().size(); + if (numGroups == 0) return new ArrayList(); + + //add a node with no blockers + Game sim = game.copy(); + engagements.put(sim.getCombat().getValue(sim), sim.getCombat()); + sim.fireEvent(GameEvent.getEvent(GameEvent.EventType.DECLARED_BLOCKERS, playerId, playerId)); + + List blockers = getAvailableBlockers(game); + addBlocker(game, blockers, engagements); + + return new ArrayList(engagements.values()); + } + + protected void addBlocker(Game game, List blockers, Map engagements) { + if (blockers.size() == 0) + return; + int numGroups = game.getCombat().getGroups().size(); + //try to block each attacker with each potential blocker + Permanent blocker = blockers.get(0); + if (logger.isLoggable(Level.FINE)) + logger.fine("simulating -- block:" + blocker); + List remaining = remove(blockers, blocker); + for (int i = 0; i < numGroups; i++) { + if (game.getCombat().getGroups().get(i).canBlock(blocker, game)) { + Game sim = game.copy(); + sim.getCombat().getGroups().get(i).addBlocker(blocker.getId(), playerId, sim); + if (engagements.put(sim.getCombat().getValue(sim), sim.getCombat()) != null) + logger.fine("simulating -- found redundant block combination"); + addBlocker(sim, remaining, engagements); // and recurse minus the used blocker + } + } + addBlocker(game, remaining, engagements); + } + + @Override + public boolean triggerAbility(TriggeredAbility source, Game game) { + Ability ability = source.copy(); + List options = getPlayableOptions(ability, game); + if (options.size() == 0) { + if (logger.isLoggable(Level.FINE)) + logger.fine("simulating -- triggered ability:" + ability); + game.getStack().push(new StackAbility(ability, playerId)); + ability.activate(game, false); + game.applyEffects(); + game.getPlayers().resetPassed(); + } + else { + SimulationNode parent = (SimulationNode) game.getCustomData(); + int depth = parent.getDepth() - 1; + if (depth == 0) return true; + logger.fine("simulating -- triggered ability - adding children:" + options.size()); + for (Ability option: options) { + addAbilityNode(parent, option, depth, game); + } + } + return true; + } + + protected void addAbilityNode(SimulationNode parent, Ability ability, int depth, Game game) { + Game sim = game.copy(); + sim.getStack().push(new StackAbility(ability, playerId)); + ability.activate(sim, false); + sim.applyEffects(); + SimulationNode newNode = new SimulationNode(sim, depth, playerId); + logger.fine("simulating -- node #:" + SimulationNode.getCount() + " triggered ability option"); + for (Target target: ability.getTargets()) { + for (UUID targetId: target.getTargets()) { + newNode.getTargets().add(targetId); + } + } + for (Choice choice: ability.getChoices()) { + newNode.getChoices().add(choice.getChoice()); + } + parent.children.add(newNode); + } + + @Override + public void priority(Game game) { + //should never get here + } + +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulationNode.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulationNode.java new file mode 100644 index 0000000000..954e4c7097 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulationNode.java @@ -0,0 +1,127 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ + +package mage.player.ai; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import mage.abilities.Ability; +import mage.game.Game; +import mage.game.combat.Combat; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class SimulationNode implements Serializable { + + protected static int nodeCount; + + protected Game game; + protected int gameValue; + protected List abilities; + protected int depth; + protected List children = new ArrayList(); + protected List targets = new ArrayList(); + protected List choices = new ArrayList(); + protected UUID playerId; + protected Combat combat; + + public SimulationNode(Game game, int depth, UUID playerId) { + this.game = game; + this.depth = depth; + this.playerId = playerId; + game.setCustomData(this); + nodeCount++; + } + + public SimulationNode(Game game, List abilities, int depth, UUID playerId) { + this(game, depth, playerId); + this.abilities = abilities; + } + + public SimulationNode(Game game, Ability ability, int depth, UUID playerId) { + this(game, depth, playerId); + this.abilities = new ArrayList(); + abilities.add(ability); + } + + public static void resetCount() { + nodeCount = 0; + } + + public static int getCount() { + return nodeCount; + } + + public Game getGame() { + return this.game; + } + + public int getGameValue() { + return this.gameValue; + } + + public void setGameValue(int value) { + this.gameValue = value; + } + + public List getAbilities() { + return this.abilities; + } + + public List getChildren() { + return this.children; + } + + public int getDepth() { + return this.depth; + } + + public UUID getPlayerId() { + return this.playerId; + } + + public Combat getCombat() { + return this.combat; + } + + public void setCombat(Combat combat) { + this.combat = combat; + } + + public List getTargets() { + return this.targets; + } + + public List getChoices() { + return this.choices; + } +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulationWorker.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulationWorker.java new file mode 100644 index 0000000000..b5a5876ef0 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/SimulationWorker.java @@ -0,0 +1,69 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ + +package mage.player.ai; + +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.logging.Logger; +import mage.abilities.Ability; +import mage.game.Game; +import mage.util.Logging; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class SimulationWorker implements Callable { + + private final static Logger logger = Logging.getLogger(SimulationWorker.class.getName()); + + private Game game; + private SimulatedAction previousActions; + private Ability action; + private SimulatedPlayer player; + + public SimulationWorker(Game game, SimulatedPlayer player, SimulatedAction previousActions, Ability action) { + this.game = game; + this.player = player; + this.previousActions = previousActions; + this.action = action; + } + + @Override + public Object call() { + try { +// player.simulateAction(game, previousActions, action); + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + return null; + } + +} + diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ma/ArtificialScoringSystem.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ma/ArtificialScoringSystem.java new file mode 100644 index 0000000000..a76b079e0c --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ma/ArtificialScoringSystem.java @@ -0,0 +1,150 @@ +package mage.player.ai.ma; + +import mage.Constants; +import mage.Mana; +import mage.abilities.Ability; +import mage.abilities.keyword.HasteAbility; +import mage.cards.Card; +import mage.counters.CounterType; +import mage.game.Game; +import mage.game.permanent.Permanent; + +import java.util.UUID; + +/** + * @author ubeefx, nantuko + */ +public class ArtificialScoringSystem { + + public static final int WIN_GAME_SCORE=100000000; + public static final int LOSE_GAME_SCORE=-WIN_GAME_SCORE; + + private static final int LIFE_SCORES[] = {0, 1000, 2000, 3000, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7400, 7800, 8200, 8600, 9000, 9200, 9400, 9600, 9800, 10000}; + private static final int MAX_LIFE = LIFE_SCORES.length - 1; + private static final int UNKNOWN_CARD_SCORE = 300; + private static final int PERMANENT_SCORE = 300; + private static final int LIFE_ABOVE_MULTIPLIER = 100; + + public static int getCardDefinitionScore(final Game game, final Card card) { + int value = 0; //TODO: add new rating system card value + if (card.getCardType().contains(Constants.CardType.LAND)) { + int score = (int) ((value / 2.0f) * 50); + //TODO: check this for "any color" lands + //TODO: check this for dual and filter lands + /*for (Mana mana : card.getMana()) { + score += 50; + }*/ + score += card.getMana().size()*50; + return score; + } + + final int score = value * 100 - card.getManaCost().convertedManaCost() * 20; + if (card.getCardType().contains(Constants.CardType.CREATURE)) { + return score + (card.getPower().getValue() + card.getToughness().getValue()) * 10; + } else { + return score + (/*card.getRemoval()*50*/ +card.getRarity().getRating() * 30); + } + } + + public static int getFixedPermanentScore(final Game game, final Permanent permanent) { + //TODO: cache it inside Card + int score = getCardDefinitionScore(game, permanent); + if (permanent.getCardType().contains(Constants.CardType.CREATURE)) { + // TODO: implement in the mage core + //score + =cardDefinition.getActivations().size()*50; + //score += cardDefinition.getManaActivations().size()*80; + } else { + score += PERMANENT_SCORE; + if (permanent.getSubtype().contains("Equipment")) { + score += 100; + } + } + return score; + } + + public static int getVariablePermanentScore(final Game game, final Permanent permanent) { + + int score = permanent.getCounters().getCount(CounterType.CHARGE) * 30; + if (!canTap(permanent)) { + score += getTappedScore(permanent); + } + if (permanent.getCardType().contains(Constants.CardType.CREATURE)) { + final int power = permanent.getPower().getValue(); + final int toughness = permanent.getToughness().getValue(); + int abilityScore = 0; + for (Ability ability : permanent.getAbilities()) { + abilityScore += MagicAbility.getAbilityScore(ability); + } + score += power * 300 + getPositive(toughness) * 200 + abilityScore * (getPositive(power) + 1) / 2; + //TODO: it can be improved + //score += permanent.getEquipmentPermanents().size() * 50 + permanent.getAuraPermanents().size() * 100; + int enchantments = 0; + int equipments = 0; + for (UUID uuid : permanent.getAttachments()) { + Card card = game.getCard(uuid); + if (card != null) { + if (card.getCardType().contains(Constants.CardType.ENCHANTMENT)) { + enchantments++; + } else { + equipments++; + } + } + } + score += equipments*50 + enchantments*100; + } + return score; + } + + private static boolean canTap(Permanent permanent) { + return !permanent.isTapped() + &&(!permanent.hasSummoningSickness() + ||!permanent.getCardType().contains(Constants.CardType.CREATURE) + ||permanent.getAbilities().contains(HasteAbility.getInstance())); + } + + private static int getPositive(int value) { + return value > 0 ? value : 0; + } + + public static int getTappedScore(final Permanent permanent) { + return permanent.getCardType().contains(Constants.CardType.CREATURE) ? -10 : -5; + } + + public static int getLifeScore(final int life) { + if (life > MAX_LIFE) { + return LIFE_SCORES[MAX_LIFE] + (life - MAX_LIFE) * LIFE_ABOVE_MULTIPLIER; + } else if (life >= 0) { + return LIFE_SCORES[life]; + } else { + return 0; + } + } + + public static int getManaScore(final int amount) { + return -amount; + } + + public static int getAttackerScore(final Permanent attacker) { + //TODO: implement this + /*int score = attacker.getPower().getValue() * 5 + attacker.lethalDamage * 2 - attacker.candidateBlockers.length; + for (final MagicCombatCreature blocker : attacker.candidateBlockers) { + + score -= blocker.power; + } + // Dedicated attacker. + if (attacker.hasAbility(MagicAbility.AttacksEachTurnIfAble) || attacker.hasAbility(MagicAbility.CannotBlock)) { + score += 10; + } + // Abilities for attacking. + if (attacker.hasAbility(MagicAbility.Trample) || attacker.hasAbility(MagicAbility.Vigilance)) { + score += 8; + } + // Dangerous to block. + if (!attacker.normalDamage || attacker.hasAbility(MagicAbility.FirstStrike) || attacker.hasAbility(MagicAbility.Indestructible)) { + score += 7; + } + */ + int score = 0; + return score; + } +} diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ma/MagicAbility.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ma/MagicAbility.java new file mode 100644 index 0000000000..47a55969ed --- /dev/null +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ma/MagicAbility.java @@ -0,0 +1,50 @@ +package mage.player.ai.ma; + +import mage.abilities.Ability; +import mage.abilities.StaticAbility; +import mage.abilities.keyword.*; +import mage.cards.basiclands.Plains; + +import java.util.HashMap; +import java.util.Map; +import java.util.zip.Inflater; + +/** + * @author nantuko + */ +public class MagicAbility { + + private static Map scores = new HashMap() {{ + scores.put(DeathtouchAbility.getInstance().getRule(), 60); + scores.put(DefenderAbility.getInstance().getRule(), -100); + scores.put(DoubleStrikeAbility.getInstance().getRule(), 100); + scores.put(DoubleStrikeAbility.getInstance().getRule(), 100); + scores.put(new ExaltedAbility().getRule(), 10); + scores.put(FirstStrikeAbility.getInstance().getRule(), 50); + scores.put(FlashAbility.getInstance().getRule(), 0); + scores.put(FlyingAbility.getInstance().getRule(), 50); + scores.put(new ForestwalkAbility().getRule(), 10); + scores.put(HasteAbility.getInstance().getRule(), 0); + scores.put(IndestructibleAbility.getInstance().getRule(), 150); + scores.put(InfectAbility.getInstance().getRule(), 60); + scores.put(IntimidateAbility.getInstance().getRule(), 50); + scores.put(new IslandwalkAbility().getRule(), 10); + scores.put(new MountainwalkAbility().getRule(), 10); + scores.put(new PlainswalkAbility().getRule(), 10); + scores.put(ReachAbility.getInstance().getRule(), 20); + scores.put(ShroudAbility.getInstance().getRule(), 60); + scores.put(new SwampwalkAbility().getRule(), 10); + scores.put(TrampleAbility.getInstance().getRule(), 30); + scores.put(UnblockableAbility.getInstance().getRule(), 100); + scores.put(VigilanceAbility.getInstance().getRule(), 20); + scores.put(WitherAbility.getInstance().getRule(), 30); + }}; + + public static int getAbilityScore(Ability ability) { + if (!scores.containsKey(ability.getRule())) { + System.err.println("Couldn't find ability score: " + ability.getRule()); + //TODO: add handling protection from ..., levelup, kicker, etc. abilities + } + return scores.get(ability.getRule()); + } +} diff --git a/Mage.Server.Plugins/pom.xml b/Mage.Server.Plugins/pom.xml index c52d2a0b06..7d79087696 100644 --- a/Mage.Server.Plugins/pom.xml +++ b/Mage.Server.Plugins/pom.xml @@ -21,6 +21,7 @@ Mage.Game.TwoPlayerDuel Mage.Player.AI Mage.Player.AIMinimax + Mage.Player.AI.MA Mage.Player.Human Mage.Tournament.BoosterDraft diff --git a/Mage.Server/config/config.xml b/Mage.Server/config/config.xml index f6c0206984..08f9d514c5 100644 --- a/Mage.Server/config/config.xml +++ b/Mage.Server/config/config.xml @@ -7,6 +7,7 @@ + diff --git a/Mage/src/mage/cards/CardImpl.java b/Mage/src/mage/cards/CardImpl.java index 28d7cb70d0..d835ce3a66 100644 --- a/Mage/src/mage/cards/CardImpl.java +++ b/Mage/src/mage/cards/CardImpl.java @@ -207,7 +207,7 @@ public abstract class CardImpl> extends MageObjectImpl game.getPlayer(ownerId).removeFromGraveyard(this, game); break; default: - logger.warning("moveToZone, not fully implemented: from="+event.getFromZone() + ", to="+event.getToZone()); + //logger.warning("moveToZone, not fully implemented: from="+event.getFromZone() + ", to="+event.getToZone()); } game.rememberLKI(objectId, event.getFromZone(), this); }