小张编写了一个VB程序来解这个游戏,功能如下:点击“初始化”按钮Command1初始化游戏,程序随机地将1~8这8个整数填入到数阵的外层圆圈中,同时将该状态下的数阵显示在列表框List1中。点击“开始”按钮Command2,程序开始移数字,并将移动过程中的每一步输出在列表框List2中,最后统计总移动步数到标签Label1中。为了清楚地描述输出数字在数阵中的每一步移动步骤,小张给数阵中的每一个圆圈都进行了编号,具体编号方法如图c所示,因此1号圈中的数字移动到2号圈可以表示为“1#-->2#”。程序运行界面如图d所示。
实现上述功能的VB代码如下。
Dim a(1 To 8) As String
Private Sub Command1_Click()
Dim temp As Integer, i As Integer, j As Integer
Dim flag(1 To 8) As Boolean
For i = 1 To 8
①
Next i
Randomize
For i = 1 To 8
temp = Int(Rnd() * 8 + 1) '生成1~8之间的随机整数
Do While flag(temp)
temp = Int(Rnd() * 8 + 1) '生成1~8之间的随机整数
Loop
a(i) = temp
flag(temp) = True
Next i
List1.Clear
List1.AddItem "初始状态:"
PrintCircle
End Sub
Private Sub Command2_Click()
Dim i As Integer, j As Integer, temp As String, n As Integer, moveStep As String
moveStep = ""
List2.Clear
n = 0
For i = 1 To 7 '使用冒泡排序对圆圈中的数字进行移动
For j = 1 To ②
If a(j) >= a(j + 1) Then
temp = a(j): a(j) = a(j + 1): a(j + 1) = temp
moveStep = Str(j) & "#--> 0#"
moveStep = moveStep & " " & Str(j + 1) & "#-->" & Str(j) & "#"
moveStep = moveStep & " " & "0#-->" & Str(j + 1) & "#"
List2.AddItem moveStep
n = n + 1
End If
Next j
Next i
List1.AddItem "移动数字后:"
PrintCircle
Label1.Caption = "总移动步数:" & ③
End Sub
'在列表框List1中输出当前的数阵状态
Function PrintCircle()
List1.AddItem "-------------------------"
List1.AddItem "[" & a(1) & "]-[" & a(2) & "]-[" & a(3) & "]"
List1.AddItem " | \ | / |"
List1.AddItem "[" & a(8) & "]-[" & " " & "]-[" & a(4) & "]"
List1.AddItem " | / | \ |"
List1.AddItem "[" & a(7) & "]-[" & a(6) & "]-[" & a(5) & "]"
List1.AddItem "-------------------------"
End Function
① ② ③