Reputation: 1
I am trying to code a little RPG and I'm stuck at getting images to my game. I have a problem with loading a tileset. I wrote a tileSet class, but I the tileset is always null.
Check my code, maybe someone could find the problem.
TileSet class:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
public class TileSet {
public static final int TILEWIDTH = 64, TILEHEIGHT = 64;
private BufferedImage[] tiles;
BufferedImage tileSet;
public TileSet(String path, int sizeX, int sizeY) {
tiles = new BufferedImage[sizeX * sizeY];
try {
tileSet = ImageIO.read(TileSet.class.getResource(path));
} catch (IOException e) {
e.printStackTrace();
return;
}
int i = 0;
for(int y = 0; y < sizeY; y++) {
for(int x = 0; x < sizeX; x++) {
tiles[i++] = tileSet.getSubimage(x * (TILEWIDTH + 3), y * (TILEHEIGHT + 3),
TILEWIDTH, TILEHEIGHT);
}
}
}
public void renderTile(Graphics g, int tileNum, int x, int y){
g.drawImage(tiles[tileNum], x, y, TILEWIDTH, TILEHEIGHT, null);
}
}
Main class:
package rpgame;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
public class RPGame implements Runnable {
public static final int FPS = 60;
public static final long maxLoopTime = 1000 / FPS;
public static final int SCREEN_WIDTH = 640;
public static final int SCREEN_HEIGHT = 640;
public Screen screen;
public static void main(String[] arg) {
RPGame game = new RPGame();
new Thread(game).start();
}
Level level;
@Override
public void run() {
long timestamp;
long oldTimestamp;
BufferedImage playerImages;
screen = new Screen("Game", SCREEN_WIDTH, SCREEN_HEIGHT);
TileSet tileSet = new TileSet("/tiles/rpg.webp", 12, 12);
level = new Level("/level/level1.txt", tileSet);
while(true) {
oldTimestamp = System.currentTimeMillis();
update();
timestamp = System.currentTimeMillis();
if(timestamp-oldTimestamp > maxLoopTime) {
System.out.println("Wir sind zu spät!");
continue;
}
render();
timestamp = System.currentTimeMillis();
System.out.println(maxLoopTime + " : " + (timestamp-oldTimestamp));
if(timestamp-oldTimestamp <= maxLoopTime) {
try {
Thread.sleep(maxLoopTime - (timestamp-oldTimestamp) );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
void update() {
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
};
}
BufferStrategy bs;
Graphics g;
void render() {
Canvas c = screen.getCanvas();
// c.setBackground(Color.blue);
bs = c.getBufferStrategy();
if(bs == null){
screen.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
//Clear Screen
g.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
level.renderMap(g);
bs.show();
g.dispose();
}
}
I have tried to change the path of the image file / working with File class.
Upvotes: 0
Views: 23