随后,开始编写程序自动运行的代码。由于俄罗斯方块是生成方块后,按照一定的速度进行下降,一旦碰到障碍物后本方块结束,再生成新的方块,如此循环。由于VBA不支持定时器,所以我们采用while(true)循环的方法进行不断生成方块。为了避免CPU资源过度占用,我们在循环之间加入延时函数,供循环调用,代码如下:
'延时函数 By@yaxi_liu
Private Sub delay(T As Single)
Dim T1 As Single
T1 = Timer
Do
DoEvents
Loop While Timer - T1 < T
End Sub
在下降过程中,我们需要知道是否某一行已经满了,判断的方法很简单,查询整行是否全部涂色即可。如果满了,我们删除本行,同时将第一行到本行下降填充。同时更新分数。因此我们再引入一个函数DeleteFullRow,代码如下:
'消除满行函数 By@yaxi_liu
Private Sub DeleteFullRow()
Dim i As Integer, j As Integer
For i = 1 To 20
For j = 2 To 11
If MySheet.Cells(i, j).Interior.ColorIndex < 0 Then
Exit For
ElseIf j = 11 Then
MySheet.Range(Cells(1, 2), Cells(i - 1, j)).Cut Destination:=MySheet.Range(Cells(2, 2), Cells(i, j)) 'Range("B2:K18")
iScore = iScore 10
End If
Next j
Next i
MySheet.Range("N1").Value = "分数"
MySheet.Range("O1").Value = iScore
End Sub
再在Start()函数里面添加while循环,上面两个函数一样添加进去代码如下:
'启动函数 By@yaxi_liu
Sub Start()
Call Init
While (True)
Call GetBlock
bIsObjectEnd = False '本方块对象是否结束
While (bIsObjectEnd = False)
Call delay(0.5)
Call MoveBlock(iCenterRow, iCenterCol, MyBlock, ColorArr(iColorIndex), 0)
MySheet.Range("L21").Select
With MySheet.Range("B1:K20")
.Borders(xlEdgeBottom).Weight = xlMedium
.Borders(xlEdgeRight).Weight = xlMedium
.Borders(xlEdgeLeft).Weight = xlMedium
End With
Wend
Call DeleteFullRow
Wend
End Sub
到这里,本游戏的编写就算彻底结束了,点击Sheet1界面上面的“按钮1”按钮即可开始游戏。我们再试玩一下,向左键代表向左,右键代表向右,上键代表旋转,下键代表下降。看一下效果:
哈哈,试玩结束没问题,非常完美,过程虽然长久,但值得你细细研究,也希望你能从中够体会到编程的乐趣。
,