1.3-Object-Georienteerd-Programmeren

ChillyGame - Part 4: Chilly gets refactored

Screenshot of the end result

Ok, this week we are going to reorganise the internal structure of the game using polymorphism and methods. Until now we had a list of Fish objects and a list of Crack objects. Our code become easier when we merge them into one list of GameObjects. After that we make our loop() much more readable and wqe update the logic in a way that we can easily expand the game. A last topic (a bit more advanced) is adding a friend for Chilly as a second player.

Step 1: Refactoring your code.

Check the old classdiagram (on top) and the new classdiasgram that we want (below). It looks much less complicated! Do the following steps to arrange this:

Now it’s up to you to implement this diagram into your project:

Step 2: Split up the loop() method

To keep the code more readable we will split up the loop() method in several smaller methods. There is not much new code, but a lot of code will be moved. Maybe you sometimes wonder why we’ve setup the methods the way we do. Please note that is all for readability and to make it as easy as possible to expand the game.

Our suggestion is to have the following:

In our code the loop methods now looks like this, which is much more clear then before and offers oppertunities for easy extension of the game:

    public void loop() {
        // Clear the screen and add the background
        SaxionApp.clear();
        SaxionApp.drawImage("resources/background.png", 0,0, 1024,768);

        //Draw the health bar and gameObjects
        drawHealthBar(player, 20);
        drawGameObjects();

        //Handle player movement and health
        handlePlayerMovement(player);
        if (handlePlayerHealth()) {
            SaxionApp.quit();
        }

        //Spawn crack or fishes and check collisions
        spawnCracksOrFishes();
        GameObject gameObject = detectCollision(player);
        if (gameObject != null) {
            handleCollision(player, gameObject);
        }
    }

Advanced Suggestion 1: Add a second player

SO, now we have made the code more generic it becomes a lot easier to extend the game with more gameobjects. It is even quite easy to add a second player. It’s up to you how to do that, but here are a few clues: