Table of Contents
Create two elves and build background elements
Zongzi and love
Background construction
collision module
Eat the ❤ when the collision is reached, set
Use
Home Backend Development Python Tutorial How to implement cute little rice dumplings in Python

How to implement cute little rice dumplings in Python

May 13, 2023 pm 09:25 PM
python

Create two elves and build background elements

Zongzi and love

First create a zongzi object, which is an elf, and the class needs to inherit pygame.sprite.Sprite Class, this is an important part of the collision module. updateThe function is to control the direction of the zongzi and prevent the zongzi from running out of the boundary. When the zongzi touches the boundary, it starts the bottom-out function, causing the zongzi to bounce in the other direction of the boundary.

class Player(pygame.sprite.Sprite):
    """
    粽子对象
    """
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('min2.png')
        self.image = pygame.transform.scale(self.image, (130, 130))
        print(self.image)
        self.rect = self.image.get_rect()
        self.rect.midbottom = (20, screen_height )
    def update(self):
        screen.blit(self.image, (self.rect.x, self.rect.y))
        screen.blit(self.image, self.rect)
        x_move = 0
        y_move = 0
        # 获取按键,并进行相应的移动
        key = pygame.key.get_pressed()
        #通过控制数字来设置粽子速度
        if key[pygame.K_LEFT]:
            x_move -= 4
        if key[pygame.K_RIGHT]:
            x_move += 4
        if key[pygame.K_UP]:
            y_move -= 4
        if key[pygame.K_DOWN]:
            y_move += 4
        self.rect.x += x_move
        self.rect.y += y_move
        # 控制人物的最低位置
        if self.rect.bottom > screen_height+330 :
            self.rect.bottom = screen_height + 330
        # 绘制粽子
        screen.blit(self.image, self.rect)
        #防止粽子跑出边界
        if  self.rect.right > 1400:
            self.rect.x -= 20
        elif  self.rect.left <=-10:
            self.rect.x += 20
        elif  self.rect.top < 0:
            self.rect.y += 50
        elif self.rect.bottom> 730:
            self.rect.y -= 60
Copy after login

Add a ❤ and score points when the salty rice dumpling eats ❤. It must also inherit the pygame.sprite.Sprite class, and use Move_update to make ❤ appear randomly in the game and move within the game boundaries.

class Heart_game(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.Heart_speed = [2,-3]
        # 加载小球图片
        self.image = pygame.image.load(&#39;min_love.png&#39;).convert_alpha()
        # 获取小球图片的区域开状
        self.rect = self.image.get_rect()
        x,y = random.randint(0,1300),random.randint(0,700)
        self.active = True
        self.rect.midbottom = (x, y )
    def Move_update(self):
        self.rect = self.rect.move(self.Heart_speed)
        #绘制爱心图片
        screen.blit(self.image, self.rect)
        if  self.rect.right > 1400:
            x = random.randint(-5, 0)
            y = random.randint(-5, -2) or random.randint(1, 5)
            self.Heart_speed = [x, y]
        elif  self.rect.left <=-10:
            x = random.randint(0, 5)
            y = random.randint(-5, 5)
            self.Heart_speed = [x, y]
        elif  self.rect.top < -10:
            x = random.randint(-3,3)
            y = random.randint(0,3)
            self.Heart_speed = [x,y]
        elif self.rect.bottom> 695:
            x = random.randint(-3, 3)
            y = random.randint(-3,0)
            self.Heart_speed = [x, y]
Copy after login

Note: \color{#FF45b0}{Note:} Note: screen.blit(image, rect)In order to draw a picture in the game, it must contain two parameters, one is The picture itself, and the other is the position of the picture in the game, which is rect.

Background construction

Import pictures directly and display them in the loop

bg = pygame.image.load("vack.jpeg").convert()
#下句需在游戏主循环中使用
screen.blit(bg, (0, 0))
Copy after login

After the construction is completed, it will be

How to implement cute little rice dumplings in Python

collision module

I worked hard on the collision part, using the following sentences, especially! ! \color{blue}{Especially! ! } especially! ! I thought there was no collision at first, so I added multiple statements. In fact, it happened, but I didn’t add any statements ->What would happen under this condition, causing this tragedy... Let’s analyze this carefully. Segment condition,

player

is a zongzi object, group is a group containing ❤, pygame.sprite.collide_circle_ratio(0.5) can control the image collision volume, so the collision Conditions met! <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>if pygame.sprite.spritecollide(player,group,True,pygame.sprite.collide_circle_ratio(0.5)) : 语句</pre><div class="contentsignin">Copy after login</div></div>Greedy module

Eat the ❤ when the collision is reached, set

l

to an empty array, use l.append(aixin)Add the ❤ instance. When the array l exists, enter the collision link. After the collision, use the pop function to delete ❤. Then add judgment. If the array l is empty, add a new ❤ game instance, which is the above ❤ instance

    for each in l:
        each.Move_update()
        screen.blit(each.image, each.rect)
        if pygame.sprite.spritecollide(player,group,True,pygame.sprite.collide_circle_ratio(0.5)) :
                l.pop()
                score += 1
                print(score)
                # del aixin
    if not l:
        l.append(Heart_game())
        group.add(l[0])
Copy after login

Counting mechanism

Use

score

Calculate, reference a ttf font file <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>score = 0 score_font = pygame.font.Font(&quot;font.ttf&quot;,50) score_text = score_font.render(&quot;Score: % s&quot; % str(score), True, BLACK) screen.blit(score_text, (0, 0))</pre><div class="contentsignin">Copy after login</div></div> and finally render it as

How to implement cute little rice dumplings in Python

## complete code How to implement cute little rice dumplings in Python

import pygame
from pygame.locals import *
import pygame
import sys
import asyncio
import time
import random
class Player(pygame.sprite.Sprite):
    #粽子对象
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(&#39;min2.png&#39;)
        self.image = pygame.transform.scale(self.image, (130, 130))
        print(self.image)
        self.rect = self.image.get_rect()
        self.rect.midbottom = (20, screen_height )
    def update(self):
        screen.blit(self.image, (self.rect.x, self.rect.y))
        screen.blit(self.image, self.rect)
        x_move = 0
        y_move = 0
        # 获取按键,并进行相应的移动
        key = pygame.key.get_pressed()
        if key[pygame.K_LEFT]:
            x_move -= 4
        if key[pygame.K_RIGHT]:
            x_move += 4
        if key[pygame.K_UP]:
            y_move -= 4
        if key[pygame.K_DOWN]:
            y_move += 4
        self.rect.x += x_move
        self.rect.y += y_move
        # 控制人物的最低位置
        # 绘制人物
        screen.blit(self.image, self.rect)
        if  self.rect.right > 1400:
            self.rect.x -= 20
        elif  self.rect.left <=-10:
            self.rect.x += 20
        elif  self.rect.top < 0:
            self.rect.y += 50
        elif self.rect.bottom> 730:
            self.rect.y -= 60
    # def eat(self):
class Heart_game(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.Heart_speed = [2,-3]
        # 加载小球图片
        self.image = pygame.image.load(&#39;min_love.png&#39;).convert_alpha()
        # 获取小球图片的区域开状
        self.rect = self.image.get_rect()
        x,y = random.randint(0,1300),random.randint(0,700)
        self.active = True
        self.rect.midbottom = (x, y )
    def Move_update(self):
        self.rect = self.rect.move(self.Heart_speed)
        screen.blit(self.image, self.rect)
        if  self.rect.right > 1400:
            x = random.randint(-5, 0)
            y = random.randint(-5, -2) or random.randint(1, 5)
            self.Heart_speed = [x, y]
        elif  self.rect.left <=-10:
            x = random.randint(0, 5)
            y = random.randint(-5, 5)
            self.Heart_speed = [x, y]
        elif  self.rect.top < -10:
            x = random.randint(-3,3)
            y = random.randint(0,3)
            self.Heart_speed = [x,y]
        elif self.rect.bottom> 695:
            x = random.randint(-3, 3)
            y = random.randint(-3,0)
            self.Heart_speed = [x, y]
# 加载基本的窗口和时钟
pygame.init()
screen_width = 1400
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption(&#39;迟到的端午&#39;)
clock = pygame.time.Clock()  # 设置时钟
# 加载背景,粽子,爱心
bg = pygame.image.load("vack.jpeg").convert()
player = Player()
aixin = Heart_game()
group = pygame.sprite.Group(aixin)
count = 0
score = 0
score_font = pygame.font.Font("font.ttf",50)
BLACK= (0,0,0)
l = []
l.append(aixin)
#  游戏主循环
game_run = 1
while game_run:
    clock.tick(60)
    screen.blit(bg, (0, 0))
    # 持续更新
    count += 1
    for each in l:
        each.Move_update()
        screen.blit(each.image, each.rect)
        if pygame.sprite.spritecollide(player,group,True,pygame.sprite.collide_circle_ratio(0.5)) :
                l.pop()
                score += 1
                print(score)
                # del aixin
    if not l:
        l.append(Heart_game())
        group.add(l[0])
    player.update()
    score_text = score_font.render("Score: % s" % str(score), True, BLACK)
    screen.blit(score_text, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_run = False
    # 窗口更新并绘制
    pygame.display.update()
pygame.quit()
Copy after login

The above is the detailed content of How to implement cute little rice dumplings 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 Article Tags

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 download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download deepseek Xiaomi

What are the advantages and disadvantages of templating? What are the advantages and disadvantages of templating? May 08, 2024 pm 03:51 PM

What are the advantages and disadvantages of templating?

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Jul 01, 2024 am 07:22 AM

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step May 06, 2024 pm 03:52 PM

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

Share several .NET open source AI and LLM related project frameworks

A complete guide to golang function debugging and analysis A complete guide to golang function debugging and analysis May 06, 2024 pm 02:00 PM

A complete guide to golang function debugging and analysis

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

How do you ask him deepseek

What software is NET40? What software is NET40? May 10, 2024 am 01:12 AM

What software is NET40?

See all articles