Learn VB .NET Through Game Programming [Electronic resources]

Matthew Tagliaferri

نسخه متنی -صفحه : 106/ 20
نمايش فراداده

Tying the Functionality Together

All that remains at this point is to link the die moving and die drawing code into a loop to complete the animated effect. Of course, the loop has to have a built-in mechanism for ending so the die can stop rolling and display the result. Listing 1-13 shows the method RollTheDie, which contains that loop and other functionality.

Listing 1.13: The RollTheDie Routine

Private Sub RollTheDie() 
Dim iLoop As Integer = 0 
lbResult.Text = " 
Do 
diexDir = oRand.Next(-8, 9) 
Loop Until Math.Abs(diexDir) > 3 
Do 
dieyDir = oRand.Next(-8, 9) 
Loop Until Math.Abs(dieyDir) > 3 
'decide what the result will be 
dieResult = oRand.Next(1, 7) 
Application.DoEvents() 
Me.Cursor = Cursors.WaitCursor 
dieStatus = DieMovementStatus.dmsRolling 
Do 
UpdateDiePosition() 
DrawDie() 
iLoop += 1 
Select Case dieStatus 
Case DieMovementStatus.dmsRolling 
'after 100 frames, have a 15% chance 
'that the die will stop rolling 
If iLoop > 100 And oRand.Next(1, 100) < 10 Then 
dieStatus = DieMovementStatus.dmsLanding 
iLoop = 0 
dieFrame = dieResult * 6 
End If 
Case DieMovementStatus.dmsLanding 
'die lands for 6 frames and stops 
If iLoop > 5 Then 
dieStatus = DieMovementStatus.dmsStopped 
End If 
End Select 
Loop Until dieStatus = DieMovementStatus.dmsStopped 
Me.Cursor = Cursors.Default 
End Sub 

This routine does the following tasks:

Clears the result label (Try Again or Correct!).

Initializes the diexDir and dieyDir variables. After a bit more experimenting, I decided the die didn’t look right if the values of these variables were +/–1 or 2, so the final code initializes the value from +/–3 to +/–8.

Picks what the die will land on (1–6).

Sets the cursor to an hourglass.

Starts the rolling loop. Within each loop iteration, the methods UpdateDiePosition and DrawDie are called.

Sees if it’s time to begin the die landing process. There is a 15-percent chance the die will land after drawing at least 100 frames.

If the die is already in the landing process, then stop the loop after six frames are drawn (the sixth frame in the landing bitmap is the final frame).

Sets the cursor back to an arrow.

You should be able to match up the code in Listing 1-13 with each of these tasks.