刮刮乐
刮刮卡通常指卡上的一种覆盖数字和字母密码等的涂层,通常包括纸质和电子两种类型,刮刮卡在市场上有着比较广泛的应用,我们见到最多的应该是各类抽奖活动了
首先,我们弄几张图片做底板,如下所示:
一等奖、二等奖、谢谢惠顾三种,如果我们参与过刮刮卡抽奖的话,会发现几乎刮开都是谢谢惠顾之类的,也就是有个概率的问题,这里我们也简单设置一下,一等奖放一张、二等奖放两张、谢谢惠顾放三张,生成刮刮卡时随机使用底图就可以了。
实现刮刮卡,我们主要用到是 pygame 模块,之前做小游戏时已经用到过几次了,大家应该都比较熟悉,下面看一下具体实现。
我们先定义一下常量,如:路径、图片类型、颜色等,代码实现如下:
1 path = 'prize' 2 ptype = ['jpg', 'png', 'bmp', 'JPG', 'PNG', 'BMP'] 3 # 窗口大小 4 screen_size = (600, 400) 5 white = (255, 255, 255, 20) 6 gray = (192, 192, 192)
然后创建一个窗口,代码实现如下
1 pygame.init() 2 pygame.mouse.set_cursor(*pygame.cursors.diamond) 3 screen = pygame.display.set_mode(screen_size) 4 pygame.display.set_caption('刮一刮抽奖')
接着从所有底图中随机取出一张绑定到窗口,代码实现如下:
1 filenames = os.listdir(path) 2 filenames = [f for f in filenames if f.split('.')[-1] in ptype] 3 imgpath = os.path.join(path, random.choice(filenames)) 4 image_used = pygame.transform.scale(pygame.image.load(imgpath), screen_size) 5 screen.blit(image_used, (0, 0))
再接着做一个灰色的图层覆盖到底图上,代码实现如下:
1 surface = pygame.Surface(screen_size).convert_alpha() 2 surface.fill(gray) 3 screen.blit(surface, (0, 0))
最后,我们定义一下鼠标事件,在鼠标移动经过的地方,将图层置为透明,漏出底图,代码实现如下:
1 mouse_event = pygame.mouse.get_pressed() 2 if mouse_event[0]: 3 pygame.draw.circle(surface, white, pygame.mouse.get_pos(), 40) 4 elif mouse_event[-1]: 5 surface.fill(gray) 6 image_used = pygame.transform.scale(pygame.image.load(imgpath), screen_size)
代码:
1 import os 2 import sys 3 import random 4 import pygame 5 6 path = 'prize' 7 ptype = ['jpg', 'png', 'bmp', 'JPG', 'PNG', 'BMP'] 8 # 窗口大小 9 screen_size = (600, 400) 10 white = (255, 255, 255, 20) 11 gray = (192, 192, 192) 12 pygame.init() 13 pygame.mouse.set_cursor(*pygame.cursors.diamond) 14 screen = pygame.display.set_mode(screen_size) 15 pygame.display.set_caption('刮一刮抽奖') 16 surface = pygame.Surface(screen_size).convert_alpha() 17 surface.fill(gray) 18 filenames = os.listdir(path) 19 filenames = [f for f in filenames if f.split('.')[-1] in ptype] 20 imgpath = os.path.join(path, random.choice(filenames)) 21 image_used = pygame.transform.scale(pygame.image.load(imgpath), screen_size) 22 while True: 23 for event in pygame.event.get(): 24 if event.type == pygame.QUIT: 25 pygame.quit() 26 sys.exit(-1) 27 mouse_event = pygame.mouse.get_pressed() 28 if mouse_event[0]: 29 pygame.draw.circle(surface, white, pygame.mouse.get_pos(), 40) 30 elif mouse_event[-1]: 31 surface.fill(gray) 32 image_used = pygame.transform.scale(pygame.image.load(imgpath), screen_size) 33 screen.blit(image_used, (0, 0)) 34 screen.blit(surface, (0, 0)) 35 pygame.display.update()