亲宝软件园·资讯

展开

Python粽子

Love And Program 人气:1

粽子和爱心制作

PS截取小爱心和我最爱的咸粽子

建立两个精灵并搭建背景元素

粽子和爱心

先是建立一个粽子对象,也就是一个精灵,类里面需要继承pygame.sprite.Sprite类,这是碰撞模块的重要部分。update函数是控制粽子方向,并防止粽子跑出边界,当粽子触碰到边界时出发触底反弹功能,使粽子向边界另一方向反弹移动。

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

在添加一个❤,当咸粽吃到❤时得分。其也必须继承pygame.sprite.Sprite类,通过Move_update使❤随机出现在游戏中,并在游戏边界内移动。

class Heart_game(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.Heart_speed = [2,-3]
        # 加载小球图片
        self.image = pygame.image.load('min_love.png').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]

注 意 : \color{#FF45b0}{注意:} 注意:screen.blit(image, rect)为在游戏中绘制图片,必须包含两个参数,一个是图片本身,另一个是图片在游戏中的位置,即为rect

背景搭建

直接导入图片并在循环中显示

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

搭建完成后为

碰撞模块

碰撞部分我可是煞费苦心啊,使用以下语句, 尤 其 是 ! ! \color{blue}{尤其是!!} 尤其是!!我一开始以为没有碰撞,添加多个语句,实际上他发生了,只是我没有加语句->在此条件下会发生什么,造成这个惨案…

我们来好好分析这段条件,player 是粽子对象,group是一个包含❤的组,pygame.sprite.collide_circle_ratio(0.5)可以控制图片碰撞体积,于是碰撞条件达成!

if pygame.sprite.spritecollide(player,group,True,pygame.sprite.collide_circle_ratio(0.5)) :
	语句

贪吃模块

当达到碰撞时把❤吃掉,设l为一个空数组,用l.append(aixin)加入❤实例,当数组l存在时,进入碰撞环节,碰撞后用pop函数删除❤。

然后加入判断,若数组l为空,则新加入❤游戏实例,也就是上述❤实例

    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])

计数机制

score计算,引用一个ttf字体文件

score = 0
score_font = pygame.font.Font("font.ttf",50)
score_text = score_font.render("Score: % s" % str(score), True, BLACK)
screen.blit(score_text, (0, 0))

最终呈现为

完整代码

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('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
        # 控制人物的最低位置
        # 绘制人物
        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('min_love.png').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('迟到的端午')
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()

加载全部内容

相关教程
猜你喜欢
用户评论