Search in sources :

Example 1 with MageException

use of mage.MageException in project mage by magefree.

the class MageServerImpl method quitDraft.

@Override
public void quitDraft(final UUID draftId, final String sessionId) throws MageException {
    execute("quitDraft", sessionId, () -> {
        try {
            callExecutor.execute(() -> {
                managerFactory.sessionManager().getSession(sessionId).ifPresent(session -> {
                    UUID userId = session.getUserId();
                    UUID tableId = managerFactory.draftManager().getControllerByDraftId(draftId).getTableId();
                    Table table = managerFactory.tableManager().getTable(tableId);
                    if (table.isTournament()) {
                        UUID tournamentId = table.getTournament().getId();
                        managerFactory.tournamentManager().quit(tournamentId, userId);
                    }
                });
            });
        } catch (Exception ex) {
            handleException(ex);
        }
    });
}
Also used : Table(mage.game.Table) MageVersionException(mage.remote.MageVersionException) MageException(mage.MageException)

Example 2 with MageException

use of mage.MageException in project mage by magefree.

the class TournamentController method init.

private void init() {
    tournament.addTableEventListener((Listener<TableEvent>) event -> {
        switch(event.getEventType()) {
            case CHECK_STATE_PLAYERS:
                checkPlayersState();
                break;
            case INFO:
                managerFactory.chatManager().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, null, MessageType.STATUS, null);
                logger.debug(tournament.getId() + " " + event.getMessage());
                break;
            case START_DRAFT:
                startDraft(event.getDraft());
                break;
            case CONSTRUCT:
                if (!isAbort()) {
                    construct();
                } else {
                    endTournament();
                }
                break;
            case START_MATCH:
                if (!isAbort()) {
                    initTournament();
                    startMatch(event.getPair(), event.getMatchOptions());
                }
                break;
            case START_MULTIPLAYER_MATCH:
                if (!isAbort()) {
                    initTournament();
                    MatchOptions matchOptions = event.getMatchOptions();
                    if (matchOptions != null && event.getMultiplayerRound() != null) {
                        for (TournamentPlayer player : event.getMultiplayerRound().getAllPlayers()) {
                            matchOptions.getPlayerTypes().add(player.getPlayerType());
                        }
                    }
                    startMultiplayerMatch(event.getMultiplayerRound(), event.getMatchOptions());
                }
                break;
            case END:
                endTournament();
                break;
        }
    });
    tournament.addPlayerQueryEventListener((Listener<PlayerQueryEvent>) event -> {
        try {
            switch(event.getQueryType()) {
                case CONSTRUCT:
                    construct(event.getPlayerId(), event.getMax());
                    break;
            }
        } catch (MageException ex) {
            logger.fatal("Player event listener error", ex);
        }
    });
    for (TournamentPlayer player : tournament.getPlayers()) {
        if (!player.getPlayer().isHuman()) {
            player.setJoined();
            logger.debug("player " + player.getPlayer().getId() + " has joined tournament " + tournament.getId());
            managerFactory.chatManager().broadcast(chatId, "", player.getPlayer().getLogName() + " has joined the tournament", MessageColor.BLACK, true, null, MessageType.STATUS, null);
        }
    }
    checkStart();
}
Also used : MultiplayerRound(mage.game.tournament.MultiplayerRound) MessageType(mage.view.ChatMessage.MessageType) DraftController(mage.server.draft.DraftController) MessageColor(mage.view.ChatMessage.MessageColor) TableEvent(mage.game.events.TableEvent) ConcurrentMap(java.util.concurrent.ConcurrentMap) Logger(org.apache.log4j.Logger) TableManager(mage.server.managers.TableManager) MatchOptions(mage.game.match.MatchOptions) User(mage.server.User) Draft(mage.game.draft.Draft) TournamentPairing(mage.game.tournament.TournamentPairing) TourneyQuitStatus(mage.game.result.ResultProtos.TourneyQuitStatus) TournamentView(mage.view.TournamentView) TableState(mage.constants.TableState) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Deck(mage.cards.decks.Deck) UUID(java.util.UUID) MageException(mage.MageException) PlayerType(mage.players.PlayerType) SoundToPlay(mage.view.ChatMessage.SoundToPlay) PlayerQueryEvent(mage.game.events.PlayerQueryEvent) ManagerFactory(mage.server.managers.ManagerFactory) TournamentPlayer(mage.game.tournament.TournamentPlayer) Entry(java.util.Map.Entry) Table(mage.game.Table) Optional(java.util.Optional) TournamentPlayerState(mage.constants.TournamentPlayerState) Listener(mage.game.events.Listener) GameException(mage.game.GameException) Tournament(mage.game.tournament.Tournament) TableEvent(mage.game.events.TableEvent) TournamentPlayer(mage.game.tournament.TournamentPlayer) MageException(mage.MageException) MatchOptions(mage.game.match.MatchOptions) PlayerQueryEvent(mage.game.events.PlayerQueryEvent)

Example 3 with MageException

use of mage.MageException in project mage by magefree.

the class GameImpl method playPriority.

@Override
public void playPriority(UUID activePlayerId, boolean resuming) {
    int errorContinueCounter = 0;
    infiniteLoopCounter = 0;
    int rollbackBookmark = 0;
    clearAllBookmarks();
    try {
        applyEffects();
        while (!isPaused() && !checkIfGameIsOver() && !this.getTurn().isEndTurnRequested()) {
            if (!resuming) {
                state.getPlayers().resetPassed();
                state.getPlayerList().setCurrent(activePlayerId);
            } else {
                state.getPlayerList().setCurrent(this.getPriorityPlayerId());
            }
            fireUpdatePlayersEvent();
            Player player;
            while (!isPaused() && !checkIfGameIsOver()) {
                try {
                    if (rollbackBookmark == 0) {
                        rollbackBookmark = bookmarkState();
                    }
                    player = getPlayer(state.getPlayerList().get());
                    state.setPriorityPlayerId(player.getId());
                    while (!player.isPassed() && player.canRespond() && !isPaused() && !checkIfGameIsOver()) {
                        if (!resuming) {
                            // 603.3. Once an ability has triggered, its controller puts it on the stack as an object that's not a card the next time a player would receive priority
                            checkStateAndTriggered();
                            applyEffects();
                            if (state.getStack().isEmpty()) {
                                resetLKI();
                            }
                            saveState(false);
                            if (isPaused() || checkIfGameIsOver()) {
                                return;
                            }
                            // resetPassed should be called if player performs any action
                            if (player.priority(this)) {
                                if (executingRollback()) {
                                    return;
                                }
                                // needed here to handle triggers e.g. from paying costs like sacrificing a creatures before LKIShort is cleared
                                getState().handleSimultaneousEvent(this);
                                applyEffects();
                            }
                            if (isPaused()) {
                                return;
                            }
                        }
                        resuming = false;
                    }
                    resetShortLivingLKI();
                    resuming = false;
                    if (isPaused() || checkIfGameIsOver()) {
                        return;
                    }
                    if (allPassed()) {
                        if (!state.getStack().isEmpty()) {
                            // 20091005 - 115.4
                            resolve();
                            checkConcede();
                            applyEffects();
                            state.getPlayers().resetPassed();
                            fireUpdatePlayersEvent();
                            resetShortLivingLKI();
                            break;
                        } else {
                            resetLKI();
                            return;
                        }
                    }
                } catch (Exception ex) {
                    logger.fatal("Game exception gameId: " + getId(), ex);
                    if ((ex instanceof NullPointerException) && errorContinueCounter == 0 && ex.getStackTrace() != null) {
                        logger.fatal(ex.getStackTrace());
                    }
                    this.fireErrorEvent("Game exception occurred: ", ex);
                    // stack info
                    String info = this.getStack().stream().map(MageObject::toString).collect(Collectors.joining("\n"));
                    logger.info(String.format("\nStack before error %d: \n%s\n", this.getStack().size(), info));
                    // rollback game to prev state
                    GameState restoredState = restoreState(rollbackBookmark, "Game exception: " + ex.getMessage());
                    rollbackBookmark = 0;
                    if (errorContinueCounter > 15) {
                        throw new MageException("Iterated player priority after game exception too often, game ends! Last error:\n " + ex.getMessage());
                    }
                    if (restoredState != null) {
                        this.informPlayers(String.format("Auto-restored to %s due game error: %s", restoredState, ex.getMessage()));
                    } else {
                        logger.error("Can't auto-restore to prev state.");
                    }
                    Player activePlayer = this.getPlayer(getActivePlayerId());
                    if (activePlayer != null && !activePlayer.isTestsMode()) {
                        errorContinueCounter++;
                        continue;
                    } else {
                        throw new MageException(UNIT_TESTS_ERROR_TEXT);
                    }
                } finally {
                    setCheckPlayableState(false);
                }
                state.getPlayerList().getNext();
            }
        }
    } catch (Exception ex) {
        logger.fatal("Game exception " + ex.getMessage(), ex);
        this.fireErrorEvent("Game exception occurred: ", ex);
        this.end();
        // don't catch game errors in unit tests, so test framework can process it (example: errors in AI simulations)
        if (ex.getMessage() != null && ex.getMessage().equals(UNIT_TESTS_ERROR_TEXT)) {
            // this.getContinuousEffects().traceContinuousEffects(this);
            throw new IllegalStateException(UNIT_TESTS_ERROR_TEXT);
        }
    } finally {
        resetLKI();
        clearAllBookmarks();
        setCheckPlayableState(false);
    }
}
Also used : TargetPlayer(mage.target.TargetPlayer) Player(mage.players.Player) MageException(mage.MageException) MageObject(mage.MageObject) IOException(java.io.IOException) MageException(mage.MageException)

Example 4 with MageException

use of mage.MageException in project mage by magefree.

the class DraftController method init.

private void init() {
    draft.addTableEventListener((Listener<TableEvent>) event -> {
        try {
            switch(event.getEventType()) {
                case UPDATE:
                    updateDraft();
                    break;
                case END:
                    endDraft();
                    break;
            }
        } catch (MageException ex) {
            logger.fatal("Table event listener error", ex);
        }
    });
    draft.addPlayerQueryEventListener((Listener<PlayerQueryEvent>) event -> {
        try {
            switch(event.getQueryType()) {
                case PICK_CARD:
                    pickCard(event.getPlayerId(), event.getMax());
                    break;
            }
        } catch (MageException ex) {
            logger.fatal("Table event listener error", ex);
        }
    });
    for (DraftPlayer player : draft.getPlayers()) {
        if (!player.getPlayer().isHuman()) {
            player.setJoined();
            logger.debug("player " + player.getPlayer().getId() + " has joined draft " + draft.getId());
        }
    }
    checkStart();
}
Also used : DraftPickView(mage.view.DraftPickView) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TableEvent(mage.game.events.TableEvent) Set(java.util.Set) UUID(java.util.UUID) MageException(mage.MageException) DraftPlayer(mage.game.draft.DraftPlayer) Player(mage.players.Player) ConcurrentMap(java.util.concurrent.ConcurrentMap) Logger(org.apache.log4j.Logger) PlayerQueryEvent(mage.game.events.PlayerQueryEvent) ManagerFactory(mage.server.managers.ManagerFactory) Entry(java.util.Map.Entry) Optional(java.util.Optional) Listener(mage.game.events.Listener) GameController(mage.server.game.GameController) Draft(mage.game.draft.Draft) DraftPlayer(mage.game.draft.DraftPlayer) TableEvent(mage.game.events.TableEvent) MageException(mage.MageException) PlayerQueryEvent(mage.game.events.PlayerQueryEvent)

Example 5 with MageException

use of mage.MageException in project mage by magefree.

the class GameController method init.

private void init() {
    game.addTableEventListener((Listener<TableEvent>) event -> {
        try {
            PriorityTimer timer;
            UUID playerId;
            switch(event.getEventType()) {
                case UPDATE:
                    updateGame();
                    break;
                case INFO:
                    managerFactory.chatManager().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, event.getGame(), MessageType.GAME, null);
                    logger.trace(game.getId() + " " + event.getMessage());
                    break;
                case STATUS:
                    managerFactory.chatManager().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), event.getWithTurnInfo() ? event.getGame() : null, MessageType.GAME, null);
                    logger.trace(game.getId() + " " + event.getMessage());
                    break;
                case ERROR:
                    error(event.getMessage(), event.getException());
                    break;
                case END_GAME_INFO:
                    endGameInfo();
                    break;
                case INIT_TIMER:
                    final UUID initPlayerId = event.getPlayerId();
                    if (initPlayerId == null) {
                        throw new MageException("INIT_TIMER: playerId can't be null");
                    }
                    createPlayerTimer(event.getPlayerId(), game.getPriorityTime());
                    break;
                case RESUME_TIMER:
                    playerId = event.getPlayerId();
                    if (playerId == null) {
                        throw new MageException("RESUME_TIMER: playerId can't be null");
                    }
                    timer = timers.get(playerId);
                    if (timer == null) {
                        Player player = game.getState().getPlayer(playerId);
                        if (player != null) {
                            timer = createPlayerTimer(event.getPlayerId(), player.getPriorityTimeLeft());
                        } else {
                            throw new MageException("RESUME_TIMER: player can't be null");
                        }
                    }
                    timer.resume();
                    break;
                case PAUSE_TIMER:
                    playerId = event.getPlayerId();
                    if (playerId == null) {
                        throw new MageException("PAUSE_TIMER: playerId can't be null");
                    }
                    timer = timers.get(playerId);
                    if (timer == null) {
                        throw new MageException("PAUSE_TIMER: couldn't find timer for player: " + playerId);
                    }
                    timer.pause();
                    break;
            }
        } catch (MageException ex) {
            logger.fatal("Table event listener error ", ex);
        }
    });
    game.addPlayerQueryEventListener((Listener<PlayerQueryEvent>) event -> {
        logger.trace(new StringBuilder(event.getPlayerId().toString()).append("--").append(event.getQueryType()).append("--").append(event.getMessage()).toString());
        try {
            switch(event.getQueryType()) {
                case ASK:
                    ask(event.getPlayerId(), event.getMessage(), event.getOptions());
                    break;
                case PICK_TARGET:
                    target(event.getPlayerId(), event.getMessage(), event.getCards(), event.getPerms(), event.getTargets(), event.isRequired(), event.getOptions());
                    break;
                case PICK_ABILITY:
                    target(event.getPlayerId(), event.getMessage(), event.getAbilities(), event.isRequired(), event.getOptions());
                    break;
                case SELECT:
                    select(event.getPlayerId(), event.getMessage(), event.getOptions());
                    break;
                case PLAY_MANA:
                    playMana(event.getPlayerId(), event.getMessage(), event.getOptions());
                    break;
                case PLAY_X_MANA:
                    playXMana(event.getPlayerId(), event.getMessage());
                    break;
                case CHOOSE_ABILITY:
                    String objectName = null;
                    if (event.getChoices() != null && !event.getChoices().isEmpty()) {
                        objectName = event.getChoices().iterator().next();
                    }
                    chooseAbility(event.getPlayerId(), objectName, event.getAbilities(), event.getMessage());
                    break;
                case CHOOSE_PILE:
                    choosePile(event.getPlayerId(), event.getMessage(), event.getPile1(), event.getPile2());
                    break;
                case CHOOSE_MODE:
                    chooseMode(event.getPlayerId(), event.getModes(), event.getMessage());
                    break;
                case CHOOSE_CHOICE:
                    chooseChoice(event.getPlayerId(), event.getChoice());
                    break;
                case AMOUNT:
                    amount(event.getPlayerId(), event.getMessage(), event.getMin(), event.getMax());
                    break;
                case MULTI_AMOUNT:
                    multiAmount(event.getPlayerId(), event.getMessages(), event.getMin(), event.getMax(), event.getOptions());
                    break;
                case PERSONAL_MESSAGE:
                    informPersonal(event.getPlayerId(), event.getMessage());
                    break;
            }
        } catch (MageException ex) {
            logger.fatal("Player event listener error ", ex);
        }
    });
    joinWaitingExecutor.scheduleAtFixedRate(() -> {
        try {
            sendInfoAboutPlayersNotJoinedYetAndTryToFixIt();
        } catch (Exception ex) {
            logger.fatal("Send info about player not joined yet:", ex);
        }
    }, GAME_TIMEOUTS_CHECK_JOINING_STATUS_EVERY_SECS, GAME_TIMEOUTS_CHECK_JOINING_STATUS_EVERY_SECS, TimeUnit.SECONDS);
    checkStart();
}
Also used : MatchPlayer(mage.game.match.MatchPlayer) java.util(java.util) Zone(mage.constants.Zone) MessageType(mage.view.ChatMessage.MessageType) Splitter(mage.server.util.Splitter) mage.game(mage.game) MessageColor(mage.view.ChatMessage.MessageColor) TableEvent(mage.game.events.TableEvent) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Player(mage.players.Player) mage.view(mage.view) Logger(org.apache.log4j.Logger) ManaType(mage.constants.ManaType) PlayerAction(mage.constants.PlayerAction) User(mage.server.User) SystemUtil(mage.server.util.SystemUtil) StreamUtils(mage.utils.StreamUtils) Card(mage.cards.Card) DeckCardLists(mage.cards.decks.DeckCardLists) PriorityTimer(mage.utils.timer.PriorityTimer) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Choice(mage.choices.Choice) PassAbility(mage.abilities.common.PassAbility) java.util.concurrent(java.util.concurrent) Cards(mage.cards.Cards) Deck(mage.cards.decks.Deck) Plane(mage.game.command.Plane) MageException(mage.MageException) CardRepository(mage.cards.repository.CardRepository) Collectors(java.util.stream.Collectors) Phase(mage.game.turn.Phase) Action(mage.interfaces.Action) Lock(java.util.concurrent.locks.Lock) PlayerQueryEvent(mage.game.events.PlayerQueryEvent) ManagerFactory(mage.server.managers.ManagerFactory) Main(mage.server.Main) java.io(java.io) CardInfo(mage.cards.repository.CardInfo) Permanent(mage.game.permanent.Permanent) Entry(java.util.Map.Entry) Listener(mage.game.events.Listener) GZIPOutputStream(java.util.zip.GZIPOutputStream) Ability(mage.abilities.Ability) MatchPlayer(mage.game.match.MatchPlayer) Player(mage.players.Player) TableEvent(mage.game.events.TableEvent) MageException(mage.MageException) PriorityTimer(mage.utils.timer.PriorityTimer) PlayerQueryEvent(mage.game.events.PlayerQueryEvent) MageException(mage.MageException)

Aggregations

MageException (mage.MageException)5 Entry (java.util.Map.Entry)3 Listener (mage.game.events.Listener)3 PlayerQueryEvent (mage.game.events.PlayerQueryEvent)3 TableEvent (mage.game.events.TableEvent)3 Player (mage.players.Player)3 ManagerFactory (mage.server.managers.ManagerFactory)3 Logger (org.apache.log4j.Logger)3 Optional (java.util.Optional)2 UUID (java.util.UUID)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ConcurrentMap (java.util.concurrent.ConcurrentMap)2 Deck (mage.cards.decks.Deck)2 Table (mage.game.Table)2 Draft (mage.game.draft.Draft)2 java.io (java.io)1 IOException (java.io.IOException)1 java.util (java.util)1 Set (java.util.Set)1 java.util.concurrent (java.util.concurrent)1