No se puede escribir y leer archivos guardados del juego

B.brown:

Estoy teniendo problemas para escribir los datos de mi juego en un archivo y cargarlo para que pueda reanudar el juego desde el estado en que estaba cuando yo guardado de datos. He conseguido hasta ahora, pero los tiros consistentemente una excepción de puntero nulo. Cuando hago clic en SaveGame Puedo usar un escritor tamponada para escribir el valor de cadena de todos mis datos. entonces me carga el archivo mediante la lectura del archivo, no estoy seguro de cómo mostrar realmente los datos de lectura, pero antes de tratar de llegar tan lejos tengo que arreglar un saque de banda excepción de puntero nulo suceda. He tratado de escribir en el fichero de la que estoy bastante seguro en el camino correcto siendo así que no estoy seguro de por qué está haciendo esto.

Código


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;

public class LifeApplication extends JFrame implements Runnable, MouseListener, MouseMotionListener {

    private BufferStrategy strategy;
    private Graphics offscreenBuffer;
    private boolean gameState[][][]= new boolean[40][40][2];
    private int gameStateFrontBuffer = 0;
    private boolean isGameRunning = false;
    private boolean initialised;
    private static LoadSave loadSave;

    public LifeApplication()
    {
        Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        int x = screensize.width/2 - 400;
        int y = screensize.height/2 - 400;
        setBounds(x,y,800,800);
        setVisible(true);
        this.setTitle("Conway's Game of Life");

        createBufferStrategy(2);
        strategy = getBufferStrategy();
        offscreenBuffer = strategy.getDrawGraphics();

        addMouseListener(this);
        addMouseMotionListener(this);

        for(x = 0; x < 40; x++)
        {
            for(y = 0; y < 40; y++)
            {
                gameState[x][y][0] = gameState[x][y][1] = false;
            }
        }

        Thread t = new Thread(this);
        t.start();

        initialised = true;
    }

    @Override
    public void run()
    {
        while(true)
        {
            try{Thread.sleep(100);}
            catch(InterruptedException e){
                System.out.println("Something happened but dont worry");
            }

            if(isGameRunning)
                applyRules();

            this.repaint();
        }
    }

    private void applyRules()
    {
        int front = gameStateFrontBuffer;
        int back = (front +1)%2;

        for(int x = 0; x < 40; x++)
        {
            for(int y = 0; y < 40; y++)
            {
                int liveneighbours = 0;
                for(int xx = -1; xx <= 1; xx++)
                {
                    for(int yy = -1; yy <= 1; yy++)
                    {
                        if(xx!=0 || yy!=0)
                        {
                            int xxx = x+xx;
                            if(xxx < 0)
                                xxx=39;
                            else if(xxx > 39)
                                xxx = 0;
                            int yyy = y + yy;
                            if(yyy < 0)
                                yyy=39;
                            else if (yyy>39)
                                yyy=0;
                            if(gameState[xxx][yyy][front])
                                liveneighbours++;
                        }
                    }
                }

                if(gameState[x][y][front])
                {
                    if(liveneighbours < 2)
                        gameState[x][y][back] =false;
                    else if(liveneighbours < 4)
                        gameState[x][y][back] =true;
                    else
                        gameState[x][y][back] =false;
                }
                else
                {
                    if(liveneighbours == 3)
                        gameState[x][y][back] =true;
                    else
                        gameState[x][y][back] =false;
                }
            }
        }
        gameStateFrontBuffer = back;
    }

    private void randomiseGameState()
    {
        for(int x = 0; x < 40; x++)
        {
            for(int y = 0; y < 40; y++)
            {
                gameState[x][y][gameStateFrontBuffer] = (Math.random()< 0.25);
            }
        }
    }

        @Override
    public void mouseClicked(MouseEvent m)
    {

    }

    @Override
    public void mouseEntered(MouseEvent m)
    {

    }

    @Override
    public void mouseExited(MouseEvent m)
    {

    }

    @Override
    public void mousePressed(MouseEvent m)
    {
        if(!isGameRunning)
        {
            int x = m.getX();
            int y = m.getY();
            if(x >= 15 && x <= 85 && y >= 40 && y <= 70) {
                isGameRunning = true;
                return;
            }

            if(x >= 115 && x <= 215 && y >= 40 && y <= 70) {
                randomiseGameState();
                return;
            }

            if(x >= 245 && x <= 315 && y >= 40 && y <= 70){
                loadSave.saveGame();
            }
            if(x >= 345 && x <= 415 && y >= 40 && y <= 70){
                loadSave.loadGame();
                isGameRunning = true;
            }
        }

        int x = m.getX()/20;
        int y = m.getY()/20;

        gameState[x][y][gameStateFrontBuffer] = !gameState[x][y][gameStateFrontBuffer];

        this.repaint();
    }

    @Override
    public void mouseReleased(MouseEvent m)
    {

    }

    @Override
    public void mouseDragged(MouseEvent mouseEvent) {
        if(!isGameRunning) {
            int x = mouseEvent.getX();
            int y = mouseEvent.getY();
            try {
                if (gameState[x / 20][y / 20][gameStateFrontBuffer]) {
                    gameState[x / 20][y / 20][gameStateFrontBuffer] = !gameState[x / 20][y / 20][gameStateFrontBuffer];
                }
                if (!gameState[x / 20][y / 20][gameStateFrontBuffer]) {
                    gameState[x / 20][y / 20][gameStateFrontBuffer] = true;
                }
            }
            catch(ArrayIndexOutOfBoundsException e){
                System.out.println("Cant go there thats out of bounds");
            }
        }
    }

    @Override
    public void mouseMoved(MouseEvent mouseEvent) {

    }

    public void paint(Graphics g)
    {
        if(!initialised)
            return;

        g = offscreenBuffer;

        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 800, 800);

        g.setColor(Color.GREEN);
        g.fillRect(245, 40, 70, 30);
        g.setColor(Color.BLACK);
        g.drawString("Save", 252, 62);

        g.setColor(Color.GREEN);
        g.fillRect(345, 40, 70, 30);
        g.setColor(Color.BLACK);
        g.drawString("Load", 352, 62);


        g.setColor(Color.WHITE);
        for(int x = 0; x < 40; x++)
        {
            for(int y = 0; y < 40; y++)
            {
                if(gameState[x][y][gameStateFrontBuffer])
                    g.fillRect(x*20, y*20, 20, 20);
            }
        }

        if(!isGameRunning)
        {
            g.setColor(Color.GREEN);
            g.fillRect(15, 40, 70, 30);
            g.fillRect(115, 40, 100, 30);
            g.setFont(new Font("Times", Font.PLAIN, 24));
            g.setColor(Color.BLACK);
            g.drawString("Start", 22, 62);
            g.drawString("Random", 122, 62);
        }
        strategy.show();
    }

    public static void main(String[] args) {
        LifeApplication lifeApp = new LifeApplication();
    }

}


import java.io.*;

public class LoadSave {
    LifeApplication lifeApplication;

    public void saveGame() {

        String filename = "C:\\Users\\brads\\Desktop\\GameOfLife.txt";
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(filename));

            writer.write(String.valueOf(lifeApplication));
            writer.close();
        }
        catch (IOException e) {
            System.out.println("Cannot write to file");
        }
    }

    public void loadGame() {
        String line = null;
        String filename = "saveFile.txt";
        try {
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            do {
                try {
                    line = reader.readLine();

                } catch (IOException e) {
                    System.out.println("Cannot read from text file");
                }
            }
            while (line != null);
            reader.close();
        } catch (IOException e) {
        }
    }
}


Compañero :

No creo que va a crear la LoadSaveinstancia.

Trate de añadir algo como:

public LifeApplication()
{
    ...

    loadSave = new LoadSave();
    loadSave.lifeAaplication = this;

    ....
}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=338233&siteId=1
Recomendado
Clasificación