①1号和2号机器人需要交替运动,即第一轮由1号进行运动,第二轮则由2号进行运动,第三轮由1号进行运动……以此类推直至第K轮。
②每轮运动时,机器人将先判断前方是否可以前进,若无法前进,则不断顺时针旋转90°至可以前进为止,随后前进直至停止,由另一个机器人开始下一轮运动。
③机器人在前进过程中遇到边界、障碍物或者另一个机器人时都将停止。
如图a所示,机器人1号和2号分别位于左上角和右下角,且分别朝向右侧和左侧,黑块表示障碍物,当进行了4轮运动后,状态如图b所示。
编写程序,启动后随机生成矩阵并在List1中输出,其中"#"表示障碍物,"_"表示可以行走的空格子,机器人用数字1和2表示。在文本框Text1中输入轮数K,点击按钮Command1,在列表框List1中输出K轮后的矩阵。程序界面如图c所示。
图a | 图b | 图c |
Const n = 10
Dim a(100) As String, steps(3) As Integer, pos(2) As Integer
Dim towards(2) As Integer, cur As Integer, nex As Integer, K As Integer
Private Sub Form_Load()
'生成矩阵存储在数组a中并输出,代码略
End Sub
Private Sub Command1_Click()
steps(0) = -n: steps(1) = 1: steps(2) = n: steps(3) = -1
pos(1) = 1: towards(1) = 1: pos(2) = n * n: towards(2) = 3
i = 1 : K = Val(Text1.Text)
Do While i <= K
cur = (i - 1) Mod 2 + 1
nex = GetNext(pos(cur), towards(cur))
Do While Check(nex)
pos(cur) = nex
nex = GetNext(pos(cur), towards(cur))
Loop
nex = GetNext(pos(cur), towards(cur))
Do While Not Check(nex)
towards(cur) =
nex = GetNext(pos(cur), towards(cur))
Loop
i = i + 1
Loop
'输出矩阵,代码略
End Sub
Function Check(x As Integer) As Boolean
Check = x <> 0 And a(x) <> "#" And
End Function
Function GetNext(x, t) As Integer
GetNext = x + steps(t)
If x >= 1 And x <= n And t = 0 Then GetNext = 0
If x > (n - 1) * n And x <= n * n And t = 2 Then GetNext = 0
If Then GetNext = 0
If x Mod n = 0 And t = 1 Then GetNext = 0
End Function