Click here to Skip to main content
15,887,434 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
So recently i did a snake game, how can i accumulate my points on a label and show them, for exemple, everytime i eat something it gives me 10 points and show it on a label or textbox.

This is the code of her eating, i was thinking on putting one label there that adds 10 points every time she does it, but how?


Private Sub comer_comida()
       If snake(0).Bounds.IntersectsWith(mouse.Bounds) Then
           compi_cobra()
           mouse.Top = r.Next(pb1.Top, pb1.Bottom - 10)
           mouse.Left = r.Next(pb1.Left, pb1.Right - 10)
           Label2.Text = Label2.Text + 10


       End If
Posted

You are trying to add an integer to a string (.Text) which will result in the runtime exception
Quote:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

Instead do something like this ...
First you need to get the current text of the label as an actual number - I've used a Long hoping that you get big scores :-)
I've used the TryParse method in case the label doesn't have any score in it yet
Once I get the number that is in there I add 10 to it
Then I assign the label text to that value converted to a string.
VB.NET
Dim i As Long
If Not Long.TryParse(Label2.Text, i) Then
        i = 0
End If

i += 10
Label2.Text = i.ToString()
 
Share this answer
 
v2
"Accumulate points" suggests you need to use some collection, in particular System.Collections.Generic.List:
https://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.110%29.aspx[^].

See also: https://msdn.microsoft.com/en-us/library/system.collections.generic%28v=vs.110%29.aspx[^].

But if your only purpose is to collect data in some string, to show it on screen, as a label or anything else, the main principle is: don't use multiple string concatenation. Strings are immutable, so this is bad, inefficient. Instead, use the mutable variant of a string, System.Text.StringBuilder:
https://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900