0% found this document useful (0 votes)
62 views

Flappy Bird - Java Code

A reference and break down of a java code for a simple game of flappy bird.

Uploaded by

jeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Flappy Bird - Java Code

A reference and break down of a java code for a simple game of flappy bird.

Uploaded by

jeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

package flappybird;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics; The list of imported classes to be used
import java.awt.Graphics2D; for graphics, mouse and key
import java.awt.Rectangle; interactions, array, random int, timer
import java.awt.RenderingHints; and screen frame.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.Timer;

public class FlappyBird implements ActionListener, MouseListener, KeyListener {

public static FlappyBird flappyBird;


public final int WIDTH = 1000, HEIGHT = 650; The flappy bird class implements
ActionListener, MouseListener, and
public Renderer renderer; KeyListener, ActionListenerr - allows
public Rectangle bird; the code to define a beahaviour to
public ArrayList<Rectangle> columns; occur periodically. MouseListener and
public int ticks, yMotion, score, elapsedSeconds; KeyListener to set up buttons or keys
public boolean gameOver, started; that can be used to interact or make
List of intances of
variables our sprite fly/jump.
private float columnSpeedMultiplier = 1.0f;

public Random rand;

public FlappyBird() {

JFrame frame = new JFrame();


Timer timer = new Timer(20, this); This FlappyBird method handles the frame
variables and set up of the game and is
renderer = new Renderer(); important to avoid error with non-static
rand = new Random(); variables.

frame.add(renderer);
frame.setTitle("Flappy Bird");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.addMouseListener(this);
frame.addKeyListener(this);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);

bird = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 20, 20);


columns = new ArrayList<Rectangle>(); When the game is run, it sets the bird sprite in
the middle of the screen and calls the columns in
for (int i = 0; i <= 4; i++) { the Rectangle array at the ready.
addColumn(true);
}

The timer.start() initiates the


timer.start(); game loop.
}

private void addColumn(boolean start) {


int space = 300; The rand.nextInt(300) gives a
int width = 100; random number that changes the
height of the columns.
int height = 50 + rand.nextInt(300);

if (start) {
columns.add(new Rectangle(WIDTH + width + columns.size() * 300, HEIGHT - height - 120, width, height));
columns.add(new Rectangle(WIDTH + width + (columns.size() - 1) * 300, 0, width, HEIGHT - height - space));
} else {
columns.add(new Rectangle(columns.get(columns.size() - 1).x + 600, HEIGHT - height - 120, width, height));
columns.add(new Rectangle(columns.get(columns.size() - 1).x, 0, width, HEIGHT - height - space));
}
}

If start becomes true, green rectangles that are opposite of each other are
created, replicating the pipes in the original Flappy Bird game.

It will set the columns on the right side of the screen then, it will continue to
create it as the game goes. The height is set to random to create variation for
the bird’s obstacles.

public void paintColumn(Graphics g, Rectangle column) { This method gives the column its
g.setColor(Color.green.darker()); shape and color.
g.fillRect(column.x, column.y, column.width, column.height);
}
Public void jump() {

if (gameOver) {
bird = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 20, 20);
If gameOver is true, a new rectangle
columns.clear();
will be created. The columns will be
yMotion = 0;
cleared, the yMotion and score will
score = 0;
revert back to 0. The
columnSpeedMultiplier = 1;
columnSpeedMultiplier will go back
to 1.
for (int i = 0; i <= 4; i++) {
addColumn(true);
New columns will be called again and
}
the gameOver will be set to false.
gameOver = false;
}

if (!started) {
If started is false, asign it with true.
started = true;
And as the jump method is being
} else if (!gameOver) {
called, it will assign -8 to the yMotion
if (yMotion > 0) {
of the bird sprite.
yMotion = 0;
}
Else, if the gameOver is false set the
yMotion -= 8;
the yMotion to 0 is it’s greater than
}
0.
}

When the time.start()


@Override actionPerformed is called repeatedly
public void actionPerformed(ActionEvent e) { through the interval for the game
logic and graphical to be updated.

int speed = (int) (10 * columnSpeedMultiplier);

The speed variable controls the


elapsedSeconds += 20; speed in which the columns passes
throught the screen.
if (elapsedSeconds >= 10000) {
columnSpeedMultiplier += 0.2f;
elapsedSeconds = 0;
} For every 10 seconds the
columnSpeedMultiplier will increase
by 0.2 that will then be multiplied
with speed.

elapsedSeconds will turn back to 0 to


give the game another 10 seconds
before the column speed increases.
ticks++; If started is true columns in the
Rectangle array will be moved to the
if (started) { left side of the screen.
for (int i = 0; i < columns.size(); i++) {
Rectangle column = columns.get(i); Ticks increases everytime
column.x -= speed; actionPerformed is called. If ticks
} divided by 2 is equals to 0 and the
yMotion is less than 15, increase the
if (ticks % 2 == 0 && yMotion < 15) { yMotion to 2. This will simulate
yMotion += 2; gravity for the bird sprite when
} jump() is not being called.

for (int i = 0; i < columns.size(); i++) {


Rectangle column = columns.get(i);
For each column within the
Rectangle array; if the column’s x
if (column.x + column.width < 0) {
and y are less than 0, or out of
columns.remove(column);
bound of the screen, then remove
that column from the array.
if (column.y == 0) {
addColumn(false);
If the column’s y postion is 0, set
}
addColumn false.
}
}

Updates the bird srite’s position


bird.y += yMotion;
as the game progress.

for (Rectangle column : columns) {


if (column.y == 0 && bird.x + bird.width / 2 > column.x + column.width / 2 - 10
&& bird.x + bird.width / 2 < column.x + column.width / 2 + 10) {
score++;

if (column.intersects(bird)) {
gameOver = true;

For each column in the Rectangle array, if the bird’s


width and x postion doesn’t meet with the top
column’s x and width, it has successfully passes by.

The score increases.

If the bird intersects with the columns, gameOver wil


be set to true.
if (bird.x <= column.x) {
bird.x = column.x - bird.width;
} else {
if (column.y != 0) {
bird.y = column.y - bird.height; If the column and bird intersects, the bird will be
} else if (bird.y < column.height) { given a new value so that it won’t overlap with the
bird.y = column.height; column’s area.
}
}
}
}

if (bird.y > HEIGHT - 120 || bird.y < 0) {


If the bird sprite’s y postion is greater than the height
gameOver = true;
- 120 (inlcuding the orange bar that acts as the
}
ground) or of it goes beyond 0, set the gameOver to
true.
if (bird.y + yMotion >= HEIGHT - 120) {
bird.y = HEIGHT - 120 - bird.height;
If the bird’s y position and yMotion is equals to the
gameOver = true;
position of the ground. Set it’s y position so that it
}
stays above ground and not overlap with the graphic.
}
Then call and update the graphics of the game
renderer.repaint();
through renderer.repaint()
}

private void paintCloud(Graphics g) {


int[] cloudX = { 100, 400, 600, 500, 700 };
int[] cloudY = { 200, 500, 200, 300, 500 };

for (int i = 0; i < cloudX.length; i++) {


drawCloud(g, cloudX[i], cloudY[i]);
} If the column and bird intersects, the bird will be
} given a new value so that it won’t overlap with the
column’s area.
private void drawCloud(Graphics g, int x, int y) {
g.setColor(Color.WHITE);

g.fillRect(x, y, 50, 20);


g.fillRect(x - 5, y + 5, 40, 20);
g.fillRect(x + 20, y - 10, 20, 20);
}

The repaint(Graphics g) handles the background, the


bird, the ground, the columns, as well as the text on
public void repaint(Graphics g) {
the screen.
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

g.setColor(new Color(124, 230, 201));


g.fillRect(0, 0, WIDTH, HEIGHT);

paintCloud(g);

g.setColor(Color.orange);
g.fillRect(0, HEIGHT - 120, WIDTH, 120);

g.setColor(Color.green);
g.fillRect(0, HEIGHT - 120, WIDTH, 20);

g2d.setColor(Color.yellow);
g.fillOval(bird.x, bird.y, bird.width, bird.height);

g2d.setColor(Color.black);
g.drawOval(bird.x, bird.y, bird.width, bird.height);

for (Rectangle column : columns) {


paintColumn(g, column);
}

g.setColor(Color.white);
g.setFont(new Font("Arial", 1, 100));

if (!started) {
g.drawString("Click to start!", 150, HEIGHT / 2 - 50);
}

if (gameOver) {
g.drawString("Game Over!", 220, HEIGHT / 2 - 90); The drawString method shows the
g.drawString("Retry Again!", 220, HEIGHT / 2 - 0); texts and score on the screen of the
game.
g.setFont(new Font("Arial", 1, 50));
g.drawString("Score: " + score, WIDTH / 2 - 70, HEIGHT / 2 + 150);
}

if (!gameOver && started) {


g.drawString("Score: " + score, WIDTH / 2 - 250, 100);
}
}

public static void main(String[] args) {


flappyBird = new FlappyBird();
}
@Override
public void mouseClicked(MouseEvent e) {
jump();
} The mouseClicked and keyReleased
event calls on the jump() method
@Override when, a mouse was clicked or of the
public void keyReleased(KeyEvent e) { space bar is pressed.
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
jump();
}
}

@Override
public void mousePressed(MouseEvent e) {
}

@Override
public void mouseReleased(MouseEvent e) {
}

@Override
public void mouseEntered(MouseEvent e) {
}

@Override
public void mouseExited(MouseEvent e) {
}

@Override
public void keyTyped(KeyEvent e) {
}

@Override
public void keyPressed(KeyEvent e) {
}
}
import java.awt.Graphics;

import javax.swing.JPanel;

public class Renderer extends JPanel


{ The renderer class renders the
@Override graphics and allows the repaint
protected void paintComponent(Graphics g) method to be updated.
{
super.paintComponent(g);
FlappyBird.flappyBird.repaint(g);

}
}

You might also like