' Ch. 9 Demo 3
' Mr. Minich
' Purpose - reading from and writing to files to track the high score of a game
Option Explicit
Dim mintScore As Integer ' user's score
Private Sub Form_Load()
' opens files and displays first question
Dim strFirstQuestion As String ' first question
Open "Z:\Basic\Ch 9\Ch9Demo3\ch9demo3data.txt" For Input As #1
Input #1, strFirstQuestion ' reading & displaying first question
lblQuestion.Caption = strFirstQuestion
End Sub
Private Sub cmdNext_Click()
Dim strQuestion As String ' next question
Dim strAnswer As String ' answer to next question
Dim intPreviousHighScore As Integer ' previous high score
If (cmdNext.Caption = "&Enter") Then
Input #1, strAnswer
If (strAnswer = txtUserAnswer.Text) Then
mintScore = mintScore + 1 ' adding point if answered correctly
End If
If (Not(EOF(1))) Then ' displaying next question if not past end of file
Input #1, strQuestion
lblQuestion.Caption = strQuestion
txtUserAnswer.SetFocus
Else ' close file otherwise
lblQuestion.Caption = "You scored " & mintScore & " points."
cmdNext.Caption = "E&xit"
cmdNext.SetFocus
End If
txtUserAnswer.Text = ""
Else ' preparing to exit game
Open "Z:\Basic\Ch 9\Ch9Demo3\ch9demo3scores.txt" For Input As #2
Input #2, intPreviousHighScore
Close #2
Open "Z:\Basic\Ch 9\Ch9Demo3\ch9demo3scores.txt" For Output As #2
If (mintScore > intPreviousHighScore) Then
Print #2, mintScore ' writing new high score to file
End If
Close ' closing all files
Unload Me
End If
End Sub
' 1.Notice how one sequential access file (ch9demo3data.txt) is opened for Input
' in the program above and the other file (ch9demo3scores.txt) is opened first
' for Input and then it is closed and opened again for Output.
' 2.Realize that the questions & answers in ch9demo3data.txt must be originally typed
' with a question on one line and then the answer to that question on the next line.
' Example of ch9demo3data.txt:
' What color is the sky?
' blue
' What is the nickname of the Wyomissing Area High School?
' Spartans
' etc.
' 3.Notice the interesting use of the Caption property of cmdNext. When all of the questions
' have been read, the Caption property for cmdNext is changed. The need to have a separate
' cmdExit command button is eliminated due to the use of the If/Else statement in the
' cmdNext Click event procedure. VB programmers do this kind of thing once in a while!
' 4.Notice the use of the EOF() function to check if the end of file #1 has been reached yet.
' This avoids the infamous run-time error "Input past end of file"