iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >基于Python实现自制拼图小游戏
  • 714
分享到

基于Python实现自制拼图小游戏

Python拼图游戏Python拼图 2022-11-13 19:11:49 714人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

咱们python 集中营有一个专题就是分享一些有意思的东西,今天大概看了一下pygame的这个非标准库就想着使用它来做个小游戏-拼图。 通过加入自己定义的图片,对这个图片完成一定数

咱们python 集中营有一个专题就是分享一些有意思的东西,今天大概看了一下pygame的这个非标准库就想着使用它来做个小游戏-拼图。

通过加入自己定义的图片,对这个图片完成一定数量的拆分后再将拆分后的小图片进行随机打乱,这也算是实现一个拼图小游戏的基本思路吧。

为了将其做成一个桌面应用,这里使用的是pygame这一个非标准库。Python环境中还没有pygame的话可以选择使用pip的方式安装一下。

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/

下面将开发中使用到的python库都列举一下,除了pygame处理游戏之外,还有sys、random分别用来做系统操作和随机数的处理。

# Importing the pygame, sys, and random modules.
import pygame, sys, random

# Importing all the constants from the pygame.locals module.
from pygame.locals import *

创建一个python类GameMain,将所有的游戏处理相关的业务全部写到这个类中进行处理,包括一些初始化操作等等,最后我们通过main函数调用启动整个拼图游戏。

class GameMain():
    def __init__(self, window_width, window_height, background_color,
                 fps, colums, max_round_time, game_image):

        self.init_static_data(window_width=window_width, window_height=window_height,
                              background_color=background_color, fps=fps, colums=colums, max_round_time=max_round_time)

        self.init_game_data(game_image='./wd.jpeg')

        self.init_game_main()

通过GameMain类的初始化函数init来做类的初始化并且分别调用init_static_data、init_game_data、init_game_main三个主要的实现函数。

init_static_data函数主要用来将一些全局的静态参数进行初始化赋值,为了避免没有值时候的报错默认分别给这些参数都赋值,包括背景颜色、拼图游戏分割成小图片的列数等等。

def init_static_data(self, window_width=500, window_height=500,
                         background_color=(255, 255, 255), fps=40, colums=3, max_round_time=100):
        """
                The function initializes the game data and the game main

                :param window_width: The width of the game window
                :param window_height: The height of the game window
                :param background_color: The background color of the game window
                :param fps: The number of frames per second that the game will run at
                :param colums: The number of columns in the game
                :param max_round_time: The maximum time for each round
                :param game_image: The image that will be used for the game
                """
        self.window_width = window_width
        self.window_height = window_height
        self.background_color = background_color
        self.black_color = (0, 0, 0)
        self.fps = fps
        self.colums = colums
        self.cell_nums = self.colums * self.colums
        self.max_round_time = max_round_time

init_game_data函数,主要将游戏执行过程中的一些参数进行计算或者计算之后的数据值进行保存,因为在后面的游戏主循环中肯定是需要用到的,包括游戏载入的一整张图片的路径以及游戏窗口的标题等等。

def init_game_data(self, game_image='./wd.jpeg'):
        """
        > This function initializes the game data by reading the game image and extracting the game data from it

        :param game_image: The image of the game you want to play, defaults to ./wd.jpeg (optional)
        """

        pygame.init()
        self.main_clock = pygame.time.Clock()

        self.game_image = pygame.image.load(game_image)
        self.game_rect = self.game_image.get_rect()

        self.window_surface = pygame.display.set_mode((self.game_rect.width, self.game_rect.height))
        pygame.display.set_caption('拼图游戏')

        self.cell_width = int(self.game_rect.width / self.colums)
        self.cell_height = int(self.game_rect.height / self.colums)

        self.finished = False

        self.game_board, self.black_cell = self.generate_game_borad()

init_game_main函数中加入了死循环的方式让游戏一直处于执行中的状态,除非是已经完成了游戏或是直接退出游戏了才会停止。主要实现的是游戏步骤以及键盘的监听或鼠标的点击事件维持整个游戏状态的运行。

def init_game_main(self):
        """
        > This function initializes the game data by reading the game image and extracting the game data from it

        :param game_image: The image of the game you want to play, defaults to ./wd.jpeg (optional), defaults to ./wd.jpeg
        (optional)
        """
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    self.game_exit()
                if self.finished:
                    continue
                if event.type == KEYDOWN:
                    if event.key == K_LEFT or event.key == ord('a'):
                        self.black_cell = self.move_left(self.game_board, self.black_cell)
                    if event.key == K_RIGHT or event.key == ord('d'):
                        self.black_cell = self.move_right(self.game_board, self.black_cell)
                    if event.key == K_UP or event.key == ord('w'):
                        self.black_cell = self.move_up(self.game_board, self.black_cell)
                    if event.key == K_DOWN or event.key == ord('s'):
                        self.black_cell = self.move_down(self.game_board, self.black_cell)
                if event.type == MOUSEBUTTONDOWN and event.button == 1:
                    x, y = pygame.mouse.get_pos()
                    col = int(x / self.cell_width)
                    row = int(y / self.cell_height)
                    index = col + row * self.colums
                    if (
                            index == self.black_cell - 1 or index == self.black_cell + 1 or index == self.black_cell - self.colums or index == self.black_cell + self.colums):
                        self.game_board[self.black_cell], self.game_board[index] = self.game_board[index], \
                                                                                   self.game_board[self.black_cell]
                        self.black_cell = index

            if (self.is_finished(self.game_board)):
                self.game_board[self.black_cell] = self.cell_nums - 1
                self.finished = True

            self.window_surface.fill(self.background_color)

            for i in range(self.cell_nums):
                row_dst = int(i / self.colums)
                col_dst = int(i % self.colums)
                rect_dst = pygame.Rect(col_dst * self.cell_width, row_dst * self.cell_height, self.cell_width,
                                       self.cell_height)

                if self.game_board[i] == -1:
                    continue

                row_area = int(self.game_board[i] / self.colums)
                col_area = int(self.game_board[i] % self.colums)
                rect_area = pygame.Rect(col_area * self.cell_width, row_area * self.cell_height, self.cell_width,
                                        self.cell_height)
                self.window_surface.blit(self.game_image, rect_dst, rect_area)

            for i in range(self.colums + 1):
                pygame.draw.line(self.window_surface, self.black_color, (i * self.cell_height, 0),
                                 (i * self.cell_width, self.game_rect.height))
            for i in range(self.colums + 1):
                pygame.draw.line(self.window_surface, self.black_color, (0, i * self.cell_height),
                                 (self.game_rect.width, i * self.cell_height))

            pygame.display.update()
            self.main_clock.tick(self.fps)

game_exit函数,执行游戏退出操作。

def game_exit(self):
        """
        It exits the game.
        """
        pygame.quit()
        sys.exit()

generate_game_borad函数,生成游戏运行的主布局。

def generate_game_borad(self):
        """
        It generates the game board.
        """
        board = []
        for i in range(self.cell_nums):
            board.append(i)
        black_cell = self.cell_nums - 1
        board[black_cell] = -1

        for i in range(self.max_round_time):
            direction = random.randint(0, 3)
            if (direction == 0):
                black_cell = self.move_left(board, black_cell)
            elif (direction == 1):
                black_cell = self.move_right(board, black_cell)
            elif (direction == 2):
                black_cell = self.move_up(board, black_cell)
            elif (direction == 3):
                black_cell = self.move_down(board, black_cell)
        return board, black_cell

move_right函数,执行向右移动的操作。

def move_right(self, board, black_cell):
        """
        > The function `move_right` takes in a board and a black cell and returns the board after the black cell has moved
        right

        :param board: the board that the game is being played on
        :param black_cell: the cell that is currently black
        """
        if black_cell % self.colums == 0:
            return black_cell
        board[black_cell - 1], board[black_cell] = board[black_cell], board[black_cell - 1]
        return black_cell - 1

move_left函数,执行向左移动的操作。

def move_left(self, board, black_cell):
        """
        It moves the black cell to the left.

        :param board: the board that the game is being played on
        :param black_cell: the cell that is currently black
        """
        if black_cell % self.colums == self.colums - 1:
            return black_cell
        board[black_cell + 1], board[black_cell] = board[black_cell], board[black_cell + 1]
        return black_cell + 1

move_down函数,执行向下移动的操作。

def move_left(self, board, black_cell):
        """
        It moves the black cell to the left.

        :param board: the board that the game is being played on
        :param black_cell: the cell that is currently black
        """
        if black_cell % self.colums == self.colums - 1:
            return black_cell
        board[black_cell + 1], board[black_cell] = board[black_cell], board[black_cell + 1]
        return black_cell + 1

def move_down(self, board, black_cell):
        """
        It moves the black cell down.

        :param board: the board that the game is being played on
        :param black_cell: the cell that the player is currently on
        """
        if black_cell < self.colums:
            return black_cell
        board[black_cell - self.colums], board[black_cell] = board[black_cell], board[black_cell - self.colums]
        return black_cell - self.colums

move_up函数,执行向下移动的操作。

def move_up(self, board, black_cell):
        """
        It moves the black cell up one space.

        :param board: the board that the game is being played on
        :param black_cell: the cell that the player is currently on
        """
        if black_cell >= self.cell_nums - self.colums:
            return black_cell
        board[black_cell + self.colums], board[black_cell] = board[black_cell], board[black_cell + self.colums]
        return black_cell + self.colums

is_finished函数,校验拼图是否已经完成的操作。

def is_finished(self, board):
        """
        If the board is full, the game is over

        :param board: a 2D array representing the current state of the board. The board is composed of 3 characters: 'X',
        'O', and ' '. 'X' and 'O' represent the two players. ' ' represents an empty space
        """
        for i in range(self.cell_nums - 1):
            if board[i] != i:
                return False
        return True

最后,只需要通过main的主函数将这个游戏应用调用就可以直接打开拼图游戏了,并且可以设置相关的图片参数想对哪个图片拼图就设置哪个,一般建议设置1024像素以内的图片效果会比较好。

# This is a special variable in Python that is set when the program is run. If the program is being run directly (as
# opposed to being imported), then `__name__` will be set to `'__main__'`.
if __name__ == '__main__':
    """
            It moves the black cell up one space

            :param board: the board that the game is being played on
            :param black_cell: the cell that the player is currently on
            :return: The new position of the black cell.
            """
    GameMain(window_width=500, window_height=500,
             background_color=(255, 255, 255), fps=40,
             colums=3, max_round_time=100, game_image='./wd.jpeg')

以上就是基于Python实现自制拼图小游戏的详细内容,更多关于Python拼图游戏的资料请关注编程网其它相关文章!

--结束END--

本文标题: 基于Python实现自制拼图小游戏

本文链接: https://www.lsjlt.com/news/170855.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 基于Python实现自制拼图小游戏
    咱们Python 集中营有一个专题就是分享一些有意思的东西,今天大概看了一下pygame的这个非标准库就想着使用它来做个小游戏-拼图。 通过加入自己定义的图片,对这个图片完成一定数...
    99+
    2022-11-13
    Python拼图游戏 Python拼图
  • C++基于EasyX库实现拼图小游戏
    用C++的EasyX库做的拼图小游戏,供大家参考,具体内容如下   记录一下自己做的第一个项目,还有一些改进空间QWQ,可以支持难度升级,但是通关判断似乎有点...
    99+
    2022-11-12
  • C++基于EasyX库如何实现拼图小游戏
    这篇“C++基于EasyX库如何实现拼图小游戏”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“C++基于EasyX库如何实现拼...
    99+
    2023-06-19
  • iOS实现拼图小游戏
    本文实例为大家分享了iOS实现拼图小游戏的具体代码,供大家参考,具体内容如下 首先找到这8张图片,还需要一张空白的图片,自己随便剪一张吧。 定义三个属性:button可变数组,图片...
    99+
    2022-11-13
  • 怎么用Python实现拼图小游戏
    本篇内容主要讲解“怎么用Python实现拼图小游戏”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用Python实现拼图小游戏”吧!开发工具Python版本:...
    99+
    2022-10-19
  • 基于Python实现射击小游戏的制作
    目录1.游戏画面1.1开始1.2射击怪物2.涉及知识点3.代码3.1发射声3.2背景3.3射击效果4.经验总结1.游戏画面 1.1开始 1.2射击怪物 2.涉及知识点 1.spr...
    99+
    2022-11-10
  • 用js实现拼图小游戏
    本文实例为大家分享了js实现拼图小游戏的具体代码,供大家参考,具体内容如下 一、js拼图是什么? 用js做得小游戏 二、使用步骤 1、先创建div盒子 <style>...
    99+
    2022-11-11
  • 基于Python实现骰子小游戏
    目录导语一、环境准备 二、代码展示三、效果展示导语 哈喽!大家晚上好,我是木木子吖,很久没给大家更新游戏代码的类型啦~ 骰子,是现在娱乐场所最常见的一种玩乐项目。一般骰子分...
    99+
    2023-02-28
    Python实现骰子游戏 Python骰子游戏 Python游戏
  • jQuery如何实现拼图小游戏
    这篇文章给大家分享的是有关jQuery如何实现拼图小游戏的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。小熊维尼拼图jQuery代码实现拼图小游戏,鼠标选中拼块,用上下左右键移动拼...
    99+
    2022-10-19
  • js实现简单拼图小游戏
    本文实例为大家分享了js实现简单拼图小游戏的具体代码,供大家参考,具体内容如下 游戏很简单,拼拼图,鼠标拖动一块去和另一块互换。语言是HTML+js,注释写的有不明白的可以留言问一下...
    99+
    2022-11-12
  • 基于Python自制视觉桌上冰球小游戏
    目录介绍1. 文件配置1.1 导入工具包1.2 素材图片准备2. 手部关键点检测、素材导入2.1 方法介绍2.2 代码展示3. 关键点处理、球拍移动3.1 方法介绍3.2 代码展示4...
    99+
    2022-11-10
  • 基于Python实现炸弹人小游戏
    目录前言效果展示开发工具环境搭建原理简介主要代码前言 今天用Python实现的是一个炸弹人小游戏,废话不多说,让我们愉快地开始吧~ 效果展示 开发工具 Python版本: 3.6....
    99+
    2022-11-12
  • java控制台实现拼图游戏
    本文实例为大家分享了java控制台实现拼图游戏的具体代码,供大家参考,具体内容如下 1、首先对原始的拼图进行多次无规律的移动,将拼图打乱 2、然后进行游戏,在游戏移动同时对拼图顺序进...
    99+
    2022-11-12
  • 基于Python制作打地鼠小游戏
    效果展示 打地鼠小游戏 简介 打地鼠的游戏规则相信大家都知道,这里就不多介绍了,反正就是不停地拿锤子打洞里钻出来的地鼠呗~ 首先,让我们确定一下游戏中有哪些元素。打地鼠打地鼠,地鼠当...
    99+
    2022-11-13
  • 微信小程序实现拼图游戏
    本文实例为大家分享了微信小程序实现拼图游戏的具体代码,供大家参考,具体内容如下 页面展示 项目链接 微信小程序实现拼图游戏 项目设计 首页面 wxml <!--inde...
    99+
    2022-11-12
  • 基于Python实现英语单词小游戏
    目录导语一、敲代码之前的小tips二、运行环境三、素材(图片等)四、代码展示1)主程序(英文打字小游戏主入口模块)2)游戏配置信息模块3)游戏视图模块4)PyGame游戏精灵模块五、...
    99+
    2022-11-16
    Python英语单词游戏 Python 单词游戏 Python 游戏
  • 基于Python怎么实现射击小游戏
    本文小编为大家详细介绍“基于Python怎么实现射击小游戏”,内容详细,步骤清晰,细节处理妥当,希望这篇“基于Python怎么实现射击小游戏”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。1.游戏画面1.1开始1....
    99+
    2023-06-29
  • 基于Python如何实现骰子小游戏
    这篇文章主要讲解了“基于Python如何实现骰子小游戏”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“基于Python如何实现骰子小游戏”吧!一、环境准备 1)运行环境 &...
    99+
    2023-07-05
  • 基于Python如何实现格斗小游戏
    本文小编为大家详细介绍“基于Python如何实现格斗小游戏”,内容详细,步骤清晰,细节处理妥当,希望这篇“基于Python如何实现格斗小游戏”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。一、简易版本格斗impor...
    99+
    2023-07-05
  • 基于Python如何实现彩票小游戏
    本篇内容主要讲解“基于Python如何实现彩票小游戏”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“基于Python如何实现彩票小游戏”吧!一、游戏规则游戏里面有提前设置好的奖项,分为三个,一等奖...
    99+
    2023-07-05
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作