This site requires JavaScript, please enable it in your browser!
Greenfoot back
sadistic_angel
sadistic_angel wrote ...

2012/5/5

save a generated world to file?

1
2
sadistic_angel sadistic_angel

2012/5/5

#
ok so i want my randomly generated world, found here , to make a new file that saves the world to a text document that can also be interpreted and read to load a game. i would need the file to expand with the world where the world is never ending. i have made a test script that can make and read a file but i don't know where to go from there.
danpost danpost

2012/5/5

#
You could create an array of strings (let us start with your initial world, and go from there). Your world, as is, is 21 x 21, and you have 5 possibilities for each plot of 'land' { dirt, grass, sand, water, and unknown }. I added the unknown in there for uncharted territories. By using the initial letter for each one, you could create a String object for each row that at least one plot is known. In addition, you can capitalize the first letter in the initial square the player either starts on or was last on (so that, when parsing the Strings, we know where to put the player). You will obviously have to keep track of not how big the 'virtual' world is, but its starting and ending row numbers; and base the indices in the array of strings on those numbers. It would not matter if these numbers were different after reading back in the file, because the relationships are maintained. When the player moves into uncharted territories, there are several things you may have to do: If moving left into new column (first time in that column), all strings will have to be prefixed with a 'u' (except for the one the player is on; which becomes its land type). If moving right into new column(first time in that column), all strings will have to be appended with a 'u' (except for the one the player is on; which becomes its land type). If moving up or down into new row (first time in that row - and this could be a little tricky), you will have to add a new String to the array. The easiest thing to do here is, create a different String array that is the size needed and use the System.arraycopy(fromArray, fromStartingIndex, toArray, toStartingIndex, numberOfElementsToCopy) command to transfer your String array into it (if player moved up, copy from index 0 to index 1; if down, copy from 0 to 0). Then add the new String (at 0 if up, and end if down). Recreate the initial String array to the proper size and System.arraycopy(from, 0, to, 0, all) the data back to it.
sadistic_angel sadistic_angel

2012/5/5

#
This sounds genius but i'm a little confused because i have only started in java and greenfoot a few months ago. I'm taking a class and my teacher can't even help me, by what I can tell your method would defiantly work for what I want to do and I would love to implement it. but I don't know how I would go about doing it. I also wonder if this could keep the number of objects in the world down? by despawning whats outside of the game border the respawning in the right tile when I walk over to it again? I have never used an array, or added to a string before, so i'm going to be reading up on those for a bit. any more insight would help. Thanks!
danpost danpost

2012/5/5

#
The best place to look is in the Java tutorials. The second section on the left labeled in red, 'Trails Covering the Basics', has the link you should probably go to: 'Learning the Java language'. You will find everything on Strings, arrays, and much more.
sadistic_angel sadistic_angel

2012/5/5

#
It seems with this method there would be a lot of copying arrays (which could get quite large) and creating new arrays. I have read up on arrays and strings a bit and have found adding to each string would be easy but adding to an array would prove very difficult. I wonder how i could make the same thing work with a single text file stored on the computers HDD? rather than in an array inside of java. so all it would do is add a new line to the end of the file or the beginning of the file for moving down or up and add a prefix to all lines or a suffix to all lines for moving left or right. would that work better? or be more efficient? also how would i parse said file for individual letters to regenerate the world?
danpost danpost

2012/5/5

#
HDD file ops are much slower than copying arrays. You would only want to do file operations at the time you save the world or read in a saved world. As far as parsing: You would read in one line at a time, and iterate through each character of the string, and find the index of that character in the string of possibilities
int stringsRead = 0;
String string = (read first string from file) //this line needs fixed
while (not end of file) // this line needs fixed
{
    for (int i = 0; i < string.length(); i++)
    {
        int landType = "dgswuDGSWU".indexOf(string.charAt(i));
        Actor actor = null;
        switch (landType % 5)
        {
            case 0: actor = new Dirt(); break;
            case 1: actor = new Grass(); break;
            case 2: actor = new Sand(); break;
            case 3: actor = new Water(); break;
            case 4: break;
        }
        // the next two lines need fixed
        if (actor != null) addObject(actor, i * (width of images), stringsRead * (height of images));
        if (landType > 4) addObject(new Player(), i * (width of land images), stringsRead * (height of land images));
    }
    stringsRead++;
    string = (read next line from file) // needs fixed
}
It would probably be easiest to re-start the player object back at its original starting square (in other words, capitalizing that same square when saving the world to file). Then, we can move all the objects the same offset to put the player object in the center of the window.
Actor player = (Actor) getObjects(Player.class).get(0);
int dx = 10 - player.getX(), dy = 10 - player.getY();
for (Object obj : getObjects(null))
{
    Actor actor = (Actor) obj;
    setLocation(actor.getX() - dx, actor.getY() - dy);
}
startRow = dy;
endRow = dy + stringsRead - 1;
sadistic_angel sadistic_angel

2012/5/5

#
and how would i go about exporting these to a file in the end to save the world?
danpost danpost

2012/5/5

#
The capitalizing of the initial location of the player can be done when the initial window is populated. So, all that would need to be done is output the strings to the file. I could do some searching to find the basic code, as I know I have it somewhere.
sadistic_angel sadistic_angel

2012/5/5

#
that would be great i have the code to output to file but by what i've seen it only outputs one line.
danpost danpost

2012/5/5

#
Show the code.
sadistic_angel sadistic_angel

2012/5/5

#
TestWorld tw = (TestWorld)getWorld();
        try
        {
             //create file
             FileWriter fstream = new FileWriter ("RootBeer.wld");
             BufferedWriter out = new BufferedWriter (fstream);
             out.write (tw.x + "");
             //close output
             out.close();
        }
             catch (Exception e) 
                {
                 System.err.println("Error: " + e.getMessage());
                }
danpost danpost

2012/5/5

#
What is 'x' in TestWorld? Show the declaration statement in the world class and explain what it is used for.
sadistic_angel sadistic_angel

2012/5/5

#
String x = null;
it can be any string and i as just using it to try input from a variable which was read from another file using this code.
public class Read extends Button
{
    String y;
    /**
     * Act - do whatever the Read wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        
        readFile("testread.txt");
    }
    private String readFile(String fileName)
    {
        TestWorld tw = (TestWorld)getWorld();
        File file = new File(fileName);
        
        char[] buffer = null;
        
        try
        {
            BufferedReader bufferedReader = new BufferedReader(
                new FileReader(file));
                
            buffer = new char[(int)file.length()];
            
            int i = 0;
            int c = bufferedReader.read();
            
            while (c != -1) 
            {
                buffer[i++] = (char)c;
                c = bufferedReader.read();
            }
        }
        catch (FileNotFoundException e)
        {
            
        }
        catch (IOException e)
        {
            
        }
        tw.x = new String(buffer);
        return new String(buffer);
        
    }
}
so tw.x starts as null and becomes what ever is in the read file.
danpost danpost

2012/5/5

#
Try changing 'tw.x' in the output code to the name of your String array (without the square brackets). If that does not work, create a 'for' loop to output each string of the array separately before closing the file.
sadistic_angel sadistic_angel

2012/5/5

#
i've been trying to figure this out and am further confusing myself so either i should work on something else such as scrolling first or i should post the source so you can have a look at how i have everything working. its not the most elegant code and there are almost no comments but like i said I've been coding in greenfoot for only a few months. what do you think?
There are more replies on the next page.
1
2