Search in sources :

Example 26 with SOCPlayer

use of soc.game.SOCPlayer in project JSettlers2 by jdmonin.

the class SOCDiscardOrGainResDialog method setVisible.

/**
 * Show or hide this dialog.
 * If showing (<tt>vis == true</tt>), also sets the initial values
 * of our current resources, based on {@link SOCPlayer#getResources()},
 * and requests focus on the Discard/Pick button.
 *
 * @param vis  True to make visible, false to hide
 */
@Override
public void setVisible(final boolean vis) {
    if (vis) {
        /**
         * set initial values
         */
        SOCPlayer player = playerInterface.getGame().getPlayer(playerInterface.getClient().getNickname());
        SOCResourceSet resources = player.getResources();
        keep[0].setIntValue(resources.getAmount(SOCResourceConstants.CLAY));
        keep[1].setIntValue(resources.getAmount(SOCResourceConstants.ORE));
        keep[2].setIntValue(resources.getAmount(SOCResourceConstants.SHEEP));
        keep[3].setIntValue(resources.getAmount(SOCResourceConstants.WHEAT));
        keep[4].setIntValue(resources.getAmount(SOCResourceConstants.WOOD));
        okBut.requestFocus();
        playerInterface.playSound((isDiscard) ? SOCPlayerInterface.SOUND_RSRC_LOST : SOCPlayerInterface.SOUND_RSRC_GAINED_FREE);
    }
    super.setVisible(vis);
}
Also used : SOCPlayer(soc.game.SOCPlayer) SOCResourceSet(soc.game.SOCResourceSet)

Example 27 with SOCPlayer

use of soc.game.SOCPlayer in project JSettlers2 by jdmonin.

the class SOCDBHelper method saveGameScores.

/**
 * Record this completed game's time, players, and scores in the database.
 *
 * @param ga  Game that's just completed
 * @param gameLengthSeconds  Duration of game
 *
 * @return true if the save succeeded
 * @throws IllegalArgumentException if {@link SOCGame#getPlayerWithWin() ga.getPlayerWithWin()} is null
 * @throws SQLException if an error occurs
 */
public static boolean saveGameScores(final SOCGame ga, final int gameLengthSeconds) throws IllegalArgumentException, SQLException {
    final SOCPlayer winner = ga.getPlayerWithWin();
    if (winner == null)
        throw new IllegalArgumentException("no winner");
    if (checkConnection()) {
        // DB max 6; ga.maxPlayers max 4 or 6
        String[] names = new String[SOCGame.MAXPLAYERS];
        short[] scores = new short[SOCGame.MAXPLAYERS];
        for (int pn = 0; pn < ga.maxPlayers; ++pn) {
            SOCPlayer pl = ga.getPlayer(pn);
            names[pn] = pl.getName();
            scores[pn] = (short) pl.getTotalVP();
        }
        final int db_max_players = (schemaVersion < SCHEMA_VERSION_1200) ? 4 : 6;
        if ((ga.maxPlayers > db_max_players) && !(ga.isSeatVacant(4) && ga.isSeatVacant(5))) {
            // Need to try and fit player 5 and/or player 6
            // into the 4 db slots (backwards-compatibility)
            saveGameScores_fit6pInto4(ga, names, scores);
        }
        try {
            saveGameCommand.setString(1, ga.getName());
            int i = 2;
            for (int pn = 0; pn < db_max_players; ++i, ++pn) saveGameCommand.setString(i, names[pn]);
            for (int pn = 0; pn < db_max_players; ++i, ++pn) if ((scores[pn] != 0) || (names[pn] != null))
                saveGameCommand.setShort(i, scores[pn]);
            else
                saveGameCommand.setNull(i, Types.SMALLINT);
            saveGameCommand.setTimestamp(i, new Timestamp(ga.getStartTime().getTime()));
            ++i;
            if (schemaVersion >= SCHEMA_VERSION_1200) {
                saveGameCommand.setInt(i, gameLengthSeconds);
                ++i;
                saveGameCommand.setString(i, winner.getName());
                ++i;
                final Map<String, SOCGameOption> opts = ga.getGameOptions();
                final String optsStr = (opts == null) ? null : SOCGameOption.packOptionsToString(opts, false);
                saveGameCommand.setString(i, optsStr);
            }
            saveGameCommand.executeUpdate();
            return true;
        } catch (SQLException sqlE) {
            errorCondition = true;
            sqlE.printStackTrace();
            throw sqlE;
        }
    }
    return false;
}
Also used : SQLException(java.sql.SQLException) SOCGameOption(soc.game.SOCGameOption) SOCPlayer(soc.game.SOCPlayer) Timestamp(java.sql.Timestamp)

Example 28 with SOCPlayer

use of soc.game.SOCPlayer in project JSettlers2 by jdmonin.

the class SOCServerMessageHandler method handleSITDOWN.

/**
 * handle "sit down" message
 *
 * @param c  the connection that sent the message
 * @param mes  the message
 * @since 1.0.0
 */
private void handleSITDOWN(Connection c, SOCSitDown mes) {
    if (c == null)
        return;
    final String gaName = mes.getGame();
    SOCGame ga = gameList.getGameData(gaName);
    if (ga == null) {
        // Out of date client info, or may be observing a deleted game.
        // Already authenticated (c != null), so replying is OK by security.
        // "Game not found."
        srv.messageToPlayerKeyed(c, gaName, "reply.game.not.found");
        // <--- Early return: No active game found ---
        return;
    }
    /**
     * make sure this player isn't already sitting
     */
    boolean canSit = true;
    boolean gameIsFull = false, gameAlreadyStarted = false;
    /*
           for (int i = 0; i < SOCGame.MAXPLAYERS; i++) {
           if (ga.getPlayer(i).getName() == c.getData()) {
           canSit = false;
           break;
           }
           }
         */
    // D.ebugPrintln("ga.isSeatVacant(mes.getPlayerNumber()) = "+ga.isSeatVacant(mes.getPlayerNumber()));
    /**
     * if this is a robot, remove it from the request list
     */
    boolean isBotJoinRequest = false;
    {
        Hashtable<Connection, Object> joinRequests = srv.robotJoinRequests.get(gaName);
        if (joinRequests != null)
            isBotJoinRequest = (null != joinRequests.remove(c));
    }
    /**
     * make sure a person isn't sitting here already;
     * if a robot is sitting there, dismiss the robot.
     * Can't sit at a vacant seat after everyone has
     * placed 1st settlement+road (state >= START2A).
     *
     * If a human leaves after game is started, seat will appear vacant when the
     * requested bot sits to replace them, so let the bot sit at that vacant seat.
     */
    final int pn = mes.getPlayerNumber();
    ga.takeMonitor();
    try {
        if (ga.isSeatVacant(pn)) {
            gameAlreadyStarted = (ga.getGameState() >= SOCGame.START2A);
            if (!gameAlreadyStarted)
                gameIsFull = (1 > ga.getAvailableSeatCount());
            if (gameIsFull || (gameAlreadyStarted && !isBotJoinRequest))
                canSit = false;
        } else {
            SOCPlayer seatedPlayer = ga.getPlayer(pn);
            if (seatedPlayer.isRobot() && (ga.getSeatLock(pn) != SOCGame.SeatLockState.LOCKED) && (ga.getCurrentPlayerNumber() != pn)) {
                /**
                 * boot the robot out of the game
                 */
                Connection robotCon = srv.getConnection(seatedPlayer.getName());
                robotCon.put(SOCRobotDismiss.toCmd(gaName));
                /**
                 * this connection has to wait for the robot to leave
                 * and then it can sit down
                 */
                Vector<SOCReplaceRequest> disRequests = srv.robotDismissRequests.get(gaName);
                SOCReplaceRequest req = new SOCReplaceRequest(c, robotCon, mes);
                if (disRequests == null) {
                    disRequests = new Vector<SOCReplaceRequest>();
                    disRequests.addElement(req);
                    srv.robotDismissRequests.put(gaName, disRequests);
                } else {
                    disRequests.addElement(req);
                }
            }
            canSit = false;
        }
    } catch (Exception e) {
        D.ebugPrintStackTrace(e, "Exception caught at handleSITDOWN");
    }
    ga.releaseMonitor();
    // D.ebugPrintln("canSit 2 = "+canSit);
    if (canSit) {
        srv.sitDown(ga, c, pn, mes.isRobot(), false);
    } else {
        /**
         * if the robot can't sit, tell it to go away.
         * otherwise if game is full, tell the player.
         */
        if (mes.isRobot()) {
            c.put(SOCRobotDismiss.toCmd(gaName));
        } else if (gameAlreadyStarted) {
            srv.messageToPlayerKeyed(c, gaName, "member.sit.game.started");
        // "This game has already started; to play you must take over a robot."
        } else if (gameIsFull) {
            srv.messageToPlayerKeyed(c, gaName, "member.sit.game.full");
        // "This game is full; you cannot sit down."
        }
    }
}
Also used : Hashtable(java.util.Hashtable) Connection(soc.server.genericServer.Connection) StringConnection(soc.server.genericServer.StringConnection) SOCPlayer(soc.game.SOCPlayer) SOCGame(soc.game.SOCGame) SQLException(java.sql.SQLException) MissingResourceException(java.util.MissingResourceException)

Example 29 with SOCPlayer

use of soc.game.SOCPlayer in project JSettlers2 by jdmonin.

the class SOCServerMessageHandler method handleRESETBOARDVOTE.

/**
 * handle message of player's vote for a "reset-board" request.
 * Register the player's vote with {@link SOCServer#resetBoardVoteNotifyOne(SOCGame, int, String, boolean)}.
 * If all votes have now arrived and the vote is unanimous,
 * resets the game to a copy with same name and players, new layout.
 *
 * @param c  the connection
 * @param mes  the message
 * @see #handleRESETBOARDREQUEST(Connection, SOCResetBoardRequest)
 * @see SOCServer#resetBoardAndNotify(String, int)
 * @since 1.1.00
 */
private void handleRESETBOARDVOTE(Connection c, final SOCResetBoardVote mes) {
    final String gaName = mes.getGame();
    SOCGame ga = gameList.getGameData(gaName);
    if (ga == null)
        return;
    final String plName = c.getData();
    SOCPlayer reqPlayer = ga.getPlayer(plName);
    if (reqPlayer == null) {
        // Not playing in that game (security)
        return;
    }
    // Register this player's vote, and let game members know.
    // If vote succeeded, go ahead and reset the game.
    // If vote rejected, let everyone know.
    srv.resetBoardVoteNotifyOne(ga, reqPlayer.getPlayerNumber(), plName, mes.getPlayerVote());
}
Also used : SOCPlayer(soc.game.SOCPlayer) SOCGame(soc.game.SOCGame)

Example 30 with SOCPlayer

use of soc.game.SOCPlayer in project JSettlers2 by jdmonin.

the class SOCServerMessageHandler method handleRESETBOARDREQUEST.

/**
 * handle "reset-board request" message.
 * If {@link SOCGame#getResetVoteActive()} already or {@link SOCPlayer#hasAskedBoardReset()} this turn,
 * ignore. Otherwise: If multiple human players, start a vote with {@link SOCGame#resetVoteBegin(int)}.
 * If requester is sole human player, reset the game to a copy with same name and (copy of) same players,
 * new layout, by calling {@link SOCServer#resetBoardAndNotify(String, int)}.
 *<P>
 * The requesting player doesn't vote, but server still sends them a vote-request message to tell that client their
 * request was accepted and voting has begun.
 *<P>
 * If only one player remains (all other humans have left at end), ask them to start a new game instead.
 * This is a rare occurrence and we shouldn't bring in new robots and all,
 * since we already have an interface to set up a game.
 *<P>
 * If any human player's client is too old to vote for reset, assume they vote Yes.
 *
 * @param c  the connection
 * @param mes  the message
 * @see #handleRESETBOARDVOTE(Connection, SOCResetBoardVote)
 * @since 1.1.00
 */
private void handleRESETBOARDREQUEST(Connection c, final SOCResetBoardRequest mes) {
    final String gaName = mes.getGame();
    SOCGame ga = gameList.getGameData(gaName);
    if (ga == null)
        return;
    SOCPlayer reqPlayer = ga.getPlayer(c.getData());
    if (reqPlayer == null) {
        // Not playing in that game (Security)
        return;
    }
    /**
     * Is voting already active from another player?
     * Or, has this player already asked for voting this turn?
     */
    if (ga.getResetVoteActive() || reqPlayer.hasAskedBoardReset()) {
        // that would end the already-active round of voting.
        return;
    }
    /**
     * Is there more than one human player?
     * Grab connection information for humans and robots.
     */
    Connection[] humanConns = new Connection[ga.maxPlayers];
    Connection[] robotConns = new Connection[ga.maxPlayers];
    final int numHuman = SOCGameBoardReset.sortPlayerConnections(ga, null, gameList.getMembers(gaName), humanConns, robotConns);
    final int reqPN = reqPlayer.getPlayerNumber();
    if (numHuman < 2) {
        // Are there robots? Go ahead and reset if so.
        boolean hadRobot = false, hadUnlockedRobot = false;
        for (int i = robotConns.length - 1; i >= 0; --i) {
            if (robotConns[i] != null) {
                hadRobot = true;
                if (ga.getSeatLock(i) == SOCGame.SeatLockState.UNLOCKED) {
                    hadUnlockedRobot = true;
                    break;
                }
            }
        }
        if (hadUnlockedRobot) {
            srv.resetBoardAndNotify(gaName, reqPN);
        } else if (hadRobot) {
            srv.messageToPlayerKeyed(c, gaName, "resetboard.request.unlock.bot");
        // "Please unlock at least one bot, so you will have an opponent."
        } else {
            srv.messageToGameKeyed(ga, true, "resetboard.request.everyone.left");
        // "Everyone has left this game. Please start a new game with players or bots."
        }
    } else {
        // Probably put it to a vote.
        gameList.takeMonitorForGame(gaName);
        // First, Count number of other players who can vote (connected, version chk)
        int votingPlayers = 0;
        for (int i = ga.maxPlayers - 1; i >= 0; --i) {
            if ((i != reqPN) && !ga.isSeatVacant(i)) {
                Connection pc = srv.getConnection(ga.getPlayer(i).getName());
                if ((pc != null) && pc.isConnected() && (pc.getVersion() >= 1100))
                    ++votingPlayers;
            }
        }
        if (votingPlayers == 0) {
            // No one else is capable of voting.
            // Reset the game immediately.
            srv.messageToGameKeyed(ga, false, "resetboard.vote.request.alloldcli", c.getData());
            // ">>> {0} is resetting the game - other connected players are unable to vote (client too old)."
            gameList.releaseMonitorForGame(gaName);
            srv.resetBoardAndNotify(gaName, reqPN);
        } else {
            // Put it to a vote
            srv.messageToGameKeyed(ga, false, "resetboard.vote.request", c.getData());
            // "requests a board reset - other players please vote."
            String vrCmd = SOCResetBoardVoteRequest.toCmd(gaName, reqPN);
            ga.resetVoteBegin(reqPN);
            gameList.releaseMonitorForGame(gaName);
            for (int i = 0; i < ga.maxPlayers; ++i) if (humanConns[i] != null)
                if (humanConns[i].getVersion() >= 1100)
                    humanConns[i].put(vrCmd);
                else
                    ga.resetVoteRegister(ga.getPlayer(humanConns[i].getData()).getPlayerNumber(), true);
        }
    }
}
Also used : Connection(soc.server.genericServer.Connection) StringConnection(soc.server.genericServer.StringConnection) SOCPlayer(soc.game.SOCPlayer) SOCGame(soc.game.SOCGame)

Aggregations

SOCPlayer (soc.game.SOCPlayer)61 SOCGame (soc.game.SOCGame)17 SOCShip (soc.game.SOCShip)12 SOCSettlement (soc.game.SOCSettlement)11 SOCRoad (soc.game.SOCRoad)9 SOCResourceSet (soc.game.SOCResourceSet)8 SOCCity (soc.game.SOCCity)7 SOCBoardLarge (soc.game.SOCBoardLarge)6 SOCFortress (soc.game.SOCFortress)5 ArrayList (java.util.ArrayList)4 SOCBoard (soc.game.SOCBoard)4 Connection (soc.server.genericServer.Connection)4 SOCInventoryItem (soc.game.SOCInventoryItem)3 SOCVillage (soc.game.SOCVillage)3 SQLException (java.sql.SQLException)2 Iterator (java.util.Iterator)2 Stack (java.util.Stack)2 SOCLRPathData (soc.game.SOCLRPathData)2 SOCPlayingPiece (soc.game.SOCPlayingPiece)2 SOCSpecialItem (soc.game.SOCSpecialItem)2