Game Development Reference
In-Depth Information
interface. We could have set the Maximum Hit Points label Text property to 4
instead of 888 and selected Mage as the character class, knowing that we set the
Level control to start with a value of 1. Doing so would force us into keeping all
three controls synchronized whenever we reprogram any of them. It also means
that the formula to compute maximum hit points would exist in two places:
invisibly implied by the value we use in the Maximum Hit Points label Text
property and explicitly stated somewhere in our code. If we change the formula,
we would also have to remember to change the label.
There is a better way to ensure that our software wakes up sane. We are going to
write code that changes the Maximum Hit Points label Text property whenever the
user changes the level or class. Our Load event handler will act like a user and set the
user interface to sane values. Then, all the code we have to write anyway will work on
our behalf to wake up sane. We will be able to see at a glance that our code works.
We want the formula to exist in only one place. Add the following code between
the end of the form Load event handler and the end of the class:
Sub ComputeHitPoints()
HitPointsLabel.Text = CStr(dieSize * Level.Value)
End Sub
Adding this code sets the label text to the product of the character level (from the
Level control) and their die size (the variable) all converted to a string, since the Text
property is of type string and not of type integer. We need to call this code any
time the user interface changes the level or class settings. How will our code know
the user interface changed?
Whenever the controls are changed by the user, VB will fire events for the
controls. We have an event handler for the form's Load event; now we need
handlers for the Level and Class controls.
1. Click the GameForm.vb [Design] tab.
2. Double-click the NumericUpDown control.
3. Visual Basic creates a handler for the ValueChanged event. This is the exact
event we need to handle. Add a line to the handler to compute the new
maximum hit points:
Call ComputeHitPoints()
4. The Call keyword is not required, but it does help beginning programmers
understand that the code is invoking a subroutine. Click the Design tab again.
Search Nedrilad ::

Custom Search