I am attempting to make an infinite world 2d game
source for the class is here:
package com.blazingkin.world;
import java.util.LinkedList;
import java.util.List;
import com.blazingkin.atrox.AtroxAdventrum;
public class World {
public World(AtroxAdventrum aa){
chunks = new LinkedList<List<Chunk>>();
}
public void setBlock(int x, int y, int newBlock){
}
public void setMetadata(int x, int y, int newMeta){
}
public int getBlock(int x, int y){
try{
Chunk c = chunks.get(x/64 - x%64).get(y/64 - y%64);
return c.chunk[x%64][y%64];
}
catch(Exception e){
try{
Chunk c = new Chunk(y, x/64 - x%64, y/64 - y%64);
chunks.get(x/64 - x%64).add(y/64 - y%64 - 1, c);
return c.chunk[x%64][y%64];
}catch(Exception e1){
Chunk c = new Chunk(y, x/64 - x%64, y/64 - y%64);
List<Chunk> newlist = new LinkedList<Chunk>();
System.out.println(""+x+", "+y);
for (int i = 0; i<y/64 - y%64; i++){
newlist.add(i, new Chunk(y - (y/64 - y%64 - i), x/64 - x%64, y/64 - y%64 - (y/64 - y%64 - i)));
}
newlist.add(y/64 - y%64 - 1, c);
for (int i = 0; i<x/64 - x%64; i++){
newlist.add(i, new Chunk(x - (x/64 - x%64 - i), x/64 - x%64, x/64 - x%64 - (x/64 - x%64 - i)));
}
chunks.add(x/64 - 1 - x%64, null);
return 0;
}
}
}
public int getMetadata(int x, int y){
return 1;
}
public List<List<Chunk>> chunks;
}
However, when i attempt to run this code i get the following error:
Exception in thread “main” java.lang.IndexOutOfBoundsException: Index: 23, Size: 0
at java.util.LinkedList.entry(Unknown Source)
at java.util.LinkedList.add(Unknown Source)
at com.blazingkin.world.World.getBlock(World.java:41)
at com.blazingkin.render.ScreenOutput.render(ScreenOutput.java:30)
at com.blazingkin.atrox.AtroxAdventrum.draw(AtroxAdventrum.java:34)
at com.blazingkin.atrox.Core.gameLoop(Core.java:60)
at com.blazingkin.atrox.Core.run(Core.java:27)
at com.blazingkin.atrox.AtroxAdventrum.main(AtroxAdventrum.java:14)
Any suggestions as to how i could fix this?
A LinkedList is not a good choice for what you are trying to do. First, attempting to access elements of LinkedList by index is bad (performs O(n) instead of O(1)).
Use:
In your code, you can use setChunk(1238238, -12938123, new Chunk(…)) and it will key the chunk under the x and y coordinate. To retrieve the value, use getChunk(1238238, -12938123). If no chunk exists for a given x, y, null will be returned.