Reputation: 41
I have made a simple game, lucky 7 on visual basic using vb code. The score counter doesn't work properly, for example if I win the game once (get a 7 in one of the 3 slots), I get 10 points and the score label changes to 10. If I continue pressing the spin button and win again, the score label still stays on the number 10, and does not change to 20.
Here is the code for the spin button I wrote:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim rand = New Random
Dim slots = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim score = 0
For i = 0 To 2
slots(i) = rand.Next(10)
Next
Label1.Text = (slots(0).ToString)
Label2.Text = (slots(1).ToString)
Label3.Text = (slots(2).ToString)
If slots(0) = 7 Or slots(1) = 7 Or slots(2) = 7 Then
score = score + 10
Label4.Text = (score.ToString)
PictureBox1.Visible = True
Else
PictureBox1.Visible = False
End If
End Sub
Do I need to add a while loop or something similar to make the score change as many times as I win the game?
Upvotes: 1
Views: 4374
Reputation: 1398
You need to move your variable declaration at class level.
At the moment, you create it when you click on your button. Therefore, each time you click, you delete the score
variable and create it again.
Move the
Dim score = 0
line as follows:
'Assuming your Form is called Form1
Public Class Form1 Inherits Form
Dim score = 0
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Your current code
End Sub
End Class
And your problem is solved.
You should probably read some documentation about scopes.
An extract about your little mistake :
If you declare a variable within a procedure, but outside of any If statement, the scope is until the End Sub or End Function. The lifetime of the variable is until the procedures ends.
Upvotes: 5