2

I recently was coding but encountered an null pointer exception the stack trace says

Exception in thread "main" java.lang.NullPointerException
at com.masterkgames.twisteddream.level.SpawnLevel.generateLevel(SpawnLevel.java:34)
at com.masterkgames.twisteddream.level.Level.<init>(Level.java:22)
at com.masterkgames.twisteddream.level.SpawnLevel.<init>(SpawnLevel.java:16)
at com.masterkgames.twisteddream.Game.<init>(Game.java:49)
at com.masterkgames.twisteddream.Game.main(Game.java:138)

below are the 3 mentioned classes

Spawnlevel.java: package com.masterkgames.twisteddream.level;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.masterkgames.twisteddream.level.tile.Tile;

public class SpawnLevel extends Level {

private Tile[] tiles;
private int[] levelPixels;

public SpawnLevel(String path) {
    super(path);

}

protected void loadLevel(String path){
    try{
        BufferedImage image = ImageIO.read(SpawnLevel.class.getResource(path));
        int w = image.getWidth();
        int h = image.getHeight();
        tiles = new Tile[w * h];
        levelPixels = new int[w * h];
        image.getRGB(0,0,w,h,levelPixels,0,w);
    }catch(IOException e){
        e.printStackTrace();
    }

}
protected void generateLevel(){
        for(int i = 0; i < levelPixels.length; i++){
            if(levelPixels[i] == 0xff00) tiles[i] = Tile.Grass;
            if(levelPixels[i] == 0xffff00) tiles[i] = Tile.Rose;
            if(levelPixels[i] == 0x7f7f00) tiles[i] = Tile.Stone;
        }
    }
}

level.java:

package com.masterkgames.twisteddream.level;

import com.masterkgames.twisteddream.graphics.Screen;
import com.masterkgames.twisteddream.level.tile.Tile;

public class Level {

public Screen screen;
protected int width, height;
protected Tile[] tiles;
protected int[] tilesInt;

public Level(int width, int height) {
    this.width = width;
    this.height = height;
    tilesInt = new int[width * height];
    generateLevel();
}

public Level(String path) {
    loadLevel(path);
    generateLevel();
}

protected void generateLevel() {

}

private void loadLevel(String path) {

}

public void update() {

}

private void time() {

}

public void render(int xScroll, int yScroll, Screen screen) {
    screen.setOffset(xScroll, yScroll);
    int x0 = xScroll >> 4;
    int x1 = (xScroll + screen.width + 16) >> 4;
    int y0 = yScroll >> 4;
    int y1 = (yScroll + screen.height + 16) >> 4;

    for (int y = y0; y < y1; y++) {
        for (int x = x0; x < x1; x++) {
            // getTile(x, y).render(x, y, screen);
            if (x + y * 16 < 0 || x + y * 16 >= 256) {
                Tile.Void.render(x, y, screen);
                continue;
            }
            tiles[x + y * 16].render(x, y, screen);

        }
    }
}

public Tile getTile(int x, int y) {
    if (x < 0 || y < 0)
        return Tile.Void;
    if (x >= width || y >= height)
        return Tile.Void;
    if (tilesInt[x + y * width] == 0)
        return Tile.Grass;
    if (tilesInt[x + y * width] == 1)
        return Tile.Rose;
    if (tilesInt[x + y * width] == 2)
        return Tile.Stone;

    return Tile.Void;
}

}

and lastly game.java:

package com.masterkgames.twisteddream;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;

import javax.swing.JFrame;

import com.masterkgames.twisteddream.entity.mob.Player;
import com.masterkgames.twisteddream.graphics.Screen;
import com.masterkgames.twisteddream.input.Keyboard;
import com.masterkgames.twisteddream.level.Level;
import com.masterkgames.twisteddream.level.SpawnLevel;

public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;

public static int width = 300;
public static int height = 168;
public static int scale = 3;

public String Title = "Twisted Dream";

private Thread thread;

private boolean running = false;

private Screen screen;
private Keyboard key;
private Level level;
private Player player;

private JFrame frame;
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();

public Game() {
    Dimension size = new Dimension(width * scale, height * scale);
    setPreferredSize(size);

    screen = new Screen(width,height);
    key = new Keyboard();
    level = new SpawnLevel("/textures/level.png");
    player = new Player(key);

    frame = new JFrame();

    addKeyListener(key);
}

public synchronized void start() {
    thread = new Thread(this, "Display");
    thread.start();
    running = true;
}

public synchronized void stop() {
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void run() {
    long lastTime = System.nanoTime();
    long timer = System.currentTimeMillis();
    final double ns = 1000000000.0 / 60.0;
    double delta = 0; 
    int frames = 0;
    int updates = 0;
    requestFocus();
    while (running) {
        long nowTime = System.nanoTime();
        delta += (nowTime - lastTime) / ns;
        lastTime = nowTime;
        while (delta >= 1){
        update();
        updates++;
        delta--;

        }
        render();
        frames++;

        if(System.currentTimeMillis() - timer > 1000){
            timer += 1000;
            System.out.println(updates + " ups, " + frames + " fps");
            frame.setTitle(Title + "  |  " + updates + " ups, " + frames + " fps");
            updates = 0;
            frames = 0;
        }
    }
    stop();
}

public void update() {
    key.update();
    player.update();
}

public void render() {
    BufferStrategy bs = getBufferStrategy();

    if (bs == null) {
        createBufferStrategy(3);
        return;
    }


    screen.clear();
    int xScroll = player.x - screen.width / 2;
    int yScroll = player.y - screen.height / 2;
    level.render(xScroll, yScroll, screen);
    player.render(screen);


    for(int i = 0; i < pixels.length; i++){
        pixels[i] = screen.pixels[i];
    }

    Graphics g = bs.getDrawGraphics();
    g.drawImage(image,0,0,getWidth(),getHeight(),null);
    g.setFont(new Font("arial", 0, 15));
    g.setColor(Color.white);
    g.dispose();
    bs.show();
}

public static void main(String[] args) {
    Game game = new Game();

    game.frame.setResizable(false);
    game.frame.setTitle(game.Title);
    game.frame.add(game);
    game.frame.pack();
    game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.frame.setLocationRelativeTo(null);
    game.frame.setVisible(true);

    game.start();
}

}

p.s this issue according to the stack trace is in the line for(int i = 0; i < levelPixels.length; i++) in SpawnLevel.java

2 Answers2

2

in Level contructor you have generateLevel(); where you are using levelPixels, which is not initialized

contructor call

private void loadLevel(String path) {

}

from class Level, you have to call method loadLevel in SpawnLevel constructor

karci10
  • 375
  • 3
  • 15
0

You are accessing the null array levelPixels.

Here is where your error is: In your main you call a new SpawnLevel(path) But SpawnLevel(path) calls the super constructor, which calls its blank yet defined loadLevel and generateLevel. The loadLevel and generateLevel in SpawnLevel are never called, and the member variables are never initialized.

So basically, you tried to use the Level class as an abstract class but you didnt do it correctly. The member variables should be in the Level class if they are to be shared by children of that class. Im guessing this is what you want to do.

you should really get familiar with the debugger, it will be a lifesaver for little problems like this.

frankie liuzzi
  • 1,680
  • 12
  • 13