Sometimes the logic that you are developing may be too complicated to be represented using the different variations of the If…Then statements. However, you can greatly extend the power of the If…Then statements by nesting them within one another. This enables you to develop logic that tests for one condition and then further tests other conditions based on the result of the previous test.
Nesting is the process of embedding one statement within another statement of the same type, such as when you embed If…Then statements in order to develop more complicated conditional logic.
You've already seen examples of nested If statements in previous chapter game projects. For example, the following code comes from the btnDone_C1ick event belonging to the Speed Typing game that you worked on in Chapter 3.
If intwrong = 3 Then 'If intWrong equals three the player has struck out 'Time to determine the player's typing skill level If intCount < 2 Then 'Set rank when less than 2 tests were passed MessageBox.Show("Game over. Your typing skill level " _ & "is: Beginner. Please play again!") intCount = 0 intWrong = 0 Return 'Exit procedure immediately End If If intCount < 4 Then 'Set rank when less than 4 tests, were passed MessageBox.Show("Game over. Your typing skill level " _ & "is: Intermediate. Please play again!") intCount = 0 intWrong = 0 Return 'Exit procedure immediately End If If intCount < 5 Then 'Set rank when less than 5 tests were passed MessageBox.Show("Game over. Your typing skill level " _ & "is: Advanced. Please play again!") intCount = 0 intwrong = 0 Return 'Exit procedure immediately End If End If
In the Speed typing game, the game is set up to end if the player gets three strikes. The number of strikes made by the player is stored in the intWrong variable. The game also tracks the number of typing tests passed by the player by incrementing the value assigned to the intCounter variable.
In this example, the value of intWrong is first evaluated to see if it is equal to 3. If it is, then a series of three embedded If…Then statements are executed, each of which further refines the analysis by checking the value assigned to the intCount variable.
Trap | You can embed as many If…Then statements as you want within one another. However, the deeper you go, the more difficult your program code will be to PP read and maintain. |