1 package de.aikiit.game.kaiser;
2
3 import lombok.Getter;
4
5 import java.math.BigDecimal;
6 import java.math.MathContext;
7 import java.math.RoundingMode;
8 import java.security.SecureRandom;
9 import java.util.Objects;
10 import java.util.Random;
11
12 /**
13 * Maintains the city's population, land, grain stocks and reign statistics, and
14 * applies the rules from KAISER.BAS (09.08.1992) without performing console I/O.
15 * The caller controls the dialogue and the order in which the player's actions
16 * are requested.
17 * <p>
18 * A year starts with {@link #startNewRound()}, which adds immigrants and applies
19 * any plague determined at the end of the previous year. After reporting that
20 * state, the caller invokes {@link #prepareLandTrading()}, offers buying or
21 * selling land, allocates food and processes planting. Finally,
22 * {@link #finishRoundAfterActions()} determines immigration and starvation and
23 * may dismiss the ruler. After ten action years, one further year-start update
24 * prepares the final report and marks the reign as completed.
25 * <p>
26 * BASIC's reused variables are deliberately separated here: Q is food allocated
27 * and later a plague roll; Y is harvest yield and later land price; C is several
28 * unrelated random factors. Quantities may be fractional. Explicit BASIC
29 * {@code INT} operations round down, while fractional statistics retain decimal
30 * precision. Negative action quantities abort the game; other invalid quantities
31 * are rejected before the action changes resources.
32 */
33 @Getter
34 public class KaiserEngine {
35 private static final MathContext PRECISION = MathContext.DECIMAL128;
36 private static final BigDecimal HUNDRED = BigDecimal.valueOf(100);
37
38 /** Describes whether further annual updates and player actions are permitted. */
39 public enum GameState {
40 /** The reign is in progress and the caller may advance the game. */
41 RUNNING,
42 /** The ten action years and the final year-start update have completed. */
43 COMPLETED,
44 /** More than 45 percent of the population starved in one year. */
45 DISMISSED,
46 /** The player or console input ended the game before completion. */
47 ABORTED
48 }
49
50 /** Final rating based on average starvation and land owned per inhabitant. */
51 public enum Regency {
52 /** Average starvation exceeds 33 percent, or land per person is below seven hectares. */
53 DISASTROUS,
54 /** Below the disastrous tier, but starvation exceeds 10 percent or land per person is below nine. */
55 TYRANNICAL,
56 /** Below the worse tiers, but starvation exceeds three percent or land per person is below ten. */
57 MEDIOCRE,
58 /** Average starvation is at most three percent and land per person is at least ten hectares. */
59 EXCELLENT
60 }
61
62 @Getter(lombok.AccessLevel.NONE)
63 private final Random random;
64 private int year;
65 private BigDecimal population;
66 private BigDecimal landArea;
67 private BigDecimal grainStocks;
68 private BigDecimal harvestYield;
69 private BigDecimal totalHarvest;
70 private BigDecimal ratLoss;
71 private BigDecimal immigrants;
72 private BigDecimal starvationDeaths;
73 private BigDecimal totalStarvationDeaths;
74 private BigDecimal averageStarvationPercentage;
75 private BigDecimal landPrice;
76 private BigDecimal foodAllocated;
77 private int plagueRoll;
78 private int immigrationFactor;
79 private boolean plagueOccurred;
80 private GameState state;
81
82 /**
83 * Creates a new reign with the BASIC starting resources and a secure random
84 * source for prices, harvests, rat losses, immigration and plague events.
85 * The first annual population update is deferred until {@link #startNewRound()}.
86 */
87 public KaiserEngine() {
88 this(new SecureRandom());
89 }
90
91 /**
92 * Creates a new reign using a caller-supplied source of random values. Injecting
93 * a known sequence makes the BASIC calculations and random draw order testable
94 * without changing the game rules.
95 *
96 * @param random source supplying values in the interval {@code [0, 1)}
97 * @throws NullPointerException if {@code random} is null
98 */
99 KaiserEngine(Random random) {
100 this.random = Objects.requireNonNull(random);
101 reset();
102 }
103
104 /**
105 * Restores all resources, annual figures and accumulated statistics to their
106 * starting values, and makes the game runnable again. The city starts with
107 * 95 inhabitants, 1000 hectares and 2800 dt of grain. Its initial report refers
108 * to a harvest of 3000 dt at three dt per hectare, 200 dt lost to rats and five
109 * immigrants who will arrive at the first year start.
110 * <p>
111 * The supplied random source is retained rather than reseeded, so a replay
112 * continues drawing new values from the same source. Corresponds to BASIC
113 * lines 90–110 and is also used when the player starts again.
114 */
115 void reset() {
116 year = 0;
117 population = BigDecimal.valueOf(95);
118 grainStocks = BigDecimal.valueOf(2800);
119 totalHarvest = BigDecimal.valueOf(3000);
120 harvestYield = BigDecimal.valueOf(3);
121 landArea = BigDecimal.valueOf(1000);
122 ratLoss = BigDecimal.valueOf(200);
123 immigrants = BigDecimal.valueOf(5);
124 starvationDeaths = BigDecimal.ZERO;
125 totalStarvationDeaths = BigDecimal.ZERO;
126 averageStarvationPercentage = BigDecimal.ZERO;
127 landPrice = BigDecimal.ZERO;
128 foodAllocated = BigDecimal.ZERO;
129 plagueRoll = 1;
130 immigrationFactor = 0;
131 plagueOccurred = false;
132 state = GameState.RUNNING;
133 }
134
135 /**
136 * Advances to the next report year, adds the previously calculated immigrants
137 * and applies the stored plague roll. A roll of zero or less halves the updated
138 * population, rounding down; plague deaths do not enter starvation statistics.
139 * Land ownership, harvest figures and rat losses remain unchanged for reporting.
140 * <p>
141 * On entering year 11, the same population update still takes place, but the
142 * game becomes {@link GameState#COMPLETED}: the caller should report and evaluate
143 * the reign without offering another action phase. This method prepares the
144 * report data but does not print it. Corresponds to BASIC lines 220–270.
145 *
146 * @throws IllegalStateException if the game has already ended
147 */
148 public void startNewRound() {
149 requireRunning();
150 year++;
151 population = population.add(immigrants);
152 plagueOccurred = plagueRoll <= 0;
153 if (plagueOccurred) {
154 population = floor(population.divide(BigDecimal.valueOf(2), PRECISION));
155 }
156 if (year == KaiserGame.MAX_ROUNDS + 1) {
157 state = GameState.COMPLETED;
158 }
159 }
160
161 /**
162 * Draws the grain price for one hectare of land, uniformly from 17 through 26 dt,
163 * and stores it for both buying and selling during the current year. It does not
164 * replace the previous harvest yield or consume grain.
165 * <p>
166 * The caller invokes this after reporting the previous harvest and before
167 * asking for a trade, matching BASIC line 310.
168 *
169 * @throws IllegalStateException if the game has already ended
170 */
171 public void prepareLandTrading() {
172 requireRunning();
173 landPrice = BigDecimal.valueOf((int) Math.floor(10 * random.nextDouble()) + 17);
174 }
175
176 /**
177 * Buys a whole-number quantity of land using the same validation, grain payment
178 * and abort handling as {@link #buyLand(BigDecimal)}.
179 *
180 * @param hectares hectares requested; zero skips buying and a negative value aborts
181 * @return the requested quantity, including zero or a negative abort request
182 * @throws IllegalArgumentException if the purchase costs more grain than is available
183 * @throws IllegalStateException if the game has already ended
184 */
185 public long buyLand(long hectares) {
186 buyLand(BigDecimal.valueOf(hectares));
187 return hectares;
188 }
189
190 /**
191 * Increases owned land by the requested hectares and pays for it from grain stocks
192 * at the current land price. Spending exactly all available grain is allowed.
193 * A zero quantity changes no resources and lets the caller offer selling instead.
194 * A negative quantity aborts the game without changing land or stocks.
195 * <p>
196 * The caller must first establish the year's price with
197 * {@link #prepareLandTrading()}. Corresponds to BASIC lines 320–334.
198 *
199 * @param hectares requested land area, which may be fractional
200 * @return the requested quantity; a negative return denotes an abort, not a purchase
201 * @throws IllegalArgumentException if the purchase costs more grain than is available
202 * @throws IllegalStateException if the game has already ended
203 */
204 public BigDecimal buyLand(BigDecimal hectares) {
205 requireRunning();
206 if (abortOnNegative(hectares)) {
207 return hectares;
208 }
209 BigDecimal price = landPrice.multiply(hectares);
210 if (price.compareTo(grainStocks) > 0) {
211 throw new IllegalArgumentException("Not Enough Supplies");
212 }
213 landArea = landArea.add(hectares);
214 grainStocks = grainStocks.subtract(price);
215 return hectares;
216 }
217
218 /**
219 * Sells a whole-number quantity of land using the same price, ownership checks
220 * and abort handling as {@link #sellLand(BigDecimal)}.
221 *
222 * @param hectares hectares offered; zero skips selling and a negative value aborts
223 * @throws IllegalArgumentException if the quantity equals or exceeds owned land
224 * @throws IllegalStateException if the game has already ended
225 */
226 public void sellLand(long hectares) {
227 sellLand(BigDecimal.valueOf(hectares));
228 }
229
230 /**
231 * Reduces owned land by the offered hectares and credits grain stocks at the
232 * current land price. The city must retain some land: selling exactly the owned
233 * area is rejected just like selling more. Zero leaves resources unchanged;
234 * a negative quantity aborts the game without a trade.
235 * <p>
236 * The caller offers this action only when the player bought zero hectares and
237 * must first establish the year's price with {@link #prepareLandTrading()}.
238 * Corresponds to BASIC lines 340–350, including the strict comparison at line 342.
239 *
240 * @param hectares offered land area, which may be fractional
241 * @throws IllegalArgumentException if the quantity equals or exceeds owned land
242 * @throws IllegalStateException if the game has already ended
243 */
244 public void sellLand(BigDecimal hectares) {
245 requireRunning();
246 if (abortOnNegative(hectares)) {
247 return;
248 }
249 if (hectares.compareTo(landArea) >= 0) {
250 throw new IllegalArgumentException("Not Enough Land");
251 }
252 landArea = landArea.subtract(hectares);
253 grainStocks = grainStocks.add(landPrice.multiply(hectares));
254 }
255
256 /**
257 * Allocates a whole-number amount of grain for feeding using the same stock
258 * checks, deferred starvation calculation and abort handling as
259 * {@link #feedToPopulation(BigDecimal)}.
260 *
261 * @param grain grain to distribute in dt; zero is valid and a negative value aborts
262 * @throws IllegalArgumentException if the allocation exceeds available grain stocks
263 * @throws IllegalStateException if the game has already ended
264 */
265 public void feedToPopulation(long grain) {
266 feedToPopulation(BigDecimal.valueOf(grain));
267 }
268
269 /**
270 * Removes the requested grain from stocks and remembers it as this year's food
271 * allocation. Population does not change immediately: at year end, every complete
272 * 20 dt will support one inhabitant. This separates BASIC's food variable Q from
273 * the later plague roll so that a random event cannot overwrite the allocation.
274 * <p>
275 * Zero is a valid allocation, distributing all available stocks is allowed, and
276 * a negative quantity aborts without consuming grain. The caller invokes feeding
277 * once after trading and before planting. Corresponds to BASIC lines 411–430;
278 * the stored allocation is evaluated at line 540.
279 *
280 * @param grain grain to distribute in dt, which may be fractional
281 * @throws IllegalArgumentException if the allocation exceeds available grain stocks
282 * @throws IllegalStateException if the game has already ended
283 */
284 public void feedToPopulation(BigDecimal grain) {
285 requireRunning();
286 if (abortOnNegative(grain)) {
287 return;
288 }
289 if (grain.compareTo(grainStocks) > 0) {
290 throw new IllegalArgumentException("Not Enough in Stock");
291 }
292 foodAllocated = grain;
293 grainStocks = grainStocks.subtract(grain);
294 }
295
296 /**
297 * Plants a whole-number area and processes the harvest using the same resource
298 * checks, random draws and abort handling as {@link #cultivate(BigDecimal)}.
299 *
300 * @param hectares area to plant; zero still processes the season and a negative value aborts
301 * @throws IllegalArgumentException if the land, seed or worker limits are violated
302 * @throws IllegalStateException if the game has already ended
303 */
304 public void cultivate(long hectares) {
305 cultivate(BigDecimal.valueOf(hectares));
306 }
307
308 /**
309 * Validates the planted area, consumes seed grain and processes this year's
310 * harvest and rat damage. For a positive area, the city must own at least that
311 * much land, have strictly more grain than {@code floor(hectares / 2)}, and
312 * plant strictly fewer than ten hectares per inhabitant. Validation failures
313 * change no resources and consume no random values.
314 * <p>
315 * After consuming the seed, a roll from one through five determines harvest
316 * yield per hectare. A second such roll determines rat losses: even rolls remove
317 * {@code floor(remaining stocks / roll)} grain, while odd rolls cause no damage.
318 * Rat losses are deducted before the new harvest is added. A third roll is
319 * retained as the factor for the year-end immigration calculation.
320 * <p>
321 * Planting zero bypasses resource checks and seed consumption but still performs
322 * all three draws and stock updates, with a harvest of zero. Negative input
323 * aborts without processing the season. Corresponds to BASIC lines 441–531.
324 *
325 * @param hectares area to plant, which may be fractional
326 * @throws IllegalArgumentException if the land, seed or worker limits are violated
327 * @throws IllegalStateException if the game has already ended
328 */
329 public void cultivate(BigDecimal hectares) {
330 requireRunning();
331 if (abortOnNegative(hectares)) {
332 return;
333 }
334 BigDecimal plantedArea = hectares;
335 BigDecimal seed = plantedArea.divide(BigDecimal.valueOf(2), 0, RoundingMode.FLOOR);
336 if (hectares.signum() != 0) {
337 if (plantedArea.compareTo(landArea) > 0) {
338 throw new IllegalArgumentException("You cannot cultivate more area than you have.");
339 }
340 // These two comparisons are strictly '<' in the printed BASIC.
341 if (seed.compareTo(grainStocks) >= 0) {
342 throw new IllegalArgumentException("You cannot cultivate more than you have.");
343 }
344 if (plantedArea.compareTo(population.multiply(BigDecimal.TEN)) >= 0) {
345 throw new IllegalArgumentException("Not enough workers available.");
346 }
347 grainStocks = grainStocks.subtract(seed);
348 }
349
350 harvestYield = BigDecimal.valueOf(rollOneToFive());
351 totalHarvest = plantedArea.multiply(harvestYield);
352 int ratRoll = rollOneToFive();
353 // Line 522 skips damage for odd C; only even rolls cause rat losses.
354 ratLoss = ratRoll % 2 == 0
355 ? grainStocks.divide(BigDecimal.valueOf(ratRoll), 0, RoundingMode.FLOOR)
356 : BigDecimal.ZERO;
357 grainStocks = grainStocks.subtract(ratLoss).add(totalHarvest);
358 immigrationFactor = rollOneToFive();
359 }
360
361 /**
362 * Resolves the year's demographic consequences after trading, feeding and
363 * planting. Immigration for the next year is calculated from owned land,
364 * remaining grain, current population and the factor drawn during planting.
365 * The food allocation supports {@code floor(foodAllocated / 20)} inhabitants;
366 * only after calculating that number is next year's plague roll drawn.
367 * <p>
368 * If food supports more people than currently live in the city, starvation
369 * deaths become zero, but population and accumulated starvation statistics
370 * remain unchanged. Otherwise, unsupported inhabitants count as starvation
371 * deaths. Losing more than 45 percent of the population immediately sets
372 * {@link GameState#DISMISSED}, without updating population or accumulated statistics.
373 * <p>
374 * For a surviving reign, the running annual starvation percentage and total
375 * deaths are updated, and population is reduced to the supported number.
376 * Immigrants and any plague take effect only at the next year start; plague
377 * victims are never counted as starvation deaths. Corresponds to BASIC lines 533–556.
378 *
379 * @throws IllegalStateException if the game has already ended
380 */
381 public void finishRoundAfterActions() {
382 requireRunning();
383 BigDecimal immigrationNumerator = BigDecimal.valueOf(immigrationFactor)
384 .multiply(BigDecimal.valueOf(20).multiply(landArea).add(grainStocks));
385 immigrants = immigrationNumerator.divide(population.multiply(HUNDRED), 0, RoundingMode.FLOOR)
386 .add(BigDecimal.ONE);
387 BigDecimal supportedPopulation = foodAllocated.divide(BigDecimal.valueOf(20), 0, RoundingMode.FLOOR);
388 plagueRoll = (int) Math.floor(10 * random.nextDouble() - 0.3);
389
390 if (population.compareTo(supportedPopulation) < 0) {
391 // BASIC jumps through line 210: D=0, without updating P1 or D1.
392 starvationDeaths = BigDecimal.ZERO;
393 return;
394 }
395 starvationDeaths = population.subtract(supportedPopulation);
396 if (starvationDeaths.compareTo(population.multiply(new BigDecimal("0.45"))) > 0) {
397 state = GameState.DISMISSED;
398 return;
399 }
400 averageStarvationPercentage = averageStarvationPercentage.multiply(BigDecimal.valueOf(year - 1L))
401 .add(starvationDeaths.multiply(HUNDRED).divide(population, PRECISION))
402 .divide(BigDecimal.valueOf(year), PRECISION);
403 population = supportedPopulation;
404 totalStarvationDeaths = totalStarvationDeaths.add(starvationDeaths);
405 }
406
407 /**
408 * Calculates owned hectares per current inhabitant without rounding the result
409 * to a whole number. Evaluation uses this ratio so fractional differences near
410 * the seven-, nine- and ten-hectare thresholds remain significant.
411 *
412 * @return land area divided by population, using the engine's decimal precision
413 */
414 public BigDecimal getLandPerPerson() {
415 return landArea.divide(population, PRECISION);
416 }
417
418 /**
419 * Classifies the reign using average annual starvation and current land per
420 * inhabitant, checking the worst applicable tier first. More than 33 percent
421 * average starvation or fewer than seven hectares per person is disastrous;
422 * more than ten percent or fewer than nine hectares is tyrannical; more than
423 * three percent or fewer than ten hectares is mediocre. Otherwise the reign
424 * is excellent. Threshold comparisons use unrounded values.
425 * <p>
426 * This method only evaluates the current figures: it does not end the game,
427 * print a message or consume randomness. The caller normally uses it after
428 * the final report-year update. Corresponds to BASIC lines 880–896.
429 *
430 * @return the worst rating whose starvation or land condition applies
431 */
432 public Regency getRegency() {
433 BigDecimal landPerPerson = getLandPerPerson();
434 if (averageStarvationPercentage.compareTo(BigDecimal.valueOf(33)) > 0
435 || landPerPerson.compareTo(BigDecimal.valueOf(7)) < 0) {
436 return Regency.DISASTROUS;
437 }
438 if (averageStarvationPercentage.compareTo(BigDecimal.TEN) > 0
439 || landPerPerson.compareTo(BigDecimal.valueOf(9)) < 0) {
440 return Regency.TYRANNICAL;
441 }
442 if (averageStarvationPercentage.compareTo(BigDecimal.valueOf(3)) > 0
443 || landPerPerson.compareTo(BigDecimal.TEN) < 0) {
444 return Regency.MEDIOCRE;
445 }
446 return Regency.EXCELLENT;
447 }
448
449 /**
450 * Draws the number of residents who would like to hang the ruler in the
451 * mediocre-reign message. The result is
452 * {@code floor(population * 0.8 * randomValue)}, rather than a fixed 80 percent
453 * of the population. No population or resource figures are changed.
454 * <p>
455 * Each call consumes a fresh random value. To preserve the BASIC draw order,
456 * the caller invokes this only when rendering that evaluation message, as
457 * at BASIC line 961.
458 *
459 * @return a non-negative, whole-number count of discontented residents
460 */
461 public BigDecimal countDiscontentedResidents() {
462 return floor(population.multiply(new BigDecimal("0.8"))
463 .multiply(BigDecimal.valueOf(random.nextDouble())));
464 }
465
466 /**
467 * Indicates whether the reign completed, the ruler was dismissed or play was
468 * aborted. All three terminal states prevent further annual updates and actions.
469 *
470 * @return {@code true} whenever the state is not {@link GameState#RUNNING}
471 */
472 public boolean isGameOver() {
473 return state != GameState.RUNNING;
474 }
475
476 /**
477 * Marks the game as aborted without changing resources or demographic figures.
478 * Used for negative action quantities and exhausted console input. The caller
479 * is responsible for stopping the dialogue and displaying any closing message.
480 */
481 public void abort() {
482 state = GameState.ABORTED;
483 }
484
485 /**
486 * Applies the shared BASIC rule that a negative action quantity ends the game
487 * instead of requesting another quantity. Non-negative values are left for
488 * the action's normal validation.
489 *
490 * @param input quantity supplied to a player action
491 * @return whether the game was aborted because the quantity was negative
492 */
493 private boolean abortOnNegative(BigDecimal input) {
494 if (input.signum() < 0) {
495 abort();
496 return true;
497 }
498 return false;
499 }
500
501 /**
502 * Prevents an annual update or player action from modifying an ended reign.
503 * This checks the terminal state, not the ordering of actions within a year;
504 * the caller remains responsible for that order.
505 *
506 * @throws IllegalStateException if the game has completed, dismissed the ruler or been aborted
507 */
508 private void requireRunning() {
509 if (isGameOver()) {
510 throw new IllegalStateException("The game has ended.");
511 }
512 }
513
514 /**
515 * Consumes one random value and converts it to the inclusive range one through
516 * five, matching the BASIC subroutine used for harvest, rat and immigration rolls.
517 *
518 * @return a uniformly distributed integer from one through five
519 */
520 private int rollOneToFive() {
521 return (int) Math.floor(random.nextDouble() * 5) + 1;
522 }
523
524 /**
525 * Implements BASIC's {@code INT} operation by rounding toward negative infinity,
526 * not toward zero or to the nearest integer.
527 *
528 * @param value number whose fractional part is to be rounded down
529 * @return the greatest integer less than or equal to {@code value}, with scale zero
530 */
531 private static BigDecimal floor(BigDecimal value) {
532 return value.setScale(0, RoundingMode.FLOOR);
533 }
534 }