不能发东西上来~
代码又太长了~
主要是有图形表示很直观~所以代码多了点~
在不考虑碰头和调头需要时间的前提下最大时间为24最少时间为11
Private Const cm1 = 350 '定义1厘米的距离
'用一个图片控件表示木棍 名字为 stick
'用图片控件数组mayi来表示蚂蚁
Dim maf(1 To 5) As Integer '定义蚂蚁前进方向 0表示向左.1表示向右
Dim max(1 To 5) As Long '蚂蚁所在的位置
Dim i As Integer '循环用的变量
Dim num As Long '整个过程所用时间
Const sx = 150 '木棍的位置(X坐标)
Const sy = 500 '木棍的位置(Y坐标)
Const may = 350 '蚂蚁的Y坐标
Private Sub Command1_Click()
Timer1.Enabled = True
End Sub
Private Sub Command2_Click()
Timer1.Enabled = False
End Sub
Private Sub Form_Load()
Me.Width = cm1 * 30
'初始化木棍
stick.Move sx + cm1, sy '木棍的位置
stick.Width = cm1 * 27 '设置木棍的长度为27厘米
'初始化蚂蚁的图片
mayi(1).Visible = True
mayi(1).Picture = LoadPicture("left.bmp")
i = 2
Do While i < 6
Load mayi(i)
mayi(i).Visible = True
mayi(i).Picture = LoadPicture("left.bmp")
i = i + 1
Loop
'初始化蚂蚁的前进方向
'用一个控件数组mayi()来表示蚂蚁
'其中载入的图片有两张可选,一张是头朝左的一张是头朝右的.图片中红色的一端表示蚂蚁的头
i = 1
Do While i < 6
maf(i) = 0
i = i + 1
Loop
'定义5只蚂蚁的初始位置
max(1) = sx + 3 * cm1
max(2) = sx + 7 * cm1
max(3) = sx + 11 * cm1
max(4) = sx + 17 * cm1
max(5) = sx + 23 * cm1
'把蚂蚁放到初始位置去
i = 1
Do While i < 6
mayi(i).Move max(i), may
i = i + 1
Loop
'初始化定时器
Timer1.Interval = 1000
Timer1.Enabled = False
End Sub
Private Sub mayi_Click(Index As Integer)
If (maf(Index)) = 0 Then
mayi(Index).Picture = LoadPicture("right.bmp")
maf(Index) = 1
Else
mayi(Index).Picture = LoadPicture("left.bmp")
maf(Index) = 0
End If
End Sub
Private Sub Timer1_Timer()
'计时
num = num + 1
Label1.Caption = num
'移动蚂蚁
i = 1
Do While i < 6
If maf(i) = 0 Then '头向左
max(i) = max(i) - cm1
Else
max(i) = max(i) + cm1
End If
mayi(i).Move max(i), may
If max(i) <= sx Then
mayi(i).Visible = False '蚂蚁从木棍左边离开
max(i) = sx '离开后的蚂蚁位置将不再变化
End If
If max(i) >= sx + cm1 * 27 Then
mayi(i).Visible = False '蚂蚁从木棍右边离开
max(i) = sx + cm1 * 27 + 1 '离开后的蚂蚁位置将不再变化
End If
i = i + 1
Loop
'是否碰头
i = 1
Do While i < 6
If i + 1 < 6 Then
If mayi(i).Visible = True Then
If mayi(i + 1).Visible = True Then
If max(i) = max(i + 1) Then
'两只蚂蚁碰头
'换方向 也就调头
'换图片
If maf(i) = 0 Then
maf(i + 1) = 0
mayi(i + 1).Picture = LoadPicture("left.bmp")
maf(i) = 1
mayi(i).Picture = LoadPicture("right.bmp")
Else
maf(i) = 0
mayi(i).Picture = LoadPicture("left.bmp")
maf(i + 1) = 1
mayi(i + 1).Picture = LoadPicture("Right.bmp")
End If
End If
End If
End If
End If
i = i + 1
Loop
'检查是否所有的蚂蚁都离开木棍
Dim bf As Integer
bf = 1
i = 1
Do While i < 6
If max(i) > sx Then
If max(i) <= sx + cm1 * 27 Then
bf = 0
Exit Do
End If
End If
i = i + 1
Loop
If bf = 1 Then
Timer1.Enabled = False
End If
'显示每只蚂蚁当前状态
Text1.Text = (max(1) - sx) / cm1
Text2.Text = maf(1)
Text3.Text = (max(2) - sx) / cm1
Text4.Text = maf(2)
Text5.Text = (max(3) - sx) / cm1
Text6.Text = maf(3)
Text7.Text = (max(4) - sx) / cm1
Text8.Text = maf(4)
Text9.Text = (max(5) - sx) / cm1
Text10.Text = maf(5)
End Sub