我一直相信,使生活如此美丽的,是我们藏起来的真诚和童心。
六一节快到了,520可以不过,但是儿童节绝对不能错过,毕竟谁还不是个几百个月的宝宝了,而且凭借自身智商,过这个节完全不成问题,哈哈哈哈哈。
作为程序媛,当然要用代码来过节啦,那就一起用 Python 开发个连连看小游戏来欢度六一吧!
从零造轮子那是不可能的,毕竟 Python 完全零基础,所以还是采取参考别人的例子的方式,从理解分析外加改造的过程中,来学习新的知识~
先来看一下最后的效果:
实现步骤如下:
一. 安装依赖包
安装 pygame 依赖包
python -m pip install pygame
二. 代码流程分析
导入需要的依赖
import sys, time
import math, random
import threading
import pygame
from pygame.locals import *
声明全局的设置类,并实例化设置对象
# 全局的设置类
class Settings:
# __init__方法负责对象的初始化
def __init__(self):
# 定义游戏窗口大小(800*640)
self.screen_size = (self.screen_width, self.screen_height) = (800, 640)
# 游戏中的块数排列(8行*10列)
self.game_size = (self.game_row, self.game_col) = (8, 10)
# 连连看的总块数
self.map_total = self.game_row * self.game_col
# 定义元素个数(共16种图片)
self.element_num = 16
self.bg_color = (220, 220, 220)
self.title = '智障儿童连连看'
self.win_image = './images/win.png'
self.lose_image = './images/lose.png'
self.grid_size = 80
self.scale_size = (76, 76)
self.points = []
# 实例化设置对象
settings = Settings()
声明全局变量
# 图像列表映射
map_list = []
#global map_list
image_list = []
# 点击右上角直接结束游戏标志位
is_exit = False
# 时间截止标志位
time_out = False;
声明图片按钮类,即每一个消除的小方块
# 图片按钮类
class ImageBtn:
__checkable = True
__checked = False
def __init__(self, screen, image_path, x, y, number, element):
self.x = x
self.y = y
# 元素标号(1-16)
self.element = element
self.number = number
self.screen = screen
# 图片原始大小为 200x200,所以要进行缩放
self.image = pygame.transform.scale(pygame.image.load(image_path), settings.scale_size)
def __del__(self):
pass
def display(self):
# 描边
if self.__checked:
pygame.draw.rect(self.image, (0,205,205,255), (0,0,self.image.get_width()-1,self.image.get_height()-1), 2)
self.screen.blit(self.image, (self.x, self.y))
def hide(self):
self.__checked = False
self.__checkable = False
# 图片不可见
self.image.fill((255, 255,240))
def is_checkable(self):
return self.__checkable
def click(self):
self.__checked = not self.__checked
return self.__checked
def reset(self):
self.__checked = False
def get_geometry(self):
return (int(self.x), int(self.y), settings.scale_size[0], settings.scale_size[1])
定义最核心的 水平扫