通过Python把学姐照片做成拼图游戏


Posted in Python onFebruary 15, 2022

前言

事情是这样的

马上就快到毕业季了,大四的学姐们快要离校了

你心中那个没有说出口的学姐,你还记得吗

通过Python把学姐照片做成拼图游戏

跟着博主,用pygame给你心中那个学姐做一款专属于她的拼图游戏

万一有什么意外收获呢?

通过Python把学姐照片做成拼图游戏

先上效果

我用隔壁诗诗学姐的照片,给她做了一个拼图游戏

通过Python把学姐照片做成拼图游戏

结果,我自己的拼不出来了

通过Python把学姐照片做成拼图游戏

配置环境

安装pygame模块

#pip install pygame
 
PS C:\Users\lex> pip install pygame Looking in indexes: 
http://mirrors.aliyun.com/pypi/simple Requirement already satisfied:
 pygame in f:\develop\python36\lib\site-packages (2.0.1)
 
PS C:\Users\lex>

配置文件

cfg.py

配置需要读取的学姐的照片路径、引入游戏引用到的字体及颜色。

'''配置文件'''
import os
 
'''屏幕大小'''
SCREENSIZE = (640, 640)
'''读取学姐照片'''
PICTURE_ROOT_DIR = os.path.join(os.getcwd(), 'resources/pictures')
'''字体路径'''
FONTPATH = os.path.join(os.getcwd(), 'resources/font/FZSTK.TTF')
'''定义一些颜色'''
BACKGROUNDCOLOR = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
'''FPS'''
FPS = 40
'''随机打乱拼图次数'''
NUMRANDOM = 100

引入资源

将诗诗学姐的照片,添加到resources/pictures路径下,

游戏启动时,根据我们在cfg.py中的配置,会自动将该路径的照片

加载成为我们拼图的原材料。

通过Python把学姐照片做成拼图游戏

主函数代码

pintu.py

代码结构搞的简单一点。一个配置文件cfg,一个资源路径resources,存放字体和图片。

主函数代码放在这里:

1、定义四个可移动函数,在存在空格的情况下,允许向空格的方向移动。

2、createboard:随机将图片拆分,并且打乱。

3、开始时,随机从图片文件夹获取一张图片:如果想给整个宿舍的学姐做游戏,

就把所有人的照片放进去,这样每次打开,会随机生成一个学姐的照片作为游戏背景。

'''
Function:
    拼图小游戏
作者:
    LexSaints
'''
import os
import sys
import cfg
import random
import pygame
 
 
'''判断游戏是否结束'''
def isGameOver(board, size):
    assert isinstance(size, int)
    num_cells = size * size
    for i in range(num_cells-1):
        if board[i] != i: return False
    return True
 
 
'''将空白Cell左边的Cell右移到空白Cell位置'''
def moveR(board, blank_cell_idx, num_cols):
    if blank_cell_idx % num_cols == 0: return blank_cell_idx
    board[blank_cell_idx-1], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx-1]
    return blank_cell_idx - 1
 
 
'''将空白Cell右边的Cell左移到空白Cell位置'''
def moveL(board, blank_cell_idx, num_cols):
    if (blank_cell_idx+1) % num_cols == 0: return blank_cell_idx
    board[blank_cell_idx+1], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx+1]
    return blank_cell_idx + 1
 
 
'''将空白Cell上边的Cell下移到空白Cell位置'''
def moveD(board, blank_cell_idx, num_cols):
    if blank_cell_idx < num_cols: return blank_cell_idx
    board[blank_cell_idx-num_cols], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx-num_cols]
    return blank_cell_idx - num_cols
 
 
'''将空白Cell下边的Cell上移到空白Cell位置'''
def moveU(board, blank_cell_idx, num_rows, num_cols):
    if blank_cell_idx >= (num_rows-1) * num_cols: return blank_cell_idx
    board[blank_cell_idx+num_cols], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx+num_cols]
    return blank_cell_idx + num_cols
 
 
'''获得打乱的拼图'''
def CreateBoard(num_rows, num_cols, num_cells):
    board = []
    for i in range(num_cells): board.append(i)
    # 去掉右下角那块
    blank_cell_idx = num_cells - 1
    board[blank_cell_idx] = -1
    for i in range(cfg.NUMRANDOM):
        # 0: left, 1: right, 2: up, 3: down
        direction = random.randint(0, 3)
        if direction == 0: blank_cell_idx = moveL(board, blank_cell_idx, num_cols)
        elif direction == 1: blank_cell_idx = moveR(board, blank_cell_idx, num_cols)
        elif direction == 2: blank_cell_idx = moveU(board, blank_cell_idx, num_rows, num_cols)
        elif direction == 3: blank_cell_idx = moveD(board, blank_cell_idx, num_cols)
    return board, blank_cell_idx
 
 
'''随机选取一张图片'''
def GetImagePath(rootdir):
    imagenames = os.listdir(rootdir)
    assert len(imagenames) > 0
    return os.path.join(rootdir, random.choice(imagenames))
 
 
'''显示游戏结束界面'''
def ShowEndInterface(screen, width, height):
    screen.fill(cfg.BACKGROUNDCOLOR)
    font = pygame.font.Font(cfg.FONTPATH, width//15)
    title = font.render('恭喜! 你成功完成了拼图!', True, (233, 150, 122))
    rect = title.get_rect()
    rect.midtop = (width/2, height/2.5)
    screen.blit(title, rect)
    pygame.display.update()
    while True:
        for event in pygame.event.get():
            if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                pygame.quit()
                sys.exit()
        pygame.display.update()
 
 
'''显示游戏开始界面'''
def ShowStartInterface(screen, width, height):
    screen.fill(cfg.BACKGROUNDCOLOR)
    tfont = pygame.font.Font(cfg.FONTPATH, width//4)
    cfont = pygame.font.Font(cfg.FONTPATH, width//20)
    title = tfont.render('拼图游戏', True, cfg.RED)
    content1 = cfont.render('按H或M或L键开始游戏', True, cfg.BLUE)
    content2 = cfont.render('H为5*5模式, M为4*4模式, L为3*3模式', True, cfg.BLUE)
    trect = title.get_rect()
    trect.midtop = (width/2, height/10)
    crect1 = content1.get_rect()
    crect1.midtop = (width/2, height/2.2)
    crect2 = content2.get_rect()
    crect2.midtop = (width/2, height/1.8)
    screen.blit(title, trect)
    screen.blit(content1, crect1)
    screen.blit(content2, crect2)
    while True:
        for event in pygame.event.get():
            if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == ord('l'): return 3
                elif event.key == ord('m'): return 4
                elif event.key == ord('h'): return 5
        pygame.display.update()
 
 
'''主函数'''
def main():
    # 初始化
    pygame.init()
    clock = pygame.time.Clock()
    # 加载图片
    game_img_used = pygame.image.load(GetImagePath(cfg.PICTURE_ROOT_DIR))
    game_img_used = pygame.transform.scale(game_img_used, cfg.SCREENSIZE)
    game_img_used_rect = game_img_used.get_rect()
    # 设置窗口
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('拼图游戏 —— Linux黑客小课堂')
    # 游戏开始界面
    size = ShowStartInterface(screen, game_img_used_rect.width, game_img_used_rect.height)
    assert isinstance(size, int)
    num_rows, num_cols = size, size
    num_cells = size * size
    # 计算Cell大小
    cell_width = game_img_used_rect.width // num_cols
    cell_height = game_img_used_rect.height // num_rows
    # 避免初始化为原图
    while True:
        game_board, blank_cell_idx = CreateBoard(num_rows, num_cols, num_cells)
        if not isGameOver(game_board, size):
            break
    # 游戏主循环
    is_running = True
    while is_running:
        # --事件捕获
        for event in pygame.event.get():
            # ----退出游戏
            if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                pygame.quit()
                sys.exit()
            # ----键盘操作
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT or event.key == ord('a'):
                    blank_cell_idx = moveL(game_board, blank_cell_idx, num_cols)
                elif event.key == pygame.K_RIGHT or event.key == ord('d'):
                    blank_cell_idx = moveR(game_board, blank_cell_idx, num_cols)
                elif event.key == pygame.K_UP or event.key == ord('w'):
                    blank_cell_idx = moveU(game_board, blank_cell_idx, num_rows, num_cols)
                elif event.key == pygame.K_DOWN or event.key == ord('s'):
                    blank_cell_idx = moveD(game_board, blank_cell_idx, num_cols)
            # ----鼠标操作
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                x, y = pygame.mouse.get_pos()
                x_pos = x // cell_width
                y_pos = y // cell_height
                idx = x_pos + y_pos * num_cols
                if idx == blank_cell_idx-1:
                    blank_cell_idx = moveR(game_board, blank_cell_idx, num_cols)
                elif idx == blank_cell_idx+1:
                    blank_cell_idx = moveL(game_board, blank_cell_idx, num_cols)
                elif idx == blank_cell_idx+num_cols:
                    blank_cell_idx = moveU(game_board, blank_cell_idx, num_rows, num_cols)
                elif idx == blank_cell_idx-num_cols:
                    blank_cell_idx = moveD(game_board, blank_cell_idx, num_cols)
        # --判断游戏是否结束
        if isGameOver(game_board, size):
            game_board[blank_cell_idx] = num_cells - 1
            is_running = False
        # --更新屏幕
        screen.fill(cfg.BACKGROUNDCOLOR)
        for i in range(num_cells):
            if game_board[i] == -1:
                continue
            x_pos = i // num_cols
            y_pos = i % num_cols
            rect = pygame.Rect(y_pos*cell_width, x_pos*cell_height, cell_width, cell_height)
            img_area = pygame.Rect((game_board[i]%num_cols)*cell_width, (game_board[i]//num_cols)*cell_height, cell_width, cell_height)
            screen.blit(game_img_used, rect, img_area)
        for i in range(num_cols+1):
            pygame.draw.line(screen, cfg.BLACK, (i*cell_width, 0), (i*cell_width, game_img_used_rect.height))
        for i in range(num_rows+1):
            pygame.draw.line(screen, cfg.BLACK, (0, i*cell_height), (game_img_used_rect.width, i*cell_height))
        pygame.display.update()
        clock.tick(cfg.FPS)
    # 游戏结束界面
    ShowEndInterface(screen, game_img_used_rect.width, game_img_used_rect.height)
 
 
'''run'''
if __name__ == '__main__':
    main()

游戏运行方法

1、开发工具启动

如果你有python开发环境VScode、sublimeText、notepad+、pycharm等等这些环境,可以直接在工具中,运行游戏。

2、命令行运行游戏

如下图:

通过Python把学姐照片做成拼图游戏

以上就是通过Python把学姐照片做成拼图游戏的详细内容,更多关于Python拼图游戏的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python语言技巧之三元运算符使用介绍
Mar 04 Python
Python 专题六 局部变量、全局变量global、导入模块变量
Mar 20 Python
教你用一行Python代码实现并行任务(附代码)
Feb 02 Python
TensorFlow实现Batch Normalization
Mar 08 Python
详解【python】str与json类型转换
Apr 29 Python
Python统计一个字符串中每个字符出现了多少次的方法【字符串转换为列表再统计】
May 05 Python
python 用户交互输入input的4种用法详解
Sep 24 Python
pytorch之添加BN的实现
Jan 06 Python
django model的update时auto_now不被更新的原因及解决方式
Apr 01 Python
python 图像增强算法实现详解
Jan 24 Python
Python机器学习算法之决策树算法的实现与优缺点
May 13 Python
Python装饰器的练习题
Nov 23 Python
Python帮你解决手机qq微信内存占用太多问题
Feb 15 #Python
python flappy bird小游戏分步实现流程
Python 居然可以在 Excel 中画画你知道吗
Feb 15 #Python
Python 恐龙跑跑小游戏实现流程
详解Python+OpenCV进行基础的图像操作
Appium中scroll和drag_and_drop根据元素位置滑动
Feb 15 #Python
python 远程执行命令的详细代码
Feb 15 #Python
You might like
php语言流程控制中的主动与被动
2012/11/05 PHP
PHP 关于访问控制的和运算符优先级介绍
2013/07/08 PHP
php+html5+ajax实现上传图片的方法
2016/05/14 PHP
详解PHP5.6.30与Apache2.4.x配置
2017/06/02 PHP
PHP正则之正向预查与反向预查讲解与实例
2020/04/06 PHP
仅IE不支持setTimeout/setInterval函数的第三个以上参数
2011/05/25 Javascript
一个JQuery写的点击上下滚动的小例子
2011/08/27 Javascript
form表单action提交的js部分与html部分
2014/01/07 Javascript
一个简单的Node.js异步操作管理器分享
2014/04/29 Javascript
js实现一个链接打开两个链接地址的方法
2015/05/12 Javascript
jQuery头像裁剪工具jcrop用法实例(附演示与demo源码下载)
2016/01/22 Javascript
深入理解关于javascript中apply()和call()方法的区别
2016/04/12 Javascript
学习Javascript闭包(Closure)知识
2016/08/07 Javascript
angularjs中ng-attr的用法详解
2016/12/31 Javascript
JS实现图片高斯模糊切换效果的焦点图实例
2017/01/21 Javascript
jQuery实现鼠标经过显示动画边框特效
2017/03/24 jQuery
Servlet返回的数据js解析2种方法
2019/12/12 Javascript
vue-cli脚手架的.babelrc文件用法说明
2020/09/11 Javascript
[01:07:13]TNC vs Pain 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/20 DOTA
[01:20:37]FNATIC vs NIP 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/19 DOTA
python学习之面向对象【入门初级篇】
2017/01/21 Python
Python实现定时任务
2017/02/08 Python
pycharm创建scrapy项目教程及遇到的坑解析
2019/08/15 Python
Python元组 tuple的概念与基本操作详解【定义、创建、访问、计数、推导式等】
2019/10/30 Python
使用matplotlib绘制图例标签中带有公式的图
2019/12/13 Python
微信浏览器左上角返回按钮拦截功能
2017/11/21 HTML / CSS
图片上传插件ImgUploadJS:用HTML5 File API 实现截图粘贴上传、拖拽上传
2016/01/20 HTML / CSS
稀有和绝版书籍:Biblio.com
2017/02/02 全球购物
销售主管的自我评价分享
2014/01/03 职场文书
《自然之道》教学反思
2014/02/11 职场文书
新文化运动的口号
2014/06/21 职场文书
纪律教育学习心得体会
2014/09/02 职场文书
毕业生银行实习自我鉴定
2014/10/14 职场文书
家长会欢迎词
2015/01/23 职场文书
大学军训通讯稿
2015/07/18 职场文书
python套接字socket通信
2022/04/01 Python