简体   繁体   中英

How do I load a game in Java but also return to the state the game was in?

I'd like to start off by saying that I'm relatively new to working with swing in Java. I can make swing do things, like in gaming, but I'm not sure if I truly understand what's going on behind the scenes. So, I started working on a game, kind of like Civilization, in Java and I've made some decent progress. I wanted to turn my attention to saving the game and loading it back up. However, I've run into a bit of trouble with this. So I did some research and I found out about making an object serializable and saving/loading from there. That worked great, I can save my game and load it up. The issue is, everything appears on the screen again (Terrain tiles, units, HUD) but it seems that the data that was stored in some of my objects has been set back to its initialization point. For example, I can end on tile 41 in the X direction, but when I load the game it sets it back to 0.

A brief description of how I set the game up: I have a Main class that creates a new Window object. The Window object is essentially a JFrame that contains button information and a Panel class that is just the JPanel that the game gets painted in. Everything that happens in the game gets created in the JPanel. I'm not new to programming, I'm a computational Materials Scientist, but I'm new to writing games in Java, and I feel like I'm making a really simple mistake. I'll post the JFrame and JPanel (part of it, it's quite long) below.

Frame

public class GameWindow extends JFrame implements ActionListener
{
//ints
private int fCounter = 0;   

//timers
private Timer t;

//Panels
private GamePanel gamePanel;

//menu bars
private JMenuBar menuBar;

//menus
private JMenu fileMenu;

//menu items
private JMenuItem save; 
private JMenuItem load; 
private JMenuItem exit; 
private JMenuItem newGame;

//menu panels
private JPanel menuPanel;

//File objects  
private File file;

//File Chooser
private JFileChooser chooser;

//user objects
private Player humanPlayer;
private AI aIPlayer;
private FileActions fileActions;
//**************************************************************************constructor 
public GameWindow()
{
    //set specifications for frame
    super("New Game v 0.00: pre-Alpha");
    this.setResizable(false);
    setFocusable(true);     
    setSize(1600, 800);


    //creates a new menubar
    menuBar = new JMenuBar();

    //craetes a new file menu
    fileMenu = new JMenu("File");

    //creates the file options
    save = new JMenuItem("Save");
    save.addActionListener(this);
    load = new JMenuItem("Load");
    load.addActionListener(this);
    newGame = new JMenuItem("New Game");
    newGame.addActionListener(this);
    exit = new JMenuItem("Exit");
    exit.addActionListener(this);

    //adds file options to the file menu
    fileMenu.add(save);
    fileMenu.add(load);
    fileMenu.add(newGame);
    fileMenu.add(exit);

    //adds the file menu to the menubar
    menuBar.add(fileMenu);

    //establishes the menu panel as a new JPanel
    menuPanel = new JPanel();

    //adds the menu to the menubar
    menuPanel.add(menuBar);

    //sets user class objects
    humanPlayer = new Player();
    aIPlayer = new AI();
    fileActions = new FileActions();

    //panels
    gamePanel = new GamePanel();
    gamePanel.setSize(750, 750);
    gamePanel.setFocusable(true);
    addKeyListener(gamePanel);
    addMouseListener(gamePanel);
    addMouseMotionListener(gamePanel);
    setVisible(true);

    //adds panels to the frame with layout
    add(menuPanel, BorderLayout.EAST);
    add(gamePanel, BorderLayout.CENTER);    

    //add file choosers
    chooser = new JFileChooser();

    //adds file objects
    file = new File("");        

    //timers
    t = new Timer(1, this);
    t.start();  
}
@Override
public void actionPerformed(ActionEvent e)
{
    // TODO Auto-generated method stub
    //save a game
    if(e.getSource() == save)
    {
        //fCounter = chooser.showSaveDialog(this);
        //if(fCounter == JFileChooser.APPROVE_OPTION)
        //{
            //file = chooser.getSelectedFile(); 
            fileActions.addObject(gamePanel);       
            fileActions.saveGame();
        //}
    }
    //load a save file
    if(e.getSource() == load)
    {
        this.remove(gamePanel);

        gamePanel = fileActions.loadGame();

        this.add(gamePanel);
        gamePanel.setFocusable(true);
        addKeyListener(gamePanel);
        addMouseListener(gamePanel);
        addMouseMotionListener(gamePanel);
        add(gamePanel, BorderLayout.CENTER);
        setVisible(true);
    }
    //starts a new game
    if(e.getSource() == newGame)
    {
        //gamePanel = null;
        //gamePanel = new GamePanel();

        gamePanel.setNewGameSetup(true);
        gamePanel.setMainMenuView(false);

    }
    //exits the game
    if(e.getSource() == exit)
    {
        System.exit(0);
    }
    gamePanel.repaint();        
}

}


Part of the Panel Class

public class GamePanel extends JPanel  implements        
ActionListener,KeyListener,MouseListener,MouseMotionListener,Serializable
{
//globals
private static int mapHeight = 0;
private static int mapWidth= 0;
private static int currentMapHoriztonal= 0;
private static int currentMapVertical= 0;
private static int currentMouseMapHoriztonal= 0;
private static int currentMouseMapVertical= 0;
private static int turnNumber= 0;
private  int unitFocusNumber = -1;
private  int cityFocusNumber = -1;

private Terrain[][] terrain;
private ArrayList<Unit> playerUnits = new ArrayList<Unit>();
private ArrayList<City> playerCities = new ArrayList<City>();

private boolean terrainCreate = true;
private boolean mainMenu = true;
private boolean newGameSetup = false;
private boolean mapView = false;
private boolean mapSizeOptions = false;
private boolean playerTurn = true;
private boolean[] move = new boolean[4];

private Font mainMenuTitle = new Font("Algerian",Font.BOLD,75);
private Font mainMenuOptions = new Font("Calibri",Font.BOLD,15);

private Player player = new Player();

private FileActions fA;

private AI aI = new AI();

public GamePanel()
{

}
//getters
public int getMapHeight()
{
    return mapHeight;
}
public boolean getMapView()
{
    return mapView;
}
public Terrain[][] getTerrain()
{
    return terrain;
}


//setters
public void setMapHeight(int height)
{
    mapHeight = height;
}
public void setMapWidth(int width)
{
    mapWidth = width;
}
public void setMapView(boolean b)
{
    mapView = b;
}
public void setMainMenuView(boolean b)
{
    mainMenu = b;
}
public void setNewGameSetup(boolean b)
{
    newGameSetup = b;
}


//painters

//paints the game
public void paintComponent(Graphics g)
{       
    if(mainMenu == true)
    {
        paintMainMenu(g);
    }
    if(newGameSetup == true)
    {
        paintSetupScreen(g);
    }
    else if(mapView == true)
    {
        if(terrainCreate == true)
        {
            //sets the terrain
            terrain  = new Terrain[mapHeight][mapWidth];

            for(int i = 0; i < mapHeight; i++)
            {
                for(int j = 0; j < mapWidth; j++)
                {                   
                    terrain[i][j] = new Terrain(j,i,mapWidth,mapHeight);
                    terrain[i][j].setTerrain(j,i);
                }
            }
            for(int i = 0; i < 4; i++)
            {
                playerUnits.add(new Scout(75*i,75*i));
            }
            playerUnits.add(new Settler(75*9,75*8));
            playerUnits.add(new Settler(75*14,75*12));

            terrainCreate = false;
        }
        if(terrainCreate == false)
        {
            paintTerrain(g);
            paintCities(g);
            paintUnits(g);
            paintHud(g);
        }           
    }                       
}

Any help would be greatly appreciated!

Edit: Here's the class that actually loads and saves the game.

public class FileActions implements Serializable
{
    private ArrayList<Object> objects = new ArrayList<Object>();

    //setters
    public void addObject(Object o)
    {
        objects.add(o);
    }

    //getters

    public void saveGame()
    {
        try
        {  // Catch errors in I/O if necessary.
            // Open a file to write to, named SavedObj.sav.
            FileOutputStream saveFile=new FileOutputStream("NTT.sav");

            // Create an ObjectOutputStream to put objects into save file.
            ObjectOutputStream save = new ObjectOutputStream(saveFile);

            // Now we do the save.
            for(int i = 0; i < objects.size();i++)
            {
                save.writeObject(objects.get(i));
            }
            // Close the file.
            save.close(); // This also closes saveFile.
        }
        catch(Exception exc)
        {
            exc.printStackTrace(); // If there was an error, print the info.            
        }       
    }
    public GamePanel loadGame()
    {
        GamePanel stuff = new GamePanel();
        try
        {
            // Open file to read from, named SavedObj.sav.
            FileInputStream saveFile = new FileInputStream("NTT.sav");

            // Create an ObjectInputStream to get objects from save file.
            ObjectInputStream save = new ObjectInputStream(saveFile);           

             stuff = (GamePanel) save.readObject();

            // Close the file.
            save.close(); // This also closes saveFile.

        }
        catch(Exception exc)
        {
            exc.printStackTrace(); // If there was an error, print the info.
        }
        System.out.println(stuff);

        return stuff;       
    }
}

Okay, so i did some more digging, essentially I shouldn't use static variables when using serialization as the method of saving because the static variables are not part of the GamePanel object but the class, so when the save method saves the object it doesn't actually save whatever the static variables had become. I made all variables that I need to save non-static and everything works great

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM