I am trying to create a "Snap!" game. I'm trying to check if the previous text of a label corresponds to the current text of a label, e.g. if the previous text of a label was bee
, and the current display is bee
it will display, 'Snap!'.
Here is my code so far:
Private Sub btnOne_Click(sender As Object, e As EventArgs) Handles btnOne.Click
Dim imageResourceNames = {"Owl", "Bee", "Bird", "Frog", "Duck"}
Dim randImage As New Random
Dim index = randImage.Next(imageResourceNames.Length)
Dim imageResourceName = imageResourceNames(index)
Dim img = DirectCast(My.Resources.ResourceManager.GetObject(imageResourceName), Image)
picOne.Image = img
picOne.Visible = True
lblDisplay.Text = imageResourceNames(Index)
btnOne.Enabled = False
If lblDisplay.Text = imageResourceName Then
Console.WriteLine("snap!")
lblDisplay.Text = "Snap!"
End If
End Sub
While I am not getting errors, it seems that the label is always displaying 'Snap!'
. If anyone knows how to fix this I would really appreciate it!
Thanks,
CodePudding user response:
You set both imageResourceName
& lblDisplay.Text
to the same value, imageResourceNames(index)
. So when you then your if lblDisplay.Text = imageResourceName
is always going to be executed.
CodePudding user response:
A Label
is not a data store so stop treating it like one. It's just to display text to the user. If you want to know what the previous value was then store it in a variable.
Private previousImageResourceName As String
Private currentImageResourceName As String
Private randImage As New Random
and:
Dim imageResourceNames = {"Owl", "Bee", "Bird", "Frog", "Duck"}
Dim index = randImage.Next(imageResourceNames.Length)
previousImageResourceName = currentImageResourceName
currentImageResourceName = imageResourceNames(index)
Dim img = DirectCast(My.Resources.ResourceManager.GetObject(imageResourceName), Image)
picOne.Image = img
picOne.Visible = True
lblDisplay.Text = currentImageResourceName
btnOne.Enabled = False
If currentImageResourceName = previousImageResourceName Then
Console.WriteLine("snap!")
lblDisplay.Text = "Snap!"
End If