Level Reader

I’m working on a class that’s supposed to load the level for my game from a text file. I’m getting one error and I’m wondering how I could fix it.

package waffles.main;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class DataLoader {
	public String[][] Level = null;
	public DataLoader(){
		
	}
	public void LoadLevel(String level){
		try {
		    BufferedReader in = new BufferedReader(new FileReader("res/levels/" + level + ".lvl"));
		    String str;
		   
		    int line = 0;
		    String readline[];
	
		    
		    while ((str = in.readLine()) != null) {
		        readline = str.split(":");
		    	ProcessData(readline, line);
		        line++;
		    }
		    in.close();
		} catch (IOException e) {
			System.out.println("Level " + level + " is missing!");
		}
	}
	private void ProcessData(String str[], int line){
		Level[line][0] = str[]; //Here is the error.
	}
}

Any help please?

What’s the error?

“Syntax error on token “[”, Expression expected after this token”

Considering the line is “Level[line][0] = str[];” that would be a syntax error. Lose the brackets after str. Better yet, stop using raw arrays and use an ArrayList instead.


Json json = new Json();
...
Level level = ...
json.toJson(level, new FileWriter("level"));
...
Level level = json.fromJson(Level.class, new FileReader("level"));

http://code.google.com/p/jsonbeans/
:slight_smile:

How would I go about this. I’ve used ArrayLists before, but never as a 2 dimensional array.

It’s not really a 2-dimensional array, it’s just an array of arrays. Same goes for lists, it’s just a List of Lists. List<List> x = new ArrayList<ArrayList>()

I also think that writing

String var[]

instead of

String[] var

is a bit misleading, because in Java an array is not a simple datastructure as in C but an own Class.

just leav the processdata method out and write

Level[line] = readline;//in Java variables should start lowercase

notice that because Java don’t have 2 dimensional arrays but arrays of arrays we can assign to the first dimension of “Level” an array of String

How does this look?

package waffles.main;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class DataLoader {
	//public String[][] Level = null;
	public ArrayList<ArrayList<String>> LevelData = new ArrayList<ArrayList<String>>();
	public DataLoader(){
		
	}
	public void LoadLevel(String level){
		try {
		    BufferedReader in = new BufferedReader(new FileReader("res/levels/" + level + ".lvl"));
		    String str;
		   
		    
		    String[] readline;
	
		    ArrayList<String> newline = new ArrayList<String>();
		    while ((str = in.readLine()) != null) {
		        readline = str.split(":");
		        for (int counter = 0; counter < readline.length;counter++){
		        	newline.add(readline[counter]);
		        }
		        ProcessData(newline);
		    }
		    in.close();
		} catch (IOException e) {
			System.out.println("Level " + level + " is missing!");
		}
		Level.BackgroundWalls.clear();
		Level.Bullets.clear();
		Level.Elevators.clear();
		Level.Platforms.clear();
		Level.Robots.clear();
		Level.WaffleCoins.clear();
		Level.Walls.clear();
		
		ConvertData();
		
	}
	private void ProcessData(ArrayList<String> arg0){
		
		LevelData.add(arg0);
	}
	private void ConvertData(){
		for (int y = 0;y< LevelData.size();y++){
			for (int x = 0;x < LevelData.get(y).size();x++){
				String value = LevelData.get(y).get(y);
				if (value == "1"){
					Level.Platforms.add(new Platform(Art.ImgRoot + "env/platform1.png", x, y));
					
					//System.out.println("new platform");
				}
			}
		}
	}
}

I don’t get any errors, but it also doesn’t work.

How about this?

package waffles.main;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class DataLoader {
	public Level loadLevel(String levelName){//method naming convention is the same as for variables starting with lowercase then for following word upper case
                Level level = new Level();
		try(BufferedReader in = new BufferedReader(new FileReader("res/levels/" + llevelName + ".lvl"));) {	
		    for(int y=0; in.ready(); ++y) {
		        String[] xdata = in.readline().split(":");
		        for (int x = 0; x <xdata.length; ++x){
                             level.addPlatform(new Platform(Art.ImgRoot + "env/platform1.png", x, y));
		        }
		    }
		} catch (IOException e) {
			throw new RuntimeException("Level " + level + " is missing!");
		}
                return level;	
	}
}

I admit this is the best solution. On other there’s also Jackson.

That is really neat, Nate. Am I to assume that you are the author? (based on example code on that page).

Not the best, just a possibly simpler solution. This way you can serialize from objects to JSON and back, without code for each piece of data. I wonder how using Jackson would look? How does the JSON look?

Yep, that’s me! :slight_smile: I seem to have an obsession with serialization. I’ve got projects for binary, JSON, and YAML. I guess I just didn’t like the existing libraries for various reasons, and I saw the light on how straightforward it should be – objects out, objects in. For JSON and YAML, nice looking output was important to me.

Well. Now I have a reader that works. The only problem is that I don’t have a class to do the opposite. I attempted to start writing it but quickly stopped and realized that i have no idea what i was doing I don’t suppose you guys have a solution?

“No idea what I was doing. help?” isn’t a good question. What don’t you know how to do? What do you need help with? :slight_smile:

@Nate: It depends. For simplicity, that’s win ;D

If I have a list of coordinates that have one other number, how can I save that other number to the coordinates given, but in the text file?

Well depending on the protocol used…it’s a simple matter of writing plaintext into the file. What are you having trouble with?


PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File("path/to/file.txt"),"UTF-8")));

//write!

writer.close();

Better use it this way, it is faster:


PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File("path/to/file.txt"),"UTF-8"), 100416 /* One Megabyte buffer */));

//write!

writer.close();

The trouble I’m having is that the file format is set up like a matrix and I want to use the coordinates that I talked about earlier as WHERE in the matrix the other data should be stored. I don’t know how to set it up this way.