目录
  • 前言
  • 先上效果
  • 配置环境
  • 配置文件
  • 引入资源
  • 主函数代码
  • 游戏运行方法

前言

事情是这样的

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

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

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

万一有什么意外收获呢?

先上效果

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

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

配置环境

安装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中的配置,会自动将该路径的照片

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

主函数代码

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拼图游戏的资料请关注www.887551.com其它相关文章!