Flappy Bird Game using Python

Flappy Bird Game using Python

Introduction

In this article, we’ll demonstrate the process of building a Flappy Bird game using Python and Tkinter. Tkinter is a powerful library for creating graphical user interfaces (GUIs), while Python’s simplicity and versatility make it an excellent choice for game development. By the end of this tutorial, you’ll have a functional Flappy Bird game that you can play and customize.

Setup

To get started, ensure that you have Python installed on your system. Tkinter comes pre-installed with Python, so there’s no need for additional installations. You can use any text editor or IDE of your choice to write the code.

Download Python

Implementation

  1. Importing Necessary Libraries: We start by importing the required libraries. Tkinter will be used for creating the GUI components.
  2. Creating the FlappyBird Class: We define a class named FlappyBird, which will encapsulate all the functionalities of our game.
  3. Initializing the GUI: Inside the __init__ method of the FlappyBird class, we create the main window, canvas for drawing game elements, bird, pipes, labels for score display, and buttons for starting and resetting the game.
  4. Starting the Game: When the “Start Game” button is clicked, the start_game method is called. This method initializes the game state and starts the game loop by calling the move method.
  5. Game Loop: The move method handles the movement of game elements such as pipes and the bird. It also checks for collisions and updates the score accordingly.
  6. Handling User Input: We bind the spacebar key to make the bird jump when pressed. The jump method is called to move the bird upward.
  7. Collision Detection: The check_collision method detects collisions between the bird and pipes. If a collision occurs, the game ends, and the “Game Over” text is displayed.
  8. Saving and Displaying High Score: We implement methods to save and retrieve the high score from a text file. The high score is displayed on the GUI.
  9. Starting a New Game: The “New Game” button allows the player to start a new game. It resets the game state, including the score, bird position, pipe positions, and hides the “Game Over” text.

Explanation

This project utilizes Tkinter for creating a simple GUI with buttons and a canvas. The game logic is based on the classic Flappy Bird gameplay, where the player controls a bird that must navigate through a series of pipes. The objective is to avoid colliding with the pipes for as long as possible.

The game consists of a bird and a series of pipes represented as rectangles on the canvas. The bird moves vertically in response to player input (spacebar key), simulating a flying motion. The pipes move horizontally across the screen, and the player must maneuver the bird to fly through the gaps between them.

Collision detection is implemented to detect when the bird collides with a pipe or the ground. When a collision occurs, the game ends, and a “Game Over” message is displayed on the screen.

A “Start Game” button allows players to begin the game, while a “New Game” button enables them to start a new game after the current one ends. The score is displayed on the screen, updating each time the bird successfully passes through a gap between pipes.

The game responds to player input by detecting spacebar key presses, causing the bird to flap its wings and ascend slightly. The gravity effect is simulated by gradually lowering the bird’s altitude over time, creating a sense of challenge and urgency for the player.

Conclusion

In this article, we’ve demonstrated how to create a simple Flappy Bird game using Python and Tkinter. This project serves as a fun way to practice GUI programming and game development concepts. Feel free to customize and enhance the game further by adding sound effects, improving graphics, or implementing additional features. Happy coding and happy gaming!

See some more similar posts: Click Here

Source Code for Flappy Bird Game using Python

import tkinter as tk
import random

class FlappyBird:
    def __init__(self, master):
        self.master = master
        self.canvas = tk.Canvas(master, width=400, height=400)
        self.canvas.pack()

        self.bird = self.canvas.create_rectangle(50, 200, 70, 220, fill='yellow')
        self.pipe_upper = self.canvas.create_rectangle(400, 0, 420, 150, fill='green')
        self.pipe_lower = self.canvas.create_rectangle(400, 250, 420, 400, fill='green')

        self.score_label = tk.Label(master, text="Score: 0")
        self.score_label.pack()

        self.high_score_label = tk.Label(master, text="High Score: {}".format(self.get_high_score()))
        self.high_score_label.pack()

        self.start_button = tk.Button(master, text="Start Game", command=self.start_game)
        self.start_button.pack()

        self.new_game_button = tk.Button(master, text="New Game", command=self.new_game)
        self.new_game_button.pack()
        self.new_game_button.config(state=tk.DISABLED)

        self.game_over_text = None  # To store the reference to the game over text object

        self.y = 0
        self.score = 0
        self.high_score = self.get_high_score()
        self.game_over = False

        self.canvas.bind_all('<KeyPress-space>', self.jump)

    def start_game(self):
        self.start_button.config(state=tk.DISABLED)
        self.new_game_button.config(state=tk.NORMAL)
        self.canvas.focus_set()
        self.score = 0
        self.game_over = False
        self.move()
        # Remove game over text if it exists
        if self.game_over_text:
            self.canvas.delete(self.game_over_text)
            self.game_over_text = None

    def new_game(self):
        self.new_game_button.config(state=tk.DISABLED)
        self.start_game()
        # Reset bird position
        self.canvas.coords(self.bird, 50, 200, 70, 220)
        # Reset pipe positions
        self.canvas.coords(self.pipe_upper, 400, 0, 420, 150)
        self.canvas.coords(self.pipe_lower, 400, 250, 420, 400)
        # Reset game state
        self.y = 0
        self.score = 0
        self.score_label.config(text="Score: 0")
        self.game_over = False

    def move(self):
        if not self.game_over:
            self.canvas.move(self.pipe_upper, -5, 0)
            self.canvas.move(self.pipe_lower, -5, 0)
            self.check_collision()
            if self.canvas.coords(self.pipe_upper)[2] < 0:
                self.canvas.move(self.pipe_upper, 420, 0)
                self.canvas.move(self.pipe_lower, 420, 0)
                self.score += 1
                self.score_label.config(text="Score: {}".format(self.score))
                if self.score > self.high_score:
                    self.high_score = self.score
                    self.high_score_label.config(text="High Score: {}".format(self.high_score))
            self.canvas.move(self.bird, 0, self.y)
            self.y += 1
            self.master.after(20, self.move)
        else:
            self.start_button.config(state=tk.NORMAL)
            if self.score > self.high_score:
                self.save_high_score(self.score)
            if not self.game_over_text:
                self.game_over_text = self.canvas.create_text(200, 200, text="Game Over!", font=("Helvetica", 30))

    def jump(self, event):
        if not self.game_over:
            self.y = -10

    def check_collision(self):
        bird_coords = self.canvas.coords(self.bird)
        pipe_upper_coords = self.canvas.coords(self.pipe_upper)
        pipe_lower_coords = self.canvas.coords(self.pipe_lower)

        if (bird_coords[0] < pipe_upper_coords[2] and bird_coords[2] > pipe_upper_coords[0] and
                (bird_coords[1] < pipe_upper_coords[3] or bird_coords[3] > pipe_lower_coords[1])):
            self.game_over = True

    def save_high_score(self, score):
        with open("high_score.txt", "w") as file:
            file.write(str(score))

    def get_high_score(self):
        try:
            with open("high_score.txt", "r") as file:
                return int(file.read())
        except FileNotFoundError:
            return 0

def main():
    root = tk.Tk()
    root.title("Flappy Bird")
    game = FlappyBird(root)
    root.mainloop()

if __name__ == "__main__":
    main()

Output

Leave a Comment