What's new

Closed Microsoft Visual Basic 6

Status
Not open for further replies.

yus15

Forum Expert
Joined
Jul 22, 2013
Posts
2,260
Reaction
14,678
Points
2,104
Beginner Tutorial - Hello World
Level:

Level1.gif

Visual Basic is a great starter programming language. Not only is it easy to learn, but many business applications use it extensively for their applications. If you are just starting to learn to develop applications - this is a great language to start with. This tutorial and the many other Visual Basic tutorials at this site will give you a solid foundation in your Visual Basic knowledge.

Lets jump right in with a simple application. When you are done with this Visual Basic tutorial, you should have a complete working application that when you click on the button it will say "Hello, World"

Start Microsoft Visual Basic 6.0 (VB6)

The New Project dialog box will appear. If it doesn't go up to the menu bar and select File -> New Project

Visual-Basic-Tutorial-Screen1.jpg

In the New Project dialog select Standard EXE, and click the Open Button.

This will bring up your new Project 1 application with Form1 visible.

Already Visual Basic has done a lot for us. As you can see this tutorial isn't very long but already you have a full working application. You can see your new program in action by going up to the menu bar and selecting Run -> Start (Or simply press the F5 key).

You should see the Form1 window appear:

Visual-Basic-Tutorial-Screen2.jpg

This is a fully functional application. You can move it around, minimize and maximize it, and close it down. For you to do this same thing in C++ - the original language most of Windows was written in you would have written hundreds of lines of code. You area already getting to see some of the extreme power VB gives you. Now lets continue with the tutorial.

Lets make this program say hello!

Visual-Basic-Tutorial-screen3.jpg

On the left side of the screen you can see the toolbox (if this doesn't show up go to the top menu bar and select View -> Toolbox). In this toolbox you will see a picture of a button. Double click the button icon and it will create a Command1 CommandButton in the center of your form.

Visual-Basic-Tutorial-screen4.jpg

If you run the program now (Press F5) you will see your window now has a button labeled Command1 in the center of it, but if you click the button it doesn't do anything. So lets wire things up so our program will say "Hello, World" when you click the button. Close out of your running program so you are back to the main design environment (pictured above)

Visual Basic allows you to do event driven programming. This is a concept that is very powerful and easy to use. Event driven programming works as follows: Visual Basic has many different events defined that occur when a specified thing happens. We as the programmer can link into these events and write our custom code to do what we want. One very useful event is the Click event. This event occurs any time the user clicks on the specified object. I'm sure the wheels are already turning in your head, if we want to say hello world when someone clicks the button on our form than we should do something in the Click event for the Command1 button. That is exactly what we are going to do.

To write the click event code double click on the Command1 button. This will bring up the code editor and will automatically write the beginning code to handle the click event.

Visual-Basic-Tutorial-screen5.jpg

Now any code you put between the Private Sub and the End Sub statements will be executed when the user clicks the command button. To demonstrate this we will have a message box appear saying hello world. So add this line of code:

Private Sub Command1_Click()
MsgBox "Hello, World!"
End Sub

MsgBox is a built in Visual Basic function that causes a message box to be displayed to the user. The first parameter this function takes is the text string you wish to have displayed. We choose the text string "Hello, World!". MsgBox also takes other parameters to specify things such as what buttons to display and what caption to use, but these will be discussed later. For now lets see how this works. Run your newly created Visual Basic hello world program (Press F5). Once the program is running click the Command1 button, you should see a message box saying Hello, World! appear.

Visual-Basic-Tutorial-screen6.jpg

Congratulations! You have written a complete working Visual Basic program using this Hello, World tutorial. Read some of our other VB6 tutorials to learn how powerful this language really is.

Reference: You do not have permission to view the full content of this post. Log in or register now.
 

Attachments

Creating a graphic "Tic Tac Toe" game in VB6

Level:
Level2.gif

Written By You do not have permission to view the full content of this post. Log in or register now..

PROGRAMMING EXERCISE

Tic-Tac-Toe


Write a VB application that will enable a human player to play a classic game of Tic-Tac-Toe against the computer.


Requirements

The application should begin with a form that contains the following elements:

- A label saying "Welcome to Tic-Tac-Toe"

- Two option buttons enclosed in a frame. The captions for the option buttons should be "X" and "O". The caption for the frame should be "Select 'X' or 'O' and click OK".

- A command button with the caption "OK".

When the user clicks OK, exit this form and display the main form (the game board).


At the start of each game, the application should select who should go first at random, and display an appropriate message to the user in a message box (either "You go first this time." or "This time, I will go first.")


The game board should be set up with an array of label controls indexed 0 through 8. When a player clicks one of the available labels, an "X" or an "O" (depending on the user's initial selection) should appear in that label. Then the computer should make its move.


When the program detects a win, a line should be drawn through the "three in a row". If the player wins, the message "YOU WIN !!!" should flash across the game board; if the computer wins, the message "YOU LOSE!!!" (or "I WIN!!!" or "COMPUTER WINS!!!") should flash across the game board. If the game ends in a tie, the message "IT'S A TIE!!!" should flash across the game board. (Hint: To get the flashing message, use a label in conjunction with a timer and toggle the label's Visible property on and off.)


The program should provide options to play a new game and to quit.


The program should provide keep four counts: games played, games won, games lost, and games tied. These counts should be displayed on the form.


The overall appearance of the application should be tasteful and suggest "fun". Experiment with various colors and fonts until you get it the way you want it.


The Computer's AI Algorithm

Your program should implement the following algorithm to try to make the computer win:


(1) Examine the board for a winning move, and if you find one, make that move – otherwise proceed to step (2).

(2) Examine the board to see if your opponent has a winning move, and if so, select that square to block, otherwise proceed to step (3).

(3) If the center square is available, select it, otherwise proceed to step (4).

(4) If you are already occupying the center square, and a side square is available, take the side square, otherwise proceed to step (5).

(5) If a corner square is available, then take it, otherwise, take the next available square.


Note: When the above algorithm is implemented, it is possible for a smart player to beat the computer if the player is able to go first. If you switch steps (4) and (5), it may be impossible for a player to win; the best they can do is tie.


Tic-Tac-Toe

(screenshots of my version of the solution)


image001.jpg


image002.jpg


image003.jpg



D*wnload the solution for this project You do not have permission to view the full content of this post. Log in or register now..
 

Attachments

Last edited:
A Cryptogram game - simple encryption in VB6 source
Level:

Level2.gif

Written By You do not have permission to view the full content of this post. Log in or register now..

PROGRAMMING EXERCISE

Cryptogram


A cryptogram is a coded message where each letter in the cryptogram puzzle stands for a different letter of the alphabet. The coded message is often a famous quotation, proverb, or maxim. The objective of the game is to decode the message. Write a VB application that will present a cryptogram puzzle to the user and provide a way for them to enter the solution.

Below is a screenshot showing my implementation:

image001.jpg

Following is information from the help file written for the application, which will be displayed when the user clicks the "Instructions" button. It can also provide a guideline for how you might go about designing this application. Bear in mind that this applies to my implementation; you may have an entirely different vision of how this might be done. Feel free to use all, any, or none of the ideas presented here for your own implementation. As with the Calculator program, you will need to look into the KeyUp and KeyDown events as well as the KeyPreview property.

When you start the game, a new puzzle is displayed on the interface as black letters on gray tiles, with space separating each word in the puzzle. Above each gray tile is a black box in which you type the letter that the coded letter below it represents. The letters you type in the black boxes will be displayed in green.

Whatever letter you type for a coded letter will automatically be propagated throughout the puzzle. For example, if you type an "A" above an "X" tile, then the letter "A" will appear over ALL "X" tiles.

Keyboard Navigation

Whenever you type a letter in a black box, the cursor will automatically move forward to the next unused black box. To move forward to any black box, use the <right arrow> key, the <Tab> key, or click it with the mouse. To move backward to any black box, use the <left arrow> key, the <Shift-Tab> key combination or click it with the mouse. To move up or down a line, use the <up arrow> and <down arrow> keys. To go directly to the beginning of a line, use the <Home> key; to go directly to the end of a line, use the <End> key.

To delete a character in a black box, press the <Delete> key if the insertion point appears to the left of the letter, or press <Backspace> if the insertion point appears to the right of the letter.

Only letters may be entered into a black box; input of any other character is inhibited. Also, input of any letter you have already used will be inhibited. If you wish to change a coded letter to a letter you have already used, you must first delete the original occurrence of the letter.

Command Button Options

Instructions

Displays the help screen.


Check

This option checks your solution and temporarily changes the color of any incorrect letters to red (if you have not completed the puzzle, only the letters you have entered so far will be checked). Once you type a new letter or click another command button, all letters will turn back to green.

If you have completed the puzzle and your solution is correct, you will be asked if you want to play another game. If so, a new puzzle will be presented; otherwise, the program will end.


Show Solution

If your solution is incomplete or incorrect as this point, you will first be asked if you are sure you want to see the answer. If you choose Yes, the game board will temporarily freeze as the answer is revealed. At that point, you can either start a new game or exit.

If your solution is correct, you will be asked if you want to play another game. If so, a new puzzle will be presented; otherwise, the program will end.


New Puzzle

This option starts a new puzzle. If you already have a game in progress, your solution will be checked to see if it is incomplete or incorrect, and if so, you will be asked if you want to abandon the game before moving on.

If you abandon the game, the solution for the abandoned game will be shown to you, then the new game will start.


D*wnload the solution for this project You do not have permission to view the full content of this post. Log in or register now..
 

Attachments

Using standard controls to write a Fractional Math Game
Level:

Level2.gif

Written By You do not have permission to view the full content of this post. Log in or register now..

Case Study: Fraction Math

This topic presents a case study designed to bring together the concepts examined above. The vehicle for the case study is a "fraction math" application, which allows the user (such as a grade school child, or parent of that child trying to help their kid with the homework) perform one of the four basic arithmetic operations (addition, subtraction, multiplication, or division) on a pair of fractional numbers.

The program will allow the user to choose one of the four operations (add, subtract, multiply, or divide). Text boxes will be presented for the user to enter in the two terms of the problem (the problem will be limited to two "terms", or items to be operated on). Each term can be either a fraction , a mixed number, or a whole number (for example, 4). Therefore, each term will consist of three textboxes: one for the whole number portion of the problem (if any), one for the fraction numerator, and one for the fraction denominator.

After the user has entered the data for the problem and clicks the "Calculate" button, the program will display the result of the calculation. The result is expressed as a fraction, reduced to lowest terms.

The form also contains a "Clear" button, which allows a user to perform a new calculation, and an "Exit" button, which allows a user to exit the program. The form uses appropriate tabbing order and access keys.

In case you are a little rusty, here is a brief review of fraction math:

First, if there is a mixed number in the problem, convert this to a fraction by multiplying the integer portion of the number by the denominator of the fraction, then add the numerator to this result. This result becomes the new numerator, and the integer portion is discarded.


Addition
After converting any mixed numbers to fractions, you must find a common denominator for both fractions. Adjust the numerators appropriately for the new denominators by multiplying the numerator by the same number you used to get the new denominator, add the numerators together and place that result over the common denominator, then convert the result back to a mixed number.


Subtraction
(Similar to addition.) After converting any mixed numbers to fractions, you must find a common denominator for both fractions. Adjust the numerators appropriately for the new denominators by multiplying the numerator by the same number you used to get the new denominator, subtract the numerators and place the difference over the common denominator, then convert the result back to a mixed number.

Multiplication
Convert any mixed numbers to fractions. Multiply the two numerators; that product becomes the new numerator. Multiply the two denominators; that product becomes the new denominator. Convert the final result back to a mixed number.

Division
(Similar to multiplication.) Convert any mixed numbers to fractions. Switch the numerator and the denominator of the second factor. Proceed as in multiplication.


The programming solution consists of three modules – two form modules (a splash screen and the main form) and one standard module (contains one function procedure that could be used in any number of different projects).

Run-time screens are below, followed by an explanation of how the forms were built and a listing of the VB code.

When the user first runs Fraction Math, the following "splash screen" briefly appears:

The main screen then appears, where the user can select which operation they wish to perform ("Add" is the default) and key in the numbers that make up the problem:



When the user clicks the Calculate button, the solution is displayed. Note that some of the intermediate results of the solution were displayed. This was a design choice; others might have

opted to just display the final result.

Designing Fraction Math

The following section describes how the Fraction Math application was created. You may wish to build this application as a tutorial. We will start with the design of the forms.

The Splash Screen

The admittedly garish splash screen is shown below, with callouts for each control used. The callouts indicate the names and property settings for each control as well as for the form itself.

The ".WMF" files were taken from a clip-art collection called "Art Explosion"; the four files used here (for the form background, the "big 3", "big 9", and "big 5") are included with the download for this project. The ".ICO" files are all from the Graphics collection that is included with Visual Studio/Visual Basic 6. The "PEN04.ICO" icon is from the "Writing" folder, all of the other icons are from the "Misc" folder.

Note: To get the copyright symbol to display in the label at design-time, you need to use the Windows Character Map utility. On a Windows 2000 machine, you can get to it from the Start button, then Programs -> Accessories -> System Tools -> Character Map (if you are using a different OS, the path may be different).

image023.jpg

When the Character Map utility comes up, first locate the desired character (the copyright symbol in this case), the click the Select button, which will enable the Copy button. Click the Copy button.

image024.jpg


Back in your VB IDE, paste the symbol you just copied into the appropriate spot on the property sheet:

image025.jpg


The Main Form

The main form for the Fraction Math application, as it looks at design-time, is shown below:

image026.gif

With the aid of screen-shots with callouts, the names and property settings for each control on the form, as well as for the form itself, will be shown in sections.

The first section of the form is shown below. Note that for the Form, the BorderStyle property was set to 1 – Fixed Single. This means that the user will not be able to resize the form. When you set the BorderStyle to 1 – Fixed Single, VB will automatically set the MinButton and MaxButton properties to False. However, since I want to allow the user to minimize the form, I set the MinButton property back to True.

In the "Choose Operation" frame (named "fraChooseOperation"), note that there is a control array of four option buttons, named "optOperation", indexed 0 to 3. Recall that option buttons work as a group, and only one can be "on " at a given time. Recall also that an option button group works within a "container" (such as a frame or the form itself).

image027.jpg

The next portion of the form shown is the "Problem:" frame, named "fraProblem". Inside this frame, there is a control array of six textboxes, named "txtNum", indexed 0 to 5, each with their MaxLength property set to 2 (we are limiting the input of the integer, numerator, and denominator portions of each term to a maximum value of 99). Note also that each textbox here has its MultiLine property set to true. That may seem odd, because the user will not be entering mutliple lines of text in these boxes. The reason that the MultiLine property is set to true is that we want the Alignment of the data entered into the boxes to be centered – and an anomoly of VB is that the Alignment property will only be "honored" if the MultiLine property is set to True. Otherwise, the text will always be aligned left regardless of the setting of the Alignment property.

The lines for the fractions are Line controls with the default VB names "Line1" and "Line2". The multiplication symbol in the middle is an Image control named "imgOp1"; at run-time, it will display a plus, minus, times, or division symbol depending on the option button selected above.

image028.jpg

The next portion of the form shown is the "Solution:" frame, named "fraSolution". Inside this frame, there is a control array of nine labels, named "lblSol", indexed 0 to 8. These labels will display both the intermediate results of the calculation as well as the final solution. The lines for the fractions are Line controls with the default VB names "Line3", "Line4", "Line5", and "Line6". The multiplication symbol in the middle is an Image control named "imgOp2"; at run-time, it will display a plus, minus, times, or division symbol depending on the option button selected above. The "equal signs" are Image controls with default names ("Image3", "Image5", "Image6").

On the bottom right of the Solution frame, you see the four math symbols; these are Image controls named "imgPlus", "imgMinus", "imgTimes", and "imgDivide". The Visible property of these four image controls is set to ÂFalse. This set of four images is used as an "image repository" for the symbols needed by the application. At run-time, depending on what option button is selected above, the Picture property of the appropriate hidden image will be assigned to the Picture property of the imgOp1 and imgOp2 controls. (This technique was discussed in a previous topic on images.)

image029.jpg

The bottom portion of the form contains three command buttons, named "cmdCalc", "cmdClear", and "cmdExit", each with appropriate access-key enabled Captions. Note that the Default property of the Calculate button is set to True. Recall that setting a command button's Default property to True allows that button's Click event code to be executed by pressing the Enter key.

image030.jpg


Coding the Fraction Math Application

The heavily documented code for the application is presented below. This application uses a .BAS module in addition to the two forms discussed above. To add a module to your project, go to the Project menu of the IDE and choose Add Module:

image031.jpg

The Add Module dialog box appears, enabling you to add either a New or Existing module to your project. In this case, you would accept the default of New and click the Open button:

image032.jpg

An empty code module window, with the default name "Module1", is then displayed:

image033.jpg

To rename the module, press F4 while the module window is open, which will bring up its property sheet. (A module has only one property, which is the Name.) Enter the new name in the property sheet. For this application, we are using the name "modCommon".

image034.jpg

The code for modCommon is shown below. Generally, the code that is placed in a .BAS module consists of variables, constants, Subs, and Functions that are "Public", meaning the code is accessible all forms and modules within the application. In this case, the module contains a "CenterForm" routine, which is called by both forms to center themselves on the screen, as well as a "ValidKey" routine, which is used several times by the main form to filter out non-numeric keystrokes when entering the terms of the problem to be solved.


D*wnload the VB project code for the example above You do not have permission to view the full content of this post. Log in or register now..
 

Attachments

Code:
Code for modCommon:




Option Explicit

'------------------------------------------------------------------------

' Define key constant groups that can be used by any form or module in

' any project in which this module is included ...

'------------------------------------------------------------------------

Public Const gstrUPPER_ALPHA As String * 26 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

Public Const gstrLOWER_ALPHA As String * 26 = "abcdefghijklmnopqrstuvwxyz"

Public Const gstrALPHABETIC As String * 52 = gstrUPPER_ALPHA & gstrLOWER_ALPHA

Public Const gstrNUMERIC_DIGITS As String * 10 = "0123456789"

'************************************************************************

Public Sub CenterForm(pobjForm As Form)

'************************************************************************

With pobjForm

.Top = (Screen.Height - .Height) / 2

.Left = (Screen.Width - .Width) / 2

End With

End Sub

'************************************************************************

'* *

Public Function ValidKey(pintKeyValue As Integer, _

pstrSearchString As String) As Integer

'* *

'* Common function to filter out keyboard characters passed to this *

'* function from KeyPress events. *

'* *

'* Typical call: *

'* KeyAscii = ValidKey(KeyAscii, gstrNUMERIC_DIGITS) *

'* *

'************************************************************************

If pintKeyValue < 32 _

Or InStr(pstrSearchString, Chr$(pintKeyValue)) > 0 Then

'Do nothing - i.e., accept the Backspace key and any key

' in the search string passed to this function ...

Else

'cancel (do not accept) any other key ...

pintKeyValue = 0

End If

ValidKey = pintKeyValue

End Function



The code for the forms follows.



Code for frmSplash:



Option Explicit

Private Sub Form_Load()

CenterForm Me

End Sub

Private Sub tmrSplash_Timer()

tmrSplash.Enabled = False

frmMain.Show

Unload Me

End Sub




Code for frmMain:



Option Explicit

'***************************************************************************

' Module-Level (Form-Level) Variable Declarations *

'***************************************************************************

Private mblnFormActivated As Boolean

Private mintNewFocus As Integer

Private mstrErrorMsg As String

'***************************************************************************

' Form Event Procedures *

'***************************************************************************

'----------------------------------------------------------------------------

Private Sub Form_Activate()

'----------------------------------------------------------------------------

' Initialization code ...

If mblnFormActivated Then

' We only want to do this event once, so if we get here again

' (for example, the user starts this program, does something else

' in Windows, and then comes back), leave this sub ...

Exit Sub

End If

' Center the form on the screen using the programmer-defined CenterForm

' sub (located in this project's "BAS" module) ...

CenterForm Me

' Invoke the "operation" option button Click event, passing it a zero,

' indicating the "Add" operation (as if the user clicked the "Add"

' option button). This is a way of providing a default operation to the user ...

optOperation_Click 0

mblnFormActivated = True

End Sub

'***************************************************************************

' Option Button Event Procedures *

'***************************************************************************

'----------------------------------------------------------------------------

Private Sub optOperation_Click(Index As Integer)

'----------------------------------------------------------------------------

' When the user clicks an "operation" option button, put the appropriate

' symbols in the "Problem" and "Solution" frames. This is done by copying

' an "invisible" addition, subtraction, multiplication, or division image

' from its "hiding place" on the form to the image controls in the Problem

' and Solution frames ...

Select Case Index

Case 0

imgOp1.Picture = imgPlus.Picture

imgOp2.Picture = imgPlus.Picture

Case 1

imgOp1.Picture = imgMinus.Picture

imgOp2.Picture = imgMinus.Picture

Case 2

imgOp1.Picture = imgTimes.Picture

imgOp2.Picture = imgTimes.Picture

Case 3

imgOp1.Picture = imgDivide.Picture

imgOp2.Picture = imgTimes.Picture

End Select

' Set focus to the first textbox ...

txtNum(0).SetFocus

End Sub

'******************************************************************************

'* Textbox Event Procedures *

'* *

'* The three event procedures (GotFocus, KeyPress, and Change) are all *

'* shared among the 6 members of the txtNum control array (indexed 0 to 5). *

'* *

'* The GotFocus event contains the code to highlight the number in the *

'* textbox when the user moves focus to it. *

'* *

'* The KeyPress event invokes the programmer-defined ValidKey function *

'* (found the "BAS" module of this project) to ensure only digits are *

'* entered in the field. *

'* *

'* The Change event is coded to implement an "AutoTab" feature. When the *

'* user enters the maximum number of digits for each portion of the *

'* problem, they are automatically positioned on the next enterable control. *

'* *

'******************************************************************************

'----------------------------------------------------------------------------

Private Sub txtNum_GotFocus(Index As Integer)

'----------------------------------------------------------------------------

With txtNum(Index)

.SelStart = 0

.SelLength = Len(.Text)

End With

End Sub

'----------------------------------------------------------------------------

Private Sub txtNum_KeyPress(Index As Integer, KeyAscii As Integer)

'----------------------------------------------------------------------------

KeyAscii = ValidKey(KeyAscii, gstrNUMERIC_DIGITS)

End Sub

'----------------------------------------------------------------------------

Private Sub txtNum_Change(Index As Integer)

'----------------------------------------------------------------------------

With txtNum(Index)

If Len(.Text) = .MaxLength Then

If Index < 5 Then

txtNum(Index + 1).SetFocus

Else

cmdCalc.SetFocus

End If

End If

End With

End Sub

'***************************************************************************

' Command Button Event Procedures *

'***************************************************************************

'----------------------------------------------------------------------------

Private Sub cmdCalc_Click()

'

' This event contains the code to solve the fraction math problem entered

' by the user and present the solution to the user. To get here, the user would

' have entered the numbers in the "Problem" frame's textboxes and clicked the

' "Calculate" button.

'

' The comments will document a sample problem. If the user put in 5 3/8 +

' 4 2/3, this routine will do the work to come up with a solution of 10 1/24.

'

'----------------------------------------------------------------------------

Dim lngNum(0 To 5) As Long 'Array of longs to store the numbers the

'user has entered in the Problem frame textboxes

Dim lngSol(0 To 8) As Long 'Array of longs containing the numbers comprising

'the solution to the problem

Dim lngCommDenom As Long

Dim lngTemp As Long

Dim intX As Integer

Dim intReducer As Integer

' First, do some error-checking with the programmer-defined function

' DataEntryError, which will return True if there is a problem and

' False if not. If there is an error, display the corresponding message,

' set focus to the offending textbox, and get out ...

'

If DataEntryError Then

MsgBox mstrErrorMsg, _

vbExclamation, _

"Fraction Math"

txtNum(mintNewFocus).SetFocus

Exit Sub

End If

' Load the lngNum array to hold the "Problem" numbers from the txtNum textboxes.

' Using our sample problem, after the completion of this loop, the contents of

' the lngNum array will be:

' (0) (1) (2) (3) (4) (5)

' --- --- --- --- --- ---

' 5 3 8 4 2 3

For intX = 0 To 5

lngNum(intX) = Val(txtNum(intX).Text)

Next

' If either the numerator or the denominator of either the first or second

' number of the problem is zero, set them both to zero and clear those

' textboxes ...

If lngNum(1) = 0 Or lngNum(2) = 0 Then

lngNum(1) = 0

lngNum(2) = 0

txtNum(1).Text = ""

txtNum(2).Text = ""

End If

If lngNum(4) = 0 Or lngNum(5) = 0 Then

lngNum(4) = 0

lngNum(5) = 0

txtNum(4).Text = ""

txtNum(5).Text = ""

End If

' Convert mixed numbers to fractions. At this point we start to populate

' elements of the lngSol array. After the following section of code is

' complete, the contents of the lngSol array will be populated as follows:

' (0) (1) (2) (3) (4) (5) (6) (7) (8)

' --- --- --- --- --- --- --- --- ---

' 43 8 14 3

'

If lngNum(1) = 0 And lngNum(2) = 0 Then

lngSol(0) = lngNum(0)

lngSol(1) = 1

Else

lngSol(0) = (lngNum(0) * lngNum(2)) + lngNum(1)

lngSol(1) = txtNum(2).Text

End If

If lngNum(4) = 0 And lngNum(5) = 0 Then

lngSol(2) = lngNum(3)

lngSol(3) = 1

Else

lngSol(2) = (lngNum(3) * lngNum(5)) + lngNum(4)

lngSol(3) = lngNum(5)

End If

' If we are doing addition (as we are in the case of the sample problem) or

' subtraction, we must find the common denominator and adjust elements in

' the solution array (lngSol) accordingly. If we are doing division, switch

' the numerator and denominator of the second number so that it can be

' performed as multiplication. If we are doing multiplication, nothing

' special need be done at this point.

'

If optOperation(0).Value _

Or optOperation(1).Value Then

' For an addition or subtraction operation, find the common denominator

' and adjust elements in the solution array (lngSol) accordingly ...

' In our sample problem, the common denominator will be 24 (8 * 3):

lngCommDenom = lngSol(1) * lngSol(3)

' As the next four lines execute, the contents of the lngSol array

' will be populated as follows:

' (0) (1) (2) (3) (4) (5) (6) (7) (8)

' --- --- --- --- --- --- --- --- ---

lngSol(0) = lngSol(0) * lngSol(3) ' 129 8 14 3

lngSol(2) = lngSol(2) * lngSol(1) ' 129 8 112 3

lngSol(1) = lngCommDenom ' 129 24 112 3

lngSol(3) = lngCommDenom ' 129 24 112 24

ElseIf optOperation(3).Value Then

' Operation is division, so switch the numerator

' and denominator of the second number ...

lngTemp = lngSol(2)

lngSol(2) = lngSol(3)

lngSol(3) = lngTemp

End If

' The code in the Select Case structure below will populate elements (4) and

' (5) of the lngSol solution array, which will contain the numerator and

' denominator of the "raw" (non-reduced) solution ...

Select Case True

Case optOperation(0).Value

' For addition, add the numerators of the first and second numbers

' and place it over the common denominator.

' For our sample problem, after the two statements below execute,

' the contents of the lngSol array will be populated as follows:

' (0) (1) (2) (3) (4) (5) (6) (7) (8)

' --- --- --- --- --- --- --- --- ---

' 129 24 112 24 241 24

lngSol(4) = lngSol(0) + lngSol(2)

lngSol(5) = lngCommDenom

Case optOperation(1).Value

' For subtraction, subtract the numerators of the first and second

' numbers and place it over the common denominator ...

lngSol(4) = lngSol(0) - lngSol(2)

lngSol(5) = lngCommDenom

Case Else

' For a mulitplication problem, or a division probelm that was

' converted to multiplication in a previous step, multiply the

' numerators and denominators of the first and second numbers

' by each other ...

lngSol(4) = lngSol(0) * lngSol(2)

lngSol(5) = lngSol(1) * lngSol(3)

End Select

' Now, we must convert the "raw" result (numerator residing in lngSol(4),

' denominator residing in lngSol(5)) back to a mixed number. The three

' statements below will accomplish this, placing the integer portion of

' the mixed number in element (6) and the numerator and denominator of

' the mixed number in elements (7) and (8), respectively.

'

' For our sample problem, after the two statements below execute,

' the contents of the lngSol array will be populated as follows:

' (0) (1) (2) (3) (4) (5) (6) (7) (8)

' --- --- --- --- --- --- --- --- ---

' 129 24 112 24 241 24 10 1 24

'

lngSol(6) = lngSol(4) \ lngSol(5) ' Get the quotient

lngSol(7) = lngSol(4) Mod lngSol(5) ' Get the remainder

lngSol(8) = lngSol(5) ' Common denominator

' The following code serves to reduce (if necessary) the fractional

' protion of the final, mixed number result. In the case of the sample

' problem, the code will determine that reducing is not necessary in

' this particular case.

If lngSol(7) <> 0 Then

' Reduce the fractional portion of the final result by checking

' for a number that will divide evenly into both the numerator

' and the denominator. Do this by looping thru a set of values

' backwards, staring with the the value of the numerator, and working

' down toward a minimum of 2 ...

For intReducer = lngSol(7) To 2 Step -1

If (lngSol(7) Mod intReducer = 0) _

And (lngSol(8) Mod intReducer = 0) Then

' We've found a number that divides evenly into both

' the numerator and the denominator of the final answer,

' so divide and get out ...

lngSol(7) = lngSol(7) \ intReducer

lngSol(8) = lngSol(8) \ intReducer

Exit For

End If

Next

End If

' Display the solution (copy the values from the lngSol array into

' corresponding elements of the lblSol control array on the form ...

For intX = 0 To 8

lblSol(intX).Caption = lngSol(intX)

Next

' Zero-suppress if necessary ...

If lngSol(6) = 0 And lngSol(7) = 0 Then

lblSol(6).Caption = "0'"

lblSol(7).Caption = ""

lblSol(8).Caption = ""

Else

If lngSol(6) = 0 Then

lblSol(6).Caption = ""

End If

If lngSol(7) = 0 Then

lblSol(7).Caption = ""

lblSol(8).Caption = ""

End If

End If

' Set the form such that the user can't enter in a problem while

' the solution is displayed. (They can either hit the Clear button

' or Exit.)

SetFormState False, vbButtonFace

End Sub

'----------------------------------------------------------------------------

Private Sub cmdClear_Click()

'

' The Clear button prepares the form so that the user can enter a new

' problem by enabling the appropriate controls and clearing the txtNum

' and lblSol arrays.

'

'----------------------------------------------------------------------------

Dim intX As Integer

SetFormState True, vbWhite

For intX = 0 To 5

txtNum(intX).Text = ""

Next

For intX = 0 To 8

lblSol(intX).Caption = ""

Next

txtNum(0).SetFocus

End Sub

'----------------------------------------------------------------------------

Private Sub cmdExit_Click()

'----------------------------------------------------------------------------

End

End Sub

'----------------------------------------------------------------------------

Private Sub SetFormState(pblnEnabledValue As Boolean, _

plngBackColor As Long)

'

' This routine enables/disables controls on the form depending upon the

' state of the application: i.e., the user is either entering the data

' for the math problem, or is looking at the result.

'

'----------------------------------------------------------------------------

Dim intX As Integer

fraChooseOperation.Enabled = pblnEnabledValue

For intX = 0 To 3

optOperation(intX).Enabled = pblnEnabledValue

Next

fraProblem.Enabled = pblnEnabledValue

For intX = 0 To 5

txtNum(intX).BackColor = plngBackColor

Next

cmdCalc.Enabled = pblnEnabledValue

End Sub

'----------------------------------------------------------------------------

Private Function DataEntryError() As Boolean

'

' This routine is called by the "calc" procedure to make sure we have

' have good numbers before trying to solve the math problem. If any

' one of a number of data entry errors is encountered, an error message

' is set, we decide what textbox should get the focus, we set the return

' value of this function to True, and get out. The calc procedure will test

' the return value of this function and if True, will display the error

' message and set the focus appropriately.

'

'----------------------------------------------------------------------------

If txtNum(1).Text = "" And txtNum(2).Text <> "" Then

mstrErrorMsg = "The numerator of the first value is missing."

mintNewFocus = 1

DataEntryError = True

Exit Function

End If

If txtNum(2).Text = "" And txtNum(1).Text <> "" Then

mstrErrorMsg = "The denominator of the first value is missing."

mintNewFocus = 2

DataEntryError = True

Exit Function

End If

If txtNum(4).Text = "" And txtNum(5).Text <> "" Then

mstrErrorMsg = "The numerator of the second value is missing."

mintNewFocus = 4

DataEntryError = True

Exit Function

End If

If txtNum(5).Text = "" And txtNum(4).Text <> "" Then

mstrErrorMsg = "The denominator of the second value is missing."

mintNewFocus = 5

DataEntryError = True

Exit Function

End If

If optOperation(3).Value = True Then

If Val(txtNum(3).Text) = 0 And Val(txtNum(4)) = 0 Then

mstrErrorMsg = "Second value cannot be zero for division."

mintNewFocus = 3

DataEntryError = True

Exit Function

End If

End If

DataEntryError = False

End Function
 
A Simple Calculator
Level:
Level2.gif

Written By You do not have permission to view the full content of this post. Log in or register now..

PROGRAMMING EXERCISE

Calculator


Write a VB program that simulates the basic functions and behavior of the Windows calculator program. To study its interface, you can run it by clicking the Start button on the taskbar, then go to Programs, then Accessories. You should at least support the basic functions of addition, subtraction, and multiplication, as well as changing the sign of the number (the +/- key). It's up to you if you want to support the sqrt, %, and 1/x functions. Don't bother with the "M" keys on the left (MC, MR, MS, M+) or the scientific features.


image001.jpg



You do not have permission to view the full content of this post. Log in or register now..
 

Attachments

Full hangman game in VB6
Level:
Level2.gif

Written By You do not have permission to view the full content of this post. Log in or register now..

PROGRAMMING EXERCISE tutorial

Hangman

Write a VB program that implements the classic game of Hangman.

Notes

  • Start the program off with a "splash screen" that displays some sort of graphic; experiment with different fonts and colors to make your form visually attractive. The splash screen should display for a few seconds before showing the main form, which is the Hangman game board.
·The program will require three data files:

(1) The main file, called HMPuzz.dat, which contains the puzzles that the user must solve. This is a comma-delimited file containing two fields:

(a) The puzzle, which is a string containing up to 20 characters. The puzzles will contain only letters and blank spaces (no special characters such as hyphens, commas, or quotes).

(b) A "clue code", which is an integer between 1 and 5 representing a clue that can be displayed to the user on the gameboard.

A sample set of records is shown below:

"BORN TO BE WILD",4

"MARY TYLER MOORE",1

"WEST ******IA",2

"LOVE CONNECTION",4

"MAD ABOUT YOU",4

"THOMAS JEFFERSON",1

"PAPUA NEW GUINEA",2

(2) A "lookup table", called HMClues.dat, which contains two fields: (a) the "clue code" (an integer between 1 and 5) and (b) the clue description. This file contains the following data:

1,"PERSON OR GROUP"

2,"PLACE"

3,"THING"

4,"TITLE"

5,"FICTIONAL CHARACTER"

(3) A file called LastPuzz.dat, which simply contains one record with one field: a number indicating the last puzzle that was played, which will serve as a starting point for a new run of the program. This enables you to vary which puzzles are used from session to session.

At program startup, load the data from the first two files into arrays and store the "last puzzle" number into a variable. When the program first begins, and whenever the user clicks the "New Game" button, increment the "last puzzle" value and select the puzzle from the array of puzzles loaded from the first file using the "last puzzle" value as an index into the array.

·Visually present the "covered up" puzzle to the user, along with the hangman's gallows (which can be simply drawn with line controls), and a pool of the 26 letters of the alphabet (these can be labels or command buttons). Also display a clue description associated with the puzzle.

·When the user clicks a letter, if any occurrences of that letter are present in the puzzle, reveal them all to the user; if that letter is not present in the puzzle, then draw another body part on the "hanged man". In any event, disable the chosen letter.

·The hanged man has six body parts: a head, a torso, two arms and two legs. All parts can be created with the line control, except the head, which can be created with the circle option of the shape control. If the hanged man is drawn before all the letters of the puzzle are revealed, the player loses; if the all the letters of the puzzle are revealed before the hanged man is drawn, the player wins.

·Provide a "solve the puzzle" option, which enables the player to guess the answer early in the game. If the player guesses correct, the player wins; otherwise, the player loses.

·The program should provide options to play a new game and to quit.

  • The program should keep track of the number of games played and the number of games won, and display these counts on the form.

  • Upon exiting the program, update the LastPuzz.dat file with the current value of the "last puzzle" variable.
Following are some screen shots of my version of this program, to give you some ideas. Feel free to vary the design any way you want, as long as the project requirements are met.

Splash Screen

image001.jpg

When game first begins

image002.jpg

While game is in progress

image003.jpg

When player wins

image004.jpg

When player loses

image005.jpg


The "Solve Puzzle" Option

image006.jpg

Note: If you implement the "Solve Puzzle" option with an InputBox as I did, make sure you parse the user's response so that an entry that contains lowercase letters and/or extra spaces will not count against the user when you compare the user's response to the answer.

D*wnload the solution for this project You do not have permission to view the full content of this post. Log in or register now..
 

Attachments

Full Game - Concentration
Level:

Level2.gif

Written By You do not have permission to view the full content of this post. Log in or register now..

PROGRAMMING EXERCISE

Concentration


Write a VB application that implements a game of Concentration. In a game of Concentration, the player is presented with a board containing some number (24 in my implementation) of "covered" images. The player clicks on the covered pictures in sets of two to reveal the randomly assigned pictures beneath. If the two pictures match, they remain displayed; if not, they are flipped back over. The goal of the game is to reveal all matches (12 in my implementation) in as short a time as possible.


The program must maintain (in a file) the best time and display it on the screen as the "time to beat". Whenever the best score is beat, the new time becomes the best score and should be written out to the file.


My implementation also tracks the number of turns it took to reveal all matches (the fewer the better). A perfect score would be 12 in my implementation (but a score of 12 turns would be nearly impossible, as the player would have make 12 correct guesses in a row).


My implementation of the game is shown below. I am using playing cards as the pictures.


When the game first starts, all cards are shown face down. The "Best Scores" area shows the previous best time and number of turns, read in from a file. (Note: The "Reset" button effectively clears the best scores – it sets the best time to 99:99 and the number of turns to 9999.) The clock for "This Game" has started ticking.


image001.jpg



In the middle of game play, the pairs that have been matched remain face up, those yet to be matched remain face down. The clock is still ticking (one minute, 20 seconds – looks like we're not going beat the best time of one minute, 14 seconds!).


image002.jpg


At the end of the game, all cards will be face up and the clock will stop ticking.


image003.jpg


D*wnload the solution for this project You do not have permission to view the full content of this post. Log in or register now..
 

Attachments

Search mo na lang po sa Google "MS Visual Basic 6 Portable" :)


dami ko na kasi na DL sir kaso epic failed la wenta... luma a kasi 6.0 sir . . meron ka po b? hingiin ko nlng po need kasi ng sister ko.. nagsisimula pa po kasi sya eh . .
 
Status
Not open for further replies.

Similar threads

Back
Top