Python拼图小游戏,周杰伦的照片拼图你能玩到第几张?华流才是最屌的!【内附源码】

3 篇文章 0 订阅
2 篇文章 0 订阅

哈喽!大家好,我是不凡……

今天给大家带来一个周杰伦的照片拼图Python小游戏,一定要收藏哦!

环境

操作系统:Windows

Python 版本:3.8

涉及模块: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('华流才是最棒的', True, cfg.BLUE)
    content2 = cfont.render('按m、h、l开始游戏', 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('周杰伦')
    # 游戏开始界面
    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)游戏介面

2)点 m/ h/ l 任意键 游戏运行

点击上下左右键,移动模块

3)共四张拼图,看看你能玩到第几张,快来试试吧!

总结

游戏简单,有手就能玩,还能看看爱豆呢~~

需要源码的可以滴滴我哟~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python拼图游戏源码可以通过Pygame库来实现。以下是一个简单的Python拼图游戏源码示例: ``` import pygame import random # 初始化pygame pygame.init() # 设置游戏窗口尺寸和标题 WIDTH, HEIGHT = 400, 400 win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("拼图游戏") # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) # 加载拼图图片 image = pygame.image.load("image.jpg") image = pygame.transform.scale(image, (WIDTH, HEIGHT)) # 拼图块的尺寸 SIZE = 100 def split_image(image): width, height = image.get_size() image_list = [] for i in range(0, width, SIZE): for j in range(0, height, SIZE): sub_image = image.subsurface((i, j, SIZE, SIZE)) image_list.append(sub_image) random.shuffle(image_list) return image_list def draw_image(image_list): for i, sub_image in enumerate(image_list): x = (i % 4) * SIZE y = (i // 4) * SIZE win.blit(sub_image, (x, y)) def is_finished(image_list): for i, sub_image in enumerate(image_list): x = (i % 4) * SIZE y = (i // 4) * SIZE if (x, y) != (sub_image.get_rect().x, sub_image.get_rect().y): return False return True # 拼图游戏主循环 def game_loop(): clock = pygame.time.Clock() image_list = split_image(image) running = True while running: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: if pygame.mouse.get_pressed()[0]: pos = pygame.mouse.get_pos() clicked_x = pos[0] // SIZE clicked_y = pos[1] // SIZE clicked_index = clicked_y * 4 + clicked_x if clicked_index - 1 >= 0 and clicked_index % 4 != 0: image_list[clicked_index], image_list[clicked_index - 1] = image_list[clicked_index - 1],image_list[clicked_index] if clicked_index + 1 < 16 and (clicked_index + 1) % 4 != 0: image_list[clicked_index], image_list[clicked_index + 1] = image_list[clicked_index + 1],image_list[clicked_index] if clicked_index - 4 >= 0: image_list[clicked_index], image_list[clicked_index - 4] = image_list[clicked_index - 4],image_list[clicked_index] if clicked_index + 4 < 16: image_list[clicked_index], image_list[clicked_index + 4] = image_list[clicked_index + 4],image_list[clicked_index] if is_finished(image_list): print("游戏胜利!") win.fill(BLACK) draw_image(image_list) pygame.display.update() pygame.quit() # 运行拼图游戏 game_loop() ``` 这个源码使用Pygame库来创建一个基本的拼图游戏。游戏窗口大小为400x400像素,图片被分成4x4的拼图块。游戏开始时,将拼图块进行随机打乱,家通过点击相邻的拼图块来交换它们的位置,最终目标是将拼图块恢复到正确的顺序。当所有的拼图块都处于正确的位置时,游戏提示家胜利。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值