Search code examples
javajsonlibgdxtextboxgson

LibGDX : Saving user data through a GameOverScreen class in a json file and creating a textbox


I'm trying to program something like Flappy Bird in LibGDX. Right now I want to implement a class GameOverScreen, that shows different features: the score, the highscore, the placement and the name of the player.

I already implemented the score as public static int score = 0;. Every time my figure passes an object the score is incremented by one.

In my Tower class, I have the following method:

public boolean collides(Wizard wizard) {
    if (position.x < wizard.getX() + wizard.getWidth()) {
        return (Intersector.overlaps(wizard.getBoundingRectangle(), barUp)
                || Intersector.overlaps(wizard.getBoundingRectangle(), barDown));
    }
    return false;
}

So every time the Wizard collides with an object, the GameOverScreen should appear.

If the user achieved a higher score, thenhighscore = GameWorld.score; which I thought of implementing as a method:

Additionally, a textbox should appear, where the user can write his name and then save it.

To save the data I have to create a file called "highscore.json", which should contain information about the placement, the name of the player and the achieved score in JSON-format. To change data in the "highscore.json" file, I have to use Gson.

The problem I'm having is that I don't know what exactly needs to be written in the GameOverScreen class (f.ex. how to create a textbox in LibGDX and how to get the screen to open after collision), to

  • get Highscore as a text
  • get the placement and let the users write their name
  • save data in JSON format (so that it's editable)

because I'm not too familiar with LibGDX and I never worked with JSON files.

I wasn't able to find a suitable GameOver class on Google/github etc, because they were all too specific.

Can someone help me out?


Solution

  • To get Highscore as a text, you simply have to convert it to string

    int highScore = 10;
    string highScoreText = String.valueOf(highScore);
    

    To get the placement of the player, you'll need to retrieve all stored highScores and rank them (you can achieve that easily with Arrays.Sort, note that they'll be ordered in ascending order, you want descending.. you could then just iterate through the array in the reverse order to get the higher score in first position)


    To let the user write his own name, it's a bit more complicated. You'll need Libgdx Scene2D UI. I don't know if you are using it at the moment, but if you don't, this would need some structural changes in your code.

    Once you figured out how to translate to scene system and work with actors, you can add all controls offered by Scene2D UI:

    • Buttons
    • Dialog
    • TextField
    • A lot more..

    To save data as Json format, you could use the Json API that comes with LibGDX. Take a look at this thread Write to Json using libGDX