I dont know why 'Doub' isn't updating - vb.net

I'm working on a program to count every time the dice
roll a double but my variable I'm trying to add to the listbox isn't updating and I don't know why.
Here's the code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'declare vars
Dim teal, red, doub As Integer
Dim rand As New Random
teal = rand.Next(6)
red = rand.Next(6)
#Region "Clear"
Irrelevant stuff
#End Region
'green dice
irrelevant if statement
'red dice
irrelevant if statement
'doubles
**If red = teal Then
doub = doub + 1
output.Items.Clear()
output.Items.Add("Doubles: " & doub)
End If**
End Sub
End Class
In the if statements about the dice part
there is nothing to influence the 'doub' variable
so thats why i put "irrelevant if statement"
also because stackoverflow said the post was mostly code

Your doub variable is declared inside the button click handler so its scope is only within that procedure. That means it's getting released after every click. You need to have it outside your button click handler:
Dim doub As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Declare variables
Dim teal As Integer
Dim red As Integer
Dim rand As New Random
teal = rand.Next(6)
red = rand.Next(6)
Debug.Print(teal & "-" & red)
' Doubles
If red = teal Then
doub += 1
Debug.Print("Doubles: " & doub)
End If
End Sub
You can learn about variable scope in this link: How to: Control the Scope of a Variable
Output (got a double on first try!):
4-4
Doubles: 1
1-5
0-5
5-0
2-2
Doubles: 2
3-0
This quick test shows another problem in your code: you can roll 0, 1, 2, 3, 4, 5 and 6. You should use rand.Next(1,6) instead, assuming you are trying to simulate a dice throw.

Related

Moving picturebox according to the score of the dice

I am new to visual basic and am needing some help. I am creating a board game where you have to roll a dice and depending on the side it lands on, the picture box moves accordingly. I have labels put together in a square shape making up a look alike grid that is 5 rows and 10 columns. So far, I have the part for when the player clicks the button "Rouler" they get a randomized side of the dice. I would like for each time the dice is rolled it moves along the grid accordingly to the number the dice has picked.
Public Class frm1
Dim Rand As New Random
Dim Dé(5) As Image
Private Sub btnRouler_Click(sender As Object, e As EventArgs) Handles btnRouler.Click
Dim n As Integer
n = Rand.Next(4)
PictureBoxDé.Image = Dé(n)
End Sub
Private Sub frm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dé(0) = My.Resources._11
Dé(1) = My.Resources._2
Dé(2) = My.Resources._3
Dé(3) = My.Resources._4
Dé(4) = My.Resources._5
Dé(5) = My.Resources._6
I think you are saying you have 50 labels arranged in 10 columns and 5 rows. The De array contains the dice images.
This is one approach. Make a small class called Player. When you add a second player you will see the value of this.
You will need an array of the labels, indexes 0-49.
When you roll the die, you choose the appropriate image form the De array. Next, you clear the Player1.Token from the CurrentPosition Label. You also increase the players current position by n + 1. If he rolls a 1 (De(0)) you add one to n to move 1 space. Finally, you add a the Player1.Token to the label at the new position.
Public Class Player
Public Property Token As Image
Public Property CurrentPosition As Integer
Public Sub New(Pic As Image)
Token = Pic
CurrentPosition = 0
End Sub
End Class
Private Player1 As Player
Private Dé(5) As Image
Private LabelArray(49) As Label
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LabelArray = {Label1, Label2, Label3, Label4} 'etc.
Player1 = New Player(Image.FromFile("Dog.png"))
Dé(0) = My.Resources._11
Dé(1) = My.Resources._2
Dé(2) = My.Resources._3
Dé(3) = My.Resources._4
Dé(4) = My.Resources._5
Dé(5) = My.Resources._6
End Sub
Private Sub btnRouler_Click(sender As Object, e As EventArgs) Handles btnRouler.Click
Dim n As Integer
n = Rand.Next(6) 'Non negative integer, one less than the parameter - in this case 0 to 5
PictureBoxDé.Image = Dé(n)
Player1.CurrentPosition += n + 1
LabelArray(Player1.CurrentPosition).Image = Player1.Token
End Sub

Calculate cost of several items with tax and a discount

Can anyone help with this school task I have
The task is to ask the user for items and the cost of the items until they chose to stop. Then combine all the costs and take 20% VAT and 10% off from 2 randomly selected items.
Here is the code I have so far (I have 2 buttons and a listbox)
Public Class Form1
Dim CurrentA As Integer
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim Items(CurrentA) As String
Dim Coins(CurrentA) As Single
Dim Stay As String
CurrentA = 0
Do Until CurrentA = 20
Items(CurrentA) = InputBox("Please Enter The Item")
Coins(CurrentA) = InputBox("Please Enter The Cost Of The Item")
Stay = InputBox("Type Yes If More Items or Type No if no More")
Stay = Stay.ToLower
If Stay = "yes" Then
End If
If Stay = "no" Then
Exit Do
End If
ListBox1.Items.Add(Items(CurrentA) & " " & Coins(CurrentA))
CurrentA += 1
Loop
End Sub
End Class
First, a few comments on the code you presented.
Dim CurrentA As Integer
'An Integers default value is zero, I don't see why this is a class level variable
'always declare variables with as narrow a scope as possible
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Items(CurrentA) As String 'Declares an Array of Type String with an Upper Bound of 0
'Upper Bound is the highest index in the array
'Arrays start with index 0
'So your array will have 1 element at index 0
Dim Coins(CurrentA) As Single
Dim Stay As String
CurrentA = 0 'unnecessary because the default of CurrentA is already 0, but OK for clarity because it could have been changed elsewhere
'This is behaving like a console application with the code repeating in a loop.
'In Windows Forms it would be more likely to do this in a button click event (btnAddItem)
Do Until CurrentA = 20
'On the first iteration CurrentA = 0
'On the second iteration CurrentA = 1 - this exceeds the size of your array
'and will cause an index out of range error
Items(CurrentA) = InputBox("Please Enter The Item")
'With Option Strict on you must change the input to a Single
Coins(CurrentA) = CSng(InputBox("Please Enter The Cost Of The Item"))
Stay = InputBox("Type Yes If More Items or Type No if no More")
Stay = Stay.ToLower 'Good! The user might no follow directions exactly
If Stay = "yes" Then
'This is kind of silly because it does nothing
End If
'Lets say I say no on the first iteration
'This avoids the index out of range error but
'nothing is added to the list because you Exit the loop
'before adding the item to the ListBox
If Stay = "no" Then
Exit Do
End If
ListBox2.Items.Add(Items(CurrentA) & " " & Coins(CurrentA))
CurrentA += 1
Loop
End Sub
We could use arrays but not knowing how many items will be added means either making the array bigger than needed or using Redim Preserve on every addition. A much better choice is a List(Of T). They work a bit like arrays but we can just add items without the ReDim stuff.
Private lstCost As New List(Of Single)
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'Pretend this button is called btnAdd, and you have 2 test boxes
lstCost.Add(CSng(TextBox2.Text))
'The $ introduces an interpolated string. It is a step up form String.Format
ListBox2.Items.Add($"{TextBox1.Text} - {CSng(TextBox2.Text):C}") 'The C stands for currency
TextBox1.Clear()
TextBox2.Clear()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Pretend this button is called btnTotal
'Dim total As Single = (From cost In lstCost
' Select cost).Sum
Dim total As Single = lstCost.Sum
Label1.Text = total.ToString("C") 'C for Currency
End Sub

Alternative Process

I have 2 buttons and a DataGridView with 2 Columns (0 & 1).
The 1st button transfers a randomized cell from the Column(1) to a TextBox. Then, it stores that Cell in variable (a), plus the cell that opposites it in variable (b).
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim rnd As New Random
Dim x As Integer = rnd.Next(0, Form1.DataGridView1.Rows.Count)
Dim y As Integer = 1
Dim a As String = Form1.DataGridView1.Rows(x).Cells(y).Value
Dim b As String = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
The 2nd button, however, is supposed to compare if another TextBox's text has the same string variable (b) has as Strings. Now, if so, then it has to display a certain message and so on...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox4.Text = b Then '<<< ISSUE HERE!
MsgBox("Correct! ^_^")
ElseIf TextBox4.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub
The problem is that the variable (b) is surely not shared across the two "private" subs. And so, there is NOTHING to compare to in the 2nd button's sub! I presume that the solution here is to split the "randomization process" into a separate function, then execute it directly when the 1st button gets activated. Furthermore, that function's variables have to be SHARED somehow, and I certainly don't know how!
Thanks for Mr. Olivier, the code has been improved significantly! Yet, I still encounter a "wrong" comparison issue, somehow!
Dim RND As New Random
Dim x As Integer
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
x = RND.Next(0, Form1.DataGridView1.Rows.Count)
tbxRoll.Text = GetCell(x, 1)
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If tbxSubmit.Text = GetCell(x, 0) Then
MsgBox("Correct! ^_^")
ElseIf tbxSubmit.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub</code>
Well, unbelievably, I read a guide about "comparison operations" in VB.net and tried out the first yet the most primal method to compare equality - which was to use .Equals() command - and worked like a charm! Thank God, everything works just fine now. ^_^
If tbxSubmit.Text.Equals(GetCell(x, 0)) Then
Alright now... This is going to sound weird! But, following Mr. Olivier's advise to investigate "debug" the code, I rapped the string I'm trying to compare with brackets and realized that it's been outputted after a break-line space! So, I used the following function to remove the "white-space" from both of the comparison strings! And it bloody worked! This time for sure, though. ^_^
Function RemoveWhitespace(fullString As String) As String
Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function
If RemoveWhitespace(tbxSubmit.Text) = RemoveWhitespace(GetCell(x, 0)) Then
Turn the local variables into class fields.
Dim rnd As New Random
Dim x As Integer
Dim y As Integer
Dim a As String
Dim b As String
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
x = rnd.Next(0, Form1.DataGridView1.Rows.Count)
y = 1
a = Form1.DataGridView1.Rows(x).Cells(y).Value
b = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
These fields can now be accessed from every Sub, Function and Property.
Of course Button3_Click must be called before Button2_Click because the fields are initialized in the first method. If this is not the case then you should consider another approach.
Create a function for the Cell access
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) _
As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
And then compare
If TextBox4.Text = GetCell(x, y - 1) Then
...
And don't store the values in a and b anymore. If y is always 1 then use the numbers directly.
If TextBox4.Text = GetCell(x, 0) Then
...
One more thing: give speaking names to your buttons in the properties grid before creating the Click event handlers (like e.g. btnRandomize). Then you will get speaking names for those routines as well (e.g. btnRandomize_Click).
See:
- VB.NET Class Examples
- Visual Basic .NET/Classes: Fields

Getting upperbound and lowerbound from a textbox

I'm trying to figure out the code for a project but I don't completely understand it. The objective is to write a program that generates a set of 10 random numbers and stores it in an array (the 10 numbers display in the textbox correctly). It should have a button that will compute the minimum, maximum and average of the array. I cant seem to get the max and min values of it from a textbox. I know people don't post the answers and I'm not looking for that but if someone could tell my why what I'm doing for the max/min is wrong or point my in the right direction I would appreciate it. Thank you!
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim randomArray As New Random()
Dim randomNumber As Integer
For i = 1 To 10
randomNumber = randomArray.Next(1, 101)
displaynumbersTextBox1.AppendText(randomNumber & " ")
displaynumbersTextBox1.Text = Convert.ToString(randomNumber)
Next
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim randomArray As New Random()
Dim randomNumber As Integer
For i = 1 To 10
randomNumber = randomArray.Next(1, 101)
displaynumbersTextBox1.AppendText(randomNumber & " ")
Next
Dim min As Integer
min = displaynumbersTextBox1.Text.GetLowerBound()
displayminTextBox2.Text = min
End Sub
For starters, I see this code in Button1:
TextBox1.AppendText(randomNumber & " ")
TextBox1.Text = Convert.ToString(randomNumber)
The 2nd line negates the first. Just remove it. Instead, clear the textbox at the beginning of the button click handler.
Next, in button 2 the code goes through and re-creates a new set of random numbers, instead of using the set created from the first button. What is more, at no point are the numbers ever stored in an array. You need an array declared outside of either button, in in the code for Button1 set the elements of the array, so you can use those numbers again in Button2 more easily.

How to make a live score counter for Lucky 7 (vb game)

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?
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.