Writing the Code


Writing the Code

Now you're ready to write the code for the Lucky Seven program. Because most of the objects you've created already “know” how to work when the program runs, they're ready to receive input from the user and process it. The inherent functionality of objects is one of the great strengths of Visual Studio and Visual Basic—after objects are placed on a form and their properties are set, they're ready to run without any additional programming. However, the “meat” of the Lucky Seven game—the code that actually calculates random numbers, displays them in boxes, and detects a jackpot—is still missing from the program. This computing logic can be built into the application only by using program statements—code that clearly spells out what the program should do at each step of the way. Because the Spin and End buttons drive the program, you'll associate the code for the game with those buttons. You enter and edit Visual Basic program statements in the Code Editor.

In the following steps, you'll enter the program code for Lucky Seven in the Code Editor.

Reading Properties in Tables

In this chapter, you've set the properties for the Lucky Seven program step by step. In future chapters, the instructions to set properties will be presented in table format unless a setting is especially tricky. Here are the properties you've set so far in the Lucky Seven program in table format, as they'd look later in the book. Settings you need to type in are shown in quotation marks. You shouldn't type the quotation marks.

Object

Property

Setting

Button1

Text

“Spin”

Button2

Text

“End”

Label1, Label2, Label3

AutoSize

BorderStyle

Font

Text

TextAlign

False

Fixed Single

Times New Roman, Bold, 24-point

“0”

MiddleCenter

Label4

Text

Font

ForeColor

“Lucky Seven”

Arial, Bold, 18-point

Purple

PictureBox1

Image

SizeMode

Visible

“c:\vb05sbs\chap02\paycoins.jpg”

StretchImage

False

Use the Code Editor

  1. Double-click the End button on the form.

    The Code Editor appears as a tabbed document window in the center of the Visual Studio IDE, as shown here:

    graphic

    Inside the Code Editor are program statements associated with the current form. Program statements that are used together to perform some action are typically grouped in a programming construct called a procedure. A common type of procedure is a Sub procedure, sometimes called a subroutine. Sub procedures include a Sub keyword in the first line and end with End Sub. Procedures are typically executed when certain events occur, such as when a button is clicked. When a procedure is associated with a particular object and an event, it is called an event handler or an event procedure.

    When you double-clicked the End button (Button2), Visual Studio automatically added the first and last lines of the Button2_Click event procedure, as the following code shows. (The first line was wrapped to stay within the book margins.) You'll notice other lines of code in the Code Editor, which Visual Studio has added to define important characteristics of the form. However, readers familiar with Visual Basic 2002 and 2003 will see less boilerplate code than in previous versions of Visual Basic. The code block beginning with the words Windows Form Designer generated code has been removed.

    Private Sub Button2_Click(ByVal sender As System.Object, _    ByVal e As System.EventArgs) Handles Button2.Click    End Sub

    The body of a procedure fits between these lines and is executed whenever a user activates the interface element associated with the procedure. In this case, the event is a mouse click, but as you'll see later in the book, it could also be a different type of event.

  2. Type End, and then press the Down Arrow key.

    After you type the statement, the letters turn blue and are indented, indicating that Visual Basic recognizes End as one of several hundred unique reserved words, or keywords, within the Visual Basic language. You use the End keyword to stop your program and remove it from the screen. In this case, End is also a complete program statement, a self-contained instruction executed by the Visual Basic compiler, the part of Visual Studio that processes or parses each line of Visual Basic source code, combining the result with other resources to create an executable file. Program statements are a little like complete sentences in a human language—statements can be of varying lengths but must follow the grammatical “rules” of the compiler. In Visual Studio 2005, program statements can be composed of keywords, properties, object names, variables, numbers, special symbols, and other values. You'll learn more about how program statements are constructed in Chapter 5, “Visual Basic Variables and Formulas, and the .NET Framework.”

    As you enter program statements and make other edits, the Code Editor handles many of the formatting details for you, including adjusting indentation and spacing and adding any necessary parentheses. The exact spelling, order, and spacing of items within program statements is referred to as statement syntax.

    When you pressed the Down Arrow key, the End statement was indented to set it apart from the Private Sub and End Sub statements. This indenting scheme is one of the programming conventions you'll see throughout this book to keep your programs clear and readable. The group of conventions regarding how code is organized in a program is often referred to as program style.

Now that you've written the code associated with the End button, you'll write code for the Spin button. These program statements will be a little more extensive and will give you a chance to learn more about statement syntax and program style. You'll study many of the program statements later in this book, so you don't need to know everything about them now. Just focus on the general structure of the code and on typing the program statements exactly as they are printed.

Write code for the Spin button

  1. Click the View Designer button in the Solution Explorer window to display your form again.

    NOTE
    When the Code Editor is visible, you won't be able to see the form you're working on. The View Designer button is one mechanism you can use to display it again. (If more than one form is loaded in Solution Explorer, click the form you want to display first.) You can also click the Form1.vb [Design] tab at the top edge of the Code Editor. If you don't see tabs at the top of the Code Editor, enable Tabbed Documents view in the Options dialog box, as discussed in a Tip in Chapter 1.

  2. Double-click the Spin button.

    After a few moments, the Code Editor appears, and an event procedure associated with the Button1 button appears near the Button2 event procedure.

    Although you changed the text of this button to “Spin”, its name in the program is still Button1. (The name and the text of an interface element can be different to suit the needs of the programmer.) Each object can have several procedures associated with it, one for each event it recognizes. The click event is the one you're interested in now because users will click the Spin and End buttons when they run the program.

  3. Type the following program lines between the Private Sub and End Sub statements. Press Enter after each line, press Tab to indent, and take care to type the program statements exactly as they appear here. (The Code Editor will scroll to the left as you enter the longer lines.) If you make a mistake (usually identified by a jagged underline), delete the incorrect statements and try again.

    TIP
    As you enter the program code, Visual Basic formats the text and displays different parts of the program in color to help you identify the various elements. When you begin to type a property, Visual Basic also displays the available properties for the object you're using in a list box, so you can double-click the property or keep typing to enter it yourself. If Visual Basic displays an error message, you might have misspelled a program statement. Check the line against the text in this book, make the necessary correction, and continue typing. (You can also delete a line and type it from scratch.) In addition, Visual Basic might add necessary code automatically. For example, when you type the following code, Visual Basic automatically adds the End If line. Readers of previous editions of this book have found this first typing exercise to be the toughest part of this chapter—“But Mr. Halvorson, I know I typed it just as you wrote it!”—so please give this program code your closest attention. I promise you, it works!

     PictureBox1.Visible = False    ' hide picture  Label1.Text = CStr(Int(Rnd() * 10))    ' pick numbers  Label2.Text = CStr(Int(Rnd() * 10))  Label3.Text = CStr(Int(Rnd() * 10))  ' if any number is 7 display picture and beep  If (Label1.Text = "7") Or (Label2.Text = "7") _  Or (Label3.Text = "7") Then      PictureBox1.Visible = True      Beep()  End If

    When you've finished, the Code Editor looks as shown in the following graphic:

    graphic

  4. Click the Save All command on the File menu to save your additions to the program.

    The Save All command saves everything in your project—the project file, the form file, any code modules, and other related components in your application. Since this is the first time that you have saved your project, the Save Project dialog box appears prompting you for the name and location of the project. (If your copy of Visual Studio is configured to prompt you for a location when you first create your project, you won't see the Save Project dialog box now—Visual Studio just saves your changes.)

  5. Click the Browse button to the right of the Location text box, and select a location for your files.

    I recommend that you use the c:\vb05sbs\chap02 folder (the location of the book's sample files), but the location is up to you. Since you used the “My” prefix when you originally opened your project, this version won't overwrite the Lucky7 practice file that I built for you on disk.

    NOTE
    If you want to save just the item you are currently working on (the form, the code module, or something else), you can use the Save command on the File menu. If you want to save the current item with a different name, you can use the Save As command.

A Look at the Button1_Click Procedure

The Button1_Click procedure is executed when the user clicks the Spin button on the form. The procedure uses some pretty complicated statements, and because I haven't formally introduced them yet, it might look a little confusing. However, if you take a closer look, you'll probably see a few things that look familiar. Taking a peek at the contents of these procedures will give you a feel for the type of program code you'll be creating later in this book. (If you'd rather not stop for this preview, feel free to skip to the next section, “Running Visual Basic Applications.”)

The Button1_Click procedure performs three tasks:

  • It hides the digital photo.

  • It creates three random numbers for the number labels.

  • It displays the photo when the number 7 appears.

Let's look at each of these steps individually.

Hiding the photo is accomplished with the following line:

PictureBox1.Visible = False    ' hide picture

This line is made up of two parts: a program statement and a comment.

The PictureBox1.Visible = False program statement sets the Visible property of the picture box object (PictureBox1) to False (one of two possible settings). You might remember that you set this property to False once before by using the Properties window. You're doing it again now in the program code because the first task is a spin and you need to clear away a photo that might have been displayed in a previous game. Because the property will be changed at run time and not at design time, you must set the property by using program code. This is a handy feature of Visual Basic, and I'll talk about it more in Chapter 3, “Working with Toolbox Controls.”

The second part of the first line (the part displayed in green type on your screen) is called a comment. Comments are explanatory notes included in program code following a single quotation mark ('). Programmers use comments to describe how important statements work in a program. These notes aren't processed by Visual Basic when the program runs; they exist only to document what the program does. You'll want to use comments often when you write Visual Basic programs to leave an easy-to-understand record of what you're doing.

The next three lines handle the random number computations. Does this concept sound strange? You can actually make Visual Basic generate unpredictable numbers within specific guidelines—in other words, you can create random numbers for lottery contests, dice games, or other statistical patterns. The Rnd function in each line creates a random number between 0 and 1 (a number with a decimal point and several decimal places), and the Int function returns the integer portion of the result of multiplying the random number by 10. This computation creates random numbers between 0 and 9 in the program—just what you need for this particular slot machine application.

Label1.Text = CStr(Int(Rnd() * 10))    ' pick numbers

You then need to jump through a little hoop in your code. You need to copy these random numbers into the three label boxes on the form, but first the numbers need to be converted to text with the CStr (convert to string) function. Notice how CStr, Int, and Rnd are all connected together in the program statement—they work collectively to produce a result like a mathe-matical formula. After the computation and conversion, the values are assigned to the Text properties of the first three labels on the form, and the assignment causes the numbers to be displayed in bold, 24-point, Times New Roman format in the three number labels.

The following illustration shows how Visual Basic evaluates one line of code step by step to generate the random number 7 and copy it to a label object. Visual Basic evaluates the expression just like a mathematician solving a mathematical formula.

graphic

The last group of statements in the program checks whether any of the random numbers is 7. If one or more of them is, the program displays the medieval manuscript depiction of a payout, and a beep announces the winnings.

' if any number is 7 display picture and beep  If (Label1.Text = "7") Or (Label2.Text = "7") _  Or (Label3.Text = "7") Then      PictureBox1.Visible = True      Beep()  End If

Each time the user clicks the Spin button, the Button1_Click procedure is executed, or called, and the program statements in the procedure are run again.



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net