玩家通过4种指令控制小人运动:
· 左 X:小人向左移动X个格子
· 右 X:小人向右移动X个格子
· 下 X:小人向下移动X个格子
· 挖矿:收集小人所在格子的金矿
小人收集金矿需要遵循一定的规则:
①小人必须将当前行的金矿全部收集,才能去往下一行,即金矿需从上到下收集
②对于同一行的金矿,小人必须按照从左往右的顺序开始收集
现编写程序,以8*8的矩阵为例,在文本框Text1中输入金矿数量,点击按钮“开始”后,随机产生对应数量的金矿并借助图形控件输出(保证不会在同一个格子出现两个金矿),并且在列表框List1中按顺序输出指令,使小人按照规则得到所有金矿。如图a所示。请回答下列问题。
图a
图b
Const n = 8 '程序以8*8的矩阵为例
Dim x(1 To n*n) As Integer, y(1 To n*n) As Integer '存储所有金矿的位置
Dim px As Integer, py As Integer '存储小人所在的位置
Dim i As Integer, j As Integer, m As Integer, tmp As Integer
Private Sub Command1_Click()
m = Val(Text1.Text)
Randomize
'随机产生m个金矿并通过图形控件显示在界面上,代码略
For i = 1 To m - 1
For j = 1 To m - i
'将所有金矿按照从上到下、从左到右的顺序排序,以符合题目描述的规则
If x(j) > x(j + 1) Or Then
tmp = x(j): x(j) = x(j + 1): x(j + 1) = tmp
tmp = y(j): y(j) = y(j + 1): y(j + 1) = tmp
End If
Next j
Next i
px = 1: py = 1
i = 1: j = 1
Do While j <= m
Do While x(j) = x(j + 1) And j <= m
j = j + 1
Loop
If y(i) < py Then
List1.AddItem "左" + Str(py - y(i))
ElseIf y(i) > py Then
List1.AddItem "右" + Str(y(i) - py)
End If
List1.AddItem "下" + Str)
List1.AddItem "挖矿"
For k = i + 1 To j
List1.AddItem "右" + Str(y(k) - y(k - 1))
List1.AddItem "挖矿"
Next k
px = x(j)
j = j + 1
i = j
Loop
End Sub