Skip to content

Commit

Permalink
Docs: JavaDoc for save classes
Browse files Browse the repository at this point in the history
  • Loading branch information
tommyah committed May 26, 2026
1 parent fd78a3f commit a6e8218
Show file tree
Hide file tree
Showing 11 changed files with 194 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -610,21 +610,17 @@ private List<TransactionData> parseTransactionsArray(final String body) {
/**
* Parses a flat (one level deep) JSON object into a map.
*
* <p>
* Only supports string, number, boolean and null values for the
* <p>Only supports string, number, boolean and null values for the
* top-level entries (which is everything {@link SaveGame} and
* {@link OwnedShareData} / {@link TransactionData} need). Nested
* arrays and objects are skipped past with an empty-string value,
* since the array contents are read separately via
* {@link #extractArrayBody}. Returns {@code null} if the content
* can't be parsed.
* </p>
* can't be parsed.</p>
*
* <p>
* Values are returned as strings; {@code null} values are stored as
* <p>Values are returned as strings; {@code null} values are stored as
* an empty string so callers can distinguish "absent" from "null"
* using {@link Map#containsKey(Object)}.
* </p>
* using {@link Map#containsKey(Object)}.</p>
*
* @param content the raw file content.
* @return a map of field name to raw value, or {@code null}.
Expand Down Expand Up @@ -750,11 +746,9 @@ private int findStringEnd(final String s, final int start) {
* opening bracket / brace at {@code start}, accounting for quoted
* strings and nested structures. Returns -1 if no match is found.
*
* <p>
* Used by {@link #parseFlatJsonObject} to skip past nested arrays
* <p>Used by {@link #parseFlatJsonObject} to skip past nested arrays
* and objects whose content isn't needed at the top level (top-level
* arrays are read separately by {@link #extractArrayBody}).
* </p>
* arrays are read separately by {@link #extractArrayBody}).</p>
* */
private int findStructuredEnd(final String s, final int start) {
char open = s.charAt(start);
Expand Down Expand Up @@ -849,11 +843,9 @@ private String unquote(final String token) {
/**
* Sanitises a save name to a safe filesystem identifier.
*
* <p>
* All characters outside {@code [A-Za-z0-9_-]} are replaced with
* <p>All characters outside {@code [A-Za-z0-9_-]} are replaced with
* underscores. This keeps the on-disk file name predictable while
* preserving the original display name in the JSON content.
* </p>
* preserving the original display name in the JSON content.</p>
*/
private String sanitiseFileName(final String name) {
String trimmed = name.trim();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@
import edu.ntnu.idi.idatt2003.g40.mappe.service.event.EventManager;
import edu.ntnu.idi.idatt2003.g40.mappe.view.ViewController;
import edu.ntnu.idi.idatt2003.g40.mappe.view.ViewEnum;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
Expand All @@ -26,16 +24,12 @@
*
* <p>Extends {@link ViewController}.</p>
*
* <p>
* Handles the four interactions on the create-game screen: picking
* <p>Handles the four interactions on the create-game screen: picking
* the default stock data, choosing a custom stock data file, cancel
* (back to the play-game screen), and finally creating the save.
* </p>
* (back to the play-game screen), and finally creating the save.</p>
*
* <p>
* When a save is successfully written to disk a callback can be
* notified so the play-game view can refresh its save list.
* </p>
* <p>When a save is successfully written to disk a callback can be
* notified so the play-game view can refresh its save list.</p>
*/
public class CreateGameController extends ViewController<CreateGameView> {

Expand Down Expand Up @@ -114,7 +108,6 @@ public void setOnSaveCreated(final Runnable handler) {
protected void initInteractions() {
getViewElement().setOnAction(CreateGameActions.USE_DEFAULT_STOCKS, () -> {
try {
// Read the default stock resource pool to populate the initial exchange baseline
StockFileManager stockFileManager = new StockFileManager("sp500.csv");
StockFileParser stockFileParser = new StockFileParser();
List<Stock> defaultStocks = stockFileParser.getStocksFromStrings(stockFileManager.readFile());
Expand Down Expand Up @@ -206,10 +199,8 @@ private void handleCreateGame() {
}
}

// Safety check: ensure exchange baseline was built during choice selection loops
List<Stock> initialStocks = (this.exchange != null) ? this.exchange.getStocks() : List.of();

// Reconstruct utilizing the full array snapshot layout tracking parameter
SaveGame newSave = new SaveGame(
name,
capital,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,19 +220,21 @@ protected void initInteractions() {
});
}

/**
* Method for setting a new list of stocks for the view and controller.
*
* @param updatedStocks new list of stocks.
* */
public void handleStockPoolUpdate(final List<Stock> updatedStocks) {
if (updatedStocks == null || updatedStocks.isEmpty()) {
return;
}

// Synchronize our final referenced list tracking structure
this.stockList.clear();
this.stockList.addAll(updatedStocks);

// Rebuild the sidebar UI item buttons with the new stock identifiers
populateStockList(this.selectedFilter);

// Default active UI chart presentation view elements focus to the first stock
Stock firstStock = this.stockList.getFirst();
BigDecimal ownedAmount = this.player.getPortfolio()
.getTotalShareQuantityBySymbol(firstStock.getSymbol());
Expand All @@ -249,8 +251,6 @@ public void handleStockPoolUpdate(final List<Stock> updatedStocks) {
* */
@Override
public <T> void handleEvent(final EventData<T> data) {
System.out.println("[dashboard] STATE_RESET: shares in portfolio = "
+ player.getPortfolio().getShares().size());
populateStockList(selectedFilter);
if (!stockList.isEmpty()) {
Stock first = stockList.getFirst();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -577,29 +577,4 @@ private String formatShares(final float amount) {
String formatted = String.format(java.util.Locale.US, "%.3f", amount);
return formatted.replaceAll("0+$", "").replaceAll("\\.$", "");
}

/**
* Clears the sidebar and populates it with a new list of stock buttons,
* executing the provided configuration logic on each button.
*
* @param newStocks the new collection of {@link Stock} objects to display.
* @param clickLogic the controller logic to bind to each newly generated button.
*/
public void updateStockPool(final List<Stock> newStocks, final Consumer<Stock> clickLogic) {
if (newStocks == null || clickLogic == null) {
return;
}

// Clear the sidebar layout elements container completely
clearStockList();

// Generate fresh buttons for every stock inside the new collection pool
for (Stock stock : newStocks) {
String buttonText = stock.getSymbol() + " - " + stock.getCompany();
Button stockBtn = createStockButton(buttonText);

// Wire the interaction mapping back to the controller logic
setOnStockAction(stockBtn, stock, clickLogic);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import edu.ntnu.idi.idatt2003.g40.mappe.service.event.EventSubscriber;
import edu.ntnu.idi.idatt2003.g40.mappe.service.event.EventType;
import edu.ntnu.idi.idatt2003.g40.mappe.view.ViewController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -33,7 +32,8 @@ public SummaryController(final SummaryView viewElement,
super(viewElement, eventManager);
eventManager.addSubscriber(this, EventType.STATE_RESET);
eventManager.addSubscriber(this, EventType.PRE_LOAD_SAVE);
getViewElement().setBalance(player.getStartingMoney().floatValue(), player.getStartingMoney().floatValue());
getViewElement().setBalance(player.getStartingMoney().floatValue(),
player.getStartingMoney().floatValue());
}

@Override
Expand Down Expand Up @@ -113,13 +113,12 @@ public <T> void handleEvent(final EventData<T> data) {
return;
}

// STATE_RESET block
if (playerNetWorthHistory == null) {
playerNetWorthHistory = new ArrayList<>();
}

playerNetWorthHistory.clear();
if (player.getNetWorthHistory() != null && !player.getNetWorthHistory().isEmpty()) {
if (!player.getNetWorthHistory().isEmpty()) {
playerNetWorthHistory.addAll(player.getNetWorthHistory());
} else {
playerNetWorthHistory.add(player.getStartingMoney());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,11 @@ private int ownedQuantity(final String symbol) {
}

/**
* Refreshes the underlying tracking context references and triggers a complete
* rebuilding processing loop for the graphical marketplace card components.
* Refreshes the view element with updated context.
*
* @param updatedExchange the current active exchange engine.
* @param updatedPlayer the current active player profile context.
* @param freshStocks the new active collection pool of stocks.
* @param updatedExchange the current active exchange.
* @param updatedPlayer the current active player.
* @param freshStocks the new active collection of stocks.
*/
public void handleStockPoolUpdate(final Exchange updatedExchange,
final Player updatedPlayer,
Expand All @@ -128,12 +127,10 @@ public void handleStockPoolUpdate(final Exchange updatedExchange,
return;
}

// Synchronize engine references
this.exchange = updatedExchange;
this.player = updatedPlayer;
this.stockList = freshStocks;

// Push the changes down to the presentation layer view layout grid
getViewElement().updateStockPool(freshStocks);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -378,8 +378,7 @@ private Polyline buildMiniChart(final Stock stock) {
}

/**
* Replaces the entire underlying stock data collection pool and forces
* a full graphical UI re-render layout processing update loop.
* Re-renders the ui with a list of updated stocks.
*
* @param updatedStocks the fresh list of stocks parsed from the save file.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@ public void updateStockPool(final List<String> newSymbols) {
}
this.availableSymbols = List.copyOf(newSymbols);

// Regenerate the current round so symbols from a previous save don't linger on screen
generateRound();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,7 @@ private static final class Aggregate {
}

/**
* Updates the underlying tracking engine references and fully
* synchronizes the metric graphs to match the newly loaded save state.
* Updates the graphs and information of the page given a new exchange and player.
*
* @param updatedExchange the current active exchange engine.
* @param updatedPlayer the current active player context profile.
Expand All @@ -222,21 +221,14 @@ public void handleContextUpdate(final Exchange updatedExchange, final Player upd
this.balanceHistory = new ArrayList<>();
}

// 1. Clear the stale session data entirely
this.balanceHistory.clear();

// 2. Reconstruct the entire weekly history timeline directly from the
// loaded player/stock data if available, or fetch it from the save.
// If your Player model stores historical net worth, parse it here:
if (this.player.getNetWorthHistory() != null && !this.player.getNetWorthHistory().isEmpty()) {
if (!this.player.getNetWorthHistory().isEmpty()) {
this.balanceHistory.addAll(this.player.getNetWorthHistory());
} else {
// Fallback: If no history array exists, use the baseline points
this.balanceHistory.add(this.player.getStartingMoney());
this.balanceHistory.add(this.player.getNetWorth());
}

// 3. Flush completely recalculated asset structures to the UI
pushSnapshot();
}
}
9 changes: 8 additions & 1 deletion src/main/resources/saves/Halleluja.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,12 @@
"name": "Halleluja",
"balance": 1000650901.43,
"startingCapital": 10000.0,
"stockDataPath": null
"stockDataPath": null,
"week": 1,
"ownedShares": [],
"transactions": [],
"stocks": [
{ "symbol": "TOTA", "name": "Total badass1", "price": 136.80 },
{ "symbol": "LIBR", "name": "Libra avenger of worlds", "price": 19134.23 }
]
}
Loading

0 comments on commit a6e8218

Please sign in to comment.