81 lines
2.8 KiB
Java
81 lines
2.8 KiB
Java
package de.craftix.game;
|
|
|
|
import de.craftix.game.block.Block;
|
|
import de.craftix.game.block.Material;
|
|
import de.craftix.game.entity.Player;
|
|
|
|
import java.awt.*;
|
|
import java.io.BufferedReader;
|
|
import java.io.File;
|
|
import java.io.FileReader;
|
|
|
|
public class World {
|
|
|
|
private int blocksX;
|
|
private int blocksY;
|
|
private Block[][] blocks;
|
|
private File worldFile;
|
|
|
|
public World(String worldFile) {
|
|
this.worldFile = new File("worlds/" + worldFile);
|
|
loadWorldFromFile();
|
|
}
|
|
|
|
public void update() {
|
|
for(int row = 0; row < blocksY; row++) {
|
|
for(int col = 0; col < blocksX; col++) {
|
|
blocks[row][col].update();
|
|
}
|
|
}
|
|
}
|
|
|
|
public void render(Graphics2D g) {
|
|
int blocksRendered = 0;
|
|
Player player = Playstate.player;
|
|
int startX = player.getCenterX() - GamePanel.width / GamePanel.SCALE / 2;
|
|
int startY = player.getCenterY() - GamePanel.height / GamePanel.SCALE / 2;
|
|
int endX = player.getCenterX() + GamePanel.width / GamePanel.SCALE / 2 + Game.BLOCKSIZE;
|
|
int endY = player.getCenterY() + GamePanel.height / GamePanel.SCALE / 2 + Game.BLOCKSIZE;
|
|
|
|
for (int row = startY; row <= endY; row += Game.BLOCKSIZE) {
|
|
for (int col = startX; col <= endX; col += Game.BLOCKSIZE) {
|
|
int blockX = getColTile(col);
|
|
int blockY = getRowTile(row);
|
|
if (blockX >= 0 && blockY >= 0 && blockX < this.blocksX && blockY < this.blocksY) {
|
|
blocks[blockY][blockX].render(g);
|
|
blocksRendered++;
|
|
}
|
|
}
|
|
}
|
|
|
|
g.setColor(Color.WHITE);
|
|
g.drawString("Blocks Rendered: " + blocksRendered, 5, 10);
|
|
}
|
|
|
|
private void loadWorldFromFile() {
|
|
try {
|
|
BufferedReader reader = new BufferedReader(new FileReader(worldFile));
|
|
blocksX = Integer.parseInt(reader.readLine());
|
|
blocksY = Integer.parseInt(reader.readLine());
|
|
blocks = new Block[blocksY][blocksX];
|
|
|
|
for (int row = 0; row < blocksY; row++) {
|
|
String line = reader.readLine();
|
|
String[] tokens = line.split(" ");
|
|
for (int col = 0; col < blocksX; col++){
|
|
int id = Integer.parseInt(tokens[col]);
|
|
blocks[row][col] = new Block(Material.values()[id], col * Game.BLOCKSIZE, row * Game.BLOCKSIZE, Game.BLOCKSIZE, Game.BLOCKSIZE);
|
|
}
|
|
}
|
|
reader.close();
|
|
} catch (Exception e) {e.printStackTrace();}
|
|
}
|
|
|
|
public int getRowTile(int y) {return y / Game.BLOCKSIZE;}
|
|
public int getColTile(int x) {return x / Game.BLOCKSIZE;}
|
|
|
|
public Block[][] getBlocks() {return blocks;}
|
|
public Block getBlock(float x, float y) {return blocks[getRowTile((int)y)][getColTile((int)x)];}
|
|
|
|
}
|