A.I, Data and Software Engineering

Touch me if you can (V.0.1)- Hero vs monsters game

T
Hero VS Monsters

This is a (very) simple JAVA implementation of the game “hero vs monsters” as part of the year 1 BSE lab. The implementation is mainly for demonstrating the custom view and touch event. Video tutorial is at the end of the article.

The UI

it will be a very simple UI with only one view (game view) that extends Android View. In the scene, a hero is trying to kill monsters appears in different locations.

You will need to prepare some image resource, i.e. hero and monsters. No XML layout is needed as we will set the game view to the content view in the MainActivity. And that is all we need for the MainActivity.

The Game View

We will create a custom view, namely GameView, to display hero and monsters. The class will extends View and implement Runnable interface.

As we need a hero and monster, we will declare some corresponding variables right below the class name.

We init these above variables with an initialisation method and call the init method in constructors:

After that, we will display monster and hero on screen by overriding the onDraw method.

Next, as we want to move the hero around the screen we will override the method onTouchEvent. We will move the hero to follow the finger movement, check the collision with monsters, and we tell the view to redraw the view using the postinvalidate method defined in View.

In case you want to use handler, you can uncomment the hander statement and add the hander variable.

Finally, we need to handle the regeneration of the new monster at the new location with randomMonster method. Just make sure that the monster is not out of the screen bounds.

Video tutorial

Enjoy the 10 min video to understand the custom view and simple interaction.

Wrapping up

It is quite simple to complete the game with just a few lines of code. Nevertheless, using custom views is NOT recommended for animation in more complicated gaming projects. Refer to surface view tutorial for advanced game animation. Other useful links:

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest

Newsletters

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.