pygame最简无碰撞多关卡示例程序_mask碰撞检测练习

"""
   最简无碰撞多关卡示例程序。本程序实现一个最简单的多关卡程序。仅在抛砖引玉,迷宫程序的碰撞检测最好采用mask。
   请读者把它修改为采用mask进行碰撞的程序,并实现能退回到下一关。当然,读者有兴趣也能把本程序改成用类来实现,即设计一个Level类, 
  设计一个Ball类。
"""

import pygame
from pygame.locals import *

width,height = size = 480,360
screen = pygame.display.set_mode(size)
pygame.display.set_caption("最简无碰撞多关卡示例程序by李兴球")

level_index = 0
level_images = [f"levels/level{i}.png" for i in range(5)]
level_images = [pygame.image.load(im) for im in level_images]
level_masks = [pygame.mask.from_surface(im) for im in level_images]
level_amounts = len(level_images)
sprite = "basketball.png"
sprite = pygame.image.load(sprite)
sprite_mask = pygame.mask.from_surface(sprite)#  角色的mask
pos = (25,280)
sprite_rect = sprite.get_rect(center=pos)
dx, dy = 0, 0                  # 水平和垂直速度
bg_image = level_images[level_index]

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:running=False
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:dx,dy = 1,0
            if event.key == K_LEFT:dx,dy = -1,0
            if event.key == K_UP:dx,dy = 0,-1
            if event.key == K_DOWN:dx,dy = 0,1
        if event.type == KEYUP:dx,dy = 0,0
        

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