Creating a full-featured Flappy Bird game in Android Studio is an extensive project. Below is a step-by-step guide with all the necessary code to build a functional Flappy Bird clone, including audio, main menu, and gameplay elements.
Due to the complexity and length of the code, the implementation will be broken down into sections for clarity.
Project Setup
-
Create a New Project:
- Open Android Studio.
- Select "New Project" > "Empty Activity".
- Name your project (e.g., "FlappyBirdClone").
- Choose a package name, set the minimum SDK (e.g., API 21).
-
Add Required Permissions:
-
Prepare Assets:
- Create a new directory:
app/src/main/assets.
- Add images and audio files:
- Bird sprites (
bird.png, bird_flap.png).
- Background image (
background.png).
- Pipe images (
pipe_top.png, pipe_bottom.png).
- Game over image (
game_over.png).
- Button images (
play_button.png).
- Audio files (
wing.wav, point.wav, hit.wav).
Main Menu Activity
Create a main menu with a "Play" button.
MainActivity.java:
package com.example.flappybirdclone;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button playButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playButton = findViewById(R.id.play_button);
playButton.setOnClickListener(view -> {
Intent intent = new Intent(MainActivity.this, GameActivity.class);
startActivity(intent);
});
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@style/Theme.FlappyBirdClone"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/background"
android:scaleType="centerCrop" />
<Button
android:id="@+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:background="@drawable/play_button"
android:layout_centerInParent="true" />
</RelativeLayout>
Game Activity and View
The GameActivity will host the GameView, where all the game rendering and logic take place.
GameActivity.java:
package com.example.flappybirdclone;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class GameActivity extends Activity {
GameView gameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make the game full screen.
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Initialize GameView and set it as the content view.
gameView = new GameView(this);
setContentView(gameView);
}
// Handle the back button.
@Override
public void onBackPressed() {
super.onBackPressed();
gameView.thread.setRunning(false);
finish();
}
}
GameView.java:
package com.example.flappybirdclone;
import android.content.Context;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
GameThread thread;
Context context;
public GameView(Context context) {
super(context);
this.context = context;
getHolder().addCallback(this);
thread = new GameThread(getHolder(), this);
setFocusable(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
thread.setRunning(false);
thread.join();
retry = false;
} catch (InterruptedException e) {
// Try again to shut down the thread
}
}
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
// Add drawing code here (background, bird, pipes, etc.)
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
GameThread.java:
package com.example.flappybirdclone;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class GameThread extends Thread {
private SurfaceHolder surfaceHolder;
private GameView gameView;
private boolean running;
public static Canvas canvas;
public GameThread(SurfaceHolder surfaceHolder, GameView gameView) {
super();
this.surfaceHolder = surfaceHolder;
this.gameView = gameView;
}
public void setRunning(boolean isRunning) {
running = isRunning;
}
@Override
public void run() {
long startTime;
long timeMillis;
long waitTime;
int targetFPS = 60;
long targetTime = 1000 / targetFPS;
while (running) {
startTime = System.nanoTime();
canvas = null;
// Try locking the canvas for exclusive pixel editing on the surface
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
this.gameView.update();
this.gameView.draw(canvas);
}
} catch (Exception e) { }
finally {
if (canvas != null) {
try {
surfaceHolder.unlockCanvasAndPost(canvas);
} catch (Exception e) { e.printStackTrace(); }
}
}
timeMillis = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - timeMillis;
try {
if (waitTime > 0)
this.sleep(waitTime);
} catch (Exception e) { }
}
}
}
GameView Update and Touch Handling
Update the GameView to handle the game logic, touch events, and drawing.
Update GameView.java:
// ... previous imports
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.view.MotionEvent;
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
// ... previous code
private Bird bird;
private PipeManager pipeManager;
private Bitmap background;
private int screenWidth, screenHeight;
private boolean gameOver;
private Paint paint;
public GameView(Context context) {
// ... previous code
// Initialize game objects
background = BitmapFactory.decodeResource(getResources(), R.drawable.background);
background = Bitmap.createScaledBitmap(background, getWidth(), getHeight(), false);
bird = new Bird(getResources());
pipeManager = new PipeManager(getResources(), getWidth(), getHeight());
paint = new Paint();
gameOver = false;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (canvas != null) {
// Draw background
canvas.drawBitmap(background, 0, 0, null);
// Draw bird and pipes
bird.draw(canvas);
pipeManager.draw(canvas);
// If game over, show game over text
if (gameOver) {
paint.setTextSize(100);
paint.setColor(Color.RED);
canvas.drawText("Game Over", getWidth() / 2 - 200, getHeight() / 2, paint);
}
}
}
public void update() {
if (!gameOver) {
bird.update();
pipeManager.update();
// Check for collisions
if (pipeManager.checkCollision(bird) || bird.getY() > getHeight() || bird.getY() < 0) {
gameOver = true;
// Play hit sound
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Handle touch for flapping
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (!gameOver) {
bird.flap();
// Play flap sound
} else {
// Reset the game
bird = new Bird(getResources());
pipeManager = new PipeManager(getResources(), getWidth(), getHeight());
gameOver = false;
}
}
return true;
}
}
Bird Class
Create a Bird class to represent the player's character.
Bird.java:
package com.example.flappybirdclone;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
public class Bird {
private Bitmap birdBitmap;
private int x, y, width, height;
private float velocity = 0;
private float gravity = 0.6f;
private float lift = -15;
public Bird(Resources res) {
birdBitmap = BitmapFactory.decodeResource(res, R.drawable.bird);
width = birdBitmap.getWidth();
height = birdBitmap.getHeight();
// Scale the bird
width /= 4;
height /= 4;
birdBitmap = Bitmap.createScaledBitmap(birdBitmap, width, height, false);
x = 100;
y = GameView.screenHeight / 2;
}
public void draw(Canvas canvas) {
canvas.drawBitmap(birdBitmap, x, y, null);
}
public void update() {
velocity += gravity;
y += velocity;
}
public void flap() {
velocity = lift;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
Pipe Manager and Pipe Classes
Create classes to manage the pipes and their movement.
PipeManager.java:
package com.example.flappybirdclone;
import android.content.res.Resources;
import android.graphics.Canvas;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class PipeManager {
private List<Pipe> pipes;
private int screenWidth, screenHeight;
private Resources res;
private int pipeGap = 400;
private int distanceBetweenPipes = 800;
private Random random;
public PipeManager(Resources res, int screenWidth, int screenHeight) {
this.res = res;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
pipes = new ArrayList<>();
random = new Random();
// Initialize pipes
for (int i = 1; i <= 3; i++) {
int y = random.nextInt(screenHeight / 2) + pipeGap;
pipes.add(new Pipe(res, screenWidth + i * distanceBetweenPipes, y, pipeGap, screenHeight));
}
}
public void update() {
for (Pipe pipe : pipes) {
pipe.update();
// If pipe off screen, reset position
if (pipe.getX() + pipe.getWidth() < 0) {
int y = random.nextInt(screenHeight / 2) + pipeGap;
pipe.resetPosition(screenWidth, y);
}
}
}
public void draw(Canvas canvas) {
for (Pipe pipe : pipes) {
pipe.draw(canvas);
}
}
public boolean checkCollision(Bird bird) {
for (Pipe pipe : pipes) {
if (pipe.collidesWith(bird)) {
return true;
}
}
return false;
}
}
Pipe.java:
package com.example.flappybirdclone;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
public class Pipe {
private Bitmap topPipe, bottomPipe;
private int x, y, width, height;
private int speed = 10;
private int gap;
public Pipe(Resources res, int x, int y, int gap, int screenHeight) {
topPipe = BitmapFactory.decodeResource(res, R.drawable.pipe_top);
bottomPipe = BitmapFactory.decodeResource(res, R.drawable.pipe_bottom);
width = topPipe.getWidth();
height = topPipe.getHeight();
// Scale pipes
topPipe = Bitmap.createScaledBitmap(topPipe, width, height, false);
bottomPipe = Bitmap.createScaledBitmap(bottomPipe, width, height, false);
this.x = x;
this.y = y;
this.gap = gap;
}
public void update() {
x -= speed;
}
public void draw(Canvas canvas) {
canvas.drawBitmap(topPipe, x, y - gap - height, null);
canvas.drawBitmap(bottomPipe, x, y, null);
}
public void resetPosition(int x, int y) {
this.x = x;
this.y = y;
}
public boolean collidesWith(Bird bird) {
// Collision detection logic
return false; // Implement rectangle collision detection
}
public int getX() {
return x;
}
public int getWidth() {
return width;
}
}
Audio Implementation
Use SoundPool to play sound effects.
In GameView.java:
Add the following imports and variables:
import android.media.AudioAttributes;
import android.media.SoundPool;
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
// ... previous code
private SoundPool soundPool;
private int soundWing, soundPoint, soundHit;
// ... inside constructor
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
soundPool = new SoundPool.Builder()
.setMaxStreams(3)
.setAudioAttributes(audioAttributes)
.build();
soundWing = soundPool.load(context, R.raw.wing, 1);
soundPoint = soundPool.load(context, R.raw.point, 1);
soundHit = soundPool.load(context, R.raw.hit, 1);
}
Play sounds at appropriate places:
public void update() {
if (!gameOver) {
// ... previous code
if (pipeManager.checkCollision(bird)) {
gameOver = true;
soundPool.play(soundHit, 1, 1, 0, 0, 1);
}
}
}
public boolean onTouchEvent(MotionEvent event) {
// ... previous code
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (!gameOver) {
bird.flap();
soundPool.play(soundWing, 1, 1, 0, 0, 1);
}
}
return true;
}
Collision Detection
Implement collision detection between the bird and the pipes.
Update Pipe.java:
public boolean collidesWith(Bird bird) {
// Bird rectangle
Rect birdRect = new Rect(bird.getX(), bird.getY(), bird.getX() + bird.getWidth(), bird.getY() + bird.getHeight());
// Top pipe rectangle
Rect topPipeRect = new Rect(x, y - gap - height, x + width, y - gap);
// Bottom pipe rectangle
Rect bottomPipeRect = new Rect(x, y, x + width, y + height);
return Rect.intersects(birdRect, topPipeRect) || Rect.intersects(birdRect, bottomPipeRect);
}
Final Adjustments
-
Screen Dimensions:
-
Update GameView constructor to get screen dimensions:
Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
-
Bird Position:
-
Adjust Pipe Positioning:
- Ensure pipes are generated and moved correctly based on screen dimensions.
Conclusion
This is a simplified version of the Flappy Bird game. You may need to adjust image scaling, positions, and collision detection to suit your specific images and screen sizes. Also, consider adding features like score tracking, better game over handling, and smoother animations for a more polished game.
Note: Be sure to replace placeholder resource IDs (e.g., R.drawable.bird, R.raw.wing) with your actual resource files. The code provided is a basic template and may require debugging and additional enhancements.