Python 一步一步教你用pyglet制作汉诺塔游戏(终篇)

 

目录

汉诺塔游戏

完整游戏

后期展望


汉诺塔游戏

汉诺塔(Tower of Hanoi),是一个源于印度古老传说的益智玩具。这个传说讲述了大梵天创造世界的时候,他做了三根金刚石柱子,并在其中一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门将这些圆盘从下面开始按大小顺序重新摆放在另一根柱子上,并规定在小圆盘上不能放大圆盘,同时在三根柱子之间一次只能移动一个圆盘。当盘子的数量增加时,移动步骤的数量会呈指数级增长,圆盘数为n时,总步骤数steps为2^n - 1。

n = 64, steps = 2^64 - 1 = 18446744073709551616 ≈ 1.845 x 10^19

汉诺塔问题是一个递归问题,也可以使用非递归法来解决,例如使用栈来模拟递归过程。这个问题不仅是一个数学和逻辑问题,也是一个很好的教学工具,可以用来教授递归、算法和逻辑思考等概念。同时,汉诺塔游戏也具有一定的娱乐性,人们可以通过解决不同规模的汉诺塔问题来挑战自己的智力和耐心。

本篇接着上期讲下去,前2篇的链接地址:

Python 一步一步教你用pyglet制作汉诺塔游戏(续)-CSDN博客

Python 一步一步教你用pyglet制作汉诺塔游戏-CSDN博客


完整游戏

前2期代码的基础上,添加了完整的提示功能,一个汉诺塔游戏作品终于完工了,效果如下:

信息提示功能都放在了鼠标事件中:

@window.event
def on_mouse_press(x, y, dx, dy):
    global xy, hanns, gamecompleted
    if not hanns.success():
        pole = hanns.on_mouse_over(x, y)
        if pole is not None:
            xy.append(pole)
            if len(xy)==1:
                hanns.setdiskcolor(xy[0], (255,0,0))
                if not hanns.array[pole]:
                    hanns.setdiskcolor(xy[0])
                    xy.pop()
                    return
        if len(xy)==2:
            if xy[0]!=xy[1]:
                info = hanns.move(*xy)
                hanns.setdiskcolor(xy[0])
                if info is False:
                    info1.text = '起始圆盘大于目标位置的圆盘'
                elif info is None:
                    info1.text = '所选起始位置的塔架不能为空'
                else:
                    info1.text = f'{hanns.order-hanns.array[xy[1]][-1]}号圆盘从{xy[0]+1}号塔架移动到{xy[1]+1}号塔架'
            hanns.setdiskcolor(xy[0])
            xy.clear()
            info2.text = f'当前层数:{hanns.order}\t最佳步数:{2**hanns.order-1}\t当前步数:{hanns.steps}'
        if hanns.success():
            if hanns.order<24:
                info1.text = f'恭喜您完成 {hanns.order} 层汉诺塔!任意点击层数加一!'
            else:
                info1.text = f'太棒了!您已完成 {hanns.order} 层汉诺塔,游戏结束!'
                gamecompleted = True
                return
    elif not gamecompleted:
        hanns = Hann(window.width/2, 120, hanns.order+1)
        info1.text = f' {hanns.order} 层汉诺塔,游戏开始!'
        info2.text = f'当前层数:{hanns.order}\t最佳步数:{2**hanns.order-1}\t当前步数:{hanns.steps}'

Hann 类中增加一个改色的方法,用于标注被点击的要移动的源塔架:

  def setdiskcolor(self, n, color=Color[0]):
        self.disk[n].cir1.color = color
        self.disk[n].cir2.color = color
        self.disk[n].rect.color = color

完整代码: 

import pygletwindow = pyglet.window.Window(800, 500, caption='汉诺塔')
pyglet.gl.glClearColor(1, 1, 1, 1)
batch = pyglet.graphics.Batch()Color = (182,128,18),(25,65,160),(56,170,210),(16,188,78),(20,240,20),(240,240,20),(255,128,20),(240,20,20),(245,60,138)class Disk:def __init__(self, x, y, color=(0,0,0), width=200, height=20):self.cir1 = pyglet.shapes.Circle(x+width/2-height/2, y, radius=height/2, color=color, batch=batch)self.cir2 = pyglet.shapes.Circle(x-width/2+height/2, y, radius=height/2, color=color, batch=batch)self.rect = pyglet.shapes.Rectangle(x-width/2+height/2, y-height/2, width-height, height, color=color, batch=batch)def move(self, dx, dy):self.cir1.x += dx; self.cir1.y += dyself.cir2.x += dx; self.cir2.y += dyself.rect.x += dx; self.rect.y += dyclass Hann:def __init__(self, x, y, order=2, space=250, thickness=20, width=200, height=300):assert(order>1)self.pole = [pyglet.shapes.Line(x-i*space, y, x-i*space, y+height, width=thickness, color=Color[0], batch=batch) for i in range(-1,2)]self.disk = [Disk(x+i*space, y, color=Color[0], width=width+thickness, height=thickness) for i in range(-1,2)]self.x, self.y = x, yself.order = orderself.space = spaceself.thickness = thicknessself.width = widthself.poleheight = heightself.beadheight = (height-thickness*2)/orderself.step = (width-thickness)/(order+1)self.steps = 0self.macro = []coordinates = [(self.x-space, self.y+(i+1)*self.beadheight-(self.beadheight-thickness)/2) for i in range(order)]self.beads = [Disk(*xy, Color[i%8+1], width=self.width-i*self.step, height=self.beadheight) for i,xy in enumerate(coordinates)]self.array = [[*range(order)], [], []]def move(self, pole1, pole2):if self.array[pole1]:bead = self.array[pole1].pop()if self.array[pole2] and bead<self.array[pole2][-1]:self.array[pole1].append(bead)return Falseelse:return Noneself.beads[bead].move((pole2-pole1)*self.space, (len(self.array[pole2])-len(self.array[pole1]))*self.beadheight)self.array[pole2].append(bead)self.steps += 1self.macro.append((pole1, pole2))return Truedef setdiskcolor(self, n, color=Color[0]):self.disk[n].cir1.color = colorself.disk[n].cir2.color = colorself.disk[n].rect.color = colordef on_mouse_over(self, x, y):for i in range(-1,2):if hanns.x-hanns.width/2 < x-i*hanns.space < hanns.x+hanns.width/2 and hanns.y-hanns.thickness/2 < y < hanns.y+hanns.poleheight:return i+1def success(self):return len(self.array[2]) == self.order@window.event
def on_draw():window.clear()batch.draw()@window.event
def on_mouse_press(x, y, dx, dy):global xy, hanns, gamecompletedif not hanns.success():pole = hanns.on_mouse_over(x, y)if pole is not None:xy.append(pole)if len(xy)==1:hanns.setdiskcolor(xy[0], (255,0,0))if not hanns.array[pole]:hanns.setdiskcolor(xy[0])xy.pop()returnif len(xy)==2:if xy[0]!=xy[1]:info = hanns.move(*xy)hanns.setdiskcolor(xy[0])if info is False:info1.text = '起始圆盘大于目标位置的圆盘'elif info is None:info1.text = '所选起始位置的塔架不能为空'else:info1.text = f'{hanns.order-hanns.array[xy[1]][-1]}号圆盘从{xy[0]+1}号塔架移动到{xy[1]+1}号塔架'hanns.setdiskcolor(xy[0])xy.clear()info2.text = f'当前层数:{hanns.order}\t最佳步数:{2**hanns.order-1}\t当前步数:{hanns.steps}'if hanns.success():if hanns.order<24:info1.text = f'恭喜您完成 {hanns.order} 层汉诺塔!任意点击层数加一!'else:info1.text = f'太棒了!您已完成 {hanns.order} 层汉诺塔,游戏结束!'gamecompleted = Truereturnelif not gamecompleted:hanns = Hann(window.width/2, 120, hanns.order+1)info1.text = f' {hanns.order} 层汉诺塔,游戏开始!'info2.text = f'当前层数:{hanns.order}\t最佳步数:{2**hanns.order-1}\t当前步数:{hanns.steps}'xy = []
order = 2
hanns = Hann(window.width/2, 120, order)
info1 = pyglet.text.Label('操作方法:鼠标先后点击起始和目标位置就能移动圆盘', font_size=21, color=(0,0,0,255), x=window.width/2, y=50, anchor_x='center', batch=batch)
info2 = pyglet.text.Label(f'当前层数:{order}\t最佳步数:{2**order-1}\t当前步数:0', font_size=18, color=(0,0,0,255), x=80, y=450, batch=batch)
gamecompleted = Falsepyglet.app.run()

后期展望

之后有空再优化一下代码,再添加上音效、回放等功能,游戏效果会理想些。还能把上期的自动演示功能也加进去,就更加完美了。


本文完,以下仅为凑字数,请忽略:

自动演示功能,即把以下递归函数的结果展现出来即可:

def hanoi(n, start, mid, end, moves=None):
    if moves is None:
        moves = []
    if n == 1:
        moves.append((start, end))
    else:
        hanoi(n-1, start, end, mid, moves)
        moves.append((start, end))
        hanoi(n-1, mid, start, end, moves)
    return moves
 
for order in (4,7,8):
    moves = hanoi(order, 0, 1, 2)
    print(len(moves)==2**order-1)
    print(moves)

运行结果:

True
[(0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2)]
True
[(0, 2), (0, 1), (2, 1), (0, 2), (1, 0), (1, 2), (0, 2), (0, 1), (2, 1), (2, 0), (1, 0), (2, 1), (0, 2), (0, 1), (2, 1), (0, 2), (1, 0), (1, 2), (0, 2), (1, 0), (2, 1), (2, 0), (1, 0), (1, 2), (0, 2), (0, 1), (2, 1), (0, 2), (1, 0), (1, 2), (0, 2), (0, 1), (2, 1), (2, 0), (1, 0), (2, 1), (0, 2), (0, 1), (2, 1), (2, 0), (1, 0), (1, 2), (0, 2), (1, 0), (2, 1), (2, 0), (1, 0), (2, 1), (0, 2), (0, 1), (2, 1), (0, 2), (1, 0), (1, 2), (0, 2), (0, 1), (2, 1), (2, 0), (1, 0), (2, 1), (0, 2), (0, 1), (2, 1), (0, 2), (1, 0), (1, 2), (0, 2), (1, 0), (2, 1), (2, 0), (1, 0), (1, 2), (0, 2), (0, 1), (2, 1), (0, 2), (1, 0), (1, 2), (0, 2), (1, 0), (2, 1), (2, 0), (1, 0), (2, 1), (0, 2), (0, 1), (2, 1), (2, 0), (1, 0), (1, 2), (0, 2), (1, 0), (2, 1), (2, 0), (1, 0), (1, 2), (0, 2), (0, 1), (2, 1), (0, 2), (1, 0), (1, 2), (0, 2), (0, 1), (2, 1), (2, 0), (1, 0), (2, 1), (0, 2), (0, 1), (2, 1), (0, 2), (1, 0), (1, 2), (0, 2), (1, 0), (2, 1), (2, 0), (1, 0), (1, 2), (0, 2), (0, 1), (2, 1), (0, 2), (1, 0), (1, 2), (0, 2)]
True
[(0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (2, 1), (0, 1), (2, 0), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2), (0, 1), (2, 0), (2, 1), (0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (1, 2), (0, 1), (0, 2), (1, 2)]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/740026.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unsupervised RL:METRA: Scalable Unsupervised RL with Metric-Aware Abstraction

ICLR 2024 Oral paper Intro 无监督RL旨在发现潜在的行为帮助提高下游任务效率以往方法集中于探索以及基于互信息的技能发现(skill)。然而去前者在高危复杂空间实现困难&#xff0c;后者也容易因为缺乏激励导致探索能力不足。本文提出METRA核心观点认为与其在复杂状态空间处理…

[leetcode~dfs]1261. 在受污染的二叉树中查找元素

给出一个满足下述规则的二叉树&#xff1a; root.val 0 如果 treeNode.val x 且 treeNode.left ! null&#xff0c;那么 treeNode.left.val 2 * x 1 如果 treeNode.val x 且 treeNode.right ! null&#xff0c;那么 treeNode.right.val 2 * x 2 现在这个二叉树受到「污…

python apscheduler添加监听器listener,用于自动化任务的反馈

apscheduler可以通过添加监听器&#xff0c;得到定时任务的反馈。监听会监听到的是apscheduler.events&#xff0c;进入apscheduler/events.py文件中可以看到&#xff0c;使用常量对事件的定义&#xff1a; EVENT_SCHEDULER_STARTED EVENT_SCHEDULER_START 2 ** 0 EVENT_SCH…

Games101笔记-计算机图形学概述

光栅化&#xff1a;把三维空间的几何形体显示在屏幕上 实时&#xff1a;每秒30帧的画面 曲线和曲面&#xff1a; 如何表示一条光滑曲线&#xff0c;如何表示曲面如何用简单的曲面通过细分的方法得到更复杂的曲面在形状发生变化时&#xff0c;面要如何变化&#xff0c;如何保…

深入学习默认成员函数——c++指南

前言&#xff1a;类和对象是面向对象语言的重要概念。 c身为一门既面向过程&#xff0c;又面向对象的语言。 想要学习c&#xff0c; 首先同样要先了解类和对象。 本节就类和对象的几种构造函数相关内容进行深入的解析。 目录 类和对象的基本概念 封装 类域和类体 访问限定符…

力扣235. 二叉搜索树的最近公共祖先

思路&#xff1a;要利用好二叉搜索树的特性&#xff0c;中序遍历是有序的&#xff0c;也就是说最近的公共祖先 大小一定落在区间 [p,q] 或[q,p]。 1、当p和q都大于当前root值时&#xff0c;说明当前root值太小&#xff0c;需要更大才能让它落入区间范围&#xff0c;所以要往右子…

@Insert注解是怎么用的?

苍穹外卖第二天有这段注解&#xff1a; Insert("insert into employee(name, username, password, phone, sex, id_number, create_time, update_time, create_user, update_user,status) " "values ""(#{name},#{username},#{password},#{phone},#{…

排列数字(DFS)

[Acwing 842.排列数字] 给定一个整数 n n n&#xff0c;将数字 1 ∼ n 1∼n 1∼n 排成一排&#xff0c;将会有很多种排列方法。 现在&#xff0c;请你按照字典序将所有的排列方法输出。 输入格式 共一行&#xff0c;包含一个整数 n n n 。 输出格式 按字典序输出所有排…

单词拆分-动态规划

// 单词拆分-动态规划// 输入: s "leetcode", wordDict ["leet", "code"]// 输出: true// 解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。public static boolean wordBreak(St…

如何下载安装chromium浏览器

下载安装chromium浏览器去这个网站下载&#xff1a; CNPM Binaries Mirror 参考链接&#xff1a;手写 Puppeteer&#xff1a;自动下载 Chromium - 知乎

手撸nano-gpt

nano GPT 跟着youtube上AndrejKarpathy大佬复现一个简单GPT 1.数据集准备 很小的莎士比亚数据集 wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt 1.1简单的tokenize 数据和等下的模型较简单&#xff0c;所以这里用了个…

解决mybatis-plus新增数据自增ID与之前数据不匹配问题

实体类的例子 Data public class User {TableId(value "id", type IdType.AUTO)private Integer id;private String username;// 忽略,不传到前端JsonIgnoreprivate String password;private String nickname;private String email;private String phone;private …

css---定位

定位 1. 相对定位1.1 如何设置相对定位&#xff1f;1.2 相对定位的参考点在哪里&#xff1f;1.3 相对定位的特点&#xff1a; 2. 绝对定位2.1 如何设置绝对定位&#xff1f;2.2 绝对定位的参考点在哪里&#xff1f;2.3 绝对定位元素的特点&#xff1a; 3. 固定定位3.1 如何设置…

PostgreSQL教程(三十六):服务器管理(十八)之回归测试

回归测试是PostgreSQL中对于 SQL 实现的一组综合测试集。它们测试标准 SQL 操作以及PostgreSQL的扩展能力。 一、运行测试 回归测试可以在一个已经安装并运行的服务器上运行&#xff0c;或者在编译树中的一个临时安装上运行。此外&#xff0c;还有运行该测试的“并行”和“顺…

游戏免费下载平台模板源码

功能介绍 此游戏网站模板源码是专门为游戏下载站而设计的&#xff0c;旨在为网站开发者提供一个高效、易于维护和扩展的解决方案。 特点&#xff1a; 响应式设计&#xff1a;我们的模板可以自适应不同设备屏幕大小&#xff0c;从而为不同平台的用户提供最佳的浏览体验。 …

算法---滑动窗口练习-1(长度最小的子数组)

长度最小的子数组 1. 题目解析2. 讲解算法原理3. 编写代码 1. 题目解析 题目地址&#xff1a;长度最小的子数组 2. 讲解算法原理 首先&#xff0c;定义变量n为数组nums的长度&#xff0c;sum为当前子数组的和&#xff0c;len为最短子数组的长度&#xff0c;初始值为INT_MAX&am…

javascript中的structuredClone()克隆方法

前言&#xff1a; structuredClone 是 JavaScript 的方法之一&#xff0c;用于深拷贝一个对象。它的语法是 structuredClone(obj)&#xff0c;其中 obj 是要拷贝的对象。structuredClone 方法将会创建一个与原始对象完全相同但是独立的副本。 案例&#xff1a; 当使用Web Work…

阿里巴巴按关键字搜索商品 API 返回值说明

item_search-按关键字搜索商品API测试工具 alibaba.item_search 公共参数 名称类型必须描述keyString是调用key&#xff08;必须以GET方式拼接在URL中&#xff09;secretString是调用密钥api_nameString是API接口名称&#xff08;包括在请求地址中&#xff09;[item_search,…

Shadertoy内置函数系列 - mod 取模运算

mod函数返回x % 3的结果 先看一个挑战问题题目&#xff1a; Create a pattern of alternating black and red columns, with 9 columns of each color. Then, hide every third column that is colored red.The shader should avoid using branching or conditional statemen…

2024年最新阿里云和腾讯云云服务器价格租用对比

2024年阿里云服务器和腾讯云服务器价格战已经打响&#xff0c;阿里云服务器优惠61元一年起&#xff0c;腾讯云服务器61元一年&#xff0c;2核2G3M、2核4G、4核8G、4核16G、8核16G、16核32G、16核64G等配置价格对比&#xff0c;阿腾云atengyun.com整理阿里云和腾讯云服务器详细配…