Visual Basic Windows Form - Help Loading picture corresponding to numerical value - vb.net

Hello i am trying to make a texas hold'em style game and im at the point where i filled an array with numbers 1-52 randomly assorted. I first pull the value from the first index of the array and have the corresponding card picture be set to a picturebox value. I have saved the 52 card .png files in my resources as well. These pictures are also saved with their names as 1.png, 2.png, 3.png.... etc depending the suit and value.
I am sorting the values as 1-13 spades (2-ace), 14-26 hearts, 27-39 diamonds, 40-52 clubs.
I also just saw i should probably use a global counter to keep track of the deck position.
Public Class Form1
Dim Deal As MsgBoxResult
Dim CardDeck As New Random
Dim Counter As Integer = 1
Dim CardCount(52) As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnStart.Click
Deal = MessageBox.Show("Would you like to start a Game?", "Texas Holde'em", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
ShuffleDeck()
CalculateFirst3Cards()
End Sub
Private Sub ShuffleDeck()
If Deal = MsgBoxResult.Yes Then
For num As Integer = 1 To CardCount.Length - 1
Dim DeckValue As Integer = CardDeck.Next(1, 52)
CardCount(Counter) = DeckValue
Counter += 1
Next
End If
End Sub
Private Sub CalculateFirst3Cards()
Dim counter As Integer = 1
For num As Integer = 1 To 3
Dim hold As Integer = CardCount(counter)
Dim hold1 As String = Convert.ToString(hold)
River1.Image = My.Resources.
counter += 1
Next
End Sub
End Class

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

VB.NET Random unique generator

I'l trying to generate a unique random number generator with the snippet of code from below, but it's not working. The IF section is suppose to test if it's the first random number generated, if it is, it's suppose to add the first random number to the ArrayList, if it's not the first random number, it's supposed to check if the random number is already in the ArrayList and if it's in the ArrayList it's suppose to MsgBox and generate a new unique random number that is not already in the ArrayList and add it to the ArrayList, but it's not doing any of those. Any help would be greatly appreciated.
Public Class Form1
Dim r As New Random
Dim dLowestVal As Integer = 1
Dim dHighestVal As Integer = 26
Dim dItemAmount As Integer = 1
Dim RollCheck As New HashSet(Of Integer)
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnRollDice_Click(sender As Object, e As EventArgs) Handles btnRollDice.Click
lblRandomNo.Text = r.Next(dLowestVal, dHighestVal)
lblItemAmount.Text = dItemAmount
If dItemAmount = 1 Then
RollCheck.Add(Val(lblRandomNo.Text))
ElseIf (RollCheck.Contains(Val(lblRandomNo.Text))) Then
MsgBox("Already Exists")
lblRandomNo.Text = r.Next(dLowestVal, dHighestVal)
RollCheck.Add(Val(lblRandomNo.Text))
End If
dItemAmount = dItemAmount + 1
Thanks in advance.
You could replace your whole method with this simple one
' This is globally declared at the top of your form
Dim values As New List(Of Integer)
' This is called when you construct your form
' It will store consecutive integers from 1 to 25 (25 elements)
values = Enumerable.Range(1, 25).ToList()
This is the method that extract an integer from your values that is not already used
Private Sub Roll()
' Get an index in the values list
Dim v = r.Next(0, values.Count)
' insert the value at that index to your RollCheck HashSet
RollCheck.Add(values(v))
' Remove the found value from the values list, so the next call
' cannot retrieve it again.
values.Remove(values(v))
End Sub
And you can call it from the previous event handler in this way
Private Sub btnRollDice_Click(sender As Object, e As EventArgs) Handles btnRollDice.Click
if values.Count = 0 Then
MessageBox("No more roll available")
else
Roll()
End Sub
End Sub
The point of the HashSet is that since it doesn't allow duplicates you can just check the return value of Add() to determine whether the number was successfully inserted or if it already exists in the list.
If you want to keep trying until it succeeds all you have to do is wrap it in a loop:
If dHighestVal - dLowestVal >= RollCheck.Count Then
'If the above check passes all unique values are MOST LIKELY already in the list. Exit to avoid infinite loop.
MessageBox.Show("List is full!")
Return 'Do not continue.
End If
Dim Num As Integer = r.Next(dLowestVal, dHighestVal)
'Iterate until a unique number was generated.
While Not RollCheck.Add(Num)
MessageBox.Show("Already exists!")
Num = r.Next(dLowestVal, dHighestVal)
End While
lblRandomNo.Text = Num
An alternative way of writing the loop is: While RollCheck.Add(Num) = False.

Need to know why code is repeating itself

Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim EvenNum, EvenNumCount, EvenNumAverage, Number, Result As Integer
Calculations(EvenNum, EvenNumCount)
GetInput(Number)
Output(Result)
End Sub
Sub GetInput(ByRef Number)
Number = txtInput.Text
End Sub
Sub Calculations(ByRef EvenNum, ByRef EvenNumCount)
Dim ListedNumbers, lstOutputSize As Integer
GetInput(lstOutputSize)
For i As Integer = 0 To lstOutputSize - 1
ListedNumbers = InputBox("Enter Numbers", "Input")
lstOutput.Items.Add(ListedNumbers)
Next
For i As Integer = 0 To lstOutput.Items.Count - 1
If (CInt(lstOutput.Items(i)) Mod 2 = 0) Then
EvenNum += lstOutput.Items(i)
EvenNumCount += 1
End If
Next
End Sub
Function Average(ByRef EvenNumAverage As Integer) As Integer
Dim EvenNum, EvenNumCount As Integer
Calculations(EvenNum, EvenNumCount)
EvenNumAverage = EvenNum / EvenNumCount
Return EvenNumAverage
End Function
Sub Output(ByRef EvenNumAverage)
lstOutput.Items.Add(Average(EvenNumAverage))
End Sub
The program is supposed to get input from a textbox for a desired number of numbers to be entered into a listbox from inputboxes.
It is then supposed to get the average of only the even numbers and then display that average into the listbox.
In it's current state the program will do what it is intended to do, it just repeats the calculation code. This only happens when I add the Output call statement under the button procedure.
You're calling Calculations twice
From btnCalculate_Click
From Average which is called by Output

How do I detect collision with spawned objects?

Public Class Form1
Dim i As Integer 'integer for spawning
Dim maxball As Integer = 50 'max ball able to be created
Dim RateX(maxball) As Integer 'rate of movement
Dim RateY(maxball) As Integer 'rate of movement
Dim ball(maxball) As PictureBox 'spawned ball is a picture box
Dim rnd As New Random 'random number generator
Dim rndLoc As Integer 'random locatino generator
Dim Loc As Point 'location is a point on the screen
Dim create As Integer 'integer to create new balls
Dim score As Integer = 0 'score is 0 but can increase
'move the ball
Private Sub moveball()
'For Each ball(ec) In ball
For i As Integer = 0 To create - 1
If ball(i).Left <= pbArena.Left Then 'bounce off left side
RateX(i) *= -1
End If
If ball(i).Right >= pbArena.Right Then 'bounce off right side
RateX(i) *= -1
End If
If ball(i).Top <= pbArena.Top Then 'bounce off top
RateY(i) *= -1
End If
If ball(i).Bottom >= pbArena.Bottom Then 'bounce off bottom
RateY(i) *= -1
End If
'====================================================================================================================================================
ball(i).Left += RateX(i) 'moves the ball horizontally
ball(i).Top += RateY(i) 'moves the ball vertically
'====================================================================================================================================================
Next
End Sub
'create the ball
Private Sub createball()
If create <= 50 Then '50 is max amount to
create += 1 'add 1 to create
ball(i) = New PictureBox 'ball is a picture box
ball(i).Size = New Size(45, 45) 'set size
ball(i).BackColor = Color.Red 'set color
'====================================================================================================================================================
ball(i).Top = rnd.Next(pbArena.Height - ball(i).Height) 'sets random y
ball(i).Left = rnd.Next(pbArena.Width - ball(i).Width) 'sets random x
'====================================================================================================================================================
RateX(i) = rnd.Next(-4, 4) 'random X direction/speed
RateY(i) = rnd.Next(-4, 4) 'random Y direction/speed
'====================================================================================================================================================
Me.Controls.Add(ball(i)) 'actually add teh ball
ball(i).BringToFront() 'bring to front so arena isn't in front
i += 1
End If
End Sub
'commands for when you touch black box
Private Sub pbTarget_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pbTarget.MouseEnter
pbTarget.Top = rnd.Next(pbArena.Height - pbTarget.Height) 'sets random y
pbTarget.Left = rnd.Next(pbArena.Width - pbTarget.Width) 'sets random x
'====================================================================================================================================================
'scoring system
score = score + 1
lblScore.Text = score
createball() 'creates a new ball
End Sub
'what happens when the timer ticks
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
moveball() 'every timer tick the ball will move IF its created
ball(i) = New PictureBox 'ball is a picture box
End Sub
End Class
This is my code so far. Each time the mouse intersects with the target (which is a picture box) is moves. I am replicating this game. http://www.lewpen.com/game/ I have used an array to spawn red squares on the form. I want to be able to detect when my mouse enters them. I know how to do this with picture boxes, but these are all spawned objects called ball(i). Thanks for the help!
It sounds like you want to know how to add an event handler to a dynamically created control. these are all spawned objects called ball(i) but they are all just pictureboxes. You can add event handlers when you create the balls (pictureboxes)
Private Sub createball(BallIndex As Integer)
Dim ball As New PictureBox 'ball is a picture box
' give it a name so we can find it
' ball index is PASSED to avoid sloppy global vars
ball.Name = "Ball" & BallIndex.ToString
' etc
Me.Controls.Add(ball)
AddHandler ball.MouseEnter, AddressOf BallMouseEnter
Elsewhere, you'd add the code for the event:
Private Sub BallMouseEnter(sender As Object, e As EventArgs)
' your code here
End Sub
Since the balls exist as controls in the Controls collection there is really no reason to keep a reference to them in an array. If you name them "Ball1", "Ball2" you can make them move by referencing them by name:
Me.Controls(ballname)
Where BallName would be "Ball" & index.ToString and index would be the ball/picturebox to move (like the i variable). EDIT More info:
Private Sub moveballS()
Dim ball As PictureBox
' loop thru ballS
For n As Integer = 0 To BallCount
' current ball from name
ball = Me.Controls("Ball" & n.ToString)
' your code here
If ball.Left <= pbArena.Left Then
' etc
End If
' you CAN just reference them in controls(),
' but it is wordy:
If Controls("Ball" & n.ToString).Left <= pbArena.Left Then
' etc
End If
Next n
End Sub
Another way to track them is just a List(Of String) to store the name, but that is equally unneeded if you can get them by name from Controls() as above:
Dim ballList As New List(Of String)
' when you create a ball:
ballList.Add(ball.Name)
to get a control reference:
For n As Integer = 0 To ballList.Count - 1
ball = Me.Controls(ballList(n))
' etc
It can be a bad idea to create a separate reference to dynamically created controls (like an array) since that ref can prevent the object from being disposed of if/when you reset or start over and are deleting balls/pictureboxes.