Search in sources :

Example 1 with SOCShip

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

the class SOCGameMessageHandler method handlePUTPIECE.

/**
 * handle "put piece" message.
 *<P>
 * Because the current player changes during initial placement,
 * this method has a simplified version of some of the logic from
 * {@link SOCGameHandler#endGameTurn(SOCGame, SOCPlayer, boolean)}
 * to detect and announce the new turn.
 *
 * @param c  the connection that sent the message
 * @param mes  the message
 * @since 1.0.0
 */
private void handlePUTPIECE(SOCGame ga, Connection c, SOCPutPiece mes) {
    ga.takeMonitor();
    try {
        final String gaName = ga.getName();
        final String plName = c.getData();
        SOCPlayer player = ga.getPlayer(plName);
        /**
         * make sure the player can do it
         */
        if (handler.checkTurn(c, ga)) {
            boolean sendDenyReply = false;
            /*
                   if (D.ebugOn) {
                   D.ebugPrintln("BEFORE");
                   for (int pn = 0; pn < SOCGame.MAXPLAYERS; pn++) {
                   SOCPlayer tmpPlayer = ga.getPlayer(pn);
                   D.ebugPrintln("Player # "+pn);
                   for (int i = 0x22; i < 0xCC; i++) {
                   if (tmpPlayer.isPotentialRoad(i))
                   D.ebugPrintln("### POTENTIAL ROAD AT "+Integer.toHexString(i));
                   }
                   }
                   }
                 */
            int gameState = ga.getGameState();
            final int coord = mes.getCoordinates();
            final int pieceType = mes.getPieceType();
            final int pn = player.getPlayerNumber();
            final boolean isBuyAndPut = (gameState == SOCGame.PLAY1) || (gameState == SOCGame.SPECIAL_BUILDING);
            if (isBuyAndPut) {
                if (!handleBUILDREQUEST(ga, player, c, pieceType, false)) {
                    // <--- Can't build right now ---
                    return;
                // will call ga.releaseMonitor() in finally-block before returning
                }
                // updated by handleBUILDREQUEST
                gameState = ga.getGameState();
            }
            switch(pieceType) {
                case SOCPlayingPiece.ROAD:
                    if ((gameState == SOCGame.START1B) || (gameState == SOCGame.START2B) || (gameState == SOCGame.START3B) || (gameState == SOCGame.PLACING_ROAD) || (gameState == SOCGame.PLACING_FREE_ROAD1) || (gameState == SOCGame.PLACING_FREE_ROAD2)) {
                        if (player.isPotentialRoad(coord) && (player.getNumPieces(SOCPlayingPiece.ROAD) >= 1)) {
                            final SOCRoad rd = new SOCRoad(player, coord, null);
                            // Changes game state and (if initial placement) player
                            ga.putPiece(rd);
                            // If placing this piece reveals a fog hex, putPiece will call srv.gameEvent
                            // which will send a SOCRevealFogHex message to the game.
                            /*
                               if (D.ebugOn) {
                               D.ebugPrintln("AFTER");
                               for (int pn = 0; pn < SOCGame.MAXPLAYERS; pn++) {
                               SOCPlayer tmpPlayer = ga.getPlayer(pn);
                               D.ebugPrintln("Player # "+pn);
                               for (int i = 0x22; i < 0xCC; i++) {
                               if (tmpPlayer.isPotentialRoad(i))
                               D.ebugPrintln("### POTENTIAL ROAD AT "+Integer.toHexString(i));
                               }
                               }
                               }
                             */
                            srv.gameList.takeMonitorForGame(gaName);
                            // "Joe built a road."
                            srv.messageToGameKeyed(ga, false, "action.built.road", plName);
                            srv.messageToGameWithMon(gaName, new SOCPutPiece(gaName, pn, SOCPlayingPiece.ROAD, coord));
                            if (!ga.pendingMessagesOut.isEmpty())
                                handler.sendGamePendingMessages(ga, false);
                            srv.gameList.releaseMonitorForGame(gaName);
                            // If needed, call sendTurn or send SOCRollDicePrompt
                            handler.sendTurnStateAtInitialPlacement(ga, player, c, gameState);
                            int newState = ga.getGameState();
                            if ((newState == SOCGame.STARTS_WAITING_FOR_PICK_GOLD_RESOURCE) || (newState == SOCGame.WAITING_FOR_PICK_GOLD_RESOURCE)) {
                                // gold hex revealed from fog (scenario SC_FOG)
                                handler.sendGameState_sendGoldPickAnnounceText(ga, gaName, c, null);
                            }
                        } else {
                            D.ebugPrintln("ILLEGAL ROAD: 0x" + Integer.toHexString(coord) + ": player " + pn);
                            if (player.isRobot() && D.ebugOn) {
                                D.ebugPrintln(" - pl.isPotentialRoad: " + player.isPotentialRoad(coord));
                                SOCPlayingPiece pp = ga.getBoard().roadAtEdge(coord);
                                D.ebugPrintln(" - roadAtEdge: " + ((pp != null) ? pp : "none"));
                            }
                            srv.messageToPlayerKeyed(c, gaName, "action.build.cannot.there.road");
                            // "You can't build a road there."
                            sendDenyReply = true;
                        }
                    } else {
                        srv.messageToPlayerKeyed(c, gaName, "action.build.cannot.now.road");
                    // "You can't build a road now."
                    }
                    break;
                case SOCPlayingPiece.SETTLEMENT:
                    if ((gameState == SOCGame.START1A) || (gameState == SOCGame.START2A) || (gameState == SOCGame.START3A) || (gameState == SOCGame.PLACING_SETTLEMENT)) {
                        if (player.canPlaceSettlement(coord) && (player.getNumPieces(SOCPlayingPiece.SETTLEMENT) >= 1)) {
                            final SOCSettlement se = new SOCSettlement(player, coord, null);
                            // Changes game state and (if initial placement) player
                            ga.putPiece(se);
                            srv.gameList.takeMonitorForGame(gaName);
                            // "Joe built a settlement."
                            srv.messageToGameKeyed(ga, false, "action.built.stlmt", plName);
                            srv.messageToGameWithMon(gaName, new SOCPutPiece(gaName, pn, SOCPlayingPiece.SETTLEMENT, coord));
                            if (!ga.pendingMessagesOut.isEmpty())
                                handler.sendGamePendingMessages(ga, false);
                            srv.gameList.releaseMonitorForGame(gaName);
                            // Check player and send new game state
                            if (!handler.checkTurn(c, ga))
                                // Announce new state and new current player
                                handler.sendTurn(ga, false);
                            else
                                handler.sendGameState(ga);
                            if (ga.hasSeaBoard && (ga.getGameState() == SOCGame.STARTS_WAITING_FOR_PICK_GOLD_RESOURCE)) {
                                // Prompt to pick from gold: send text and SOCSimpleRequest(PROMPT_PICK_RESOURCES)
                                handler.sendGameState_sendGoldPickAnnounceText(ga, gaName, c, null);
                            }
                        } else {
                            D.ebugPrintln("ILLEGAL SETTLEMENT: 0x" + Integer.toHexString(coord) + ": player " + pn);
                            if (player.isRobot() && D.ebugOn) {
                                D.ebugPrintln(" - pl.isPotentialSettlement: " + player.isPotentialSettlement(coord));
                                SOCPlayingPiece pp = ga.getBoard().settlementAtNode(coord);
                                D.ebugPrintln(" - settlementAtNode: " + ((pp != null) ? pp : "none"));
                            }
                            srv.messageToPlayerKeyed(c, gaName, "action.build.cannot.there.stlmt");
                            // "You can't build a settlement there."
                            sendDenyReply = true;
                        }
                    } else {
                        srv.messageToPlayerKeyed(c, gaName, "action.build.cannot.now.stlmt");
                    // "You can't build a settlement now."
                    }
                    break;
                case SOCPlayingPiece.CITY:
                    if (gameState == SOCGame.PLACING_CITY) {
                        if (player.isPotentialCity(coord) && (player.getNumPieces(SOCPlayingPiece.CITY) >= 1)) {
                            boolean houseRuleFirstCity = ga.isGameOptionSet("N7C") && !ga.hasBuiltCity();
                            if (houseRuleFirstCity && ga.isGameOptionSet("N7") && (ga.getRoundCount() < ga.getGameOptionIntValue("N7"))) {
                                // If "No 7s for first # rounds" is active, and this isn't its last round, 7s won't
                                // be rolled soon: Don't announce "Starting next turn, dice rolls of 7 may occur"
                                houseRuleFirstCity = false;
                            }
                            final SOCCity ci = new SOCCity(player, coord, null);
                            // changes game state and maybe player
                            ga.putPiece(ci);
                            srv.gameList.takeMonitorForGame(gaName);
                            // "Joe built a city."
                            srv.messageToGameKeyed(ga, false, "action.built.city", plName);
                            srv.messageToGameWithMon(gaName, new SOCPutPiece(gaName, pn, SOCPlayingPiece.CITY, coord));
                            if (!ga.pendingMessagesOut.isEmpty())
                                handler.sendGamePendingMessages(ga, false);
                            if (houseRuleFirstCity)
                                srv.messageToGameKeyed(ga, false, "action.built.nextturn.7.houserule");
                            // "Starting next turn, dice rolls of 7 may occur (house rule)."
                            srv.gameList.releaseMonitorForGame(gaName);
                            // Check player and send new game state
                            if (!handler.checkTurn(c, ga))
                                // Announce new state and new current player
                                handler.sendTurn(ga, false);
                            else
                                handler.sendGameState(ga);
                        } else {
                            D.ebugPrintln("ILLEGAL CITY: 0x" + Integer.toHexString(coord) + ": player " + pn);
                            if (player.isRobot() && D.ebugOn) {
                                D.ebugPrintln(" - pl.isPotentialCity: " + player.isPotentialCity(coord));
                                SOCPlayingPiece pp = ga.getBoard().settlementAtNode(coord);
                                D.ebugPrintln(" - city/settlementAtNode: " + ((pp != null) ? pp : "none"));
                            }
                            srv.messageToPlayerKeyed(c, gaName, "action.build.cannot.there.city");
                            // "You can't build a city there."
                            sendDenyReply = true;
                        }
                    } else {
                        srv.messageToPlayerKeyed(c, gaName, "action.build.cannot.now.city");
                    // "You can't build a city now."
                    }
                    break;
                case SOCPlayingPiece.SHIP:
                    if ((gameState == SOCGame.START1B) || (gameState == SOCGame.START2B) || (gameState == SOCGame.START3B) || (gameState == SOCGame.PLACING_SHIP) || (gameState == SOCGame.PLACING_FREE_ROAD1) || (gameState == SOCGame.PLACING_FREE_ROAD2)) {
                        // Place it if we can; canPlaceShip checks potentials and pirate ship location
                        if (ga.canPlaceShip(player, coord) && (player.getNumPieces(SOCPlayingPiece.SHIP) >= 1)) {
                            final SOCShip sh = new SOCShip(player, coord, null);
                            // Changes game state and (during initial placement) sometimes player
                            ga.putPiece(sh);
                            srv.gameList.takeMonitorForGame(gaName);
                            // "Joe built a ship."
                            srv.messageToGameKeyed(ga, false, "action.built.ship", plName);
                            srv.messageToGameWithMon(gaName, new SOCPutPiece(gaName, pn, SOCPlayingPiece.SHIP, coord));
                            if (!ga.pendingMessagesOut.isEmpty())
                                handler.sendGamePendingMessages(ga, false);
                            srv.gameList.releaseMonitorForGame(gaName);
                            // If needed, call sendTurn or send SOCRollDicePrompt
                            handler.sendTurnStateAtInitialPlacement(ga, player, c, gameState);
                            int newState = ga.getGameState();
                            if ((newState == SOCGame.STARTS_WAITING_FOR_PICK_GOLD_RESOURCE) || (newState == SOCGame.WAITING_FOR_PICK_GOLD_RESOURCE)) {
                                // gold hex revealed from fog (scenario SC_FOG)
                                handler.sendGameState_sendGoldPickAnnounceText(ga, gaName, c, null);
                            }
                        } else {
                            D.ebugPrintln("ILLEGAL SHIP: 0x" + Integer.toHexString(coord) + ": player " + pn);
                            if (player.isRobot() && D.ebugOn) {
                                D.ebugPrintln(" - pl.isPotentialShip: " + player.isPotentialShip(coord));
                                SOCPlayingPiece pp = ga.getBoard().roadAtEdge(coord);
                                D.ebugPrintln(" - ship/roadAtEdge: " + ((pp != null) ? pp : "none"));
                            }
                            srv.messageToPlayerKeyed(c, gaName, "action.build.cannot.there.ship");
                            // "You can't build a ship there."
                            sendDenyReply = true;
                        }
                    } else {
                        srv.messageToPlayerKeyed(c, gaName, "action.build.cannot.now.ship");
                    // "You can't build a ship now."
                    }
                    break;
            }
            if (sendDenyReply) {
                if (isBuyAndPut)
                    // is probably now PLACING_*, was PLAY1 or SPECIAL_BUILDING
                    handler.sendGameState(ga);
                srv.messageToPlayer(c, new SOCCancelBuildRequest(gaName, mes.getPieceType()));
                if (player.isRobot()) {
                    // Set the "force end turn soon" field
                    ga.lastActionTime = 0L;
                }
            }
        } else {
            // "It's not your turn."
            srv.messageToPlayerKeyed(c, gaName, "reply.not.your.turn");
        }
    } catch (Exception e) {
        D.ebugPrintStackTrace(e, "Exception caught in handlePUTPIECE");
    } finally {
        ga.releaseMonitor();
    }
}
Also used : SOCSettlement(soc.game.SOCSettlement) SOCCity(soc.game.SOCCity) SOCPlayingPiece(soc.game.SOCPlayingPiece) SOCShip(soc.game.SOCShip) SOCPlayer(soc.game.SOCPlayer) SOCRoad(soc.game.SOCRoad)

Example 2 with SOCShip

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

the class SOCGameMessageHandler method handleSIMPLEREQUEST.

/**
 * Handle the "simple request" message.
 * @param c  the connection
 * @param mes  the message
 * @since 1.1.18
 */
private void handleSIMPLEREQUEST(SOCGame ga, Connection c, final SOCSimpleRequest mes) {
    final String gaName = ga.getName();
    SOCPlayer clientPl = ga.getPlayer(c.getData());
    if (clientPl == null)
        return;
    final int pn = mes.getPlayerNumber();
    // probably required for most request types
    final boolean clientIsPN = (pn == clientPl.getPlayerNumber());
    final int reqtype = mes.getRequestType();
    final int cpn = ga.getCurrentPlayerNumber();
    // if true, reply with generic decline (pn = -1, reqtype, 0, 0)
    boolean replyDecline = false;
    switch(reqtype) {
        case SOCSimpleRequest.SC_PIRI_FORT_ATTACK:
            {
                final SOCShip adjac = ga.canAttackPirateFortress();
                if ((!clientIsPN) || (pn != cpn) || (adjac == null) || (adjac.getPlayerNumber() != cpn)) {
                    c.put(SOCSimpleRequest.toCmd(gaName, -1, reqtype, 0, 0));
                    // <--- early return: deny ---
                    return;
                }
                final int prevState = ga.getGameState();
                final SOCPlayer cp = ga.getPlayer(cpn);
                // in case some are lost, we'll announce that
                final int prevNumWarships = cp.getNumWarships();
                final SOCFortress fort = cp.getFortress();
                final int[] res = ga.attackPirateFortress(adjac);
                if (res.length > 1) {
                    // lost 1 or 2 ships adjacent to fortress.  res[1] == adjac.coordinate
                    srv.messageToGame(gaName, new SOCRemovePiece(gaName, adjac));
                    if (res.length > 2)
                        srv.messageToGame(gaName, new SOCRemovePiece(gaName, cpn, SOCPlayingPiece.SHIP, res[2]));
                    final int n = cp.getNumWarships();
                    if (n != prevNumWarships)
                        srv.messageToGame(gaName, new SOCPlayerElement(gaName, cpn, SOCPlayerElement.SET, SOCPlayerElement.SCENARIO_WARSHIP_COUNT, n));
                } else {
                    // player won
                    final int fortStrength = fort.getStrength();
                    srv.messageToGame(gaName, new SOCPieceValue(gaName, fort.getCoordinates(), fortStrength, 0));
                    if (0 == fortStrength)
                        srv.messageToGame(gaName, new SOCPutPiece(gaName, cpn, SOCPlayingPiece.SETTLEMENT, fort.getCoordinates()));
                }
                srv.messageToGame(gaName, new SOCSimpleAction(gaName, cpn, SOCSimpleAction.SC_PIRI_FORT_ATTACK_RESULT, res[0], res.length - 1));
                // check for end of player's turn
                if (!handler.checkTurn(c, ga)) {
                    handler.endGameTurn(ga, cp, false);
                } else {
                    // still player's turn, even if they won
                    final int gstate = ga.getGameState();
                    if (gstate != prevState)
                        // might be OVER, if player won
                        handler.sendGameState(ga);
                }
            }
            break;
        case SOCSimpleRequest.TRADE_PORT_PLACE:
            {
                if (clientIsPN && (pn == cpn)) {
                    final int edge = mes.getValue1();
                    if ((ga.getGameState() == SOCGame.PLACING_INV_ITEM) && ga.canPlacePort(clientPl, edge)) {
                        final int ptype = ga.placePort(edge);
                        // PLAY1 or SPECIAL_BUILDING
                        handler.sendGameState(ga);
                        srv.messageToGame(gaName, new SOCSimpleRequest(gaName, cpn, SOCSimpleRequest.TRADE_PORT_PLACE, edge, ptype));
                    } else {
                        // client will print a text message, no need to send one
                        replyDecline = true;
                    }
                } else {
                    srv.messageToPlayerKeyed(c, gaName, "reply.not.your.turn");
                    replyDecline = true;
                }
            }
            break;
        default:
            // deny unknown types
            replyDecline = true;
            System.err.println("handleSIMPLEREQUEST: Unknown type " + reqtype + " from " + c.getData() + " in game " + ga);
    }
    if (replyDecline)
        c.put(SOCSimpleRequest.toCmd(gaName, -1, reqtype, 0, 0));
}
Also used : SOCShip(soc.game.SOCShip) SOCPlayer(soc.game.SOCPlayer) SOCFortress(soc.game.SOCFortress)

Example 3 with SOCShip

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

the class SOCGameMessageHandler method handleDEBUGFREEPLACE.

/**
 * Handle the client's debug Free Placement putpiece request.
 * @since 1.1.12
 */
private void handleDEBUGFREEPLACE(final SOCGame ga, final Connection c, final SOCDebugFreePlace mes) {
    if (!ga.isDebugFreePlacement())
        return;
    final String gaName = ga.getName();
    final int coord = mes.getCoordinates();
    final SOCPlayer player = ga.getPlayer(mes.getPlayerNumber());
    if (player == null)
        return;
    boolean didPut = false;
    final int pieceType = mes.getPieceType();
    final boolean initialDeny = ga.isInitialPlacement() && !player.canBuildInitialPieceType(pieceType);
    switch(pieceType) {
        case SOCPlayingPiece.ROAD:
            if (player.isPotentialRoad(coord) && !initialDeny) {
                ga.putPiece(new SOCRoad(player, coord, null));
                didPut = true;
            }
            break;
        case SOCPlayingPiece.SETTLEMENT:
            if (player.canPlaceSettlement(coord) && !initialDeny) {
                ga.putPiece(new SOCSettlement(player, coord, null));
                didPut = true;
            }
            break;
        case SOCPlayingPiece.CITY:
            if (player.isPotentialCity(coord) && !initialDeny) {
                ga.putPiece(new SOCCity(player, coord, null));
                didPut = true;
            }
            break;
        case SOCPlayingPiece.SHIP:
            if (ga.canPlaceShip(player, coord) && !initialDeny) {
                ga.putPiece(new SOCShip(player, coord, null));
                didPut = true;
            }
            break;
        default:
            srv.messageToPlayer(c, gaName, "* Unknown piece type: " + pieceType);
    }
    if (didPut) {
        srv.messageToGame(gaName, new SOCPutPiece(gaName, mes.getPlayerNumber(), pieceType, coord));
        // Check for initial settlement next to gold hex
        if (pieceType == SOCPlayingPiece.SETTLEMENT) {
            final int numGoldRes = player.getNeedToPickGoldHexResources();
            if (numGoldRes > 0)
                srv.messageToPlayer(c, new SOCSimpleRequest(gaName, player.getPlayerNumber(), SOCSimpleRequest.PROMPT_PICK_RESOURCES, numGoldRes));
        }
        if (ga.getGameState() >= SOCGame.OVER) {
            // exit debug mode, announce end of game
            handler.processDebugCommand_freePlace(c, gaName, "0");
            handler.sendGameState(ga, false, false);
        }
    } else {
        if (initialDeny) {
            final String pieceTypeFirst = ((player.getPieces().size() % 2) == 0) ? "settlement" : "road";
            srv.messageToPlayer(c, gaName, "Place a " + pieceTypeFirst + " before placing that.");
        } else {
            srv.messageToPlayer(c, gaName, "Not a valid location to place that.");
        }
    }
}
Also used : SOCSettlement(soc.game.SOCSettlement) SOCCity(soc.game.SOCCity) SOCShip(soc.game.SOCShip) SOCPlayer(soc.game.SOCPlayer) SOCRoad(soc.game.SOCRoad)

Example 4 with SOCShip

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

the class SOCRobotBrain method run.

/**
 * Here is the run method.  Just keep receiving game events
 * through {@link #gameEventQ} and deal with each one.
 * Remember that we're sent a {@link SOCTimingPing} event once per second,
 * incrementing {@link #counter}.  That allows the bot to wait a certain
 * time for other players before it decides whether to do something.
 *<P>
 * Nearly all bot actions start in this method; the overview of bot structures
 * is in the {@link SOCRobotBrain class javadoc} for prominence.
 * See comments within <tt>run()</tt> for minor details.
 *<P>
 * The brain thread will run until {@link #kill()} has been called or its pinger stops,
 * or it receives a {@link SOCMessage#ROBOTDISMISS} request to exit the game.
 */
@Override
public void run() {
    // Thread name for debug
    try {
        Thread.currentThread().setName("robotBrain-" + client.getNickname() + "-" + game.getName());
    } catch (Throwable th) {
    }
    if (pinger != null) {
        pinger.start();
        while (alive) {
            try {
                // Sleeps until message received
                final SOCMessage mes = gameEventQ.get();
                final int mesType;
                if (mes != null) {
                    // Debug aid: When looking at message contents or setting a per-message breakpoint,
                    // skip the pings; note (mesType != SOCMessage.TIMINGPING) here.
                    mesType = mes.getType();
                    if (mesType != SOCMessage.TIMINGPING)
                        turnEventsCurrent.addElement(mes);
                    if (D.ebugOn)
                        D.ebugPrintln("mes - " + mes);
                } else {
                    mesType = -1;
                }
                if (waitingForTradeMsg && (counter > 10)) {
                    waitingForTradeMsg = false;
                    counter = 0;
                }
                if (waitingForTradeResponse && (counter > 100)) {
                    // Remember other players' responses, call client.clearOffer,
                    // clear waitingForTradeResponse and counter.
                    tradeStopWaitingClearOffer();
                }
                if (waitingForGameState && (counter > 10000)) {
                    // D.ebugPrintln("counter = "+counter);
                    // D.ebugPrintln("RESEND");
                    counter = 0;
                    client.resend();
                }
                if (mesType == SOCMessage.GAMESTATE) {
                    handleGAMESTATE(((SOCGameState) mes).getState());
                // clears waitingForGameState, updates oldGameState, calls ga.setGameState
                } else if (mesType == SOCMessage.STARTGAME) {
                    handleGAMESTATE(((SOCStartGame) mes).getGameState());
                // clears waitingForGameState, updates oldGameState, calls ga.setGameState
                } else if (mesType == SOCMessage.TURN) {
                    // Start of a new player's turn.
                    // Update game and reset most of our state fields.
                    // See also below: if ((mesType == SOCMessage.TURN) && ourTurn).
                    handleGAMESTATE(((SOCTurn) mes).getGameState());
                    // clears waitingForGameState, updates oldGameState, calls ga.setGameState
                    game.setCurrentPlayerNumber(((SOCTurn) mes).getPlayerNumber());
                    game.updateAtTurn();
                    // 
                    // remove any expected states
                    // 
                    expectROLL_OR_CARD = false;
                    expectPLAY1 = false;
                    expectPLACING_ROAD = false;
                    expectPLACING_SETTLEMENT = false;
                    expectPLACING_CITY = false;
                    expectPLACING_SHIP = false;
                    expectPLACING_ROBBER = false;
                    expectPLACING_FREE_ROAD1 = false;
                    expectPLACING_FREE_ROAD2 = false;
                    expectPLACING_INV_ITEM = false;
                    expectDICERESULT = false;
                    expectDISCARD = false;
                    expectMOVEROBBER = false;
                    expectWAITING_FOR_DISCOVERY = false;
                    expectWAITING_FOR_MONOPOLY = false;
                    // 
                    if (robotParameters.getTradeFlag() == 1) {
                        doneTrading = false;
                    } else {
                        doneTrading = true;
                    }
                    waitingForTradeMsg = false;
                    waitingForTradeResponse = false;
                    negotiator.resetIsSelling();
                    negotiator.resetOffersMade();
                    waitingForPickSpecialItem = null;
                    waitingForSC_PIRI_FortressRequest = false;
                    // 
                    // check or reset any special-building-phase decisions
                    // 
                    decidedIfSpecialBuild = false;
                    if (game.getGameState() == SOCGame.SPECIAL_BUILDING) {
                        if (waitingForSpecialBuild && !buildingPlan.isEmpty()) {
                        // Keep the building plan.
                        // Will ask during loop body to build.
                        } else {
                        // We have no plan, but will call planBuilding()
                        // during the loop body.  If buildingPlan still empty,
                        // bottom of loop will end our Special Building turn,
                        // just as it would in gamestate PLAY1.  Otherwise,
                        // will ask to build after planBuilding.
                        }
                    } else {
                        // 
                        // reset any plans we had
                        // 
                        buildingPlan.clear();
                    }
                    negotiator.resetTargetPieces();
                    // 
                    // swap the message-history queues
                    // 
                    {
                        Vector<SOCMessage> oldPrev = turnEventsPrev;
                        turnEventsPrev = turnEventsCurrent;
                        oldPrev.clear();
                        turnEventsCurrent = oldPrev;
                    }
                    turnExceptionCount = 0;
                }
                if (game.getCurrentPlayerNumber() == ourPlayerNumber) {
                    ourTurn = true;
                    waitingForSpecialBuild = false;
                } else {
                    ourTurn = false;
                }
                if ((mesType == SOCMessage.TURN) && ourTurn) {
                    waitingForOurTurn = false;
                    // Clear some per-turn variables.
                    // For others, see above: if (mesType == SOCMessage.TURN)
                    whatWeFailedToBuild = null;
                    failedBuildingAttempts = 0;
                    rejectedPlayDevCardType = -1;
                    rejectedPlayInvItem = null;
                }
                /**
                 * Handle some message types early.
                 *
                 * When reading the main flow of this method, skip past here;
                 * search for "it's time to decide to build or take other normal actions".
                 */
                switch(mesType) {
                    case SOCMessage.PLAYERELEMENT:
                        // If this during the ROLL_OR_CARD state, also updates the
                        // negotiator's is-selling flags.
                        // If our player is losing a resource needed for the buildingPlan,
                        // clear the plan if this is for the Special Building Phase (on the 6-player board).
                        // In normal game play, we clear the building plan at the start of each turn.
                        handlePLAYERELEMENT((SOCPlayerElement) mes);
                        break;
                    case SOCMessage.PLAYERELEMENTS:
                        // Multiple PLAYERELEMENT updates;
                        // see comment above for actions taken.
                        handlePLAYERELEMENTS((SOCPlayerElements) mes);
                        break;
                    case SOCMessage.RESOURCECOUNT:
                        handlePLAYERELEMENT(null, ((SOCResourceCount) mes).getPlayerNumber(), SOCPlayerElement.SET, SOCPlayerElement.RESOURCE_COUNT, ((SOCResourceCount) mes).getCount());
                        break;
                    case SOCMessage.DICERESULT:
                        game.setCurrentDice(((SOCDiceResult) mes).getResult());
                        break;
                    case SOCMessage.PUTPIECE:
                        handlePUTPIECE_updateGameData((SOCPutPiece) mes);
                        // For initial roads, also tracks their initial settlement in SOCPlayerTracker.
                        break;
                    case SOCMessage.MOVEPIECE:
                        {
                            SOCMovePiece mpm = (SOCMovePiece) mes;
                            SOCShip sh = new SOCShip(game.getPlayer(mpm.getPlayerNumber()), mpm.getFromCoord(), null);
                            game.moveShip(sh, mpm.getToCoord());
                        }
                        break;
                    case SOCMessage.CANCELBUILDREQUEST:
                        handleCANCELBUILDREQUEST((SOCCancelBuildRequest) mes);
                        break;
                    case SOCMessage.MOVEROBBER:
                        {
                            // 
                            // Note: Don't call ga.moveRobber() because that will call the
                            // functions to do the stealing.  We just want to set where
                            // the robber moved, without seeing if something was stolen.
                            // MOVEROBBER will be followed by PLAYERELEMENT messages to
                            // report the gain/loss of resources.
                            // 
                            moveRobberOnSeven = false;
                            final int newHex = ((SOCMoveRobber) mes).getCoordinates();
                            if (newHex >= 0)
                                game.getBoard().setRobberHex(newHex, true);
                            else
                                ((SOCBoardLarge) game.getBoard()).setPirateHex(-newHex, true);
                        }
                        break;
                    case SOCMessage.MAKEOFFER:
                        if (robotParameters.getTradeFlag() == 1)
                            handleMAKEOFFER((SOCMakeOffer) mes);
                        break;
                    case SOCMessage.CLEAROFFER:
                        if (robotParameters.getTradeFlag() == 1) {
                            final int pn = ((SOCClearOffer) mes).getPlayerNumber();
                            if (pn != -1) {
                                game.getPlayer(pn).setCurrentOffer(null);
                            } else {
                                for (int i = 0; i < game.maxPlayers; ++i) game.getPlayer(i).setCurrentOffer(null);
                            }
                        }
                        break;
                    case SOCMessage.ACCEPTOFFER:
                        if (waitingForTradeResponse && (robotParameters.getTradeFlag() == 1)) {
                            if ((ourPlayerNumber == (((SOCAcceptOffer) mes).getOfferingNumber())) || (ourPlayerNumber == ((SOCAcceptOffer) mes).getAcceptingNumber())) {
                                waitingForTradeResponse = false;
                            }
                        }
                        break;
                    case SOCMessage.REJECTOFFER:
                        if (robotParameters.getTradeFlag() == 1)
                            handleREJECTOFFER((SOCRejectOffer) mes);
                        break;
                    case SOCMessage.DEVCARDACTION:
                        {
                            SOCDevCardAction dcMes = (SOCDevCardAction) mes;
                            if (dcMes.getAction() != SOCDevCardAction.CANNOT_PLAY) {
                                handleDEVCARDACTION(dcMes);
                            } else {
                                // rejected by server, can't play our requested card
                                rejectedPlayDevCardType = dcMes.getCardType();
                                waitingForGameState = false;
                                expectPLACING_FREE_ROAD1 = false;
                                expectWAITING_FOR_DISCOVERY = false;
                                expectWAITING_FOR_MONOPOLY = false;
                                expectPLACING_ROBBER = false;
                            }
                        }
                        break;
                    case SOCMessage.SIMPLEREQUEST:
                        if (ourTurn && waitingForSC_PIRI_FortressRequest) {
                            final SOCSimpleRequest rqMes = (SOCSimpleRequest) mes;
                            if ((rqMes.getRequestType() == SOCSimpleRequest.SC_PIRI_FORT_ATTACK) && (rqMes.getPlayerNumber() == -1)) {
                                // Attack request was denied: End our turn now.
                                // Reset method sets waitingForGameState, which will bypass
                                // any further actions in the run() loop body.
                                waitingForSC_PIRI_FortressRequest = false;
                                resetFieldsAtEndTurn();
                                client.endTurn(game);
                            }
                        // else, from another player; we can ignore it
                        }
                        break;
                    case SOCMessage.SIMPLEACTION:
                        switch(((SOCSimpleAction) mes).getActionType()) {
                            case SOCSimpleAction.SC_PIRI_FORT_ATTACK_RESULT:
                                if (ourTurn && waitingForSC_PIRI_FortressRequest) {
                                    // Our player has won or lost an attack on a pirate fortress.
                                    // When we receive this message, other messages have already
                                    // been sent to update related game state. End our turn now.
                                    // Reset method sets waitingForGameState, which will bypass
                                    // any further actions in the run() loop body.
                                    waitingForSC_PIRI_FortressRequest = false;
                                    resetFieldsAtEndTurn();
                                // client.endTurn not needed; making the attack implies sending endTurn
                                }
                                break;
                        }
                        break;
                    case SOCMessage.INVENTORYITEMACTION:
                        if (((SOCInventoryItemAction) mes).action == SOCInventoryItemAction.CANNOT_PLAY) {
                            final List<SOCInventoryItem> itms = ourPlayerData.getInventory().getByStateAndType(SOCInventory.PLAYABLE, ((SOCInventoryItemAction) mes).itemType);
                            if (itms != null)
                                // any item of same type# is similar enough here
                                rejectedPlayInvItem = itms.get(0);
                            waitingForGameState = false;
                            // in case was rejected placement (SC_FTRI gift port, etc)
                            expectPLACING_INV_ITEM = false;
                        }
                        break;
                }
                // switch(mesType)
                debugInfo();
                if ((game.getGameState() == SOCGame.ROLL_OR_CARD) && !waitingForGameState) {
                    rollOrPlayKnightOrExpectDice();
                // On our turn, ask client to roll dice or play a knight;
                // on other turns, update flags to expect dice result.
                // Clears expectROLL_OR_CARD to false.
                // Sets either expectDICERESULT, or expectPLACING_ROBBER and waitingForGameState.
                }
                if (ourTurn && (game.getGameState() == SOCGame.WAITING_FOR_ROBBER_OR_PIRATE) && !waitingForGameState) {
                    // TODO handle moving the pirate too
                    // For now, always decide to move the robber.
                    // Once we move the robber, will also need to deal with state WAITING_FOR_ROB_CLOTH_OR_RESOURCE.
                    expectPLACING_ROBBER = true;
                    waitingForGameState = true;
                    counter = 0;
                    client.choosePlayer(game, SOCChoosePlayer.CHOICE_MOVE_ROBBER);
                    pause(200);
                } else if ((game.getGameState() == SOCGame.PLACING_ROBBER) && !waitingForGameState) {
                    expectPLACING_ROBBER = false;
                    if ((!waitingForOurTurn) && ourTurn) {
                        if (!((expectROLL_OR_CARD || expectPLAY1) && (counter < 4000))) {
                            if (moveRobberOnSeven) {
                                // robber moved because 7 rolled on dice
                                moveRobberOnSeven = false;
                                waitingForGameState = true;
                                counter = 0;
                                expectPLAY1 = true;
                            } else {
                                waitingForGameState = true;
                                counter = 0;
                                if (oldGameState == SOCGame.ROLL_OR_CARD) {
                                    // robber moved from playing knight card before dice roll
                                    expectROLL_OR_CARD = true;
                                } else if (oldGameState == SOCGame.PLAY1) {
                                    // robber moved from playing knight card after dice roll
                                    expectPLAY1 = true;
                                }
                            }
                            counter = 0;
                            moveRobber();
                        }
                    }
                }
                if ((game.getGameState() == SOCGame.WAITING_FOR_DISCOVERY) && !waitingForGameState) {
                    expectWAITING_FOR_DISCOVERY = false;
                    if ((!waitingForOurTurn) && ourTurn) {
                        if (!(expectPLAY1) && (counter < 4000)) {
                            waitingForGameState = true;
                            expectPLAY1 = true;
                            counter = 0;
                            client.pickResources(game, resourceChoices);
                            pause(1500);
                        }
                    }
                }
                if ((game.getGameState() == SOCGame.WAITING_FOR_MONOPOLY) && !waitingForGameState) {
                    expectWAITING_FOR_MONOPOLY = false;
                    if ((!waitingForOurTurn) && ourTurn) {
                        if (!(expectPLAY1) && (counter < 4000)) {
                            waitingForGameState = true;
                            expectPLAY1 = true;
                            counter = 0;
                            client.pickResourceType(game, monopolyStrategy.getMonopolyChoice());
                            pause(1500);
                        }
                    }
                }
                if (ourTurn && (!waitingForOurTurn) && (game.getGameState() == SOCGame.PLACING_INV_ITEM) && (!waitingForGameState)) {
                    // choose and send a placement location
                    planAndPlaceInvItem();
                }
                if (waitingForTradeMsg && (mesType == SOCMessage.BANKTRADE) && (((SOCBankTrade) mes).getPlayerNumber() == ourPlayerNumber)) {
                    // 
                    // This is the bank/port trade confirmation announcement we've been waiting for
                    // 
                    waitingForTradeMsg = false;
                }
                if (waitingForDevCard && (mesType == SOCMessage.SIMPLEACTION) && (((SOCSimpleAction) mes).getPlayerNumber() == ourPlayerNumber) && (((SOCSimpleAction) mes).getActionType() == SOCSimpleAction.DEVCARD_BOUGHT)) {
                    // 
                    // This is the "dev card bought" message we've been waiting for
                    // 
                    waitingForDevCard = false;
                }
                /**
                 * Planning: If our turn and not waiting for something,
                 * it's time to decide to build or take other normal actions.
                 */
                if (((game.getGameState() == SOCGame.PLAY1) || (game.getGameState() == SOCGame.SPECIAL_BUILDING)) && !(waitingForGameState || waitingForTradeMsg || waitingForTradeResponse || waitingForDevCard || expectPLACING_ROAD || expectPLACING_SETTLEMENT || expectPLACING_CITY || expectPLACING_SHIP || expectPLACING_FREE_ROAD1 || expectPLACING_FREE_ROAD2 || expectPLACING_ROBBER || expectWAITING_FOR_DISCOVERY || expectWAITING_FOR_MONOPOLY || waitingForSC_PIRI_FortressRequest || (waitingForPickSpecialItem != null))) {
                    expectPLAY1 = false;
                    // during other players' turns.
                    if ((!ourTurn) && waitingForOurTurn && gameIs6Player && (!decidedIfSpecialBuild) && (!expectPLACING_ROBBER)) {
                        decidedIfSpecialBuild = true;
                        if (buildingPlan.empty() && (ourPlayerData.getResources().getTotal() > 1) && (failedBuildingAttempts < MAX_DENIED_BUILDING_PER_TURN)) {
                            planBuilding();
                            if (!buildingPlan.empty()) {
                                // If we have the resources right now, ask to Special Build
                                final SOCPossiblePiece targetPiece = buildingPlan.peek();
                                final SOCResourceSet targetResources = targetPiece.getResourcesToBuild();
                                if ((ourPlayerData.getResources().contains(targetResources))) {
                                    // Ask server for the Special Building Phase.
                                    // (TODO) if FAST_STRATEGY: Maybe randomly don't ask, to lower opponent difficulty?
                                    waitingForSpecialBuild = true;
                                    client.buildRequest(game, -1);
                                    pause(100);
                                }
                            }
                        }
                    }
                    if ((!waitingForOurTurn) && ourTurn) {
                        if (!(expectROLL_OR_CARD && (counter < 4000))) {
                            counter = 0;
                            // D.ebugPrintln("DOING PLAY1");
                            if (D.ebugOn) {
                                client.sendText(game, "================================");
                                // for each player in game:
                                // sendText and debug-prn game.getPlayer(i).getResources()
                                printResources();
                            }
                            /**
                             * if we haven't played a dev card yet,
                             * and we have a knight, and we can get
                             * largest army, play the knight.
                             * If we're in SPECIAL_BUILDING (not PLAY1),
                             * can't trade or play development cards.
                             *
                             * In scenario _SC_PIRI (which has no robber and
                             * no largest army), play one whenever we have
                             * it, someone else has resources, and we can
                             * convert a ship to a warship.
                             */
                            if ((game.getGameState() == SOCGame.PLAY1) && !ourPlayerData.hasPlayedDevCard()) {
                                // might set expectPLACING_ROBBER and waitingForGameState
                                playKnightCardIfShould();
                            }
                            /**
                             * make a plan if we don't have one,
                             * and if we haven't given up building
                             * attempts this turn.
                             */
                            if ((!expectPLACING_ROBBER) && buildingPlan.empty() && (ourPlayerData.getResources().getTotal() > 1) && (failedBuildingAttempts < MAX_DENIED_BUILDING_PER_TURN)) {
                                planBuilding();
                            /*
                                         * planBuilding takes these actions, sets buildingPlan and other fields
                                         * (see its javadoc):
                                         *
                                        decisionMaker.planStuff(robotParameters.getStrategyType());

                                        if (! buildingPlan.empty())
                                        {
                                            lastTarget = (SOCPossiblePiece) buildingPlan.peek();
                                            negotiator.setTargetPiece(ourPlayerNumber, buildingPlan.peek());
                                        }
                                         */
                            }
                            // D.ebugPrintln("DONE PLANNING");
                            if ((!expectPLACING_ROBBER) && (!buildingPlan.empty())) {
                                // Time to build something.
                                // Either ask to build a piece, or use trading or development
                                // cards to get resources to build it.  See javadoc for flags set
                                // (expectPLACING_ROAD, etc).  In a future iteration of the run loop
                                // with the expected PLACING_ state, we'll build whatWeWantToBuild
                                // in placeIfExpectPlacing().
                                buildOrGetResourceByTradeOrCard();
                            }
                            /**
                             * see if we're done with our turn
                             */
                            if (!(expectPLACING_SETTLEMENT || expectPLACING_FREE_ROAD1 || expectPLACING_FREE_ROAD2 || expectPLACING_ROAD || expectPLACING_CITY || expectPLACING_SHIP || expectWAITING_FOR_DISCOVERY || expectWAITING_FOR_MONOPOLY || expectPLACING_ROBBER || waitingForTradeMsg || waitingForTradeResponse || waitingForDevCard || waitingForGameState || (waitingForPickSpecialItem != null))) {
                                // Any last things for turn from game's scenario?
                                boolean scenActionTaken = false;
                                if (game.isGameOptionSet(SOCGameOption.K_SC_FTRI) || game.isGameOptionSet(SOCGameOption.K_SC_PIRI)) {
                                    // possibly attack pirate fortress
                                    // or place a gift port for better bank trades
                                    scenActionTaken = considerScenarioTurnFinalActions();
                                }
                                if (!scenActionTaken) {
                                    resetFieldsAtEndTurn();
                                    /*
                                             * These state fields are reset:
                                             *
                                            waitingForGameState = true;
                                            counter = 0;
                                            expectROLL_OR_CARD = true;
                                            waitingForOurTurn = true;

                                            doneTrading = (robotParameters.getTradeFlag() != 1);

                                            //D.ebugPrintln("!!! ENDING TURN !!!");
                                            negotiator.resetIsSelling();
                                            negotiator.resetOffersMade();
                                            buildingPlan.clear();
                                            negotiator.resetTargetPieces();
                                             */
                                    pause(1500);
                                    client.endTurn(game);
                                }
                            }
                        }
                    }
                }
                /**
                 * Placement: Make various putPiece calls; server has told us it's OK to buy them.
                 * Call client.putPiece.
                 * Works when it's our turn and we have an expect flag set
                 * (such as expectPLACING_SETTLEMENT, in these game states:
                 * START1A - START2B or - START3B
                 * PLACING_SETTLEMENT, PLACING_ROAD, PLACING_CITY
                 * PLACING_FREE_ROAD1, PLACING_FREE_ROAD2
                 */
                if (!waitingForGameState) {
                    placeIfExpectPlacing();
                }
                /**
                 * Handle various message types here at bottom of loop.
                 */
                switch(mesType) {
                    case SOCMessage.PUTPIECE:
                        /**
                         * this is for player tracking
                         *
                         * For initial placement of our own pieces, also checks
                         * and clears expectPUTPIECE_FROM_START1A,
                         * and sets expectSTART1B, etc.  The final initial putpiece
                         * clears expectPUTPIECE_FROM_START2B and sets expectROLL_OR_CARD.
                         */
                        {
                            final SOCPutPiece mpp = (SOCPutPiece) mes;
                            final int pn = mpp.getPlayerNumber();
                            final int coord = mpp.getCoordinates();
                            final int pieceType = mpp.getPieceType();
                            handlePUTPIECE_updateTrackers(pn, coord, pieceType);
                        }
                        break;
                    case SOCMessage.MOVEPIECE:
                        /**
                         * this is for player tracking of moved ships
                         */
                        {
                            final SOCMovePiece mpp = (SOCMovePiece) mes;
                            final int pn = mpp.getPlayerNumber();
                            final int coord = mpp.getToCoord();
                            final int pieceType = mpp.getPieceType();
                            // TODO what about getFromCoord()?
                            handlePUTPIECE_updateTrackers(pn, coord, pieceType);
                        }
                        break;
                    case SOCMessage.DICERESULT:
                        if (expectDICERESULT) {
                            expectDICERESULT = false;
                            if (((SOCDiceResult) mes).getResult() == 7) {
                                final boolean robWithoutRobber = game.isGameOptionSet(SOCGameOption.K_SC_PIRI);
                                if (!robWithoutRobber)
                                    moveRobberOnSeven = true;
                                if (ourPlayerData.getResources().getTotal() > 7)
                                    expectDISCARD = true;
                                else if (ourTurn) {
                                    if (!robWithoutRobber)
                                        expectPLACING_ROBBER = true;
                                    else
                                        expectPLAY1 = true;
                                }
                            } else {
                                expectPLAY1 = true;
                            }
                        }
                        break;
                    case SOCMessage.SIMPLEREQUEST:
                        // These messages can almost always be ignored by bots.
                        // Some request types are handled at the top of the loop body;
                        // search for SOCMessage.SIMPLEREQUEST
                        {
                            final SOCSimpleRequest rqMes = (SOCSimpleRequest) mes;
                            switch(rqMes.getRequestType()) {
                                case SOCSimpleRequest.PROMPT_PICK_RESOURCES:
                                    // gold hex
                                    counter = 0;
                                    pickFreeResources(rqMes.getValue1());
                                    waitingForGameState = true;
                                    if (game.isInitialPlacement()) {
                                        if (game.isGameOptionSet(SOCGameOption.K_SC_3IP))
                                            expectSTART3B = true;
                                        else
                                            expectSTART2B = true;
                                    } else {
                                        expectPLAY1 = true;
                                    }
                                    break;
                            }
                        }
                        break;
                    case SOCMessage.DISCARDREQUEST:
                        expectDISCARD = false;
                        // {
                        if ((game.getCurrentDice() == 7) && ourTurn) {
                            if (!game.isGameOptionSet(SOCGameOption.K_SC_PIRI))
                                expectPLACING_ROBBER = true;
                            else
                                expectPLAY1 = true;
                        } else {
                            expectPLAY1 = true;
                        }
                        counter = 0;
                        client.discard(game, DiscardStrategy.discard(((SOCDiscardRequest) mes).getNumberOfDiscards(), buildingPlan, rand, ourPlayerData, robotParameters, decisionMaker, negotiator));
                        // }
                        break;
                    case SOCMessage.CHOOSEPLAYERREQUEST:
                        {
                            final int choicePl = RobberStrategy.chooseRobberVictim(((SOCChoosePlayerRequest) mes).getChoices(), game, playerTrackers);
                            counter = 0;
                            client.choosePlayer(game, choicePl);
                        }
                        break;
                    case SOCMessage.CHOOSEPLAYER:
                        {
                            final int vpn = ((SOCChoosePlayer) mes).getChoice();
                            // Cloth is more valuable.
                            // TODO decide when we should choose resources instead
                            client.choosePlayer(game, -(vpn + 1));
                        }
                        break;
                    case SOCMessage.SETSPECIALITEM:
                        if (waitingForPickSpecialItem != null) {
                            final SOCSetSpecialItem siMes = (SOCSetSpecialItem) mes;
                            if (siMes.typeKey.equals(waitingForPickSpecialItem)) {
                                switch(siMes.op) {
                                    case SOCSetSpecialItem.OP_PICK:
                                        waitingForPickSpecialItem = null;
                                        // Any specific action needed? Not for SC_WOND.
                                        break;
                                    case SOCSetSpecialItem.OP_DECLINE:
                                        waitingForPickSpecialItem = null;
                                        // TODO how to prevent asking again? (similar to whatWeFailedtoBuild)
                                        break;
                                }
                            }
                        }
                        break;
                    case SOCMessage.ROBOTDISMISS:
                        if ((!expectDISCARD) && (!expectPLACING_ROBBER)) {
                            client.leaveGame(game, "dismiss msg", false, false);
                            alive = false;
                        }
                        break;
                    case SOCMessage.TIMINGPING:
                        // Once-per-second message from the pinger thread
                        counter++;
                        break;
                }
                if (ourTurn && (counter > 15000)) {
                    // We've been waiting too long, must be a bug: Leave the game.
                    // This is a fallback, server has SOCForceEndTurnThread which
                    // should have already taken action.
                    // Before v1.1.20, would leave game even during other (human) players' turns.
                    client.leaveGame(game, "counter 15000", true, false);
                    alive = false;
                }
                if ((failedBuildingAttempts > (2 * MAX_DENIED_BUILDING_PER_TURN)) && game.isInitialPlacement()) {
                    // Apparently can't decide where we can initially place:
                    // Leave the game.
                    client.leaveGame(game, "failedBuildingAttempts at start", true, false);
                    alive = false;
                }
                /*
                       if (D.ebugOn) {
                       if (mes != null) {
                       debugInfo();
                       D.ebugPrintln("~~~~~~~~~~~~~~~~");
                       }
                       }
                     */
                yield();
            } catch (Exception e) {
                // Print exception; ignore errors due to game reset in another thread
                if (alive && ((game == null) || (game.getGameState() != SOCGame.RESET_OLD))) {
                    // TODO end our turn if too many
                    ++turnExceptionCount;
                    String eMsg = (turnExceptionCount == 1) ? "*** Robot caught an exception - " + e : "*** Robot caught an exception (" + turnExceptionCount + " this turn) - " + e;
                    D.ebugPrintln(eMsg);
                    System.out.println(eMsg);
                    e.printStackTrace();
                }
            }
        }
    } else {
        System.out.println("AGG! NO PINGER!");
    }
    // D.ebugPrintln("STOPPING AND DEALLOCATING");
    gameEventQ = null;
    client.addCleanKill();
    client = null;
    game = null;
    ourPlayerData = null;
    dummyCancelPlayerData = null;
    whatWeWantToBuild = null;
    whatWeFailedToBuild = null;
    rejectedPlayInvItem = null;
    resourceChoices = null;
    ourPlayerTracker = null;
    playerTrackers = null;
    pinger.stopPinger();
    pinger = null;
}
Also used : SOCShip(soc.game.SOCShip) SOCMakeOffer(soc.message.SOCMakeOffer) SOCInventoryItem(soc.game.SOCInventoryItem) SOCRejectOffer(soc.message.SOCRejectOffer) SOCResourceSet(soc.game.SOCResourceSet) SOCMovePiece(soc.message.SOCMovePiece) Vector(java.util.Vector) SOCAcceptOffer(soc.message.SOCAcceptOffer) SOCMessage(soc.message.SOCMessage) SOCBoardLarge(soc.game.SOCBoardLarge) SOCStartGame(soc.message.SOCStartGame) SOCDiscardRequest(soc.message.SOCDiscardRequest) SOCSimpleAction(soc.message.SOCSimpleAction) SOCSetSpecialItem(soc.message.SOCSetSpecialItem) SOCClearOffer(soc.message.SOCClearOffer) SOCSimpleRequest(soc.message.SOCSimpleRequest) SOCPutPiece(soc.message.SOCPutPiece) SOCChoosePlayerRequest(soc.message.SOCChoosePlayerRequest) SOCDevCardAction(soc.message.SOCDevCardAction)

Example 5 with SOCShip

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

the class SOCRobotBrain method buildRequestPlannedPiece.

/**
 * Have the client ask to build our top planned piece
 * (calls {@link #buildingPlan}{@link Stack#pop() .pop()}),
 * unless we've already been told by the server to not build it.
 * Sets {@link #whatWeWantToBuild}, {@link #waitingForDevCard},
 * or {@link #waitingForPickSpecialItem}.
 * Called from {@link #buildOrGetResourceByTradeOrCard()}.
 *<P>
 * Checks against {@link #whatWeFailedToBuild} to see if server has rejected this already.
 * Calls <tt>client.buyDevCard()</tt> or <tt>client.buildRequest()</tt>.
 * Sets {@link #waitingForDevCard} or {@link #waitingForPickSpecialItem},
 * or sets {@link #waitingForGameState} and a flag like {@link #expectPLACING_SETTLEMENT} (etc).
 *<P>
 * Preconditions: Call only when:
 *<UL>
 * <LI> Gamestate is {@link SOCGame#PLAY1} or {@link SOCGame#SPECIAL_BUILDING}
 * <LI> <tt>! ({@link #waitingForTradeMsg} || {@link #waitingForTradeResponse})</tt>
 * <LI> ourPlayerData.getResources().{@link SOCResourceSet#contains(soc.game.ResourceSet) contains}(targetPieceResources)
 *</UL>
 *
 * @see #placeIfExpectPlacing()
 * @since 1.1.08
 */
private void buildRequestPlannedPiece() {
    final SOCPossiblePiece targetPiece = buildingPlan.pop();
    D.ebugPrintln("$ POPPED " + targetPiece);
    lastMove = targetPiece;
    currentDRecorder = (currentDRecorder + 1) % 2;
    negotiator.setTargetPiece(ourPlayerNumber, targetPiece);
    switch(targetPiece.getType()) {
        case SOCPossiblePiece.CARD:
            client.buyDevCard(game);
            waitingForDevCard = true;
            break;
        case SOCPossiblePiece.ROAD:
            waitingForGameState = true;
            counter = 0;
            expectPLACING_ROAD = true;
            whatWeWantToBuild = new SOCRoad(ourPlayerData, targetPiece.getCoordinates(), null);
            if (!whatWeWantToBuild.equals(whatWeFailedToBuild)) {
                D.ebugPrintln("!!! BUILD REQUEST FOR A ROAD AT " + Integer.toHexString(targetPiece.getCoordinates()) + " !!!");
                client.buildRequest(game, SOCPlayingPiece.ROAD);
            } else {
                // We already tried to build this.
                cancelWrongPiecePlacementLocal(whatWeWantToBuild);
            // cancel sets whatWeWantToBuild = null;
            }
            break;
        case SOCPlayingPiece.SETTLEMENT:
            waitingForGameState = true;
            counter = 0;
            expectPLACING_SETTLEMENT = true;
            whatWeWantToBuild = new SOCSettlement(ourPlayerData, targetPiece.getCoordinates(), null);
            if (!whatWeWantToBuild.equals(whatWeFailedToBuild)) {
                D.ebugPrintln("!!! BUILD REQUEST FOR A SETTLEMENT " + Integer.toHexString(targetPiece.getCoordinates()) + " !!!");
                client.buildRequest(game, SOCPlayingPiece.SETTLEMENT);
            } else {
                // We already tried to build this.
                cancelWrongPiecePlacementLocal(whatWeWantToBuild);
            // cancel sets whatWeWantToBuild = null;
            }
            break;
        case SOCPlayingPiece.CITY:
            waitingForGameState = true;
            counter = 0;
            expectPLACING_CITY = true;
            whatWeWantToBuild = new SOCCity(ourPlayerData, targetPiece.getCoordinates(), null);
            if (!whatWeWantToBuild.equals(whatWeFailedToBuild)) {
                D.ebugPrintln("!!! BUILD REQUEST FOR A CITY " + Integer.toHexString(targetPiece.getCoordinates()) + " !!!");
                client.buildRequest(game, SOCPlayingPiece.CITY);
            } else {
                // We already tried to build this.
                cancelWrongPiecePlacementLocal(whatWeWantToBuild);
            // cancel sets whatWeWantToBuild = null;
            }
            break;
        case SOCPlayingPiece.SHIP:
            waitingForGameState = true;
            counter = 0;
            expectPLACING_SHIP = true;
            whatWeWantToBuild = new SOCShip(ourPlayerData, targetPiece.getCoordinates(), null);
            if (!whatWeWantToBuild.equals(whatWeFailedToBuild)) {
                System.err.println("L2733: " + ourPlayerData.getName() + ": !!! BUILD REQUEST FOR A SHIP AT " + Integer.toHexString(targetPiece.getCoordinates()) + " !!!");
                D.ebugPrintln("!!! BUILD REQUEST FOR A SHIP AT " + Integer.toHexString(targetPiece.getCoordinates()) + " !!!");
                client.buildRequest(game, SOCPlayingPiece.SHIP);
            } else {
                // We already tried to build this.
                cancelWrongPiecePlacementLocal(whatWeWantToBuild);
            // cancel sets whatWeWantToBuild = null;
            }
            break;
        case SOCPossiblePiece.PICK_SPECIAL:
            {
                final SOCPossiblePickSpecialItem psi = (SOCPossiblePickSpecialItem) targetPiece;
                waitingForPickSpecialItem = psi.typeKey;
                // targetPiece isn't a SOCPlayingPiece
                whatWeWantToBuild = null;
                counter = 0;
                client.pickSpecialItem(game, psi.typeKey, psi.gi, psi.pi);
            }
            break;
        default:
            // shouldn't occur: print for debugging
            System.err.println(ourPlayerData.getName() + ": buildRequestPlannedPiece: Unknown piece type " + targetPiece.getType());
    }
}
Also used : SOCSettlement(soc.game.SOCSettlement) SOCCity(soc.game.SOCCity) SOCShip(soc.game.SOCShip) SOCRoad(soc.game.SOCRoad)

Aggregations

SOCShip (soc.game.SOCShip)27 SOCRoad (soc.game.SOCRoad)17 SOCPlayer (soc.game.SOCPlayer)12 SOCSettlement (soc.game.SOCSettlement)11 SOCCity (soc.game.SOCCity)10 SOCFortress (soc.game.SOCFortress)8 SOCBoardLarge (soc.game.SOCBoardLarge)6 SOCBoard (soc.game.SOCBoard)4 SOCPlayingPiece (soc.game.SOCPlayingPiece)3 SOCResourceSet (soc.game.SOCResourceSet)3 ArrayList (java.util.ArrayList)2 SOCGame (soc.game.SOCGame)2 SOCVillage (soc.game.SOCVillage)2 Graphics2D (java.awt.Graphics2D)1 Image (java.awt.Image)1 BufferedImage (java.awt.image.BufferedImage)1 Vector (java.util.Vector)1 SOCInventoryItem (soc.game.SOCInventoryItem)1 SOCAcceptOffer (soc.message.SOCAcceptOffer)1 SOCChoosePlayerRequest (soc.message.SOCChoosePlayerRequest)1