Tag Archives: Cloney Bird

Write a Flappy Bird clone using Basic4Android and LibGDX–Part 7

In this section we’ll handle displaying text on the screen. In a previous tutorial we updated the score variable, but as yet we’re not drawing that on the screen.

Download the source code here:

https://dl.dropboxusercontent.com/u/8673694/you%20tube%20files/basic4android/CloneyBirdTutorial/Part7.zip

LibGDX uses what are called Bitmap Fonts to display text. What this means ion practice is that we need some font files that are basically just graphics files that have the alphabet, numbers and special characters in them.

These font files can be generated using a free tool like BMFont by AngelCode.

image

The BMFont main screen looks like the above image, this screen shows you all the characters that are going to be saved into your font file.

The “Font Settings” menu option allows you to set which font to use, the size, etc… I’ve added a screenshot showing the settings I’ve used for our Flappy Bird Clone.

image

Once you’ve copied those settings, open the export options menu item and copy the following settings:

image

Now simply go to the options menu again and select “Save bitmap font as…”

Then save it into your files folder in your Flappy bird project folder.

It’s probably worth saving the settings using the menu option “Save configuration as….” to save the settings for later use.

Now have our font files ready for use, we can use them in our game.

Returning to your B4A window, add the following code into your globals section:

Dim bitmapfont As lgBitmapFont

This declares an object called bitmapfont that we can use with libGDXs font functions to draw the score and any other text we want to the screen.

In order to work, we also need to tell it what the font file is called for it load it into memory, add the following to your LG_Create section:

bitmapfont.Initialize2(lGdx.Files.internal(“bmfont.fnt”)) ‘ load bitmap font file

Assuming you called your font that name, then this will work, otherwise change the filename to match what you saved your font as from the BMFont application.

We’re almost ready to draw our score. The only problem is the command to draw text to the screen is a little complex if you want to use it many times, like say to draw multiple lines of text for a title screen. The solution is to write a small function that handles it for us so we can just use a short simple command whenever we want to write some text. Add the following command at the very bottom of your source code:

Sub shadowtext(text As String, x As Int, y As Int)
    bitmapfont.Draw2(Batch,text,x-(bitmapfont.GetBounds(text).Width/2),y,bitmapfont.Color.black)
    bitmapfont.Draw2(Batch,text,x-(bitmapfont.GetBounds(text).Width/2)-2dip,y-2dip,bitmapfont.Color.white)
End Sub

This is a function that will accept a string and a set of x and y coordinates. It then uses the bitmapfont.draw2 method to write text to the screen. It also draws the text on the screen with a little offset on x and y to give a shadow effect.

This means we can draw text to the screen by using this function like this: shadowtext(“hello world”,50,,50), which is much easier than having to write bitmapfont.Draw2(Batch,”hello world”,50,50,bitmapfont.Color.black) when ever you want to write text to the screen.

Going back to the LG_Render method, add the following line to draw the score after the command to draw the bird:

shadowtext(“”&score,vpW*0.50,vpH*0.90)

We’ll call that it for this tutorial, in the next tutorial we’ll add sound effects before we add the highscore and title screen. The next tutorial will be the final part.

Write a Flappy Bird clone using Basic4Android and LibGDX–Part 8

So we have our background, our pipes, our ground scrolling, our bird and the score. We have collision detection in place and the game restarts after you die. So what’s left to do before we can call this a real game? Let’s just use this list: High-score, Title screen, sound effects.

Get the source code here!

https://dl.dropboxusercontent.com/u/8673694/you%20tube%20files/basic4android/CloneyBirdTutorial/Part8.zip

We have a score, so we’ll add the high-score first.

In the globals section, we’ll add a variable for the high-score value and then a file object for the score file.

Dim highscore As Int
Dim scorefile As RandomAccessFile

We need to add a new library here too, in the libs tab on your B4A IDE, tick the box next to RandomAccessFile, this gives us the file commands we need to handle the high-score.

Moving to the Activity_Create section add the following to handle the high-score file:

‘create highscore file
If File.Exists(File.DirInternal,”scores.dat”) Then ‘only open if file exists
scorefile.Initialize(File.DirInternal,”scores.dat”,True) ‘ open file
highscore = scorefile.ReadInt(0) ‘read score from file into highscore variable
scorefile.Close ‘ close file after use
Else
highscore = 0 ‘ set high-score to zero if first run
End If

So if the high-score file exists, then B4A will open it and read the integer value at position zero from it into the high-score variable. Otherwise, just set the high-score to zero if no file is found, this will happen the first time the game is played.

At the end of the LG_Render section, we’ll now add the code to write the high-score to the screen if the bird is dead. It will also display the message to flap to restart when the restartCD value drops below zero.

If birddead = False Then
‘if bird alive then just draw score
shadowtext(“”&score,vpW*0.50,vpH*0.90) ‘ draw score on screen
Else ‘otherwise if bird dead
restartCD = restartCD – 1 ‘decrease restartCD
‘write high-score file if new high-score
If score > highscore Then ‘if score higher than high score
highscore = score ‘set high-score to score
‘write high-score to file
scorefile.Initialize(File.DirInternal,”scores.dat”,False)
scorefile.writeInt(high-score,0) ‘write score to file
scorefile.Close ‘close score file
End If
shadowtext(“Score: ” & score,vpW*0.50,vpH*0.80) ‘write score to screen
shadowtext(“High Score: ” & highscore,vpW*0.50,vpH*0.70) ‘write high score to screen
If restartCD < 0 Then ‘if restart timer is less than zero
shadowtext(“Flap to Restart”,vpW*0.5,vpH*0.60) ‘write flap to restart text to screen
End If
End If

To explain this in sections, first, if the bird is alive, then just draw the score to the screen, otherwise, decrease the restartCD countdown, then check if the score is a new high-score, if it is, then save the high-score to the score file, then draw the score to the screen along with the high-score. Then if the restartCD countdown is less than zero then display the “Flap to restart” message on screen. This code should go in place of the command you had that just wrote the score to the screen.

Test it out, you should now see a screen that looks like this when you die:

image

Let’s add some sound:

Simple sound effects are all we need for this game. I’ve used some simple sound effects from a game I made several years ago. I’ve included these in the source code download with this tutorial. If you want to make your own, I’d advise using a simple tool like SFXR. Google “SFXR download” to find it. It’s a simple sound effect generator which is easy to use and has actually been used for commercial games such as VVVVVV which is available on Steam.

To add sounds, we need to define an object for each sound effect, these objects are of type LGSound, add the following lines to the globals section to add an effect for flapping wings and one for dying

Dim snd_hit As lgSound
Dim snd_flap As lgSound

 

The next step is to point these objects at the sound files, in the LG_Create section, add the following:

snd_hit = lGdx.Audio.NewSound(“shoot.wav”) ‘ load bird hitting object sound
snd_flap = lGdx.Audio.NewSound(“select.wav”) ‘ load flapping sound

These files need to be in your files folder. We’re now ready to use them. Find the section in the LG_Render where the bird hits the ground, insert these commands just before the line that sets birddead to true.

If birddead = False Then
snd_hit.Play
End If

We put this just before the line that sets birddead to true as it means it will only play the sound effect once.

We then add the sound effect for flapping the birds wings. Add this to the IP_Touchdown method just under the line that alters my

snd_flap.Play

so the top of the If statement in the IP_TouchDown method should now read:

If birddead = False Then ‘ and bird alive
myBird.my = 4*scaleY ‘flap wings
snd_flap.Play
Else If birddead = True AND restartCD < 0 Then

The last thing to add is the title screen

This can be done in several ways when writing games, my personal approach is to have a variable that says whether the game is running or not, if it is, then run the main LG_Render loop just as we’ve written it. If it’s not, then display a title screen. To do this, add a gamerunning boolean variable in the globals section:

Dim gamerunning As Boolean = False

We set it as false initially as we want the title screen to show first.

At the start of the LG_Render section, add the following code block:

If gamerunning = False Then
‘increment secs variable
frames = frames + speed
Batch.Begin

‘draw background
Batch.DrawTex2(myBacking,0,vpH*0.20,vpW,vpH*0.80)

‘draw ground tiles
For x = 0 To 6
‘draw each tile over 20%
Batch.DrawTex2(myGD,(x*vpW*0.20)-(frames Mod (vpW*0.20)),0,vpW*0.20,vpH*0.20)
Next

‘draw bird
Batch.DrawRegion3(BirdFrames(0,(birdColour*3)+(frames/8 Mod 3)),myBird.x,myBird.y+(10*Sin(frames/10)),vpW*0.0425,vpH*0.02,vpW*0.085,vpH*0.04,1,1,0)

‘draw title text
shadowtext(“CloneyBird”,vpW*0.5,vpH*0.8) ‘ Cloney Bird title
shadowtext(“Tap to start”,vpW*0.5,vpH*0.7) ‘ Tap to start text
shadowtext(“Get Ready!”,vpW*0.5,vpH*0.5) ‘ Get Ready text
Batch.End

End If
‘END TITLE SCREEN —————————————————————————–

‘MAIN GAME LOOP ——————————————————————————-
If gamerunning = True Then

You also need to add an End if at the end of the main game loop, just after the batch.end command but before the end sub statement.

The above section now needs some explaining. Firstly, it only runs if the gamerunning value is false. And it’s sole purpose is to display a title screen with the game game, a background, a scrolling ground and the prompt to tap the screen to start. So we increment our frames variable just as normal, then draw the background, the floor tiles just as in part 2 to make the ground scroll. We then draw the bird. For the Y coordinate of the bird, I wanted to make the bird bob up and down, the best way to do this and make it look natural is think back to trig class in maths at school, and use the Sin function to add this bobbing motion. If you take the sin value of angle between 0 and 360 then you get a smooth change in values going from –1 to 1, as shown below:

Try running the code now and you should have a fully working game, with a highscore, title screen, sound effects and the ability to restart after you die.

Now it’s up to you what to do next. You’ve got the basics for writing a game using LibGDX and Basic4Android. If you’ve used the trial version to follow this tutorial, then I’d strongly advise to go for the full version, it’s really worth it. You’ll get free upgrades during your licence period and full access to the Basic4Android forums where the community is amazingly helpful and welcoming.

Follow the “Purchase Basic4Android” link on this site to claim a 30% discount off the full price if you do decide to buy.

Thanks for following this series. I hope you’ve enjoyed writing what could be your first Android game and that you’ve leant a lot.

Please contact me if you have any requests for further tutorials, or if you want to point out any errors or improvements I could make to this series.

Happy coding!

Write a Flappy Bird Clone using Basic4Android and LibGDX – Part 5

Part 5 – Adding player input
Grab the source code:
https://dl.dropboxusercontent.com/u/8673694/you%20tube%20files/basic4android/CloneyBirdTutorial/Part5.zip

Now we’re ready to start detecting user input to make the bird flap its wings
We need to setup a method for performing an action when the user taps the screen. This is the IP_TouchDown method. This first needs declaring, just like everything else so let’s declare it in our Globals section just like everything else:

Dim IP As lgInputProcessor

Initialise the object in the LG_Create section with:

‘Sets the InputProcessor
IP.Initialize(“IP”)

We then add the method for handling touches to the screen at the end of our code.

Sub IP_TouchDown(screenX As Int, screenY As Int, Pointer As Int) As Boolean
myBird.my = 4*scaleY ‘flap wings
End Sub

The method accepts screen and screen values which tell us where on the screen the player touched and a pointer value, which tells us how many fingers are touching the screen. We’ll ignore these for now, because we want the bird to flap its wings whenever anywhere is tapped on the screen.
So every time the screen is touched we run the line within the method. We take the mybird.my value and set it to 4 x scaleY. scaleY is set to a value that should cause the bird to set its upwards speed to look the same no matter what the phone screen resolution.
In our LG_Render section, just before the command to draw the bird, we add the code to update the birds Y position:

‘stop bird going too fast
If myBird.my > (-10*scaleY) Then
myBird.my = myBird.my – (0.2*scaleY)
End If
myBird.y = myBird.y + myBird.my

We’ll only adjust the birds my value if the bird’s not going over -10 pixels per frame, this is just to stop it falling too fast. So we’ll say that -10 is our “terminal velocity” in this sense. So assuming my isn’t too low, then we set it my – 0.2*scaleY this applies a gravity value to the my value for each frame. We then update the mybird.y value by the my amount. For each frame the my value goes down by a gravity amount, it gives the impression of the bird dropping. Try changing the gravity value and seeing the effect it has.
Okay, we need to set the bird angle, this calls for a crazy formula loosely based on the my value. Pointing straight to the right is zero degrees. I had a play around with some numbers and came up with this as something that works well. Try playing with this too and see if you can make it simpler. This needs to go just before the draw bird command in the LG_Render section.

birdAngle = (((myBird.my/scaleY)+6)*5.5)+335

We’ll call that it for this session as the collision detection is going to take a little explaining, and I’d like to add scoring in the next tutorial too.
Download the source code here:
https://dl.dropboxusercontent.com/u/8673694/you%20tube%20files/basic4android/CloneyBirdTutorial/Part5.zip

Write a Flappy Bird Clone using Basic4Android and LibGDX – Part 4

Part 4 – Now we add the bird

Grab the source code here:

https://dl.dropboxusercontent.com/u/8673694/you%20tube%20files/basic4android/CloneyBirdTutorial/Part4.zip
This part deals with adding the bird to the game. We’re going to start by adding some variables to our Globals section

Type typbird(x As Float, y As Float, my As Float)
Dim myBird As typbird ‘ holds details for bird, i.e. x, y, my.

First we add a type for the bird object. Our bird will have several properties, an X and Y coordinate and an my value. The my value is how much the bird moves up or down for each frame rendered.
We next set a variable to store the angle the bird should be drawn at depending whether it’s going up or down.
Dim birdAngle As Int = 0 ‘ angle of bird

We then define the texture object that will store our bird images. I say images rather than image as the bird is animated. There are three frames of animation for it to flap its wings. And then there are four colours of bird. So if you look at the bird graphic file as shown here, you’ll see we have 12 frames in the file.

birdframes

 

First we declare a texture object to load the image file into.
We then declare a region texture object which we will copy the image to before we then split the image into separate frames which we will store in the BirdFrames texture region object.
Dim BirdTexture As lgTexture
Dim BirdRegion As lgTextureRegion
Dim BirdFrames(,) As lgTextureRegion

Lastly we add the following line to store the birdcolour value, this value is used when we draw the bird to select the right frame for the colour value:
Dim birdColour As Int = Rnd(0,4)
Moving onto the Activity_Create method, add the following line to initialise the bird object for use:
myBird.Initialize
Skip to the LG_Create section and add the following lines to load the bird graphics:
BirdTexture.Initialize(“bird.png”)
BirdRegion.InitializeWithTexture(BirdTexture)
Dim BirdFrames(,) As lgTextureRegion = BirdRegion.Split(34, 24)

First we load the bird graphic file into the BirdTexture object. Then we copy the graphic into the BirdRegion object. After this, we use the BirdRegion.Split method to split the graphic into frames that are 34 pixels wide by 24 pixels high. The method will split the graphic into how ever many frames fit this which gives us 12 frames.
We then set the starting cords for our Bird, at 20% in from the left of the screen and 50% up the screen.
myBird.x = vpW*0.2
myBird.y = vpH*0.5

We then move onto the LG_Render method where will draw our bird
‘draw bird
Batch.DrawRegion3(BirdFrames(0,(birdColour*3)+(frames/8 Mod 3)),myBird.x,myBird.y,vpW*0.0425,vpH*0.02,vpW*0.085,vpH*0.04,1,1,birdAngle)

To explain this command, it takes the following parameters:
Image, x coord, y coord, width, height, origin x, origin y, scale X, scale Y, angle
For the image value, we calculate the frame number from 0 to 11 based on the birdcolor value and the frame value. The game runs at around 60 frames per second, so in order to slow the animation down, we devide the frames amount by 8 before taking the remainder after deviding it by 3 we then add it to 3*birdcolour. So if the frame is 25 and the birdcolour is 2, then we get (((25/8) mod 3) + (2*3)). If this is too complex to understand just play with it to see how it works, try removing the birdcolour part to see what gets drawn.
Next we set the x coord based on the birds x value, then the y coord on the mybird.x value.
The origin values mean the position over the bird that the coord is taken from. So we shift this by half the birds width and half the birds height to put this point at the centre of the bird.
The width of the bird is set to 8.5% of the viewport width and the height is set to 4% of the viewport height. So the origin in the centre of the bird needs offsetting by 4.25% and 2%.
The scale values we will leave at 1 and 1 for both width and height, you could change this value if you want to make the bird bigger, but this would then mess with our collision detection we’lll be putting in in the next tutorial. The last value is angle, this is set to the BirdAngle variable. We’ll look at calculating the bird angle in the next tutorial, for now we’ll leave it at zero.
Make sure this is the last thing you draw to ensure the bird is always visible.
We’ll call that it for this part. Try running your code (remember to add the bird graphic file to your files folder), if you get any problems then check the downloadable source code against what you’ve written.
Download the source code!