如何使用文件/对象输入流加载游戏

时间:2014-12-19 11:52:15

标签: java serialization load deserialization objectinputstream

我已经编写了save / Load方法(如果保存有效,但在调用saveGame()后文件'minesweepersavestate.ser'出现在我的项目文件夹中)时,不完全确定。我想尝试让负载工作,因为目前它似乎没有做任何事情。

以下是我的功能:

   public void saveGame(){

        GameBoard b = new GameBoard();
        try {
            System.out.println("Creating File/Object output stream...");
            FileOutputStream fileOut = new FileOutputStream("minesweepersavestate.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);

            System.out.println("Writing GameBoard Object...");
            out.writeObject(b);

            System.out.println("Save Successful...\n");
            out.close();
            fileOut.close();

        } catch(FileNotFoundException e) {
            System.out.println("no");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("no");
            e.printStackTrace();
        } 

    }


    public void loadBoard()
    {
        GameBoard b = null;
        try {

            System.out.println("Creating File/Object input stream...");

            FileInputStream fileIn = new FileInputStream("minesweepersavestate.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);

            System.out.println("Loading GameBoard Object...");
            b = (GameBoard)in.readObject();

            System.out.println("Load Successful...\n");
            in.close();
            fileIn.close();

        } catch (ClassNotFoundException e) {
            System.out.println("Class not found\n");
            e.printStackTrace();
        } catch(FileNotFoundException e) {
            System.out.println("File not found\n");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

如何更改此方法,以便在调用loadBoard()方法时,它会以保存状态恢复游戏?

编辑:

GameBoard Class:

public class GameBoard extends JFrame implements Serializable
{
//MENU ITEMS
private JFrame frame;
private JMenuBar menubar = new JMenuBar();
private JTable table;

//FIELDS USED FOR GAMEPLAY
private int x;
private int y;
private boolean mineTrue;
private boolean triedTrue;
private static int boardsize = 8; 
private  int numberOfMines = 10;
public static final int Empty = 0;
public static final int Mine = -1;
public static final int Flag = -2;
public static final int FMine = -3;
public static final int RevealedMine = -4;
public static final int RevealedEmpty = -5;
// SIZE OF BUTTONS
private int gridsize = 45;
// ARRAY FOR THE BUTTONS
private JButton[][] buttons;
private int[][] board;
//VARIABLE USED FOR LABELS
private static int noGamesPlayed = 0;
private static int noGamesWon = 0;
private int mine = 10;
private int minesLeft = 10;
private static int score = 1;
private static String playername;
// GAME STATUS
private boolean gamegoing = true;
// GAME LABELS

private JLabel space = new JLabel("");
private JTextField nameEnter = new JTextField("Enter name here: ");
private JButton saveName = new JButton("Play");
private JLabel namelabel = new JLabel("Player 1: ");
private JLabel scorelabel = new JLabel("0 points ");
private JLabel status = new JLabel("Game in Progress: ");
private JLabel gamesPlayed = new JLabel("Games Played: " + noGamesPlayed);
private JLabel gamesWon = new JLabel("Games Won : " + noGamesWon);
private JLabel noMines = new JLabel("Number of Mines: " + minesLeft);


/**
 * Constructor 
 */
public GameBoard() { }

/**
 *Making the game Frame
 */
private void makeFrame() { }

// MAKING THE GAME MENU BAR
public void makeMenuBar(){  
}   

public void setx(int pmeter) { }

public void sety(int pmeter) { }

public int getx() { }

public int gety() { }

public void settried(boolean paramBoolean) { }

public boolean gettried() { }

public void setmine(boolean paramBoolean) { }

public boolean getmine() { }

//ASSIGN MINES TO RANDOM LOCATION
public void assignmines() { }

// *********************************GAME CONTROLS************
private void quit() { }

//RESETS THE BOARD
public void reset() { }    

public void newGame() { }

public void biggerBoard() { }

public void changeDifficulty() { }

public void saveGame() { }


public void loadBoard() { }

// LOSING THE GAME ALERT
public void lose() { }

// WINNING THE GAME ALERT
public void win() { }

// UPDATING THE SCORE
public void updatescore() { }

public void gamesPlayed() { }

public void UpdateName() { }

public void updateGamesPlayed() { }

public void updateGamesWon() { }

//WHAT VALUES THE CHARACTER HAVE
static char whichCharacter(int value) { }

//This method shows how many mines are around the spot that was clicked
static int minesAround(int[][] board, int row, int col) { }

// This method takes in an x and y value and defines what should happen when the user clicks there. 
public void click(int rows, int cols) { }

//ACTION WHEN USER CLICKS ON A BUTTON INNER CLASS
private class MouseListener extends MouseAdapter {
    private int x = 0;
    private int y = 0;

    public MouseListener(int row, int col) { }

    public void mouseClicked(MouseEvent e) { }

}

}

1 个答案:

答案 0 :(得分:0)

您需要确保班级中的所有字段均为Serializable this tutorial建议。特别值得注意的是,课程要求为Serializable

  

请注意,要成功序列化的类,必须满足两个条件:

     

该类必须实现java.io.Serializable接口。

     

类中的所有字段都必须是可序列化的。如果字段不可序列化,则必须将其标记为瞬态。

这意味着您必须在Javadocs中为GameBoard类中的所有字段进行挖掘。例如,我在JFrame上进行了快速搜索,当涉及到JFrame时似乎有一点nuance 保存Serialization。当您检索已保存游戏的状态时,最好从头开始重新创建GUI,而不是依靠frame.setVisible(true);为您执行此操作。 This thread似乎也同意依靠Java为您恢复GUI并不是一个好主意,但提出了如何使其工作的建议:

  

一旦反序列化,您需要使用{{1}}

显示框架