1.3-Object-Georienteerd-Programmeren

ChillyGame - Part 2: So long and thanks for all the fish!

Screenshot of the end result

Now we have a basic game we can improve it a bit. Let’s give Chilly something to eat!

Step 1: Create a Fish class

First download the images for the fish here and add them to the folder resources\fish.

The Fish class has, just like the Player class, an int x, int y, int width, int height. Besides that a fish has one more properties:

Now create a class fish with these properties and a constructor that looks like this: Fish(int x, int y, String type). Every fish has a width of 75 and a height of 50.

Note that the image String can be built up using the type String.

Don’t forget to add a fish to your game. So your init and loop function should look like this:

    public void init() {
        player = new Player(100,100);
        fish = new Fish(400,400, "tuna");
    }

    @Override
    public void loop() {
        ...

        //Draw the player
        player.draw();
        
        //Draw the fish
        fish.draw();
    }

Step 2: Add collision detection

First, check the video about collision detection in the SaxionApp here.

Please note that we simplify the boundingbox a bit by generating them on the fly as they where needed. This is not efficient (because Java creates new boudingboxes every time we check a collision), but it’s a easier to read and understand.

You should see a lot of Yummie! in the console as soon as Chilly walks over the fish.

Step 3: Randomize the fish

Before the real fun starts we will start using some constants in this game, because this will help us a lot later on.

Step 4: Eat the fish!

Eating the fish is very easy now.

Update your code in the loop() method so that the fish is removed after you collide to it. Insytead of setting the fish variable to null we generate a new fish (of another type and at another location) instantly!

        if (player.collidesWith(fish)) {
            //Enjoy the fish
            //Generate a new fish!
            fish = Fish.generateFish();
        }

Advanced suggestion 1: Give health to our little hero!

To make this a real game we’re going to add health to the player (a.k.a. Chilly). The health goes down over time, but increases when Chilly eats fish.

First update the Player class:

Then, add a healthbar drawing to loop() method. You can do that by drawing a rectangle. Use player.getHealth() * 5 for the value of the width of the bar.

After that do the following to make sure the health decreseases over time.

Type Nutrition
tuna 10
salmon 5
herring 2
shrimp 1

Advanced suggestiomn 2: Multiple fishes!

After you’ve done this we’re going to add huge upgrade.

We will not spawn only one Fish, but we will spawn a new fish every 5 seconds. Every time a fish is hit it will be removed from the game.