Class KaiserEngine

java.lang.Object
de.aikiit.game.kaiser.KaiserEngine

public class KaiserEngine extends Object
Maintains the city's population, land, grain stocks and reign statistics, and applies the rules from KAISER.BAS (09.08.1992) without performing console I/O. The caller controls the dialogue and the order in which the player's actions are requested.

A year starts with startNewRound(), which adds immigrants and applies any plague determined at the end of the previous year. After reporting that state, the caller invokes prepareLandTrading(), offers buying or selling land, allocates food and processes planting. Finally, finishRoundAfterActions() determines immigration and starvation and may dismiss the ruler. After ten action years, one further year-start update prepares the final report and marks the reign as completed.

BASIC's reused variables are deliberately separated here: Q is food allocated and later a plague roll; Y is harvest yield and later land price; C is several unrelated random factors. Quantities may be fractional. Explicit BASIC INT operations round down, while fractional statistics retain decimal precision. Negative action quantities abort the game; other invalid quantities are rejected before the action changes resources.

  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static enum 
    Describes whether further annual updates and player actions are permitted.
    static enum 
    Final rating based on average starvation and land owned per inhabitant.
  • Constructor Summary

    Constructors
    Constructor
    Description
    Creates a new reign with the BASIC starting resources and a secure random source for prices, harvests, rat losses, immigration and plague events.
    Creates a new reign using a caller-supplied source of random values.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Marks the game as aborted without changing resources or demographic figures.
    long
    buyLand(long hectares)
    Buys a whole-number quantity of land using the same validation, grain payment and abort handling as buyLand(BigDecimal).
    buyLand(BigDecimal hectares)
    Increases owned land by the requested hectares and pays for it from grain stocks at the current land price.
    Draws the number of residents who would like to hang the ruler in the mediocre-reign message.
    void
    cultivate(long hectares)
    Plants a whole-number area and processes the harvest using the same resource checks, random draws and abort handling as cultivate(BigDecimal).
    void
    Validates the planted area, consumes seed grain and processes this year's harvest and rat damage.
    void
    feedToPopulation(long grain)
    Allocates a whole-number amount of grain for feeding using the same stock checks, deferred starvation calculation and abort handling as feedToPopulation(BigDecimal).
    void
    Removes the requested grain from stocks and remembers it as this year's food allocation.
    void
    Resolves the year's demographic consequences after trading, feeding and planting.
    Calculates owned hectares per current inhabitant without rounding the result to a whole number.
    Classifies the reign using average annual starvation and current land per inhabitant, checking the worst applicable tier first.
    boolean
    Indicates whether the reign completed, the ruler was dismissed or play was aborted.
    void
    Draws the grain price for one hectare of land, uniformly from 17 through 26 dt, and stores it for both buying and selling during the current year.
    (package private) void
    Restores all resources, annual figures and accumulated statistics to their starting values, and makes the game runnable again.
    void
    sellLand(long hectares)
    Sells a whole-number quantity of land using the same price, ownership checks and abort handling as sellLand(BigDecimal).
    void
    sellLand(BigDecimal hectares)
    Reduces owned land by the offered hectares and credits grain stocks at the current land price.
    void
    Advances to the next report year, adds the previously calculated immigrants and applies the stored plague roll.

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • KaiserEngine

      public KaiserEngine()
      Creates a new reign with the BASIC starting resources and a secure random source for prices, harvests, rat losses, immigration and plague events. The first annual population update is deferred until startNewRound().
    • KaiserEngine

      KaiserEngine(Random random)
      Creates a new reign using a caller-supplied source of random values. Injecting a known sequence makes the BASIC calculations and random draw order testable without changing the game rules.
      Parameters:
      random - source supplying values in the interval [0, 1)
      Throws:
      NullPointerException - if random is null
  • Method Details

    • reset

      void reset()
      Restores all resources, annual figures and accumulated statistics to their starting values, and makes the game runnable again. The city starts with 95 inhabitants, 1000 hectares and 2800 dt of grain. Its initial report refers to a harvest of 3000 dt at three dt per hectare, 200 dt lost to rats and five immigrants who will arrive at the first year start.

      The supplied random source is retained rather than reseeded, so a replay continues drawing new values from the same source. Corresponds to BASIC lines 90–110 and is also used when the player starts again.

    • startNewRound

      public void startNewRound()
      Advances to the next report year, adds the previously calculated immigrants and applies the stored plague roll. A roll of zero or less halves the updated population, rounding down; plague deaths do not enter starvation statistics. Land ownership, harvest figures and rat losses remain unchanged for reporting.

      On entering year 11, the same population update still takes place, but the game becomes KaiserEngine.GameState.COMPLETED: the caller should report and evaluate the reign without offering another action phase. This method prepares the report data but does not print it. Corresponds to BASIC lines 220–270.

      Throws:
      IllegalStateException - if the game has already ended
    • prepareLandTrading

      public void prepareLandTrading()
      Draws the grain price for one hectare of land, uniformly from 17 through 26 dt, and stores it for both buying and selling during the current year. It does not replace the previous harvest yield or consume grain.

      The caller invokes this after reporting the previous harvest and before asking for a trade, matching BASIC line 310.

      Throws:
      IllegalStateException - if the game has already ended
    • buyLand

      public long buyLand(long hectares)
      Buys a whole-number quantity of land using the same validation, grain payment and abort handling as buyLand(BigDecimal).
      Parameters:
      hectares - hectares requested; zero skips buying and a negative value aborts
      Returns:
      the requested quantity, including zero or a negative abort request
      Throws:
      IllegalArgumentException - if the purchase costs more grain than is available
      IllegalStateException - if the game has already ended
    • buyLand

      public BigDecimal buyLand(BigDecimal hectares)
      Increases owned land by the requested hectares and pays for it from grain stocks at the current land price. Spending exactly all available grain is allowed. A zero quantity changes no resources and lets the caller offer selling instead. A negative quantity aborts the game without changing land or stocks.

      The caller must first establish the year's price with prepareLandTrading(). Corresponds to BASIC lines 320–334.

      Parameters:
      hectares - requested land area, which may be fractional
      Returns:
      the requested quantity; a negative return denotes an abort, not a purchase
      Throws:
      IllegalArgumentException - if the purchase costs more grain than is available
      IllegalStateException - if the game has already ended
    • sellLand

      public void sellLand(long hectares)
      Sells a whole-number quantity of land using the same price, ownership checks and abort handling as sellLand(BigDecimal).
      Parameters:
      hectares - hectares offered; zero skips selling and a negative value aborts
      Throws:
      IllegalArgumentException - if the quantity equals or exceeds owned land
      IllegalStateException - if the game has already ended
    • sellLand

      public void sellLand(BigDecimal hectares)
      Reduces owned land by the offered hectares and credits grain stocks at the current land price. The city must retain some land: selling exactly the owned area is rejected just like selling more. Zero leaves resources unchanged; a negative quantity aborts the game without a trade.

      The caller offers this action only when the player bought zero hectares and must first establish the year's price with prepareLandTrading(). Corresponds to BASIC lines 340–350, including the strict comparison at line 342.

      Parameters:
      hectares - offered land area, which may be fractional
      Throws:
      IllegalArgumentException - if the quantity equals or exceeds owned land
      IllegalStateException - if the game has already ended
    • feedToPopulation

      public void feedToPopulation(long grain)
      Allocates a whole-number amount of grain for feeding using the same stock checks, deferred starvation calculation and abort handling as feedToPopulation(BigDecimal).
      Parameters:
      grain - grain to distribute in dt; zero is valid and a negative value aborts
      Throws:
      IllegalArgumentException - if the allocation exceeds available grain stocks
      IllegalStateException - if the game has already ended
    • feedToPopulation

      public void feedToPopulation(BigDecimal grain)
      Removes the requested grain from stocks and remembers it as this year's food allocation. Population does not change immediately: at year end, every complete 20 dt will support one inhabitant. This separates BASIC's food variable Q from the later plague roll so that a random event cannot overwrite the allocation.

      Zero is a valid allocation, distributing all available stocks is allowed, and a negative quantity aborts without consuming grain. The caller invokes feeding once after trading and before planting. Corresponds to BASIC lines 411–430; the stored allocation is evaluated at line 540.

      Parameters:
      grain - grain to distribute in dt, which may be fractional
      Throws:
      IllegalArgumentException - if the allocation exceeds available grain stocks
      IllegalStateException - if the game has already ended
    • cultivate

      public void cultivate(long hectares)
      Plants a whole-number area and processes the harvest using the same resource checks, random draws and abort handling as cultivate(BigDecimal).
      Parameters:
      hectares - area to plant; zero still processes the season and a negative value aborts
      Throws:
      IllegalArgumentException - if the land, seed or worker limits are violated
      IllegalStateException - if the game has already ended
    • cultivate

      public void cultivate(BigDecimal hectares)
      Validates the planted area, consumes seed grain and processes this year's harvest and rat damage. For a positive area, the city must own at least that much land, have strictly more grain than floor(hectares / 2), and plant strictly fewer than ten hectares per inhabitant. Validation failures change no resources and consume no random values.

      After consuming the seed, a roll from one through five determines harvest yield per hectare. A second such roll determines rat losses: even rolls remove floor(remaining stocks / roll) grain, while odd rolls cause no damage. Rat losses are deducted before the new harvest is added. A third roll is retained as the factor for the year-end immigration calculation.

      Planting zero bypasses resource checks and seed consumption but still performs all three draws and stock updates, with a harvest of zero. Negative input aborts without processing the season. Corresponds to BASIC lines 441–531.

      Parameters:
      hectares - area to plant, which may be fractional
      Throws:
      IllegalArgumentException - if the land, seed or worker limits are violated
      IllegalStateException - if the game has already ended
    • finishRoundAfterActions

      public void finishRoundAfterActions()
      Resolves the year's demographic consequences after trading, feeding and planting. Immigration for the next year is calculated from owned land, remaining grain, current population and the factor drawn during planting. The food allocation supports floor(foodAllocated / 20) inhabitants; only after calculating that number is next year's plague roll drawn.

      If food supports more people than currently live in the city, starvation deaths become zero, but population and accumulated starvation statistics remain unchanged. Otherwise, unsupported inhabitants count as starvation deaths. Losing more than 45 percent of the population immediately sets KaiserEngine.GameState.DISMISSED, without updating population or accumulated statistics.

      For a surviving reign, the running annual starvation percentage and total deaths are updated, and population is reduced to the supported number. Immigrants and any plague take effect only at the next year start; plague victims are never counted as starvation deaths. Corresponds to BASIC lines 533–556.

      Throws:
      IllegalStateException - if the game has already ended
    • getLandPerPerson

      public BigDecimal getLandPerPerson()
      Calculates owned hectares per current inhabitant without rounding the result to a whole number. Evaluation uses this ratio so fractional differences near the seven-, nine- and ten-hectare thresholds remain significant.
      Returns:
      land area divided by population, using the engine's decimal precision
    • getRegency

      public KaiserEngine.Regency getRegency()
      Classifies the reign using average annual starvation and current land per inhabitant, checking the worst applicable tier first. More than 33 percent average starvation or fewer than seven hectares per person is disastrous; more than ten percent or fewer than nine hectares is tyrannical; more than three percent or fewer than ten hectares is mediocre. Otherwise the reign is excellent. Threshold comparisons use unrounded values.

      This method only evaluates the current figures: it does not end the game, print a message or consume randomness. The caller normally uses it after the final report-year update. Corresponds to BASIC lines 880–896.

      Returns:
      the worst rating whose starvation or land condition applies
    • countDiscontentedResidents

      public BigDecimal countDiscontentedResidents()
      Draws the number of residents who would like to hang the ruler in the mediocre-reign message. The result is floor(population * 0.8 * randomValue), rather than a fixed 80 percent of the population. No population or resource figures are changed.

      Each call consumes a fresh random value. To preserve the BASIC draw order, the caller invokes this only when rendering that evaluation message, as at BASIC line 961.

      Returns:
      a non-negative, whole-number count of discontented residents
    • isGameOver

      public boolean isGameOver()
      Indicates whether the reign completed, the ruler was dismissed or play was aborted. All three terminal states prevent further annual updates and actions.
      Returns:
      true whenever the state is not KaiserEngine.GameState.RUNNING
    • abort

      public void abort()
      Marks the game as aborted without changing resources or demographic figures. Used for negative action quantities and exhausted console input. The caller is responsible for stopping the dialogue and displaying any closing message.