[FREE PDF SAMPLE] Learn VB NET Through Game Programming 1st Edition Matthew Tagliaferri (Auth.) ebook full chapters
[FREE PDF SAMPLE] Learn VB NET Through Game Programming 1st Edition Matthew Tagliaferri (Auth.) ebook full chapters
https://ebookultra.com/download/beginning-asp-net-2-0-in-vb-2005-from-
novice-to-professional-apr-2006-1st-edition-matthew-macdonald/
https://ebookultra.com/download/murach-s-asp-net-4-5-web-programming-
with-vb-2012-training-reference-5th-ed-edition-boehm/
Build Your Own ASP NET Website Using C VB NET 1st Edition
Zak Ruvalcaba
https://ebookultra.com/download/build-your-own-asp-net-website-using-
c-vb-net-1st-edition-zak-ruvalcaba/
https://ebookultra.com/download/vb-net-for-developers-sams-white-
book-1st-edition-keith-franklin/
Pro Silverlight 3 in VB 2nd ed. Edition Matthew Macdonald
https://ebookultra.com/download/pro-silverlight-3-in-vb-2nd-ed-
edition-matthew-macdonald/
https://ebookultra.com/download/pro-silverlight-4-in-vb-3rd-ed-3rd-
edition-matthew-macdonald/
https://ebookultra.com/download/programming-asp-net-ajax-1st-edition-
christian-wenz/
https://ebookultra.com/download/visual-c-net-programming-1st-edition-
harold-davis/
https://ebookultra.com/download/real-world-enterprise-reports-using-
vb6-and-vb-net-1st-edition-carl-ganz-jr-auth/
Learn VB NET Through Game Programming 1st Edition
Matthew Tagliaferri (Auth.) Digital Instant Download
Author(s): Matthew Tagliaferri (auth.)
ISBN(s): 9781590591147, 1590591143
Edition: 1
File Details: PDF, 13.07 MB
Year: 2003
Language: english
learn VB .NET Through
Game Progranvning
Matthew Tagliaferri
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any
information
means, electronic or mechanical, including photocopying, recording, or by any information
storage or retrieval system, without the prior written permission of the copyright owner and the
publisher.
Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement
benefit infringement of the trademark.
Editorial Board: Dan Appleman, Craig Berry, Gary Cornell, Tony Davis, Steven Rycroft, Julian
Skinner, Martin Streicher, Jim Sumser, Karen Watterson, Gavin Wray, John Zukowski
KimWimpsett
Copy Editor: Kim Wimpsett
Janet Vail
Production Editor: JanetVail
Manufacturing
Manufacturing Manager: Tom Debolsld
Debolski
phone I-S00-SPRINGER,
In the United States: phone 1-800-SPRINGER, email
email [email protected]. orvisit
[email protected], or visit
http://www.springer-ny.com. Outside the United States: fax
http://www.springer-ny.com. fax +49
+49 6221
6221 345229,
345229, email
email
orders@springer . de, or visit http://www.springer.de.
[email protected], http://www.springer.de.
information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219,
For information
94710. Phone
Berkeley, CA 94710. Phone 510-549-5930,
510-549-5930, fax
fax 510-549-5939,
510-549-5939,email
email [email protected], orvisit
[email protected], or visit
http://www.apress.com.
v
Contents
About the Author ................................................... xi
About the Technical Reviewer .................................... xii
Acknowledgments ................................................... xiii
Introduction ....................................................... xv
vii
Contents
viii
Contents
ix
About the Author
matt tagliaferrl has been developing soft-
ware since his high school obtained its
first computers-six TRS-80 Model 3s-in
1982. matt (who prefers his name in
lowercase) has developed software in sev-
eral industries, including retail, insurance,
corporate finance, and trucking before
(somewhat miraculously) landing a senior
analyst position with the Cleveland
Indians baseball organization. matt has
been with the Indians for six years and is now the manager of application
development.
Currently, matt lives in the Cleveland area with his wife and two daughters.
He enjoys collecting The Simpsons action figures and "family stuff" such as
American Idol and Friday Pizza Nights.
xi
About the Technical
Reviewer
MIKE BURGESS started writing software on computers back when they took up
whole rooms and had less memory than an average digital watch today. He has
worked for small to large corporations (including Microsoft) and has been work-
ing with Visual Basic since the beta of version 1. He's written many different types
of software including small business accounting and inventory, real estate, emer-
gency management, corporate communication, multimedia, medical diagnosis,
and some hush-hush stuff for the government.
He currently resides in northern Utah with his wife and five (yes, five) chil-
dren. He enjoys Family Game Night, Mountain Dew, and a good round of Ghost
Recon with his kids and brothers.
xii
Acknowledgments
WRITING A BOOK IS DEFINITELY not a solo project-and there are numerous people
to thank for the opportunity and the work put into this project. I'd like to thank
the entire Apress team. This is my first Apress title, and I've found it to be a first-
class organization. Individually, my list of acknowledgments probably reads like
the internal Apress organizational chart: thanks to Gary Cornell for listening to
and shaping my initial pitch, thanks to Dan Appleman for some overall direction
in finding the correct audience, and thanks to Laura Cheu and Nate McFadden
for serving as project managers and keeping the project on track. Mike Burgess
served as technical editor for the book and did a great job not only making sure
the code was complete and that everything compiled but also making sugges-
tions to help improve code clarity and readability. Kim Wunpsett filled the role of
editor, keeping my i's dotted and my gerunds gerunding. Finally, Beth Christmas
filled a multitude of roles from making sure I had the correct screen-capture soft-
ware to getting me advance copies of Visual Studio. I thank all of them for turning
a simple idea into the organized pile of pages you now hold in your hands.
On the home front, no project gets far without the understanding of my wife,
Janet, who has to put up with me running to the computer to check email as soon
as I get home from work and with the clack clack of the keyboard as she tries to
read every evening. I hope she doesn't need to read this to know how much her
love and support mean to me.
xiii
Introduction
A FEW YEARS AGO, Microsoft raised a few eyebrows (my own included) when it
announced that the next version of Visual Basic (VB) would not be backward
compatible with the current version, VB 6. There were many valid reasons for
breaking the compatibility, but many people still thought Microsoft was taking
a considerable gamble. After all, there were thousands of VB programmers crank-
ing out millions of lines of code in the modem workforce, and suddenly Microsoft
was announcing that this mountain of code would someday be considered "old"
technology.
xv
Introduction
to learn anything. A program too large doesn't work, either-you end up spend-
ing too much time bogged down in the complexity of the task, which takes away
time from learning the features of the language. like Goldilocks, you're looking
for the program not too small, not too big, but instead "just right."
I discovered a few years ago that the "small game" program fit nicely into
the "just right" category for learning the basics of a programming language.
A small game is one that fits on a single screen and can usually be played by
a single player in a few minutes. Examples of a small game include card games,
dice games, and some simple board games. Many qualities make programs
such as these good learning subjects. Programs of this type usually need to keep
track of one or more types of game piece, and these pieces are often required to
change state (such as a die rolling or a board element changing color). These
game elements often come in groups (52 cards in a deck, five dice for Yahtzee) ,
so you'll have to learn how the language stores a group of similar elements. The
user interface requirements of such games are usually more interesting (and
therefore more challenging) than the usual button/listboxl combo box interface.
Finally, when you've succeeded and completed the program, you've got a fun
game to play.
The goal of this book is to teach you how to get started programming in VISual
Basic .NET by developing games. This book doesn't intend to be a complete treatise
of all the features and capabilities of this latest version ofVB. Instead, it provides
a series of example programs that illustrate basic features of the language and begins
the huge task of introducing you to the contents of the .NET Framework. In addition,
I introduce one more important programming concept-the concept of design. Now
that object-oriented languages are more common, people have found that the vari-
ous objects in a program can be designed to interact with each other in different
ways; these interactions can make the program more or less complex or more or less
adaptable to future features or enhancements. To illustrate the importance of design
on a program, I've taken the time to walk you through the development process of
several of these programs rather than simply presenting you with the final version
of the game. By learning how to solve a program one way, then improving upon that
design in a second or third version of the program, you'll begin to recognize when your
own designs might be headed down a wrong path and some redesign is in order.
xvi
Introduction
are looking to update your skill set to something more modem. Or perhaps
you've picked up software development as a secondary skill at your job (you're
the office "Excel macros guru"), and now you want to learn something more for-
mally. Whatever the case, my assumption is that as you crack open Chapter 1,
"Developing Your First Game," you've written programs in some other language
so that you have a jumping-off point. Specifically, the following concepts should
be familiar to you:
• Flow statements such as If .. Then •. Else blocks, For loops, and While
statements
• The use of procedures and functions and how to get information into and
out of them
Getting Up to Speed
If the previous little review list gives you a queasy feeling, or you simply think you
might need a refresher on some of these topics, then you'll be happy to know that
Appendix A, "The Basics of Visual Basic" contains some introductory material.
Specifically, it covers these topics while describing how to write a simple Visual
Basic .NET program. Becoming familiar with the topics in the appendix should
give you enough background to dive into Chapter 1, "Developing Your First Game,"
and start the game writing.
xvii
Introduction
BMPStitch AppendixC
CellularAutomata ChapterS
Cellul~tomata~thSave Chapter 9
DicePanel Chapter 2
DirectXDemo ChapterS
FirstApplication Appendix A
GarbageDemoOne Chapter 9
GarbageDemoTwo Chapter 9
GuessTheDieRoll Chapter 1
GuessTheDieRoll2 Chapter 2
GuessTheDieRoll3 Chapter 2
lnterfaceEbGinlple Chapter 6
NetReversi Chapter 7
NineTiles Chapter 3
PCOpponent Chapter 6
PolymorphismEbGinlple ChapterS
ShapeTileGames Chapter 4
SpaceRocks ChapterS
ThreadParametersOne Chapter 9
ThreadParametersThree Chapter 9
ThreadParameters1\vo (broken) Chapter 9
Yahtzee Bonus game
xviii
CHAPTER 1
Developing Your
First Game
To GET THINGS ROLLING right from the start, you'll write a complete (albeit small in
scope) game in this chapter. This game will consist of a single die rolling around
in a black panel and an end user guessing the outcome of the die (see Figure 1-1).
If you consider yourself at a beginner level and think this chapter rushes through
some of the Visual Basic (VB) fundamentals, then refer to Appendix A, "The Basics
of Visual Basic," to create a simple project in a step-by-step fashion.
Try Again
Figure 1-1. The Guess the Die Roll game in all its glory
1
Chapter 1
NOTE As you go through the code for this first program, you may
find you don't agree with all the design decisions made along the
way or with how the code is organized. As it turns out, I've gone out
of my way on this first program to write the code in a distinctly
non-object-oriented style. I've done this so you'll have a point of
comparison when you rewrite the same game in Chapter 2, "Writing
Your First Game, Again." So, ifyou're new to the .NET language,
concentrate on the individual language elements and constructs, as
well as the features ofVisual Studio (VS), and pay less attention to
the form and structure of this first program.
When you saw Figure 1-1 with its slick 3D-rendered die, I hope you said to
yourself "Oooh, that's pretty cool." This book covers the VB .NET language and
object-oriented development using simple games as examples. In other words,
this book doesn't teach how to develop the next Quake killer. However, a small
game can still become extremely popular if it's done well and if it's fun to play.
Done well means that the graphics, sounds, and overall design of the game are
interesting, unique, funny, or all three. Fun to play is of course a matter of opin-
ion, so the games you write will have to at least pass your own "fun meter"-and
then perhaps you can try them out on family, friends, and coworkers to get their
input.
2
Developing Your First Game
the beginning of the coding process. Programmers new to this approach might
find this methodology difficult at first because they often can't simply jump into
their editors and start writing lines of code. Instead, before you start coding, you
must plan how you'll organize the code and group it into units and, to some
extent, how these units will interact.
3
Chapter 1
4
Developing Your First Game
You can easily model this relationship by using the sub classing ability of an
object-oriented language. You could model these constructs by creating an ancestor
class named BaseballPlayer and creating two subclasses from this class named
BaseballOffensivePlayer and BaseballPitcher. The common pieces of informa-
tion such as height, weight, age, and school would reside in the ancestor class,
and the specific pieces of information unique to hitters and pitchers would
reside in the appropriate subclass.
You'll start looking at VB classes to see examples of all these concepts soon,
but you have one stop to make first-the .NET Framework.
5
Chapter 1
Class Is in Session
The Guess the Die Roll program will begin its life as a standard Wmdows Appli-
cation solution. You can create this type of project and give it any name you like
now. Or, if you'd rather study my version of the project, refer to the project named
GuessTheDieRoll. If you haven't downloaded the source code for the book yet, you
can do so in the Downloads area of the Apress Web site (http://www.apress.com).
Uyou select Form1.vb in the Solution Explorer for this new project and then
click the View Code button at the top of the Solution Explorer, the main window
of Visual Studio will open and show you the code that makes up the default form
in your project (see Figure 1-2).
6
Developing Your First Game
Figure 1-2. The auto-generated code for the default form in a Windows Forms
project
It doesn't look like much at first, does it? The tiny amount of code declares a class
named Formi, which is a subclass of something called System. Windows. Forms. Form. This
represents the full name of a class, including the namespace in which that class
resides. The ancestor class name is Form, but it resides inside a namespace named
System. Windows. Forms.
NOTE The dot notation for the System. Windows. Forms namespace
doesn't imply that there's a namespace named Forms contained
within a namespace named Windows contained within a name-
space named System. Instead, there's a single assembly named
System. Windows. Forms. dIl on your computer (it might take
a while to get used to filenames that have multiple periods in
them). There's a System namespace, as well, contained in the
assembly System. dIl, but obviously because these two assemblies
are contained in different files, the namespaces aren't considered
one within the other.
So, the default project has a class named Formi, which is an ancestor of
a class named Form. What does that mean? Well, for starters, it means that the
Formi class automatically gains all the functionality of its ancestor. For an idea of
just what type of functionality this is, select View ~ Class View from the Visual
Studio menu, navigate down to Forml, open Bases and Interfaces, and then
open Form. Your Class View's treeview will quickly fill up with all the available
members of the Form class, as shown in Figure 1-3. Amember is a field, property,
event, or method attached to a class.
7
Chapter 1
NOTE You'll learn the definition ofall these terms as you go. For
now, it's important simply to note the sheer quantity of members
found in the Form class and know that the Formi class you're about
to build upon already contains the functionality of Form simply
because it's declared as an ancestor of the Form class. This "borrow-
ing" offunctionality is one of the truly powerful aspects of
object-oriented programming.
El ·ii1 Nothing
B {} Nothing
El ~ Forml
$_.
~ Bases and Interfaces
El ~ Form
IB- ~ Bases and Interfaces
GJ·~ ControlColledion
; <!'
[Select](ByVal Boolean, ByVal Boolean)
.'~. ActlliateO
, ,.~ ActivateMdiChud(ByVal System.Windows,Forms,Form)
'''. AddOwnedForm(ByVal System ,Windows,Forms ,Form)
~ AdjustFormSuollbars(ByVal Boolean)
~ ApplyAutoScalingO
.~ CenterToParentO
-~ CenterToScreenO
.• '''. CloseO
Figure 1-3. The Class View, showing all the functionality received for free because
Formi is a subclass of the class Form. I love free stuff, don't you?
Understanding Properties
Properties store a piece of information that helps describe an object. Think of
a property as a variable that describes some aspect of the object to which it's
attached. The Form class, for example, has properties to describe its size (height
and width) and location on the screen (top and bottom). Changing the value of
any of these four properties changes the appearance of the form.
Note that a property helps to describe an object, not a class. It's important
to understand the distinction between those two terms. The class (recipe) helps to
define the presence of the property and can declare a starting value, but the prop-
erty itself is associated with each instance of the object. This means, of course,
that each instance can have a different value for the same property. If a cake class
has a property named lcingFlavor, then of course each actual cake can have a dif-
ferent value in this property, meaning that each cake can have a different flavor of
icing. If a cake class has a property named NumberOfLayers, then each cake can be
8
Developing Your First Game
IfGuess System.WlndoW5.Forms.Form
[iJ ~. IOO ~
El Accesslbrhty
--------------------------,
AccesslbleDescrlption
AccessibleName
AccessibleRole Default
El Appearanc
BackColor o Control
Backgroundlmage o (none)
Cursor Default
I!l Font Tahoma, 8.2Spt
ForeColor Controllext
FormBorderStyle Sizable
RlghtToLeft No
Text Guess the Die Roll
El 8ella i
AllowDrop False
ContextMenu (none)
Enabled True
ImeMode NoControl
13 Lonfrguta on
I!l (DynamicProperties)
13 0 t
I!l(DataBindlngs)
Tag
13 Desrgn
(Name) fGue5S
DrawGrld True
I!l GridSize 8,8
Locked False
SnapToGrid True
13 Focu'
CausesValldatlon True
TeKt
The text contained In the control.
9
Chapter 1
The left column of the grid displays the name of each property, and the right
side displays the current value of each property. The Properties window shows
the properties for a single object at a time. To change which object is being dis-
played, you can click a new object in the Form Designer, or you can select that
object from the drop-down box at the top of the Properties window.
You can change a property by clicking the row that contains that property
and then, depending on the type of variable that the property represents, typing
a value, selecting it from a list, or sometimes selecting it from an extended
selector.
Figure 1-5 shows the Start Position property on the Forml object in the
example project being changed from the value WindowsDefaultLocation to the
value Centerscreen. This property is an enumerated type, meaning it has a finite
number of possible values, with each value represented by an easily remem-
bered word. As you can see in Figure 1-5, you change the value of the property
by selecting the desired value from a drop-down box. Once changed, the prop-
erty value displays in bold if it's different from that property's default value.
J=:tt.-o
Understanding Fields
A field on an object is so similar to a property (at least from the outside of the
object) that it's almost impossible to tell the difference between the two, so this
chapter won't cover them in any detail. Like a property, a field is like a variable
attached to an object instance that describes some aspect of the object. The dif-
ference between fields and properties is in how they're declared; because you're
not quite ready to learn about declaring, let's continue.
10
Developing Your First Game
End Sub
11
Chapter 1
'Forml
End Sub
#End Region
Visual Studio generated all of this code, including the comments, when you
created your project. There's a good deal of stuff in Listing 1-1 that isn't explain-
able right away, but one thing worth mentioning is toward the bottom, where
several properties of this form object appear (AutoscaleBaseSize, ClientSize, Name,
startposition, and Text).
Note how all of these properties are referenced with the Me keyword-for the
Clientsize property, for example, this keyword means "the property attached to
Me named Client Size." Also, notice that the property you changed in the prior
section, Start Position, is one of the properties listed. This is because the prop-
erty is no longer at its default value. If you change it back to the default value
WindowsDefaul tLocation in the Properties window, this line of code disappears.
Likewise, if you delete this line of code, the Properties window reflects this change.
It's best to get into the habit of not modifying this auto-generated code directly,
however, because you might (in the worst case) confuse the compiler or corrupt
your form to the point where Visual Studio can't read it anymore. When modify-
ing the value of properties, always use the Properties window.
NOTE You can add things to the auto-generated code; for example,
you might want to add some resource cleanup code to the Dispose
method shown previously or some initialization code to the New
method, as the comment suggests.
to the project ("Which form is Formi again?"). You can change the name of a form
or any other visual control in the Properties window. The label for the Name prop-
erty is enclosed in parentheses, as shown in Figure 1-6 (Microsoft does this so
that the Name property remains at the top of the Properties window when you
sort the properties alphabetically). For this example, enter the name fGuess as
your form name.
PIC/pc-Illes q. X
IrGuess System.Windows,Forms,Form
:= [IDOO
IIII (DataBindings)
IIII (DynamicProperties)
rGuessl
AcceptButton (none)
What this rather confusing error message is trying to tell you is that the project
no longer knows which piece of code to run first. The project was originally
instructed to run Formi on startup, but you just renamed Formi out of existence.
To fix this error, you'll need to right -click the project name (not the solution
name) in the Solution Explorer, select Properties, and change the Startup Object
in the drop-down box (you can also select Project ~ Properties from the menu
to get to the same dialog box). In a beginning project like this one, there will be
only two choices for startup, either fGuess (the renamed Formi) or Sub Main. Sub
Main is only available if you don't want to load a form in the beginning of the
project. Of course, you must have a Sub Main somewhere in your program to
choose this option.
VB got its name because designing forms is a visual process. That is, the pro-
grammer can arrange the user interface at design time by adding controls to
a form and then moving and sizing them into their desired positions. This was
13
Chapter 1
the first Windows language that allowed the graphical arrangement of controls at
design time. VB .NET is certainly no exception to this feature-you design forms
visually. Specifically, you place controls on a form by using the Toolbox, which is
docked (by default) on the left side of Visual Studio (see Figure 1-7).
*I Toofbox ~ x
a
-<
a-
0
My User Controls
Data
x Com onents
Windows Forms •
I~ Pointer
A label
~
A Unklabel
.!!!l Button
lObi TextBox
Ii! MainMenu
P CheckBox
r. RadioButton
L.J GroupBox
PictureBox
o Panel
hi r"la...t: .......
Figure 1-7. The Visual Studio Toolbox. Now where's that screwdriver. .. ?
14
Developing Your First Game
Figure 1-8. The Solution Explorer, showing the View Code button and the View
Designer button on the toolbar (the first and second buttons from the left,
respectively)
Once you place a control on a form and select it, you can use the Properties
window to change that control's appearance and behavior, just as you changed
the form's properties earlier.
The Guess the Die Roll game form has seven label controls on it. Six of the
controls are similar-they're the numbered "buttons" the user will click to make
a guess. This game will use label controls for these buttons mainly because they're
easier to color and because they don't give the 3D "clicking" effect. The choice
was purely aesthetic. The seventh label control tells users whether they won or
lost the game.
The fastest way to add these controls to a form is to add the first label, set its
properties so that it looks just the way you want it to look, and then copy and
paste it five more times (you can copy and paste controls just like in Word or
Excel). You'll then have to change the names of the six labels to IbOne, IbTwo,
IbThree, IbFour, IbFive, and IbSix.
15
Chapter 1
Table 1-1 describes the numbered labels and their common properties. (When
you view their values in the Properties window, they look slightly different.)
16
Developing Your First Game
Figure 1-9. The Guess the Die Roll program at design time
17
Chapter 1
There's quite a bit to look at in this relatively small routine, whether you're
new to VB or a VB 6 programmer learning .NET. First, three variables are declared
at the top of the procedure. The two color variables are also initialized to a default
value, which is something you wouldn't be able to do in VB 6. For this program,
these two variable values never change from their default values, so you could
theoretically make them constants. In this case, they're variables in case the game
ever expands to support variable color schemes, such as the ability to load user-
selected colors from a configuration file.
TIP The Color data type is actually a structure rather than a class.
Within it are dozens of static members that retum colors by name.
You can also specify colors by Red-Green-Blue (RGB) values. Don't
worry if any of the terms such as structure or static member are
confusing at this point in the game-it'll all be clear eventually.
The rest of the routine is a loop that iterates through all of the controls
found in the collection Me. Controls. Me is a special keyword in VB that refers to
the current object in which this code resides. In this case, the code is inside
the form fGuess, so the loop iterates through all the controls that are part of that
form. This includes the seven label controls.
The next If statement checks if the current control in the loop is a label
(there could be other classes of controls on the form besides the seven labels,
and in fact there will be other nonlabel controls by the time this project is com-
plete). If the current control is a label, then a With statement begins. A With
statement is a form of shorthand that allows you to avoid having to enter
a control's name repeatedly in a block of code. A With statement begins with the
keyword With and then contains a control name. The statements within the block
can then omit the control name and refer to properties and other members with
only a period and the member name. The With statement allows you to omit the
control name to make code shorter and more readable.
The rest of the code inside the loop checks first to see if the currently con-
sidered label has a Tag property value of "Yes" (so that the IbResul t label is never
considered in this coloring code). If it does have a Tag value of "Yes", then the
code performs a check to see if the Text (formerly called the Caption property in
VB 6 and prior) of the currently considered label control matches that of an inte-
ger variable named Guess (whose declaration you'll see later). If this label has
a Text value of 2 and the current value of Guess is 2, then the background and
foreground colors of this label change to the values of the two color variables ini-
tialized at the beginning of the routine. If the Text value and variable value aren't
equal, then the colors change to the system colors (using yet another built-in
.NET Framework enumeration named KnownColor and a function to convert this
enumeration to a color data type named FromKnownColor).
18
Developing Your First Game
The purpose of this routine is to color the six numbered labels so that the label
that matches the value of the Guess variable is blue and the other five labels remain
black on gray. If one assumes that the value of Guess can only be 1 through 6, then
this code will always color exactly one label white on blue and the other five black
on gray.
There are actually two declarations in Listing 1-3, but they're related. The
first is a private integer variable named FGuess. By declaring a variable private,
you hide that variable from any code outside of this form class. Even if someone
knew there was a variable named FGuess and tried to refer to it from outside the
class, the compiler would complain and state that this variable was unknown.
The second declaration is for the Guess property itself. This declaration is
more complex than the simple FGuess integer declaration. A property is defined
in a block that has (up to) two subblocks within it: a Get function and a Set pro-
cedure. The Get function returns the value of the property whenever someone
references it. That is, if a piece of code like the following executes:
19
Chapter 1
then the property's Get routine executes when it's time to evaluate the value of
the Guess property. Note that the code doesn't simply have to return the value
of a variable-it could go through any type or length of VB code to calculate or
derive the value of the function before returning the current value.
Guess =1
then the property Set procedure executes. In the case of this property, the pri-
vate FGuess variable is set to the value passed into the Set procedure and is
returned as the current value of the Get function. This is the simplest, most
trivial type of property to set up.
The astute reader might ask the following: "Why set up a property in this
way?" This property is functionally equivalent to this declaration:
Here, a simple integer variable is declared, but it's specified as public instead
of private. A public declaration means that the variable is visible to code outside
of the class. Therefore, something functionally equivalent was created in fewer
lines of code. Isn't that better?
Under most circumstances, shorter code that does the same thing is indeed
better, but in this situation that's not lOO-percent correct. The reason is that set-
ting up properties, even if they don't look like they're going to do much for the
program yet, are much more powerful and allow you to conserve code later. You
won't see this in action until the next chapter when you'll rewrite the Guess the
Die Roll program. At this point, just know that properties are better than fields in
helping you write more structured object-oriented code.
20
Developing Your First Game
21
Chapter 1
Figure 1-10. Viewing available event handlers for a control using the two drop-
down boxes in the code editor
As you can see in Listing 1-4, you can make the same event handler handle
events on multiple controls by listing those events after the Handles clause. This
is easy to do manually.
The event handler in Listing 1-4 does a few things. The first thing it does is
set the Guess property discussed in the previous section to some value. It obtains
that value by casting the variable sender (which is passed into the event handler
and represents the label that the user clicked) to a label type, then obtaining
the value of the Text property of that label, and in tum converting that text
(string) value to an integer. All of those things happen in a single line of code:
Stated another way, when the user clicks the 3 label, this code converts the
passed-in sender parameter to a label, converts the text of that label to an integer
value, and stores it in the Guess property.
22
Developing Your First Game
Dim lb as Label
lb = CType(sender, Label)
Guess = Cint(lb.Text)
After the Guess integer is populated based on the clicked label, the next line
of code calls the UpdateGuessButtons procedure (which has already been dis-
cussed). This procedure, as you might recall, colors the six labels in such a way
that the one matching the value of the Guess property turns blue. The complete
effect is the user clicking one of the labels and having that label change color.
The following line calls a procedure named Roll TheDie. You'll learn more
about this procedure in the "Tying the Functionality Together" section.
Finally, a new variable named dieResult, is compared with the value of the
Guess property. If the values are equal, the seventh label changes to read Correct!,
meaning the user correctly guessed the value of the die roll. If the value of the
two variables isn't equal, the message ny Again displays in the seventh label.
This simple event handler represents the complete "flow" of the Guess the
Die Roll game. When one of the numbered labels is clicked, the value is stored,
the correct label is colored, the die is rolled, and the user is notified whether she
won or lost. The game then waits for the user to click one of the labels again, and
the process repeats.
23
Chapter 1
Setting Up Methods
The procedures discussed in the previous section, UpdateGuessButtons, are called
methods. A method is a procedure or function associated with a class. In the case
of the Guess the Die Roll program, the UpdateGuessButtons method is associated
with the fGuess class, which is a subclass of the .NET Framework form class.
Methods are often thought of as the "do work" code for a class. Because of
this, it's common that a method name is an action phrase or a verb. Look at all
of the method names associated with the final (version 1) fGuess class in the
Guess the Die Roll program, and you'll see a pattern:
• RollTheDie
• UpdateDiePosition
• DrawDie
• UpdateGuessButtons
Each of the method names has a verb in it, and thus it's self-evident what
task each method performs.
24
Developing Your First Game
Figure 1-11. One of the three sets of36 frames of die-rolling animations
25
Chapter 1
• Which frame to draw at a given time (and how to figure out which frame
to draw next)
• The current location of the die on the form (as x and y coordinates)
The width and height of a frame are constants, and you can declare them as
such at the top of the fGuess form:
These values depend on how the frames of the die were created. The current
location of the die is also held in a pair of integer values:
A lowercase die designates that these are variables describing the die, and
xPos and yPos are abbreviations for the x position and y position.
Next are the two variables that represent the direction in which the die is
moving:
As the comments indicate, these two variables hold a value between -8 and 8
(but never 0). A die moving left has a negative x direction; a positive x direction
indicates it's moving right. Likewise, negative and positive y directions indicate
upward and downward movement, respectively. Because neither direction can
ever be 0, the die is always moving in some sort of diagonal. This is intentional
26
Developing Your First Game
because the animated frames of the bitmap indicate movement along the "diag-
onal" of the pseudo-3D surface upon which the die is rolling (in other words, it
looks better if the die doesn't move straight up, down, left, or right).
There are three final variables to record the state of the die, the final result of
the roll (l-6), the current frame being displayed (0-35), and a status variable to
describe in which state the die is. You might recall from Listing 1-4 that the result
variable is named dieResult. The other two variables are also appropriately
named as follows:
All of the variables declared to this point have been simple integer types.
Look at the type of the dieStatus variable-it's a type named DieMovementStatus.
It's also being initialized to a value of dslanding. Can it be that there's a variable
type built into the .NET Framework that explicitly lists the possible status values
for a rolling die? Sadly, no. Instead, you have to make you own variable type,
called DieMovementStatus, and list the possible values with the declaration. As
mentioned earlier, this is known as an enumerated type. Fortunately, it's easy to
create your own:
Enumerated types work just like integers under the hood, but they're much
easier to use for two reasons. First, the code is much more readable as follows:
dieStatus = DieMovementStatus.Rolling
dieStatus = 1
27
Chapter 1
code are expecting only 0-2, there's no telling what bug you just introduced by
placing an unexpected value in there.
Dim gr As Graphics
Dim oBitmap As Bitmap
gr = Graphics.FromImage(bmBack)
Try
gr.Clear(Color.Black)
gr. DrawImage(oBitmap, diexPos, dieyPos, r, GraphicsUnit.Pixel)
Finally
gr .DisposeO
End Try
pnLower.Invalidate()
Application.DoEvents()
End Sub
28
Developing Your First Game
As usual, this rather tiny routine is doing quite a bit of work. The variables x
and y are set up first. These variables represent the upper-left comer of one of the
36 frames within one of the three die animation bitmaps. The variable dieFrame
holds the frame number, and the two equations shown in the declaration ofvari-
abIes x and y calculate the x and y coordinates of that frame. The backward slash
in a math statement such as this one refers to an integer divide (where any deci-
mal is truncated), and the Mod operator is the remainder operator after an integer
divide. You can check out the math if you like with an example. Suppose dieFrame
holds the value 17, then the upper-left comer of frame 17 would turn out to be
as follows:
Thus, the upper-left comer of frame 17 is the coordinate (720, 288). Next,
a .NET Framework class known as a Rectangle is instantiated and filled with these
starting coordinates, as well as the constants that represent the width and height
of a die frame:
This rectangle should now describe one frame of the die within one of the
three animation bitmaps.
Now that the program knows the coordinates within the animation bitmaps
needed to draw the frame, it needs to select the proper bitmap of the three avail-
able bitmaps. Listing 1-6 shows the selection code.
29
Chapter 1
As you'll recall, the three bitmaps represent the die rolling in the two direc-
tions diagonally and coming to a stop on each of the six values. These three
bitmaps are held in variables named bmxRot, bmyRot, and bmStop, respectively
(you'll see how to load these variables with bitmaps in the next section). When
one of the three bitmaps is selected, it's placed in variable oBi tmap for later.
The process of selecting which bitmap comes first determines what state
the die is in (variable dieStatus). If that status is dmsRolling (the enumerated
type value), then more work needs to happen. If the status is any other value
(dsStopped or dsLanding), then the choice is easy-the "stopping" is the selected
bitmap, which is held in the variable bmStop.
Now, let's get back to the dmsRolling case. What must be decided is if the die
is rolling in "upper-Ieft-to-Iower-right" diagonal direction or in the "lower-Ieft-
to-upper-right" direction. These are the only two cases because the possibility
that the die is moving along a true vertical or horizontal has already been elimi-
nated. The direction in which the die is traveling is held in the diexDir and
dieyDir variables. The value in these two variables is a random value between
-8 to +8, with zero removed as a possibility. You can determine the diagonal
direction by multiplying diexDir and dieyDir and looking at the sign of the result
(proof that you can use geometry in real life). If the sign is negative, then the die
is moving along the "lower-Ieft-to-upper-right" diagonal. If the sign is positive,
then it's moving along the other one. Figure 1-12 illustrates using the two direc-
tion variables to determine the direction of the diagonal.
- dxDir -y + dxDir
- dyDir - dyDir
-x
- dxDir
"/ /
~
+x
+ dxDir
+ dyDir + dyDir
+y
Figure 1-12. Determining which diagonal the die is rolling in by using simple
geometry. Special thanks to my 10th-grade geometry teacher, Mr. Cosimi!
The code in listing 1-6 performs this multiplication and selects either the
bitmap bmxRot or bmyRot based on the sign of the result.
Okay, so now there's a source bitmap (one of the three animated die bitmaps),
a source rectangle based on which frame to draw, and a destination bitmap
(named bmBack). All that remains is to determine where to draw the die on the
destination. This is easy, though, because variables that record the position of
30
Another Random Scribd Document
with Unrelated Content
road may run off with them.” Starlight obeyed, frightened enough at
the thought of the possible loss of the borrowed articles, and quickly
returning with them to the great relief of both Hazel and himself.
Then the story went on again, turn and turn about, Flutters
gaining courage to join in now and then, till at last, when the
twilight had given place to the sort of half darkness of a starlight
night, and the fire-flies were flashing their little lanterns on every
side, they had told all there was to tell, and three foot-sore little
people confessed they were tired and sleepy and hungry, and glad
enough to go indoors and do justice to a most inviting little supper,
which Josephine had slipped away some time before to prepare.
“Bonny Kate” (as she was called more than half the time, after a
certain wilful but very charming young woman in one of
Shakespeare's great plays) had long ago fallen asleep, and lay just
where her mother, running indoors for a moment, had stowed her
away in a corner of the great hair-cloth sofa in the dining-room. One
pretty hand was folded under her rosy cheek, and such a merry
smile played over her sweet face! She surely must have been
dreaming of a remarkable little fellow, in beautiful velvet and
spangles, coming head over heels up a garden path.
CHAPTER V.—CAPTAIN BONIFACE
RECEIVES AN ANGRY LETTER.
Wind and tide favored them, and Harry was an excellent sailor, so
that in a comparatively short time they had left the waters of the
Hudson behind them, had rounded Fort George, the Battery of to-
day, and were headed up the East River, with New York on the one
side, and the then scattered town of Brooklyn on the other. Skilfully
tacking in long slants from shore to shore, the wharves and shipping
were soon exchanged for the sloping banks of Manhattan Island on
the left, and of Long Island on the right, and then suddenly the
dismasted hulk of the old “Jersey” loomed up before them.
She was a dreary enough looking object to any one, but if, like
Harry, you had been a prisoner aboard of her for eighteen long
months, you would, like him, no doubt, have shuddered at the sight
of her. Josephine shuddered too. “Oh, do not let us go any nearer!”
she said.
“All right,” was Harry's quick response, for, in point of fact, nothing
pleased him better than to comply with Josephine's slightest wish, so
the “Gretchen” veered off again.
“Oh! can't we go aboard?” cried Flutters, with a world of
disappointment in his tone, for in imagination he had already scaled
the gangway ladder that hung at her larboard side, and turned more
than one somersault on the wide sweep of her upper deck.
“Why, no, child!” answered Hazel, who was fast assuming a most
patronizing air toward her little protégé; “no one would think of
going aboard of her, would they, Cousin Harry?”
“Why, why not?” Flutters asked, half-impatiently, for Harry, giving
his attention for the moment to the management of the boat, did
not at once reply.
“Because,” he said, finally, “there has been far too much sickness
in that old hulk for any one to safely venture aboard of her; she has
been responsible for the lives of eleven thousand men. I doubt if the
strongest and longest of north winds could ever blow her free from
the fever that must be lurking in her rotten timbers.”
That was a new phase of the matter to Flutters, and he subsided
at once into thoughtful silence.
“I think this would be a good place to anchor,” suggested Harry,
but waited a moment till Josephine had given her consent before
letting the anchor run the length of its rope and bury itself in the
mud bottom beneath them.
As soon as the “Gretchen” had settled into the position
determined for her by the tide, the little party of five ranged
themselves about the boat, so as to be as comfortable as possible,
for there they meant to stay for the next hour, or two, or three, as
the case might be. It had been for some time a thoroughly
understood matter between Hazel and Harry Avery, that whenever
the day should come for this trip to the “Jersey,” they were to anchor
their boat in full sight of her, and then and there he was to tell them
the “whole story”—from the day he volunteered till the day of his
release in the previous summer.
Flutters, who had been made acquainted with the object of the
expedition, waited, with a charming native sense of the “fitness of
things,” until the others had chosen their places; then he threw
himself at Harry's feet, in one of the graceful positions so natural to
him, and which even Hans Van Wyck's rough, homespun clothes did
not altogether succeed in hiding. It was wonderful to look into
Flutters's upturned face—such complete satisfaction, such tranquil
happiness shone out of it. Even in those exciting moments when
every nerve and tissue was thrilling under Harry's narration of the
dark features of his prison life, a smile still seemed to be lurking in
the corners of his expressive mouth. Yesterday, a lonely little tumbler
in a dreary, tawdry circus company; to-day, one of a blessed circle of
warm-hearted friends. Whatever fears others might have as to the
disposal to be made of him, Flutters had none for himself. Of course
he was to be Hazel's faithful little servant from that day forward, and
it was almost worth while, he thought, to have “darkey blood” in
one's veins for the sake of rendering such happy service. Farther
than that he did not trouble himself, literally taking no thought for
the morrow, nor for what he should put on when his present
habiliments should have found their way back to their rightful owner.
The “Gretchens” little company made a pretty picture against the
blue gray of the bay, and when at last there was no more arranging
to be done, and all had repeatedly declared themselves “perfectly
comfortable,” there was a breathless, momentous little pause, as in
the moment at a play between the significant and abrupt cessation
of the orchestra and the rolling back of the curtain. “Please begin,”
said Hazel, with a great sigh, as though the intense anticipation of
that supreme moment was quite too heavy for child-nature to
endure, and Harry, looking sadly over to the old “Jersey,”
commenced his story.
CHAPTER VII—HARRY'S STORY
OOD-BYE, Hazel,”
“Good-bye, Starlight,”
“Good-bye, Josephine,”
“Good-bye, Cousin Harry,”
“Good-bye, Flutters.” Quite a medley of good-byes,
to be sure, but no more than were needed, for Harry
and Starlight, once more aboard of the “Gretchen,”
were fast gliding out on to the river, and Josephine
and Hazel and Flutters were being left behind on the
wharf. The little prison-ship party had had their
supper, and now Harry and Starlight were off for
Paulus Hook; it was high time, too, that they were,
since they had already been absent a day longer than Harry had
planned, and Aunt Frances would naturally begin to feel worried.
Little Flutters cut a queer figure as he stood there on the boating
dock in the moonlight. Hans Van Wyck's clothes, done up in a snug
bundle, were already on their way back to their lawful owner, so that
he had need to resort once more to the spangles and tinsel of his
circus costume. By way of making up for insufficient clothing, Mrs.
Boniface had thrown a shawl about him, one end of which Flutters
allowed to trail behind, pinning the other close about his throat, with
one corner thrown over his left shoulder.
“We must do something about some clothes for you, Flutters, right
away,” Hazel remarked, as they turned to walk up from the wharf,
when, amid the darkening shadows of the river, the “Gretchen's” sail
was no longer visible. “Starlight and I hoped Mrs. Van Wyck would
offer to give us that suit of Hans's to keep when he stopped to see
her this afternoon and told her about you, but she did not propose
anything of the kind. She only said 'it was very inconvenient for Hans
not to have them, and she hoped we'd manage to get them back to-
night.'”
“And you have managed, haven't you, Miss Hazel?” Flutters
answered, as if the managing were a matter to be proud of; and,
mimicking a sort of stage stride such as he had often witnessed in
tragical circus pantomimes, he apparently bestowed far more
attention on the sweep of his majestic train than on what Hazel was
saying.
“Yes, of course, I sent them back; what else could I do?”—this last
rather impatiently, because of Flutters's exasperating unconcern
__"but how are you going to manage without them is what I'd like
to know.”..
Flutters gave Hazel a comical little look. “With tights and shawls, I
s'pose, Miss Hazel, unless the Captain felt like as he could buy some
for me.”
“No,” said Hazel decidedly; “I am not going to bother father 'bout
things like that, 'specially now when he's so worried and his life's in
danger.”
This remark brought Flutters to a stand. “Is the Captain's life in
danger, really, Miss Hazel?”
“Yes, it is. Josephine said he received a very angry letter the other
night from some old friends of his. They as much as told him that he
must go away, and that his life wasn't safe here; and lots of people
are going, Flutters; people who, like father, have sided with King
George.”
“Where are they going, Miss Hazel?”
“To England, most of them.”
“And will the Captain go?”
“No, Josephine thinks not. You see he built this house, Flutters,
and he loves it, and he loves this country, too. Josephine says she
believes he'll just stay, and try and live the angry feeling down.”
“Miss Hazel,”.said Flutters, stopping to gather the trailing shawl
over one arm, for he was ready now to give his whole mind to the
matter in hand, “it's a very puzzling thing 'bout me. When Mr. Harry
was telling those sad things of the prison-ship, I thought I was a
Whig, and now when you are talking 'bout the Captain, it seems as
though I was a—a what do you call it?”
“A Loyalist, Flutters?”
“Yes, a Loyalist; but I reckon folks what has friends on both sides,
had better not be anything particular.”
“Perhaps that would be best,” Hazel replied, smiling in spite of
herself.
“Miss Hazel,” Flutters said, after a little pause, stopping and
looking round him somewhat cautiously, as though he feared his
question might be overheard, “did Starlight hear of any 'quiries for
me, when he was in the city this afternoon?”
Hazel nodded “Yes” in a most mysterious manner.
“There's no danger of their 'quiring round here, do you think?”
and Hazel saw the involuntary little tremble shoot through Flutters's
frame.
“No, indeed, Flutters, and we wouldn't give you up if they did.
Mrs. Van Wyck told Starlight that a forlorn old man, who belonged to
the circus, stopped at her gate and asked if she'd seen anything of a
little mulatto boy what had deserted from the troupe, or knowed
anything about him, and Mrs. Van Wyck said, 'Lor', no!' never
dreaming that her very own little Hans's clothes were on that same
little boy that very moment.”
“That must have been good old Bobbin,” answered Flutters, fairly
chuckling over the thought of the entire success of his escape.
“Miss Hazel,” he added, after a moment's thoughtful meditation,
“I've been thinking how I might earn the money for my clothes by
doing a little tumbling for folks round here, only I'm so awfully afraid
of being heard of by the circus people.”
The suggestion instantly flashed a new scheme through Hazel's
mind.
“Flutters,” she said, very slowly and seriously, “I've—thought—of
something. Yes, it's the very thing. I'm going to town tomorrow, to
see Colonel Hamilton about an important matter, and I'll make all the
'rangements.”
“'Rangements 'bout the clothes, Miss Hazel?”
“Yes, 'rangements 'bout everything; but, hush! 'cause nobody else
must know about it.” They had reached the porch where Mrs.
Boniface was sitting, and Josephine was close behind them, which
was the occasion for Hazel's “Hush” and so little Flutters tumbled
into bed half an hour later, still in ignorance as to what the scheme
of his “little Mistress” might be, but with perfect confidence in her
ability to make any arrangements under the sun.
Joe Ainsworth found his little friend waiting in the sunshine the
next morning, and, almost without intimation from him, the leaders
came to a standstill, and Hazel mounted to her seat beside him.
“Business in town?” ventured Joe.
“Colonel Hamilton's, please,” all intent on getting comfortably
seated.
“Oh!” exclaimed Joe, with elevated eyebrows, “haven't fixed that
matter up yet, eh?”
“Not yet. I haven't had time to see to it until to-day.”
“Haven't had time,” said Joe, with a significant smile.
“No, I haven't, really. Yesterday I had to go on a sailing party and
the day before to the circus.”
“My lands, Miss Hazel! I guess if you had to drive this Albany
coach every day of your life, week in and week out, and was ever
able to take so much as a day off for a circus or a sailing party, you
would call that having lots of time. I would, I can tell ye.”
“Well, then, perhaps it was because I couldn't do both things, Joe,
so I chose the sailing party and the circus.”
“I don't blame you, Miss Hazel. Besides, there can't be anything
very pleasant for such a loyal little Red-Coat as you to look forward
to, in calling on our American Colonel.”
“I'm not afraid of any American Colonel,” with the air of a grand
duchess.
“No, of course not, Miss Hazel, but I'd have a care to that little
tongue of yours.”
Hazel did not answer. She would not have allowed many people to
offer that unsolicited advice without some sort of a rejoinder, but she
had always a most kindly side toward Joe Ainsworth, not entirely
accounted for, either, by the fact of the free rides.
For some reason or other the coach horses kept up a good pace
that morning, and it was not long before they came to a halt at
Hazel's destination.
Colonel Hamilton's law office was in just such another wide-
porched double house as the Starlight homestead; and, like it, had
been vacated by its rightful owner during the progress of the war,
and so had shared the similar fate of being immediately claimed by
the English. They were most comfortable-looking dwellings, those
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookultra.com