簡體   English   中英

如何在Java中加載游戲,又如何返回游戲原狀?

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

首先,我想說我在Java中使用swing是比較新的東西。 我可以像在游戲中那樣做揮桿動作,但是我不確定我是否真的了解幕后發生的事情。 因此,我開始使用Java開發類似Civilization的游戲,並且取得了不錯的進步。 我想把注意力轉移到保存游戲並重新加載上。 但是,我為此遇到了一些麻煩。 因此,我做了一些研究,發現了使對象可序列化並從那里保存/加載的知識。 效果很好,我可以保存我的游戲並加載它。 問題是,所有內容再次出現在屏幕上(地形圖塊,單位,HUD),但似乎存儲在我的某些對象中的數據已重新設置為其初始化點。 例如,我可以在X方向上在圖塊41上結束,但是在加載游戲時會將其設置回0。

關於如何設置游戲的簡要說明:我有一個Main類,它創建一個新的Window對象。 Window對象本質上是一個JFrame,其中包含按鈕信息和Panel類,Panel類只是繪制游戲的JPanel。游戲中發生的所有事情都在JPanel中創建。 我對編程並不陌生,我是計算材料科學家,但是對Java編寫游戲還是陌生的,我覺得自己犯了一個非常簡單的錯誤。 我將在下面發布JFrame和JPanel(一部分,它很長)。

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();        
}

}


小組課程的一部分

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);
        }           
    }                       
}

任何幫助將不勝感激!

編輯:這是實際加載和保存游戲的類。

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;       
    }
}

好的,所以我做了更多的挖掘工作,本質上講,在將序列化用作保存方法時,我不應該使用靜態變量,因為靜態變量不是GamePanel對象而是類的一部分,因此當save方法保存對象時,它不會實際上並不會保存任何靜態變量。 我做了保存非靜態變量所需的所有變量,並且一切正常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM