Table of Contents
1. Packages that need to be imported
2. Window interface settings
3. Randomly generate fruit positions
4. Drawing fonts
5. Tips for player life
6. Game start and end screens
7. Game main loop
Home Backend Development Python Tutorial Fruit cutting brick game implemented in Python

Fruit cutting brick game implemented in Python

Apr 22, 2023 pm 06:58 PM
python game fruit Ninja

The gameplay of Fruit Ninja is very simple, just cut the thrown fruits as much as possible.

Today Xiaowu will use python to simply simulate this game. In this simple project, we use the mouse to select the fruit to cut, and the bomb will be hidden in the fruit. If the bomb is cut three times, the player will fail.

Fruit cutting brick game implemented in Python

1. Packages that need to be imported

import pygame, sys
import os
import random
Copy after login

2. Window interface settings

# 游戏窗口
WIDTH = 800
HEIGHT = 500
FPS = 15 # gameDisplay的帧率,1/12秒刷新一次
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)) # 得分字体样式
Copy after login

3. Randomly generate fruit positions

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,
}
if random.random() >= 0.75:
data[fruit]['throw'] = True
else:
data[fruit]['throw'] = False
data = {}
for fruit in fruits:
generate_random_fruits(fruit)
Copy after login
  • This function is used to randomly generate fruits and save fruit data.
  • 'x' and 'y' store the position of the fruit on the x and y coordinates.
  • Speed_x and speed_y store the moving speed of the fruit in the x and y directions. It also controls the diagonal movement of the fruit.
  • throw, used to determine whether the generated fruit coordinates are outside the game. If it is outside, it will be discarded.
  • The data dictionary is used to store randomly generated fruit data.

4. Drawing fonts

font_name = pygame.font.match_font('comic.ttf')
def draw_text(display, text, size, x, y):
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)
gameDisplay.blit(text_surface, text_rect)
Copy after login
  • The Draw_text function can draw text on the screen.
  • get_rect() returns a Rect object.
  • X and y are the positions in the X and Y directions.
  • blit() draws an image or writes text at a specified location on the screen.

5. Tips for player life

# 绘制玩家的生命
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))
Copy after login
  • img_rect gets the (x, y) coordinates of the cross icon (located at the top right).
  • img_rect .x Set the next cross icon to be 35 pixels away from the previous icon.
  • img_rect.y is responsible for determining where the cross icon starts from the top of the screen.

6. Game start and end screens

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
Copy after login
  • show_gameover_screen() function displays the initial game screen and the game end screen.
  • pygame.display.flip() will only update part of the screen, but if no arguments are passed, the entire screen will be updated.
  • pygame.event.get() will return all events stored in the pygame event queue.
  • If the event type is equal to quit, then pygame will exit.
  • event.KEYUP event, an event that occurs when the key is pressed and released.

7. Game main loop

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)
elif player_lives == 1 :
hide_cross_lives(725, 15)
elif player_lives == 2 :
hide_cross_lives(760, 15)
if player_lives < 0 :
show_gameover_screen()
game_over = True
half_fruit_path = "images/explosion.png"
else:
half_fruit_path = "images/" + "half_" + key + ".png"
value['img'] = pygame.image.load(half_fruit_path)
value['speed_x'] += 10
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()
Copy after login
  • This is the main loop of the game
  • If more than 3 bombs are cut off , game_over terminates the game and loops at the same time.
  • game_running is used to manage the game loop.
  • If the event type is exit, then the game window will be closed.
  • In this game loop, we dynamically display the fruits on the screen.
  • If a fruit is not cut, nothing will happen to it. If the fruit is cut, then a half-cut image of the fruit should appear in its place.
  • If the user clicks the bomb three times, the GAME OVER message will be displayed and the window will be reset.
  • clock.tick() will keep the loop running at the correct speed. The loop should update after every 1/12 seconds.

The above is the detailed content of Fruit cutting brick game implemented in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Can Python parameter annotations use strings? Can Python parameter annotations use strings? Apr 01, 2025 pm 08:39 PM

Alternative usage of Python parameter annotations In Python programming, parameter annotations are a very useful function that can help developers better understand and use functions...

How do Python scripts clear output to cursor position at a specific location? How do Python scripts clear output to cursor position at a specific location? Apr 01, 2025 pm 11:30 PM

How do Python scripts clear output to cursor position at a specific location? When writing Python scripts, it is common to clear the previous output to the cursor position...

How to use Python and OCR technology to try to crack complex verification codes? How to use Python and OCR technology to try to crack complex verification codes? Apr 01, 2025 pm 10:18 PM

Exploration of cracking verification codes using Python In daily network interactions, verification codes are a common security mechanism to prevent malicious manipulation of automated programs...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

How to solve the problem of missing dynamic loading content when obtaining web page data? How to solve the problem of missing dynamic loading content when obtaining web page data? Apr 01, 2025 pm 11:24 PM

Problems and solutions encountered when using the requests library to crawl web page data. When using the requests library to obtain web page data, you sometimes encounter the...

How to use Go or Rust to call Python scripts to achieve true parallel execution? How to use Go or Rust to call Python scripts to achieve true parallel execution? Apr 01, 2025 pm 11:39 PM

How to use Go or Rust to call Python scripts to achieve true parallel execution? Recently I've been using Python...

See all articles