Moving picturebox according to the score of the dice - vb.net

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

Related

How to use properties of dynamically created picturebox in vb.net

I was trying to remove this "brickn" when ball intersect with this brick
but i am facing problem that "brickn" is not declared any helps?
there is code
Dim brickWidth as Integer = 0
Public Function CreateBrick() As PictureBox
Dim Brickn As New PictureBox
Me.Controls.Add(Brickn)
Brickn.Size = Brick.Size
Brickn.Left = BrickWidth
Brickn.Top = 0
Brickn.Image = Brick.Image
Brickn.SizeMode = PictureBoxSizeMode.StretchImage
Brickn.BackColor = Color.Black
Return Brickn
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i= -75 To Me.Width
CreateBrick()
BrickWidth += 170 ' increasing brick.left on every new brick is created
i += 170 ' increasing looop count according to brick needed
Next
Private Sub Boll_control_Tick(sender As Object, e As EventArgs) Handles Boll_control.Tick
If Ball.Bounds.IntersectsWith(brickn.Bounds) Then
Me.Controls.Remove(brickn)
End If
End Sub
why this "brickn" is not saying not declared in "boll control tick " timer
You are instantiating brickn withing CreateBrick. You are returning it as the result of that function, but not assigning it to anything. So it's scope is limited to the CreateBrick fuction only, which is why it's not accessible from Boll_control_Tick.
Also you are then trying to create multiple instances of it with using a single object.
This code will allow you to create one or more. You will then need to rework your Boll_control_Tick to work out whether it intersects with any. You may want to create a list or array of PictureBox objects as Brickn instead of one.
Dim brickWidth as Integer = 0
Dim Brickn As PictureBox ' This may be better as a list or an array
Public Function CreateBrick() As PictureBox
Dim myBrickn As New PictureBox
'Note - no idea what Brick is here or where it comes from
Brickn.Size = Brick.Size
Brickn.Left = BrickWidth
Brickn.Top = 0
Brickn.Image = Brick.Image
Brickn.SizeMode = PictureBoxSizeMode.StretchImage
Brickn.BackColor = Color.Black
Return myBrickn
End Function
and then in your Form_Load method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i= -75 To Me.Width
Brickn = CreateBrick() ' or add to your List/Array here
Me.Controls.Add(Brickn)
BrickWidth += 170 ' increasing brick.left on every new brick is created
i += 170 ' increasing looop count according to brick needed
Next
That will add multiple picture boxes to your controls and, if you want, create a list or array of them for easy access. You will need to loop through those in Boll_control_Tick to see if ball bounds intersects with any and then remove that specific one only

How to turn over cards in card game?

I have created a card game where 2 x 12 different images will be loaded into 24 picture boxes in vb forms. My intention is for the user to turn over two cards at a time, trying to find pairs to match. Each time the game is loaded, there will be different pictures and they will be in different positions. So far I have loaded the image for the back of the card in the game successfully but I can’t turn them over to see if my images have loaded successfully.
I am not concerned about shuffling them yet, I just want to see if the images have loaded and to be able to have two cards turned over at a time. I’m really confused as I’m not used to using VB for such tasks so any help is appreciated. Here is my code:
Imports System.IO
Public Class Board
' as per stackoverflow Terms of Service
' this code comes from
' http://stackoverflow.com/a/40707688
'array of picture boxes
Private pBoxes As PictureBox()
'array of images
Private imgs As String() = {"1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg", "8.jpg", "9.jpg", "10.jpg", "11.jpg", "12.jpg", "13.jpg", "14.jpg", "15,jpg", "16.jpg", "17.jpg", "18.jpg", "19.jpg", "20.jpg", "21.jpg", "22.jpg", "23.jpg", "24.jpg"}
'random number generator
Private RNG = New Random
'cover image
Private coverImg As String = "bg.jpg"
'timer
Private dt As DateTime
'turns cards
Private pbFirst As PictureBox
Private pbSecond As PictureBox
Private matches As Int32 = 0
'Folder where images are held
Private ImgFolder As String
Private Sub Board1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RNG = New Random()
'array of picture boxes
pBoxes = New PictureBox() {PictureBox1, PictureBox2, PictureBox3, PictureBox4,
PictureBox5, PictureBox6, PictureBox7, PictureBox8,
PictureBox9, PictureBox10, PictureBox11, PictureBox12, PictureBox13, PictureBox14, PictureBox15, PictureBox16, PictureBox17, PictureBox18, PictureBox19, PictureBox20, PictureBox21, PictureBox22, PictureBox23, PictureBox24}
'where images are located
ImgFolder = "F: \COMPUTER SCIENCE\Test images"
coverImg = Path.Combine(ImgFolder, coverImg)
For Each p As PictureBox In pBoxes
p.ImageLocation = coverImg
Next
NewGame()
End Sub
'Take images from file
Private Sub PickImages()
Dim nums = Enumerable.Range(1, 12).ToArray()
Dim pool = nums.Concat(nums).OrderBy(Function(r) RNG.Next).ToArray()
End Sub
Private Sub Shuffle()
End Sub
' reset everything
Private Sub NewGame()
matches = 0
pbFirst = Nothing
pbSecond = Nothing
' repick, reshuffle
PickImages()
Shuffle()
dt = DateTime.Now
'tmrMain.Enabled = True
End Sub
End Class
I dont have the points to comments however are you clicking on the pictures to turn them over? If so I think you would just need to have an event such as the below to load the back of the card image.
Private Sub PictureBox1_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox1.Click
PictureBox1.ImageLocation = ("Path to Picture of back of the card")
PictureBox1.Load()
End Sub
Don't try and over-think this - forget about "turning them over" simply change the image:
Private Sub PictureBox1_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox1.Click, PictureBox2.Click 'etc
dim index as short
' to do: get the index of the PictureCard
If sender.Image is coverImg then
sender.Image = imgs(index) ' in stead of 0, use the index of the picture card
Else
sender.Image = coverImage
End if
End Sub

Displaying winner's name in picture box

Below is code for a simple voting system I am coding.
Public Class Form1
Dim winner As String
Dim maxVotes As Integer
Dim votes() As String
Dim index As String
Dim candidates As String
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If Not isValidInput(txtNewCandidate.Text) Then
Exit Sub
End If
lstCandidates.Items.Add(txtNewCandidate.Text)
txtNewCandidate.Clear()
txtNewCandidate.Focus()
ReDim Preserve votes(index)
index += 1
End Sub
Private Function isValidInput(ByRef firstName As String) As Boolean
If IsNumeric(txtNewCandidate.Text) Or txtNewCandidate.Text = "" Then
MsgBox("Please input a valid candidate name.")
txtNewCandidate.Focus()
Return False
Else
Return True
End If
End Function
Private Sub btnTally_Click(sender As Object, e As EventArgs) Handles btnTally.Click
lstTallies.Visible = True
lblTally.Visible = True
For i = 0 To lstCandidates.Items.Count - 1
lstTallies.Items.Add(lstCandidates.Items(i).ToString & " - " & votes(i))
Next
End Sub
Private Sub lstCandidates_DoubleClick(sender As Object, e As EventArgs) Handles lstCandidates.DoubleClick
If lstCandidates.SelectedIndex = -1 Then
MsgBox("Select a candidate by double-clicking")
End If
votes(lstCandidates.SelectedIndex) += 1
MsgBox("Vote Tallied")
End Sub
Private Sub pbxWinner_Click(sender As Object, e As EventArgs) Handles pbxWinner.Click
End Sub
End Class
The voter must double click on their choice of candidate in the first list box. The user then tallies the votes by clicking on a button and a second list box will appear with the votes per candidate.
Now I need to display the winner (or winners, if there is a tie) in a picture box, pbxWinner. I am not sure how to accomplish this. Any clues?
Here is what i am trying to do, though the code below doesn't work.
Private Function candidateWinner(ByRef winner As String) As Boolean
For i As Integer = 0 To lstCandidates.SelectedIndex - 1
If votes(i) > maxVotes Then
maxVotes += 1
End If
Next
g = pbxWinner.CreateGraphics
g.TranslateTransform(10.0F, 0.0F)
g.DrawString(winner, New Font("Arial", 7, FontStyle.Regular), Brushes.DarkBlue, New PointF(0, 0))
Return True
End Function
Your code is actually working fine for an initial paint, but when the picture box image doesn't have its own bitmap set, a number of events can repaint its graphics behind the scenes(even as simple as minimizing/mazimizing the form, and a whole bunch of other ones), so in effect your text seems to never appear at all or disappear almost instantly when in reality it's probable getting repainted. To fix this, use a bitmap for the graphics object's reference, paint the bitmap's graphics, and then assign the bitmap to the picturebox's image property. This will make the image persistent...give this code a try in your candidateWinner function after the for loop:
Dim bmp As New Bitmap(pbxWinner.Width, pbxWinner.Height)
Dim g As Graphics = Graphics.FromImage(bmp)
g.TranslateTransform(10.0F, 0.0F)
g.DrawString(winner, New Font("arial", 7, FontStyle.Regular), Brushes.DarkBlue, 0, 0)
pbxWinner.Image = bmp
...If you still aren't seeing text, make sure the winner string has the correct value set, I tested this code and it showed my test string correctly
Edit for Comment:
That's because of the logic you're using to calculate the winner...you are just checking to see if the currently selected candidate's vote count is higher than maxVotes and then incrementing the max by 1. If you wanted to stick with that sort of logic for picking the winner, you would want to iterate through ALL of the candidates(not just those from index 0 to the currently selected one), and if their vote count is higher than the max, then set the max EQUAL to their vote count. Then the next candidate in the loop will have their count checked against the previous max. However, tracking the winner could be done a lot easier if you just use a dictionary since you are allowing candidates to be added, and you must change your "winner" logic to actually check who has the most votes out of everyone entered. A bare bones example of that would look like this:
Dim dctTally As Dictionary(Of String, Integer)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dctTally = New Dictionary(Of String, Integer)
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
dctTally.Add(txtNewCandidate.Text, 0)
lstCandidates.Items.Add(txtNewCandidate.Text)
End Sub
Private Sub lstCandidates_DoubleClick(sender As Object, e As EventArgs) Handles lstCandidates.DoubleClick
dctTally(lstCandidates.text) += 1
End Sub
Private Sub pbxWinner_Click(sender As Object, e As EventArgs) Handles pbxWinner.Click
Dim winner = dctTally.Aggregate(Function(l, r) If(l.Value > r.Value, l, r)).Key
Dim bmp As New Bitmap(pbxWinner.Width, pbxWinner.Height)
Dim g As Graphics = Graphics.FromImage(bmp)
g.TranslateTransform(10.0F, 0.0F)
g.DrawString(winner, New Font("arial", 7, FontStyle.Regular), Brushes.DarkBlue, 0, 0)
pbxWinner.Image = bmp
End Sub
This way, the program allows as many names as you want to be added to the candidates list, and will add a vote count to their name each time their name is double-clicked on. Then, when your winner pixturebox is clicked, it will find the dictionary with the highest vote count and display their name in the winner-box.
You can try this to draw the winners:
Private Sub candidateWinner()
Dim y As Single = 0
maxVotes = votes.Select(Function(x) Convert.ToInt32(x)).Max()
For i = 0 To UBound(votes)
If votes(i) = maxVotes.ToString() Then
g = pbxWinner.CreateGraphics
g.TranslateTransform(10.0F, 0.0F)
g.DrawString(lstCandidates.Items(i).ToString(), New Font("Arial", 7, FontStyle.Regular), Brushes.DarkBlue, New PointF(0, y))
y += 10
g.Dispose()
End If
Next
End Sub

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

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

Nested timers? Trouble with logic on multiple simultaneous timer ticks

I'm trying to create a simple visual example and the first step is having a column of boxes (panels) move across the screen. So far I've accomplished that, but I'm also attempting to have each panel blink a few times, individually, while moving. The effect should be a type of 'round robin' loop where the first panel blinks a few times, then the second, then the third, etc, etc and repeat.
I'm quite new to VB and so far I've only been able to successfully make either only one panel blink or all of the panels blink, not each one individually. Here's my code so far:
Public Class Form1
Public ticks As Integer
Public p(4) As Panel
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
p(0) = Panel1
p(1) = Panel2
p(2) = Panel3
p(3) = Panel4
p(4) = Panel5
ticks = 0
End Sub
Private Sub tmr1_Tick(sender As Object, e As System.EventArgs) Handles tmr1.Tick
Dim i As Integer
If ticks = 1 Then
For i = 0 To 4
Dim randomValue = Rnd()
p(i).Top = 50 + 75 * i
p(i).Left = randomValue * 120
Next
ElseIf ticks > 30 Then
ticks = 0
Else
For i = 0 To 4
p(i).Left += 20
Next
End If
ticks += 1
End Sub
Private Sub tmr2_Tick(sender As System.Object, e As System.EventArgs) Handles tmr2.Tick
Dim i As Integer
For i = 0 To 4 'all of the panels blink at the same time..
If p(i).Visible = False Then
p(i).Visible = True
ElseIf p(i).Visible = True Then
p(i).Visible = False
End If
Next
End Sub
End Class
As of right now, all of the panels blink while moving across the screen in random locations, I'm assuming this is because the for loop responsible for the blinking is nested within the ticking timer, so for each tick it runs through the loop fully.
I'm a little stumped on what should be some very simple logic, but please bear with me as I am a novice.
Thank you for any and all help!
If I understand what you want, this would do it. They all blink now because they are all in the loop that occurs with each tick, this example changes each one by it's index in the array, and the index variable must be class level to retain it's value between ticks.
Private index As Integer
Private Sub tmr2_Tick(sender As System.Object, e As System.EventArgs) Handles tmr2.Tick
p(index).Visible = Not p(index).Visible
If index = 4 Then
index = 0
Else
index += 1
End If
End Sub