Sie sind auf Seite 1von 11

c 



   

  

 

  



 
Computer programs are usually written as the solution to some problem that a machine
can solve faster (and sometimes better) than a human. Like any problem situation, the
solution should be well thought out in advance. Visual Basic programs, from the simple
to the most complex, require some degree of planning. We are going to look at the
steps which start with a program idea and end with an executable program that can run
on any computer which has Windows as the operating system.

In writing a program we will use concepts that have been introduced in earlier lessons
and which will be looked at in greater detail later.




After a lot of serious applications such as military, business, and scientific,


programmers turned to entertainment. Today game programming is a multimillion
dollar industry. We will create a program to play a simple game (no fancy graphics,
sorry :) )

The programing problem is to create a program that can generate a random number
and have the user guess that number. If you play this type of game long enough you
will probably find the secret to guessing the correct number in a minimum of guesses.

Let's write some specifications for the program.

ë The program should generate a random number between 1 and 100


ë There has to be some way for the user to enter a guess
ë The code will compare the guess and the random number
ë ?epending on the guess, the program should generate appropriate messages
ë There should be a way to end the program

 

Because Visual Basic is graphical in nature we will divide the planning into two major
parts

ë Rlanning the Graphical Interface


ë Rlanning the Code

 
 !  

£ou can plan a rough layout of the controls by sketching on a piece of paper or if you
are in front of a computer, try laying out the design on a new project form. Either way,
you need to think about the number of controls and their function in your project. After
some thought, we conclude that we need the following controls. Of course there can be
variations:

Controls include:

ë A guess button
ë An end button
ë A textbox to input the guess
ë A label for the input text box
ë A label to display the result

This is the initial layout:


"
 
     

This looks terrible! We need to make it more presentable. By now you know that
controls have properties and some of those properties will definitely improve the look of
your interface. Think of what needs changing and make a list. On a small project you
might just change the properties in the project and adjust until you are satisfied. On
bigger projects with multiple forms it would be wise to do more in- depth planning.
Let's make a grid for our control properties.

    !#  !#
" $ BackColor Sand
  $ Name cmdGuess
BackColor Light Green
Caption GUESS
Font Arial, 12pt, bold
Style Graphical
   Name cmdEnd
BackColor Light Green
Caption EN?
Font Arial, 12pt, bold
Style Graphical
%$ Name txtGuess
Text None
&$ Name lblGuess
BackColor Sand
Caption Enter Guess
Font Arial, 10pt, bold
& Name lblHint
BackColor Sand
Guess a number
Caption
between 1 and 100
Font Arial, 14pt, bold
ForeColor Blue

&   !  

Ok, try changing the properties and see how it looks.


"
   ! 


That's a little better. Later we may make a few more improvements.

 
 

We have a functional looking interface but it's just an empty shell. It can't do anything
because we haven't told it to. Now we need to plan the program code. In formal
programming courses we would use a logical diagram called a flow chart. We will do
one to show how it looks but for now lets use plain English.

What do we want this program to do? Lets have a first try:

ë Generate a random number between 1 and 100 but keep it to yourself (meaning
the computer:)
ë Have the human enter a guess.
ë Check the guess.
ë Tell the human it's wrong or right.
ë End the program.

Well this is pretty boring! £ou only get one guess? Let's think this through again:
ë Generate a random number between 1 and 100 but keep it to yourself (meaning
the computer:)
ë Have the human enter a guess.
ë Compare the guess to the "hidden" number.
ë If the guess is correct, congratulate the human and end the program.
ë If the guess is wrong, tell the human and let them have another guess

This is getting better. But guessing a number between 1 and 100 can take a long
time. Why not give the human a hint!

ë Generate a random number between 1 and 100 but keep it to yourself (meaning
the computer:)
ë Have the human enter a guess.
ë Compare the guess to the "hidden" number.
ë If the guess is higher than the hidden number tell the human and wait for
another guess
ë If the guess is lower than the hidden number tell the human and wait for another
guess
ë If the guess is correct, congratulate the human and end the program

This seems better. At least we are giving the user a better chance. A flowchart would
show the same steps only with a diagram. Here's an example:
"
"      ! 

Now we will need to translate our English steps into Visual Basic code and we have to
be exact. Computers (unlike teachers) can't tolerate even a single word spelled wrong
or a statement which isn't precisely correct.

'
 

OK, our first task is to get the computer to generate a random number. We will need to
store this number in the computer's memory. Visual Basic provides us with neat
"storage containers" called variables. Because we will need to use this variable in a
couple of different areas of the program, we need to declare its existence. Variables
will be covered in more detail in a later lesson.

Visual Basic declares a variable using a ?im keyword. ?im is short for dimension. It
goes in the General .... ?eclarations of the code window. First we need to think up a
name for the variable, a name that describes what the variable holds and it can't be a
special Visual Basic reserved word.

How about Number! We will open the code window and type this in the proper place.


"
& 

Now that we have the Number variable declared we can generate the number that it
will contain. Visual Basic has a special function, Rnd, that generates a random
number. We won't go into detail here but it looks like the following:

-  
  

The code on the right of the equals sign will generate the random number between 1
and 100. The equals sign will assign that number to the variable (called Number)
where it will be stored.

There is only one thing wrong, this will generate the same random number every time.
When is a random number not a random number? When it's the same every time of
course. There is a little more to this then we have time for so let's just say, the fix is to
precede this line with a special Visual Basic keyword, Randomize. This causes the
number to be random. So we need to write:


-  
  

But where do we put this code? An easy way to generate the number when the
program runs is to use one of the events belonging to the form itself. The event is
called Load and any code placed in this area will run every time the form loads which in
most cases is when the program is first run. Let's put it there:

"
"  ()  

OK, look back at the flowchart. what's next? We need to have the user type the guess
into the text box and have the computer decide. We will use the GUESS command
button to put this is motion. To be more precise, we will use the cmdGuess button's
(remember we changed the name) click event to run the code.

Just as we needed a variable or container to store the random number we will need
another to store the guess. Why not name it Guess. If you are using Guess only in one
event you don't need to tell the rest of the program about it. That is, you don't have to
declare it in the ?im statement. So, after typing a guess into the text box (txtGuess)
you click the cmdGuess button. Here's what the code looks like:

Guess = val(txtGuess)

 -      


 !-   " # $ 
 %-   "&# $ 


"
  $*  +,()  

We need to explain how this code works. Let's take it apart:

 '
(  

This takes the number you typed into the text box (txtGuess) and stores it in the
variable Guess. The Val is a Basic reserved word meaning value. Remember we typed
our guess into a text box so the number is really text and not a number that you can do
calculations with. The computer treats a number and a text string (a string of
characters) differently. Val changes the text into a proper number!

 -      


This is where the real work gets done. Visual Basic uses the ))))" keywords to
compare two things. If the comparison is true, the code after" is executed. If the
comparison is false, the code is ignored and the computer moves to the next
statement. In this case the code after Then assigns the text string "Correct! Right On!"
to label2 (lblHint) which we placed at the top of the form. In actual fact we are
changing the label's caption property so we could also write the line as follows:

 -   )*    

Can you guess why we don't have to write the .Caption property name? It's because
Caption is the default property for a Label control just as Text is the default property for
the Text box control.

If you understood the last line of code, the next 2 are easy. We are using the relational
operators greater than > and less than < to do the comparison.

 !-   " # $ 


 %-   "&# $ 

Now we have a functioning program but there is one more button to write code for.
The EN? button (cmdEnd) needs to have one line of code in its click event procedure.
Here it is:

+

That's it. One keyword.

Now we really should have been saving our Visual Basic project at each of the key
stages. Sometimes you get so involved with the process that you forget to do this and
then the computer locks up. Anyway, as you should know by now, when you save a
project you are first asked for a file name for the form and then for the project. In
simple, one form projects you can use the same name. Visual Basic uses the extension
.frm and .vbp (Visual Basic Rroject) for the form and project so the names can be the
same. After the project is saved the first time, you just need to click the disk icon each
time you make additions or changes.

"
 )
"   -

 !
 (%&

The last step in the process is to make an executable. Again, that means it is compiled
into a file with the extension .exe. This type of file can be run without having Visual
Basic installed on the computer. £ou don't have to make an executable each time but
you might want to impress your friends with the programs you create!

To compile the program, we will open the File menu and select Make filename.exe. £ou
have to make sure the project is already saved. In this case the project was saved as
guess.vbp and the executable will be created and saved as )()

"
 !
 (%&"

OK, now you might want to try the object of this lesson and see if you can figure out
how to guess the correct number in the least number of guesses. The program we just
created has much room for improvement and we will do some of this later. After you
try your luck, move to the Activity page.

Click on the link below and click open to run the application.

„ 

Ä)#
The purpose of these activities is to experiment with VB programming structure and
syntax

Ä)#$  
 

Using Lesson 2 as your guide, create the guessing game application. Run Visual Basic
and when the New Rroject window opens, select Standard.EXE

"
  .(/( ! 

Make sure you save this program for future use.

Copy all files to your course portfolio

Ä)# !



The Kindergarten teacher has learned that you know something about visual basic. She
wants you to write a small program she can use with some students who are learning
to spell the names of colors. This is what she wants:

The program should have two text boxes and a command button. The student would
type the name of the color in one text box, click the button, and the second text box
should turn that color. Colors should be limited to 8.

Hints:

Name the two text boxes txtColorName (where the student types the name) and
txtColor (where the corresponding color is displayed).

When you are trying to compare a text string (a string of characters eg. a word) it must
be in double quotes.

Example

if txtColorName = "red" then txtColor = vbRed

£ou should do the following:

ë ?raw a control properties grid. Use the one in the lesson as a guide
ë Write the logic of the code in English before you do it on the computer. Again
use the lesson as a guide
ë Create the Visual Basic program, save it, test it and create a )( file
Copy all files to your course portfolio

 0   
© 2007 C?LI. All Rights Reserved.

Das könnte Ihnen auch gefallen