第二步,接受控制:Form的KeyPreview屬性要設(shè)為true,在Form_KeyPress函數(shù)中通過(guò)改變?nèi)肿兞縞x來(lái)控制賽車的位置。
第三步,游戲循環(huán):作為即時(shí)游戲,必須要有一個(gè)Timer,并在其事件Timer1_Timer()中繪制所有對(duì)象和進(jìn)行碰撞檢測(cè)。本例中,繪圖部分寫在了Timer1_Timer()中,碰撞測(cè)試放在了test()中。
……這也是所有即時(shí)游戲所共通的框架。當(dāng)然,我們往往還是根據(jù)具體的設(shè)計(jì)作一些變通,發(fā)揮一些技巧……比如這里設(shè)計(jì)的跑道是隨機(jī)產(chǎn)生的的,這就要通過(guò)一點(diǎn)技巧以便既讓玩家感到挑戰(zhàn),又不至于出現(xiàn)不可逾越的難關(guān)……
下面是全部源代碼,窗體上只需放個(gè)按鈕Command1就行了!
Const D = 100 注釋:方格的寬度
Const BT = 3000 注釋:跑道底部的y坐標(biāo)
Dim l1(22) As Integer 注釋:每層跑道左邊有幾個(gè)方塊
Dim l2(22) As Integer 注釋:每層跑道右邊有幾個(gè)方塊
Dim cx As Single 注釋:賽車的在x軸的位置
Private Sub Command1_Click()
cx = Width / 2 - 3 * D / 2
cy = Height - D
drawcar
For i = 1 To 20
l1(i) = 0
l2(i) = 0
drawway (i)
Next i
Timer1.Enabled = True
End Sub
Private Sub drawcar()
Line (cx, BT - 100)-Step(3 * D, D), BackColor, BF
Line (cx + D, BT - 200)-Step(D, D), BackColor, BF 注釋:先擦
Line (cx, BT - 100)-Step(3 * D, D), RGB(225, 0, 0), BF
Line (cx + D, BT - 200)-Step(D, D), RGB(225, 0, 0), BF
End Sub
Private Sub drawway(n)
Line (Width/2-3*D/2-2*D,BT-n*D)-Step(7*D,D),BackColor, BF
注釋:先擦后畫
Line (Width/2-3*D/2-2*D,BT-n*D)-Step(l1(n)*D, D), ,BF
Line (Width/2-3*D/2+5*D,BT-n*D)-Step(-l2(n)*D,D), ,BF
End Sub
Private Sub Form_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case Asc("a"), Asc("A")
cx = cx - D
Case Asc("s"), Asc("S")
cx = cx + D
End Select
End Sub
Private Sub Timer1_Timer()
Randomize
For i = 1 To 19
l1(i) = l1(i + 1)
l2(i) = l2(i + 1)
drawway (i)
Next i
Do
l1(20) = Int(Rnd * 5)
l2(20) = Int(Rnd * 5)
Loop Until ((l1(20) + l2(20) <= 4) And (l1(20) - l1(19) <= 1) And _
(l2(20) - l2(19) <= 1) And (l1(19) + l2(20) <= 4) And _
(l1(20) + l2(19) <= 4)) 注釋:這里生成新一層跑道,
注釋:注意要篩去玩家不可能通過(guò)的情況!
drawway (20)
注釋:以上畫出跑道
drawcar
test
End Sub
Private Sub test()
If 3.5*D-Width/2+cx
If 3.5*D-Width/2+cx+D
If 3.5*D-(cx+3*D-Width/2)
If 3.5*D-(cx+2*D-Width/2)
End Sub