Game Development 8 min read

Build a Fruit Ninja Clone in Python with Pygame – Step‑by‑Step Guide

This tutorial walks you through creating a Fruit Ninja‑style game in Python using Pygame, covering required imports, window configuration, random fruit generation, drawing text and lives, handling game‑over screens, and implementing the main game loop with full source code examples.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Build a Fruit Ninja Clone in Python with Pygame – Step‑by‑Step Guide

1. Required Packages

import pygame, sys
import os
import random

2. Window Setup

Define the display size and frame rate, initialize Pygame, set the window caption, and create the main display surface.

WIDTH = 800
HEIGHT = 500
FPS = 15  # 1/12 second per frame
pygame.init()
pygame.display.set_caption('水果忍者')
gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED   = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE  = (0, 0, 255)
background = pygame.image.load('背景.jpg')
font = pygame.font.Font(os.path.join(os.getcwd(), 'comic.ttf'), 42)
score_text = font.render('Score : ' + str(score), True, (255,255,255))

3. Random Fruit Generation

Generate a random position, speed, and image for each fruit and store the data in a dictionary.

def generate_random_fruits(fruit):
    fruit_path = "images/" + fruit + ".png"
    data[fruit] = {
        'img': pygame.image.load(fruit_path),
        'x': random.randint(100, 500),
        'y': 800,
        'speed_x': random.randint(-10, 10),
        'speed_y': random.randint(-80, -60),
        'throw': False,
        't': 0,
        'hit': False
    }

# Initialize data for all fruit types
data = {}
for fruit in fruits:
    generate_random_fruits(fruit)

4. Drawing Text

Utility function to render and blit text onto the screen.

def draw_text(display, text, size, x, y):
    font_name = pygame.font.match_font('comic.ttf')
    font = pygame.font.Font(font_name, size)
    text_surface = font.render(text, True, WHITE)
    text_rect = text_surface.get_rect()
    text_rect.midtop = (x, y)
    display.blit(text_surface, text_rect)

5. Player Lives Indicator

def draw_lives(display, x, y, lives, image):
    for i in range(lives):
        img = pygame.image.load(image)
        img_rect = img.get_rect()
        img_rect.x = int(x + 35 * i)
        img_rect.y = y
        display.blit(img, img_rect)

def hide_cross_lives(x, y):
    gameDisplay.blit(pygame.image.load("images/red_lives.png"), (x, y))

6. Game Over Screen

def show_gameover_screen():
    gameDisplay.blit(background, (0,0))
    draw_text(gameDisplay, "FRUIT NINJA!", 90, WIDTH/2, HEIGHT/4)
    if not game_over:
        draw_text(gameDisplay, "Score : " + str(score), 50, WIDTH/2, HEIGHT/2)
    draw_text(gameDisplay, "Press a key to begin!", 64, WIDTH/2, HEIGHT*3/4)
    pygame.display.flip()
    waiting = True
    while waiting:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYUP:
                waiting = False

7. Main Game Loop

The loop controls game state, renders objects, checks collisions, updates scores, and handles player lives.

first_round = True
game_over = True
game_running = True
while game_running:
    if game_over:
        if first_round:
            show_gameover_screen()
            first_round = False
        game_over = False
        player_lives = 3
        draw_lives(gameDisplay, 690, 5, player_lives, 'images/red_lives.png')
        score = 0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_running = False
    gameDisplay.blit(background, (0,0))
    gameDisplay.blit(score_text, (0,0))
    draw_lives(gameDisplay, 690, 5, player_lives, 'images/red_lives.png')
    for key, value in data.items():
        if value['throw']:
            value['x'] += value['speed_x']
            value['y'] += value['speed_y']
            value['speed_y'] += 1 * value['t']
            value['t'] += 1
            if value['y'] <= 800:
                gameDisplay.blit(value['img'], (value['x'], value['y']))
            else:
                generate_random_fruits(key)
        current_position = pygame.mouse.get_pos()
        if not value['hit'] and current_position[0] > value['x'] and current_position[0] < value['x']+60 and \
           current_position[1] > value['y'] and current_position[1] < value['y']+60:
            if key == 'bomb':
                player_lives -= 1
            if player_lives == 0:
                hide_cross_lives(690,15)
                show_gameover_screen()
                game_over = True
            elif player_lives == 1:
                hide_cross_lives(725,15)
            elif player_lives == 2:
                hide_cross_lives(760,15)
            if key != 'bomb':
                score += 1
                score_text = font.render('Score : ' + str(score), True, (255,255,255))
                value['hit'] = True
        else:
            generate_random_fruits(key)
    pygame.display.update()
    clock.tick(FPS)
pygame.quit()
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonprogrammingPygameFruit Ninja
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.