c# 实现汉诺塔游戏

汉诺塔游戏一旦掌握了规律,其实是有点单调和无聊的,不过却是学习递归的一个绝佳例子,想当初学习老谭C的时候,就卡在这儿好长时间。

对初学编程的人来说,递归本身就不易理解,如果使用C语言没有好的调试环境就更难去理解了。在这方面,VS调试输出是真方便,一目了然。

但要想理解递归求解汉诺塔,还是得先玩一玩游戏本身,有点感受。另外,设计一下这个游戏也可以加深对它的理解,同时还可以对数据结构中的栈有一个简单的认识。

因为汉诺塔的游戏规则本身就是一个栈,只能从平台最上面取走碟子,然后放在另一个平台最上面,这明显是个栈。下面是我设计的游戏界面:

游戏的玩法关键:奇数个盘子,第一个先移到C上;偶数个盘子,第一个先移到B上

平台和背景容器是事先画好的,碟子是动态生成的,使用了容器控件panel的拖动事件来实现拖动碟子(就是个label控件而已)的功能。

主要代码:

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Windows.Forms;

 

namespace 汉诺塔

{

    public partial class Form1 : Form

    {

        int dishNum = 3;

        int dishThick = 20;

        int count;            // 记录步数

        Stack<int> pileA;     // 存放平台A的数据

        Stack<int> pileB;     // 存放平台B的数据

        Stack<int> pileC;     // 存放平台C的数据

 

        public Form1()

        {

            InitializeComponent();

            InitGame();

            Result.ShowAnswer(dishNum);

        }

 

        private void InitGame()

        {

            pileA = new Stack<int>();

            pileB = new Stack<int>();

            pileC = new Stack<int>();

            panelA.Tag = pileA;

            panelB.Tag = pileB;

            panelC.Tag = pileC;

            for (int i = 0; i < dishNum; i++)

            {

                Label label = new Label();

                label.BackColor = Color.Gold;

                label.BorderStyle = BorderStyle.FixedSingle;

                label.Parent = panelA;

                label.Size = new Size(panelA.Width - (i + 1) * 12, dishThick);    // 从下往上每层宽度减少12

                label.Location = new Point(panelA.Width / 2 - label.Width / 2, panelA.Height - dishThick * (i + 1));

                label.BringToFront();

                label.MouseMove += new MouseEventHandler(Dish_MouseMove);

                label.Text = (dishNum - i).ToString();

                label.TextAlign = ContentAlignment.MiddleCenter;

                label.Name = "dish" + i;

                label.Tag = i;    // 设置碟子的编号

                pileA.Push(i);    // 存储碟子的编号

            }

            count = 0;

            lblCount.Text = "已走步数:" + count;

            lblLevel.Text = "最少步数:" + (Math.Pow(2, dishNum) - 1);

        }

 

        private void Dish_MouseMove(object sender, MouseEventArgs e)

        {

            Label label = sender as Label;

            if (e.Button == MouseButtons.Left)

            {

                label.DoDragDrop(label, DragDropEffects.Move);

            }

        }

 

        private void panelBox_DragEnter(object sender, DragEventArgs e)

        {

            if (e.Data.GetDataPresent(typeof(Label)))

            {

                //Console.WriteLine("DragEnter: {0}", (sender as Panel).Name);

                Label label = e.Data.GetData(typeof(Label)) as Label;

                Panel panelFrom = label.Parent as Panel;

                Stack<int> pileFrom = panelFrom.Tag as Stack<int>;

                int index = (int)label.Tag;

                if (pileFrom.Peek() == index) e.Effect = DragDropEffects.Move;    // 只可以拖走最顶层的碟子

                else e.Effect = DragDropEffects.None;

            }

        }

 

        private void panelBox_DragDrop(object sender, DragEventArgs e)

        {

            Panel panelTo = sender as Panel;

            //Console.WriteLine("DragDrop: {0}", panelTo.Name);

            //Point newPoint = panel.PointToClient(new Point(e.X, e.Y));

            Stack<int> pileTo = panelTo.Tag as Stack<int>;

            Label label = e.Data.GetData(typeof(Label)) as Label;

            Panel panelFrom = label.Parent as Panel;

            Stack<int> pileFrom = panelFrom.Tag as Stack<int>;

            int index = (int)label.Tag;

            if (pileTo.Count == 0 || index > pileTo.Peek())    // 只可以放置小的碟子到大的碟子上(栈为空时使用Peek会引发异常)

            {

                label.Parent = panelTo;

                label.Location = new Point(panelTo.Width / 2 - label.Width / 2, panelTo.Height - dishThick * (pileTo.Count + 1));

                label.BringToFront();

                pileFrom.Pop();

                pileTo.Push(index);

                count++;

                lblCount.Text = "已走步数:" + count;

                if (IsWin())

                {

                    if (dishNum < 9)    // 9层够玩了

                    {

                        MessageBox.Show("OK, be going to next...", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        dishNum++;

                        Reset();

                        InitGame();

                    }

                    else

                    {

                        MessageBox.Show("You Win!", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }

                }

            }

            else e.Effect = DragDropEffects.None;

        }

 

        private bool IsWin()

        {

            if (pileC.Count == dishNum) return true;

            else return false;

        }

 

        private void Reset()    // 删除现在所有的碟子

        {

            //panelC.Controls.Clear();    // 会把柱子也删除

            //Console.WriteLine("panelC: {0}", panelC.Controls.Count);

            for (int i = panelC.Controls.Count - 1; i >= 0; i--)    // 注意从前往后移除控件时控件的索引会跟着变化导致难以跟踪

            {

                //Console.WriteLine(" {0} {1}", i, panelC.Controls[i].Name);

                if (panelC.Controls[i].Name.StartsWith("dish")) panelC.Controls[i].Dispose();

            }

        }

    }

}

用C#写的代码感觉都不用怎么解释,大概思路一说,关键的地方注释一下,一看就明白了。

然后说到解法,其实就是使用老谭C的代码,不过标注了有用的调试输出信息,如下:

namespace 汉诺塔

{

class Result

{

static int count = 0;

static void Move(char x, char y) // 从x座移到y座

{

Debug.Print(" {0} ------> {1}", x, y); // 实际执行

//Console.WriteLine(" {0} --> {1}", x, y);

count++; // 把count++放到hanoi中两个move后面也可以

}

static void Hanoi(int n, char a, char b, char c) // a:源座,b:中转座,c:目标座;将n个盘从a座借助b座移到c座

{

Debug.Print("{0}: {1} -> {2} -> {3}", n, a, b, c); // 目标任务

if (n == 1)

{

Move(a, c);

}

else

{

Hanoi(n - 1, a, c, b); // 分解任务(递归调用相对于将此任务作为目标任务以便继续分解)

Debug.Print("{0}: {1} ------> {2}", n, a, c); // 实际任务

Move(a, c);

Hanoi(n - 1, b, a, c); // 分解任务(递归调用相对于将此任务作为目标任务以便继续分解)

}

}

public static void ShowAnswer(int num)

{

Hanoi(num, 'A', 'B', 'C');

Console.WriteLine("总共需{0}步", count);

}

}

}

理解1:移动n个盘子的步数是移动n-1个盘子的步数的2倍再加1,即:a[n] = 2a[n-1]+1,可推出:a[n]=2^n-1

理解2:n个盘子分配给n个人的话,第1人(总工)只需走1步,第2人(分包)走2步,第3人(分包)走4步...第n人(工人)走2^(n-1)步

理解3:从最上层开始层层分解任务,下面的所有层次干完后他再干然后下层继续补完,每个人都干活了,只有最底层的人接到任务不做分解直接开干

查看调试输出可以很容易的理解整个调用过程,有碟子数量和双箭头的为目标任务,有碟子数量和单箭头的为实际任务,只有单箭头的为实际执行步骤

3: A -> B -> C

2: A -> C -> B

1: A -> B -> C

A ------> C

2: A ------> B

A ------> B

1: C -> A -> B

C ------> B

3: A ------> C

A ------> C

2: B -> A -> C

1: B -> C -> A

B ------> A

2: B ------> C

B ------> C

1: A -> B -> C

A ------> C

总共需7步

将n个盘从a座借助b座移到c座,将上面的数据代入就可以很容易的理解了。下载地址

以上是 c# 实现汉诺塔游戏 的全部内容, 来源链接: utcz.com/z/327793.html

回到顶部