VB 河内塔 游戏
程序代码:
Dim n As Byte, pz1() As Byte, pz2() As Byte, pz3() As Byte '定义全局变量,其中n表示盘子的个数,pz1()~pz3()是记录每个杆子中盘子的情况,值为0表示没有盘子,值为几就表示第n个盘子在这个位置 Sub sleep(x As Byte) '产生停顿x表示半秒 Dim tim0 As Single, tim1 As Single tim0 = Timer While (tim0 + x / 2 >= tim1) tim1 = Timer Wend End Sub Sub hanoi(m As Byte, a() As Byte, b() As Byte, c() As Byte) '核心代码,网上找的 If m = 1 Then Call move1(a, c) Else Call hanoi(m - 1, a, c, b) Call move1(a, c) Call hanoi(m - 1, b, a, c) End If End Sub Sub move1(e() As Byte, f() As Byte) '使要移动的盘子移到杆子的最上面 sleep (1) '等待 Shape1(e(1) - 1).Top = 45 '调用平移过程 Call pingyi(e, f) '对该杆子数组重新初始化,因为最上面的盘子被移走了 For i = 1 To n - 1 e(i) = e(i + 1) Next e(n) = 0 End Sub Sub pingyi(g() As Byte, h() As Byte) '平行移动盘子 sleep (1) Shape1(g(1) - 1).Move h(0) - Shape1(g(1) - 1).Width / 2 '对该杆子数组重新初始化,因为又增加了一个盘子 For i = n To 2 Step -1 h(i) = h(i - 1) Next h(1) = g(1) Call down(g, h) '调用下移过程 End Sub Sub down(j() As Byte, k() As Byte) Dim l As Byte '判断杆子之前有没有盘子 sleep (1) For i = 2 To n l = l + k(i) Next If l = 0 Then Shape1(j(1) - 1).Top = 20 + Shape1(j(1) - 1).Height '移动并初始化 Else For i = 2 To n If k(i) <> 0 Then Shape1(j(1) - 1).Top = Shape1(k(i) - 1).Top + Shape1(k(i) - 1).Height Exit For End If Next End If End Sub Private Sub Command1_Click(Index As Integer) If Index = 0 Then Call hanoi(n, pz1, pz2, pz3) '开始移动 Else End End If End Sub Private Sub Form_Load() Dim z As String Scale (0, 60)-(4, 0) '初始化,定义窗体坐标 DrawWidth = 5 Line (1, 20)-(1, 45), vbBlue '画出杆子 Line (2, 20)-(2, 45), vbBlue Line (3, 20)-(3, 45), vbBlue Line (0.5, 20)-(3.5, 20), vbBlue Do z = InputBox("请输入盘子的个数(2~7)", "提示", 3, Screen.Width * 0.3, Screen.Height * 0.3) '提示输入盘子数 If z = "" Then End Else n = Val(z) End If Loop Until (n >= 2 And n <= 7) With Shape1(0) '对窗体上母盘初始化位置、大小 .Width = 0.8 .Left = 1 - Shape1(0).Width / 2 .Top = 20 + Shape1(0).Height End With For i = 1 To n - 1 '装载剩余的盘子并初始化 Load Shape1(i) With Shape1(i) .Visible = True .Width = Shape1(i - 1).Width - 0.1 .Left = 1 - Shape1(i).Width / 2 .Top = Shape1(i - 1).Top + Shape1(i - 1).Height End With Next ReDim pz1(0 To n) '初始化三个数组 ReDim pz2(0 To n) ReDim pz3(0 To n) For i = 1 To n pz1(i) = n + 1 - i pz2(i) = 0 pz3(i) = 0 Next pz1(0) = 1 '初始化,这里的1、2、3是三个杆子的标记,也是它们的横坐标,移动时要使用 pz2(0) = 2 pz3(0) = 3 End Sub
河内塔.rar
(2.2 KB)