使用wxPython和pillow开发拼图小游戏(一)

刚学习python,心血来潮,使用wxPython和pillow开了一个简单的拼图小游戏,大家分享一下

wxPython是Python语言的一套优秀的GUI图形库,在此项目里主要用来开发GUI客户页面;Pillow是一个非常好用的图像处理库,在此项目中主要用来对图片进行填充、切割、保存等操作。

项目初始化

考虑到项目初始化时没有图片(本项目中没有设置默认图片),所以初始化时,创建了一个3*3的数字拼图

初始化要求,9个格子填充8个数字,空格相邻的可以进行点击移动,1-8随机占8个,而且要保证一定能够通过点击恢复成正确的顺序

 _can_move = {"0": [1, 3],
                 "1": [0, 2, 4],
                 "2": [1, 5],
                 "3": [0, 4, 6],
                 "4": [1, 3, 5, 7],
                 "5": [2, 4, 8],
                 "6": [3, 7],
                 "7": [4, 6, 8],
                 "8": [5, 7]
                 }

 def random_init(self):
     self.indices = []
     self._ideal = self.vac*self.vac-1
     for i in range(0, self.vac*self.vac-1):
         self.indices.append(i)
     self.can_move_init()  #初始化,可移动集合,生成的格式如上边的_can_move
     time = 1000*self.vac  #初始化时,随机移动的次数,1000*行数
     while time > 0:       #安装可移动规则,进行随机移动
        can_move = self._can_move[str(self._ideal)]
        idx = random.randrange(0, len(can_move))
        pos = can_move[idx]
        if pos in self.indices:
            self.indices[self.indices.index(pos)] = self._ideal
            self._ideal = pos
            time -= 1

def can_move_init(self):
    for i in range(0, self.vac*self.vac):
        temp_can_move = []
        if i - self.vac >= 0:
            temp_can_move.append(i - self.vac)
        if i%self.vac != 0:
            temp_can_move.append(i-1)
        if (i+1)%self.vac != 0:
            temp_can_move.append(i+1)
        if i + self.vac <= self.vac*self.vac:
            temp_can_move.append(i + self.vac)
        self._can_move[str(i)] = temp_can_move

 在GUI中展示,部分代码如下:

index = 0
for i in self.indices:
    btn = wx.Button(self.panel_1, i, str(index + 1), size=(int(540 / self.vac), int(540 / self.vac)),pos=(int(i % self.vac * (540 / self.vac)), int((i // self.vac) * (540 / self.vac))))  # 每个格子为一个按钮,按钮上显示数字
    index += 1
    btn.SetBackgroundColour("#FFCC66")
    btn.SetFont(font)
    self.Bind(wx.EVT_BUTTON, self.OnClick, btn)  # 绑定格子的点击事件

初始化就先介绍到这儿,后续会继续和大家分享关于使用本地图片来加载游戏的方法,欢迎大家继续关注

猜你喜欢

转载自blog.csdn.net/wzl19870309/article/details/131690689