Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package nl.rug.oop.rpg;
- import java.io.*;
- import java.util.Scanner;
- /**
- * Utility class for saving and loading.
- */
- public class SaveManager {
- /**
- * The directory where the saves are stored.
- */
- public static final String SAVED_GAMES_DIRECTORY = "savedgames";
- /**
- * The file extension for saves.
- */
- public static final String SAVE_FILE_EXTENSION = ".ser";
- /**
- * Saves the current state of the game.
- *
- * @param game The game object to be saved.
- * @param filename The name of the file.
- */
- public static void saveGame(Game game, String filename) {
- ensureDirectory();
- try (ObjectOutputStream out = new ObjectOutputStream(
- new FileOutputStream(getFullPath(filename)))) {
- out.writeObject(game);
- System.out.println("Quicksave successful!");
- } catch (IOException e) {
- System.err.println("Failed to save game: " + e.getMessage());
- }
- }
- /**
- * Loading a file.
- *
- * @param filename The name of the file.
- * @return A game object representing the loaded state.
- */
- public static Game loadGame(String filename) {
- try (ObjectInputStream in = new ObjectInputStream(
- new FileInputStream(getFullPath(filename)))) {
- System.out.println("Quickload successful!");
- return (Game) in.readObject();
- } catch (IOException | ClassNotFoundException e) {
- System.err.println("Failed to load game: " + e.getMessage());
- return null;
- }
- }
- /**
- * Displays a list of available saves for the user to pick.
- *
- * @param scanner scanner object to read user input.
- * @return the loaded game object.
- */
- public static Game promptAndLoadSave(Scanner scanner) {
- File folder = new File(SAVED_GAMES_DIRECTORY);
- File[] saves = folder.listFiles((dir, name) -> name.endsWith(SAVE_FILE_EXTENSION));
- if (saves == null || saves.length == 0) {
- System.out.println("No save files found.");
- return null;
- }
- System.out.println("Which file? (-1 : none)");
- for (int i = 0; i < saves.length; i++) {
- System.out.println("(" + i + ") " + saves[i].getName());
- }
- int choice = scanner.nextInt();
- if (choice >= 0 && choice < saves.length) {
- return loadGame(saves[choice].getName());
- }
- return null;
- }
- /**
- * Returns the full path of the file.
- *
- * @param filename The name of the file.
- * @return The full path of the file.
- */
- private static String getFullPath(String filename) {
- return SAVED_GAMES_DIRECTORY +
- File.separator +
- filename +
- (filename.endsWith(SAVE_FILE_EXTENSION) ? "" : SAVE_FILE_EXTENSION);
- }
- /**
- * Ensures that the directory exists.
- */
- private static void ensureDirectory() {
- File saveDir = new File(SAVED_GAMES_DIRECTORY);
- if (!saveDir.exists()) {
- saveDir.mkdir();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement