Visual Basic Tutorial – Create a Binary Calculation Game
- Subject: Visual Basic Tutorials
- Learning Time: 4 hours
Public Class Form1
Dim total As Integer 'save the total for each binary calculated
Dim randomNum As Integer 'generates a random number
Dim attempt As Integer 'will be keeping log of the tries in the game
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'reset the binary and denary labels
binary.Text = "Binary -"
denary.Text = "Denary -"
'this loop will go through the combo boxes and check which is active
'it will check which is active by search for the 1 in binary that means active.
For Each ctl As Control In Me.Controls
If TypeOf ctl Is ComboBox Then
If ctl.Text = "1" Then
total += Convert.ToInt16(ctl.Tag)
End If
binary.Text += ctl.Text 'show the binary numbers on that binary label
End If
Next
'end of the loop
denary.Text += total.ToString() 'show the total in numbers from binary
'if statement below will check whether the player has accurately solved the binary
'if so it will show the correct message box
'else it will add 1 to the attempt variable
If total = randomNum Then
MessageBox.Show("Correct")
randomNum = Rnd() * 255
question.Text = "Convert " + randomNum.ToString() + " To Binary"
attempt = 0
tries.Text = attempt.ToString()
resetCombo()
Else
attempt += 1
tries.Text = attempt.ToString()
End If
Button1.Enabled = False
Button2.Enabled = True
End Sub
Private Sub resetCombo()
'all the codes will go here
'for loop to check the combo boxes in form
'once they are found we reset all their values to 0
For Each ctl As Control In Me.Controls
If TypeOf ctl Is ComboBox Then
ctl.Text = "0"
End If
Next
'reset all of the labels in the game too
total = 0
denary.Text = "Denary- "
binary.Text = "Binary- "
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
resetCombo() 'this is how we call the reset function
Button1.Enabled = True 'enable the check button
Button2.Enabled = False 'disable the reset button
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
resetCombo() 'run the reset function to set all the combo boxes ro 0
randomNum = Rnd() * 255 'generate a random number between 0 and 255
question.Text = "Convert " + randomNum.ToString() + " To Binary" 'show the question on screen
End Sub
End Class
Pages: 1 2