这种一般要用pygame.sprite.Sprite类(动画精灵),你再稍微改一下,即可:import sys
import pygame
class ImgSpite(pygame.sprite.Sprite):
def __init__(self, img_obj, img_name, x, y):
super().__init__()
self.image = img_obj
self.name = img_name
self.rect = self.image.get_rect(center=(x,y))
# self.clicked = False
def clicked_test(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN: # 判断鼠标是否被按下(注:鼠标有三个键哦)
# p1, p2, p3 = pygame.mouse.get_pressed()
if self.rect.collidepoint(event.pos): # 判断点击区域是否在其区域内
print(self.name, "被点击了!")
# 初始化
pygame.init()
# 背景 与 屏幕大小
bg = pygame.image.load("background.png")
sw, sh = bg.get_width(), bg.get_height()
screen = pygame.display.set_mode((sw, sh))
# 元素图片精灵
t2048 = ImgSpite(pygame.image.load("2048_0.1x.png"), 't2048', 100, 200)
snake = ImgSpite(pygame.image.load("snake_0.1x.png"),'snake', 300, 200)
group = pygame.sprite.Group([t2048, snake]) # 放到“精灵组”里,才方便监测碰撞
# group.add() # 图片精灵可以单独添加进去
while True:
event_list = pygame.event.get() # 获取全部事件(事件清单)
for event in event_list:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
for sprite in group:
sprite.clicked_test(event_list)
#绘制背景
screen.blit(bg,(0,0))
#绘制图片
screen.blit(snake.image, snake.rect)
screen.blit(t2048.image, t2048.rect)
#刷新
pygame.display.update()
|