Good evening made the following code, create an array of buttons and panels, now how do I insert random images to those buttons, can you help me please.
Public Sub crearBotonesPaneles(ByVal creaBoton(,) As Button, ByVal creaPanel As Panel)
Dim puntoLocacion As Point
puntoLocacion.X = 20
puntoLocacion.Y = 40
For filas As Integer = 0 To 1
For columnas As Integer = 0 To 3
If IsNothing(creaBoton(filas, columnas)) Then
creaBoton(filas, columnas) = New Button
creaBoton(filas, columnas).Location = puntoLocacion
creaBoton(filas, columnas).Width = 50
creaBoton(filas, columnas).Height = 50
creaPanel.Controls.Add(creaBoton(filas, columnas))
puntoLocacion.X = puntoLocacion.X + 50
End If
Next
puntoLocacion.X = 20
puntoLocacion.Y = puntoLocacion.Y + 50
Next
End Sub
Doing something random ALWAYS means generating one or more random numbers in an appropriate range and then using them in an appropriate manner. The way you determine the range is application-specific and the manner in which you use the number(s) is application-specific. In your case, you might get the paths of all the image files in a folder, use random numbers to order those paths randomly and then use the paths one by one to get the images from the files. E.g.
Private rng As New Random 'Random number generator
Private imagePaths As Queue(Of String)
Private Sub LoadImagePaths()
'Create a new queue of file paths sorted based on a random number mapped to each one.
imagePaths = New Queue(Of String)(Directory.EnumerateFiles(My.Computer.FileSystem.SpecialDirectories.MyPictures,
"*.jpg").
OrderBy(Function(s) rng.NextDouble()))
End Sub
Private Function GetNextImage() As Image
'Load the image paths is there is no queue or the current queue is empty.
If imagePaths?.Any() = False Then
LoadImagePaths()
End If
'Create an image from the next file in the queue.
Return Image.FromFile(imagePaths.Dequeue())
End Function
Based on that code, you just call GetNextImage each time you need a random image. There will be no repeats until the entire list is exhausted.
Related
This is the code i have so far, When a user gets a new high score it needs to clear the txt file and put the new high score in it or replace the number within the txt file. I am struggling to find a way to clear the file.
ElseIf HighscoreDifficulty = "E" Then
EasyHighScore = My.Computer.FileSystem.ReadAllText("EasyHighScore.txt")
If CurrentScore > EasyHighScore Then
NewHighScore.Visible = True
file = My.Computer.FileSystem.OpenTextFileWriter("EasyHighScore.txt", True)
file.WriteLine(CurrentScore)
file.Close()
Else
NoNewHighScore.Visible = True
End If
Thanks
Let's say that you want to keep the top five scores in the file. Assuming that the file always contains valid data, you could do that like this:
Private Sub SaveHighScore(score As Integer)
Const FILE_PATH = "file path here"
Const MAX_SCORE_COUNT = 5
'Read the lines of the file into a list of Integer values.
Dim scores = File.ReadLines(FILE_PATH).
Select(Function(s) CInt(s)).
ToList()
'Append the new score.
scores.Add(score)
'Sort the list in descending order.
scores.Sort(Function(x, y) y.CompareTo(x))
'Write up to the first five scores back tot he file.
File.WriteAllLines(FILE_PATH,
scores.Take(MAX_SCORE_COUNT).
Select(Function(i) i.ToString()))
End Sub
By adding the new score to the existing list, sorting and then writing out the first five, you automatically drop the lowest score. That means that there's never a need to actually check whether the new score is a high score or not.
I am making a game for my intro to comp programming class, I have a 6 by 6 board where you do something different on each tile. I am currently working on a mob collision sub where if the player collides with the mob the player has to battle. Right now I have an issue with creating multiple of the same time of mob. Here is my code
Public Sub creeperS()
' Dim creeper As New PictureBox
'This is now above so it can be used by other subs
Dim creepercount As Integer
creeper.Width = 32
creeper.Height = 32
creeper.BackColor = Color.LimeGreen
creepercount = rand.Next(0, 36)
If creepercount = 0 Then
Me.Controls.Add(creeper)
creeper.Top = 95
creeper.Left = 84
creeper.BringToFront()
ElseIf creepercount = 1 Then
Me.Controls.Add(creeper)
creeper.Top = 95
creeper.Left = 184
creeper.BringToFront()
ElseIf creepercount = 2 Then
Me.Controls.Add(creeper)
creeper.Top = 95
creeper.Left = 284
creeper.BringToFront()
ElseIf creepercount = 3 Then
It does this all the way to 36, Im wondering if you can make a picture box array so i can have several of a mob on the board.
You did not post your class code, so I will try showing you a generic method to create controls and keep them in an array. In fact a Dictionary object...
Create a variable on top of your form, at the declarations side:
Option Explicit
Private shDict As Object
Then put the next code in your Form Initialize event:
Dim i As Long, No As Long
Dim txtBox As MSForms.TextBox
No = 36 'your needed controls
Set shDict = CreateObject("Scripting.Dictionary")
For i = 84 To No * 100 Step 100
Set txtBox = Controls.Add("Forms.TextBox.1", "txt_" & i)
shDict.Add txtBox.Name, Array(txtBox, 95, i, True)
Next i
Not having your class, my example code creates text boxes and fills their Name, Top and Left properties in a Dictionary array. It can keep objects, arrays, strings etc. I tried to use your Top and Left logic, but big part of them will not fit on the form surface...
Place a button on the form (named btRepAll). It will preposition all created shapes according to the values previously input in shDict.
Private Sub btRepAll_Click()
Dim i As Long
For i = 84 To shDict.Count * 100 Step 100
shDict("txt_" & i)(0).top = shDict("txt_" & i)(1)
shDict("txt_" & i)(0).left = shDict("txt_" & i)(2)
Next i
End Sub
I wanted to ask some other preliminary questions, to clarify myself regarding your real need, but since you did not answered a simple one and I cannot stay to much at my office, I preferred to post a generic answer. You can load as many properties as you want. Please try building something similar, able to better fit your real need.
I have a vb.net program that keeps track of people that bought raffle tickets and also keeps track of their phone numbers. When I go to add a new person(via a for loop) it gets the number of tickets they bought and adds that amount of there name and number to an array. But when I click it, it adds one extra of the prevoius name and number I had put in.
I have tried moving the place where the variable assignment takes place.
I tried to null the variable and reassign it.
Button Click
Public Sub BtnAddtckt_Click(sender As Object, e As EventArgs) Handles
BtnAddtckt.Click
Reset()
Dim MNES As String = Nameinput.Text.ToString
Dim NUMES As String = Numinput.Text.ToString
Dim LenPrev = ApplicantsName.Length - 1
Dim LenNext = (LenPrev) + (NumEntries.Value - 1)
ReDim Preserve ApplicantsName(LenNext)
ReDim Preserve ApplicantsNum(LenNext)
For Subs As Integer = LenPrev To LenNext
ApplicantsNum(Subs) = NUMES
ApplicantsName(Subs) = MNES
Next
LbltotalRegistered.Text = (ApplicantsName.Length - 1).ToString
For nme As Integer = 0 To (ApplicantsName.Length - 1)
Form2.LBname.Items.Add(ApplicantsName(nme).ToString)
Next
For nem As Integer = 0 To (ApplicantsNum.Length - 1)
Form2.LBnum.Items.Add(ApplicantsNum(nem).ToString)
Next
End Sub
I expect it to not add an extra person to each aray.
Why does the messagebox show "False"?
Dim images(4, 4) As Image
For rows = 0 To 4
For columns = 0 To 4
images(rows, columns) = My.Resources.kaboom
Next
Next
MessageBox.Show(images(3, 3).Equals(My.Resources.kaboom))
If you look at the code behind the kaboom property, you will see it creates a new object every time.
'''<summary>
''' Looks up a localized resource of type System.Drawing.Bitmap.
'''</summary>
Friend ReadOnly Property kaboom() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("kaboom", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
If you keep a reference to one object, it will be equal to true. It might also be faster since it doesn't need to create a new object.
Dim kaboom As Image = My.Resources.kaboom
Dim images(4, 4) As Image
For rows = 0 To 4
For columns = 0 To 4
images(rows, columns) = kaboom
Next
Next
MessageBox.Show(images(3, 3).Equals(kaboom))
Maybe you are already planning on doing this but here is a suggestion. If you are creating some sort of game, separate the display from the game logic. This mean, save the type of tile instead of the image and compare that. Later, you can add a bunch of different properties to a tile.
Const TYPE_KABOOM As Integer = 1
Dim tileType(4, 4) As Integer
For rows = 0 To 4
For columns = 0 To 4
tileType(rows, columns) = TYPE_KABOOM
Next
Next
MessageBox.Show(tileType(3, 3).Equals(TYPE_KABOOM))
I want to create a form in which will be displayed a question and the user will have to chose the correct out of four images..
First of all I'm using an ArrayList and fill it with my questions, I'm also creating two Imagelists. I'm adding all the correct "answers" in order (ex the correct answer for the first question ( Arraylist1(0) ) will be the first Image ( Imagelist1 (0) ). The second Imagelist is full of "wrong" answers. Up to this point everything works fine.
I want the Images to appear in random order, so I tried to create a temporary list and fill it with the Correct Image and three wrong in randomly...
But I couldn't find out how to do that... Since "Contains" and "ImagelistA.Images.Add(ImagelistB(3))" are not working as I thought that they would...
PS: Following the same pattern for Arraylists instead of Imagelists worked perfectly... But I can't figure out a way to have the same outcome with Images...
Public Sub reloadForm()
'Filling the ArrayList with questions'
Dim questions As New ArrayList
questions.Add("Question1")
questions.Add("Question2")
questions.Add("Question3")
questions.Add("Question4")
questions.Add("Question5")
questions.Add("Question6")
Dim Randm As New Random
Dim rnd As New Integer
Dim temp As New ImageList
Dim flaG As Boolean
flaG = False
'Picking a random unanswered question from the ArrayList'
'Adds the Correct Image/Answer to a Temporary List'
Do
rnd = Randm.Next(0, (questions.Count))
If Not ListBox1.Items.Contains(rnd) Then
question.Text = questions(rnd)
temp.Images.Add(ImageListC(rnd))
ListBox1.Items.Add(rnd)
flaG = True
End If
Loop Until flaG = True
'Adding three wrong Images/Answers in to Temporary Imagelist'
Do
rnd = Randm.Next(0, (ImageListW.Images.Count))
If Not temp.Contains(ImageListW(rnd)) Then
temp.Images.Add(ImageListW(rnd))
End If
Loop Until temp.Count = 4
'Displays all four Images in a random order'
Dim quizlist As New Imagelist
Do
rnd = Randm.Next(0, 4)
If Not quizlist.Contains(tempList(rnd)) Then
quizlist.Images.Add(tempList(rnd))
End If
Loop Until quizList.Count = 4
PictureBox1.Image = quizlist(0)
PictureBox2.Image = quizlist(1)
PictureBox3.Image = quizlist(2)
PictureBox4.Image = quizlist(3)
End Sub
Can you suggest a solution for this one, or a different way to do it?
Thanks in advance