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

CSDN 2024-06-20 11:35:01 阅读 74

目录

汉诺塔游戏

完整游戏

演示回放

完整代码


汉诺塔游戏

汉诺塔(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 pyglet window = 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)



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。