pygame多关卡鼠标操控收集方块核心.py

"""pygame多关卡鼠标操控收集方块核心.py,阅读理解代码重点在于是如何组织多关卡."""
 
import pygame
import random
 
# 定义颜色常量
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
RED      = ( 255,   0,   0)
 
class Block(pygame.sprite.Sprite):
    """方块类,继承自角色类"""
    def __init__(self, color, width, height):
        # 调用父类的初始化方法
        super().__init__() 
 
        # 创建图像,填充颜色,也可从磁盘中加载一幅好看的图
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
 
        # 用图形的矩形对象来代表方块的坐标和宽高
        self.rect = self.image.get_rect()
 
# 初始化pygame引擎
pygame.init()
 
# 设置屏幕宽高,创建屏幕
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 400
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
pygame.display.set_caption("多关卡鼠标操控收集方块核心")
 
# 方块“列表”,由Group类创建
block_list = pygame.sprite.Group()
 
# 所有角色“列表”,由Group类创建
all_sprites_list = pygame.sprite.Group()
 
for i in range(10):
    # 实例化一个方块
    block = Block(BLACK, 20, 15)
 
    # 设置一个随机的坐标
    block.rect.x = random.randrange(SCREEN_WIDTH)
    block.rect.y = random.randrange(SCREEN_HEIGHT)
     
    # 放到方块列表和所有角色列表中,以便统一重画
    block_list.add(block)
    all_sprites_list.add(block)

You must log in to read the rest of this article. Please log in or register as a user.