Skip to content

Commit

Permalink
Docs: Javadoc
Browse files Browse the repository at this point in the history
  • Loading branch information
tommyah committed May 26, 2026
1 parent f7ae9ab commit fd78a3f
Show file tree
Hide file tree
Showing 3 changed files with 131 additions and 111 deletions.
57 changes: 42 additions & 15 deletions src/main/java/edu/ntnu/idi/idatt2003/g40/mappe/model/SaveGame.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,10 @@
/**
* Represents one save entry for the game.
*
* <p>
* Holds the display name, current balance, starting capital,
* <p>Holds the display name, current balance, starting capital,
* (optionally) the path to a custom stock data file, the in-game week,
* the list of owned shares, the list of committed transactions, and
* the current state of the exchange stocks for a single saved game.
* </p>
* the current state of the exchange stocks for a single saved game.</p>
*/
public class SaveGame {

Expand Down Expand Up @@ -96,7 +94,19 @@ public SaveGame(final String name,

/**
* Overloaded constructor that converts a List of Floats to BigDecimals.
* Helps your JSON parser map the array smoothly on load.
*
* <p>Used by JSON parser to map array</p>
*
* @param name the display name of the save.
* @param balance the current balance value.
* @param startingCapital the starting capital chosen on creation.
* @param stockDataPath absolute path to a custom stock data file,
* or {@code null} to use the default file.
* @param week the in-game week when the save was written.
* @param ownedShares the shares the player owned (may be null; treated as empty).
* @param transactions the committed transactions (may be null; treated as empty).
* @param exchangeStocks the current list of stocks from the exchange (may be null; treated as empty).
* @param dummyFlagForOverloading sample dummy flag used for overload.
*/
public SaveGame(final String name,
final double balance,
Expand All @@ -115,7 +125,17 @@ public SaveGame(final String name,
}

/**
* Legacy backward-compatible constructor matching your previous full configuration.
* Backwards-compatible overload used in a previous implementation.
*
* @param name the display name of the save.
* @param balance the current balance value.
* @param startingCapital the starting capital chosen on creation.
* @param stockDataPath absolute path to a custom stock data file,
* or {@code null} to use the default file.
* @param week the in-game week when the save was written.
* @param ownedShares the shares the player owned (may be null; treated as empty).
* @param transactions the committed transactions (may be null; treated as empty).
* @param exchangeStocks the current list of stocks from the exchange (may be null; treated as empty).
*/
public SaveGame(final String name,
final double balance,
Expand All @@ -129,7 +149,16 @@ public SaveGame(final String name,
}

/**
* Legacy backward-compatible constructor matching your previous configuration.
* Backwards-compatible overload used in a previous implementation.
*
* @param name the display name of the save.
* @param balance the current balance value.
* @param startingCapital the starting capital chosen on creation.
* @param stockDataPath absolute path to a custom stock data file,
* or {@code null} to use the default file.
* @param week the in-game week when the save was written.
* @param ownedShares the shares the player owned (may be null; treated as empty).
* @param transactions the committed transactions (may be null; treated as empty).
*/
public SaveGame(final String name,
final double balance,
Expand All @@ -143,6 +172,11 @@ public SaveGame(final String name,

/**
* Convenience constructor matching the original format used by the create-game flow.
* @param name the display name of the save.
* @param balance the current balance value.
* @param startingCapital the starting capital chosen on creation.
* @param stockDataPath absolute path to a custom stock data file,
* or {@code null} to use the default file.
*/
public SaveGame(final String name,
final double balance,
Expand All @@ -151,13 +185,6 @@ public SaveGame(final String name,
this(name, balance, startingCapital, stockDataPath, 1, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
}

/**
* Convenience constructor matching the legacy "name + balance" format.
*/
public SaveGame(final String name, final double balance) {
this(name, balance, balance, null, 1, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
}

/**
* Getter method for the name.
*
Expand Down Expand Up @@ -239,4 +266,4 @@ public List<TransactionData> getTransactions() {
public List<Stock> getExchangeStocks() {
return exchangeStocks;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import edu.ntnu.idi.idatt2003.g40.mappe.service.event.EventPublisher;
import edu.ntnu.idi.idatt2003.g40.mappe.service.event.EventSubscriber;
import edu.ntnu.idi.idatt2003.g40.mappe.service.event.EventType;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
Expand All @@ -26,16 +25,44 @@

/**
* Service that applies a {@link SaveGame} to the active {@link Player} and {@link Exchange}.
*
* <p>Calls events of type </p>
*/
public final class GameStateLoader implements EventSubscriber, EventPublisher {

/**
* Local reference to player.
* */
private final Player player;
private Exchange exchange; // Non-final to allow runtime context swaps

/**
* Local reference to exchange.
* */
private Exchange exchange;

/**
* Local reference to event manager.
* */
private final EventManager eventManager;

/**
* Baseline prices of symbols.
* */
private final Map<String, BigDecimal> baselinePrices;

/**
* Currently active save.
* */
private SaveGame activeSave;

/**
* Constructor.
*
* @param player player object.
* @param exchange exchange.
* @param stockList list of stocks for the game state.
* @param eventManager the event manager instance.
* */
public GameStateLoader(final Player player,
final Exchange exchange,
final List<Stock> stockList,
Expand All @@ -51,7 +78,9 @@ public GameStateLoader(final Player player,
}

/**
* Updates the runtime exchange reference when loading a file custom configuration.
* Setter method for exchange.
*
* @param dynamicExchange new exchange.
*/
public void setExchange(final Exchange dynamicExchange) {
if (dynamicExchange != null) {
Expand All @@ -78,25 +107,12 @@ public Player getPlayer() {
}

/**
* Refreshes the internal baseline pricing snapshot map configuration.
*/
public void setBaseStocks(final List<Stock> stockList) {
if (stockList != null) {
this.baselinePrices.clear();
this.baselinePrices.putAll(captureBaseline(stockList));
}
}

public SaveGame getActiveSave() {
return activeSave;
}

/**
* Builds a fresh {@link SaveGame} snapshot, passing along the current exchange state.
* Builds a new {@link SaveGame} snapshot,
* passing along the current exchange state.
*
* @return {@link SaveGame} object.
*/
public SaveGame snapshotActiveSave() {
// Drop the activeSave == null early return entirely so brand new games can be saved!

List<OwnedShareData> shares = new ArrayList<>();
for (Share s : player.getPortfolio().getShares()) {
shares.add(new OwnedShareData(
Expand All @@ -116,7 +132,6 @@ public SaveGame snapshotActiveSave() {
t.getWeek()));
}

// Pull the name path configs safely using the live active models
String saveName = (activeSave != null) ? activeSave.getName() : player.getName();
double startingCap = (activeSave != null) ? activeSave.getStartingCapital() : player.getStartingMoney().doubleValue();
String stockPath = (activeSave != null) ? activeSave.getStockDataPath() : null;
Expand Down Expand Up @@ -148,40 +163,42 @@ public <T> void invoke(final EventData<T> data, final EventManager manager) {
manager.invokeEvent(data);
}

/**
* Applies a save.
*
* <p>If save includes valid stocks, uses them. If not,
* uses fallback stocks (default data). </p>
*
* <p>Clears and rebuilds exchange, player, transactions,
* portfolio and net-worth history of player.</p>
*
* @param save save to apply.
* */
private void applySave(final SaveGame save) {
System.out.println("[loader] applySave: name=" + save.getName());

// 1. Determine baseline context: use the save file's embedded stocks if present,
// otherwise fall back to the system's current baseline configuration.
Map<String, BigDecimal> activeBaseline;
if (save.getExchangeStocks() != null && !save.getExchangeStocks().isEmpty()) {
activeBaseline = captureBaseline(save.getExchangeStocks());

// Re-initialize exchange's stock collection if it has changed structurally
this.exchange.updateStockPool(save.getExchangeStocks());
} else {
activeBaseline = this.baselinePrices;
}

// Reset exchange simulation state
exchange.resetStocksTo(activeBaseline);
exchange.setWeek(1);

// 2. Clear out player fields
Portfolio portfolio = player.getPortfolio();
portfolio.clear();
TransactionArchive archive = player.getTransactionArchive();
archive.clear();
player.setMoney(BigDecimal.valueOf(save.getStartingCapital()));
player.refreshProperties();

// 3. Replay history steps
int targetWeek = Math.max(1, save.getWeek());
while (exchange.getWeek() < targetWeek) {
exchange.advance();
}

// 4. Re-populate portfolio balances
for (OwnedShareData od : save.getOwnedShares()) {
if (!exchange.hasStock(od.getSymbol())) {
System.err.println("Skipping unknown stock from save: " + od.getSymbol());
Expand All @@ -191,7 +208,6 @@ private void applySave(final SaveGame save) {
portfolio.addShare(new Share(stock, od.getQuantity(), od.getPurchasePrice()));
}

// 5. Build financial histories
for (TransactionData td : save.getTransactions()) {
if (!exchange.hasStock(td.getSymbol())) {
System.err.println("Skipping transaction with unknown stock: " + td.getSymbol());
Expand All @@ -208,10 +224,8 @@ private void applySave(final SaveGame save) {
archive.add(transaction);
}

// 6 & 7. Finalize state adjustments
player.setMoney(BigDecimal.valueOf(save.getBalance()));

// Explicitly restore the saved net worth timeline history array
if (save.getNetWorthHistory() != null) {
player.setNetWorthHistory(save.getNetWorthHistory());
} else {
Expand All @@ -223,11 +237,18 @@ private void applySave(final SaveGame save) {
this.activeSave = save;
}

/**
* Creates a new map keyed by stock symbol and valued by latest stock price.
*
* @param stocks stocks to use when creating map.
*
* @return map keyed with stock symbol and valued with stock price.
* */
private static Map<String, BigDecimal> captureBaseline(final List<Stock> stocks) {
Map<String, BigDecimal> snapshot = new HashMap<>();
for (Stock s : stocks) {
snapshot.put(s.getSymbol(), s.getSalesPrice());
}
return snapshot;
}
}
}
Loading

0 comments on commit fd78a3f

Please sign in to comment.