Simple Coding a Snake Game for Android
As the title suggests, during this project we are going to build a straightforward snake vogue game. This form of game has been around since the middle 1970’s beneath different names like Worm and Surround.I contend this factor for several hours on the traditional weapon system M5 and also the “green screen” Sharp MZ80 back within the 1980’s. Snake finally reached international acclaim within the 2000s but, once it absolutely was equipped as customary with an entire generation of Nokia mobile phones.
This game can use a special engine to the opposite games on this web site because it can build a pre-determined range of “moves” every second, instead of enjoying as several frames of animation as doable and so temporal arrangement every frame for optimum smoothness. the rationale for this can be we are able to recreate a authentic blocky/jumpy animation.
Take a look at this image to see the game at the start.
One dot for the snake and one dot for Bob waiting to be eaten. Before anyone complains that snakes don’t eat Bobs, they don’t eat apples either. As the game continues and many Bobs are eaten the snake grows in length making it more likely that the player will trap or eat himself.
Let’s start coding.
Lets Coding the Snake Activity for now!
As usual, we are going to begin with AN Activity which can management a thread in an exceedingly category that controls the sport and handles input from the player. If you would like a additional in-depth discussion of the interaction between the Activity and therefore the main category then take a glance at the flight tutorial.
Create a replacement project in mechanical man Studio, use the Empty Activity guide, and decision it Snake. Leave the remainder of the settings at their defaults. decision the Activity SnakeActivity and amend its code to be identical as this.
Here we declare an instance of
called
which doesn’t exist yet but it will soon. Now code the
method of the
class to initialize the
object. Obviously there will be errors in our code but if we code SnakeActivity in full we won’t need to keep coming back to it. Add the following code and we will discuss it.
The
method uses the
class and an object of type
to get the resolution of the device the sport is running on. Our SnakeEngine category can want a respect to the Activity and also the resolution thus we tend to pass them in to the SnakeEngine creator. The final thing we tend to do is use snakeEngine to be the read of the SnakeActivity.
and
methods then these methods call the relevant methods inside
to start and stop the thread which handles the entire game.
Making the game fullscreen and landscape
We want to use every pixel that the device has to offer so we will make changes to the app’s AndroidManifest.xml configuration file.
- In the project explorer pane in Android Studio double click on the manifests folder, this will open up the AndroidManifest.xml file in the code editor.
- In the AndroidManifest.xml file, locate the following line of code: android:name=”.SnakeActivity”>
- Place the cursor before the closing > shown above. Tap the enter key a couple of times to move the > a couple of lines below the rest of the line shown above.
- Immediately below ParallaxActivity but BEFORE the newly positioned > type or copy and paste these two lines to make the game run full screen and lock it in the landscape orientation.
Add the sound to the project
Download the sounds by right-clicking on the files listed below. Add them to the Snake project by using your operating system’s file browser go to the appsrcmain folder of the project and create a new folder called assets. Add your sound files to this folder. Here are my sound effects. Right-click and select Save link as… to download them.
snake_crash
eat_bob
We can now get rid of the errors by moving on to the SnakeEngine class.
Coding SnakeGame on android
Add a new class called SnakeEngine and amend the code as shown next so we have all the required imports.
When we extend
so that the call to
in the
class works and we implement the
interface so we can later pass this class to the
constructor to create a
instance.
has one method that we must implement and we will overide
soon.
The SnakeGame variables
Add all the member variables after the class declaration then they will be ready for use as we proceed through the rest of the code.
We can now code the constructor.
Coding the SnakeGame constructor
Add this code next, be sure to add it inside the closing curly brace of the
class.
First, we initialize,
,
and
with the values passed in from
. Next, we divide the number of pixels by the final int
in order to determine the appropriate number of pixels in the width of
. Now we can use this to work out, based on the number of vertical pixels, how many blocks high the playable area will be.
Next, the sound files are loaded and associated with an appropriately named identifier. They are now ready to play at will with
.
What follows is we initialize
and
.
After this, we initialized the two
arrays.
will hold the horizontal coordinate of each segment of the snake and
will hold each vertical coordinate.
The last part of the code we call the
method which unsurprisingly starts the game. We will code
shortly.
Making thread run the game loop and keep it up
All the within the run technique, as well as technique calls from the run technique, works during a separate thread to the robot UI. this may permit our game to run swimmingly at constant time as listening for player input. Add the run technique moreover as pause and resume and so we’ll remark them.
The
and
methods are called by
when Android or the player causes the app to call
or
. The
method creates a new instance of
when required and
stops the it when required. Now our instance of
will play nicely with Android.
Everything in, and called by the run method, will now happen in a separate thread.
The
method calls
and then
. The whole thing is wrapped in a
loop that repeats continuously if
is set to
and the thread is running.
These calls are also contained within
. Only if this is
are the
and
methods called. The
method can, therefore, control the frame rate of the game ensureing the blocky/authentic motion.
Some important methods
As we saw, the
method is called by the constructor it is also called when the snake crashes and a new game is required. Add the newGame method.
In the
, the snake is prepared. The length is set to just one block then the head of the snake is set to the center of the screen. The first position of each of the arrays holds the head. It is only the head that we will use when we code the collision detection. Next, Bob is prepared for a terrible demise by calling
and
is initialized to
.
The final bit of code in the
method sets
to whatever the current time is. This will cause the
and
methods run.
Re-spawn and eating Bobby
The spawnBob method uses two random int values within the ranges of zero and NUM_BLOCKS_WIDE, zero and numBlocksHigh, then initializes the horizontal and vertical location of the mouse.
Optimization tip: Instantiating a new instance of
is slow and could be done in the constructor then just reused each time
is called. In this context, however it will not affect the smooth running of the game.
The
method is simple too.
The snake’s length is increased by one block, a new mouse is spawned, 1 is added to the score and a sound effect is played.
Here is the code for the
method to add after the
method.
The
method is quite long but doesn’t involve anything too tricky. Add the code and then we can go through it.
The
loop starts at the last block of the snake in
and
and advances it into the location previously occupied by the block ahead of it. When the
loop is complete the last position is in the place the block ahead used to be in and the block that was just behind the head is where the head used to be.
Therefore, as long as we handle the head properly all the other blocks will be correctly positioned too.
To move the head we
based on the current value of heading and add or subtract 1 from either the heads vertical or horizontal position.
In the
method, we do collision detection. Notice in the code that follows we check for two things. Has the snake’s head bumped into the edge of the screen and has the snake’s head bumped into a block of the snake’s body?
If either of the collision possibilities happens then
returns
to the
method which takes further action.
Coding the online self-update methods
This method does three things:
- It checks if the head has touched/eaten a mouse. If it has then the
method handles things. - It calls the
method which was coded previously. - It calls the
method and if it returns
a sound is played and the game begins again.
All this happens ten times per second because of the way
will work. We will code
in a minute. Add the code for the update method.
Lets Drawing the SneakGame
Add all the code for the
method and then we will go through it.
First, we lock the surface which is required by Android. If this works, we clear the screen with
and then change the color of all future objects we will draw by calling
. We do this once for the snake and once for Bob. Now we draw the text for the score.
We use a
loop to draw a block/square to represent each block of the snake. The code positions the blocks to screen coordinates by using their grid positions(contained in the array) multiplied by
which was determined in the constructor based on screen resolution.
Now we can draw single block to represent Bob.
Coding updateRequired
We are almost done!
The
method will let us know if the
variable has been exceeded by the actual current time. If it has then a new time is retrieved and put back in
. The method then returns
allowing draw and update to execute. If not,
is returned and the next frame is delayed until it is time.
You can now add the updateRequired method.
Handling screen touches (player input)
The final code handles the player removing their finger. Holding won’t work. The
method uses
to detect MotionEvent.ACTION_UP. This notifies us the player’s finger has left the screen. We then use motionEvent.getX() to determine if that action was on the left or the right of the screen.
If they faucet on the left facet of the screen then the snake moves to ensuing direction within the enumeration going anti-clockwise if they faucet on the correct then it’s dextral.
It’s meant to be awkward, it’s authentic to the initial. Add this code to handle touches on the screen.
You can now play the game!