编程语言:C#
带音效带自动演示
核心代码
private void Hanoi(int n1, char x, char y, char z)
{
if (n1 == 1)
{
MoveDisc(x, 1, z);//编号为1的盘子从x到y
}
else
{
Hanoi(n1 - 1, x, z, y);//n-1个盘子从x经y到z;
MoveDisc(x, n1, z);//编号为n的盘子从x到z;
Hanoi(n1 - 1, y, x, z);//n-1个盘子从y经x到z;
}
}
private void MoveDisc(char x, int n1, char z)
{
int j, t = 0;
i = i + 1;
labeloutput.Text += "\r\n" + i.ToString().PadLeft(2) + ":砖块" + n1.ToString().PadLeft(2) + x + "→" + z;
labeloutput.Visible = true;
buttonwatch.Visible = true;
buttonclean.Visible = true;
//从对应柱子中的数组列表中删除盘片n;
if (x.Equals('A'))
{
A.Remove(n1);
}
if (x.Equals('B'))
{
B.Remove(n1);
}
if (x.Equals('C'))
{
C.Remove(n1);
}
//往目标柱的对应数组中添加盘片n;
switch (z)
{
case 'A':
A.Add(n1);
t = A.Count;
break;
case 'B':
B.Add(n1);
t = B.Count;
break;
case 'C':
C.Add(n1);
t = C.Count;
break;
}
//动画效果 移动盘子;
int oldtop, newtop, step1;
oldtop = plate[n1].Top;
//首先垂直方向移动到顶部
newtop = 0;
for (j = oldtop; j >= newtop; j--)
{
plate[n1].Top = plate[n1].Top - 1;//一步一步移动产生动画效果
System.Windows.Forms.Application.DoEvents();
}
//其次水平方向移动
step1 = (z - x) / Math.Abs(z - x);//进行正负的赋值
for (j = 0; j < Math.Abs(z - x) * 190; j++)//不可以用<=;
{
plate[n1].Left = plate[n1].Left + step1;//一步一步移动产生动画效果
System.Windows.Forms.Application.DoEvents();
}
//在垂直方向向下移动
oldtop = 0;
newtop = 390 - (t + 1) * plateHeight;
step1 = (newtop - oldtop) / Math.Abs(newtop - oldtop);
for (j = oldtop; j <= newtop; j += step1)
{
plate[n1].Top = plate[n1].Top + step1;
System.Windows.Forms.Application.DoEvents();
}
}
部分图片如下图
来源:CSDN
作者:哲-1-
链接:https://blog.csdn.net/zhe170/article/details/104119154