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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

See all articles