473,396 Members | 2,033 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to use one method to display random dice to 12 picture boxes?

I have 12 picture boxes and I am calling a method called ShowDice() to show the image of the dice.

Here is what I am doing exactly:

- Generate a random number for 12 integers
- Use a for loop to count which dice is being shown:

Expand|Select|Wrap|Line Numbers
  1. for (int count = 1; count < 13; count++)
  2. {
  3.   ShowDice(diceNum, count)
  4. }
  5.  
So, diceNum is a random number ranging from 1 to 6 because dices only have values from 1 to 6. I am displaying 12 dices hence count < 13 because count starts at 1.

In the ShowDice method, I want to be able to display the dice to the appropriate picture box without having to repeat the same lines of code. So here is what I'm doing:

Expand|Select|Wrap|Line Numbers
  1. ShowDice(int diceNum, int count)
  2. {
  3. if (count == 1) //First Dice Picture Box
  4.   switch (diceNum)
  5.     {
  6.        case 1:
  7.          picDice1.Image = Dice_Roll.Properties.Resources.Dice1; //Displays the image of a dice of value that is 1
  8.          break;
  9.        case 2:
  10.          etc..
  11.     }
  12. }
  13.  
As you can see, if I repeat the same lines of code, but change the picture box from picDice1 to picDice2, the code will be very inefficient. What is a more efficient way of doing this?
Oct 3 '10 #1
12 4355
Joseph Martell
198 Expert 128KB
There are a couple of different ways you could structure this code.

I think that the path I would personally take is to create an array or collection of the picture boxes and an array or collection of the six dice images. Then your assignment basically becomes like this:

Expand|Select|Wrap|Line Numbers
  1. picBox[count] = diceImage[diceNum];
The price you pay is the overhead of the collection objects, but the structure of the program and maintainability of the code would make this the better option as far as I'm concerned. Plus, if you get all nerdy and want to have a twenty sided die, you don't have to modify this code :).
Oct 3 '10 #2
How would I go about to create an array of picture boxes and assign each picture box to an existing picture box on the form. Like:

picDice1.Image = picBox[1].Image;
Oct 3 '10 #3
HaLo2FrEeEk
404 256MB
Expand|Select|Wrap|Line Numbers
  1. using System.Collections.Generic;
  2.  
  3. List<PictureBox> pictBoxes;
  4.  
  5. private void Form1_Load(object sender, EventArgs e)
  6. {
  7.     pictBoxes = this.Controls.OfType<PictureBox>().ToList<PictureBox>();
  8. }
pictBoxes now contains a dynamically-generated array of all the pictureboxes you have contained in the form. Hopefully order isn't an issue because I got some weird results:



The one labeled 0 is actually named pictureBox10, and the one labeled 1 is actually named pictureBox5. Dunno how to fix that other than maybe naming your picture boxes with standard names and incrementing numbers, like box0, box1, box2, box3. With this, you could access them like this (in a loop):

PictureBox pictBox = (PictureBox)this.Controls["box" + i];
pictBox.image = (your image);
Oct 4 '10 #4
Joseph Martell
198 Expert 128KB
HaLo2FrEeEk has a good start to a solution. You can do something similar for the 12 dice images.

Expand|Select|Wrap|Line Numbers
  1. using System.Collections.Generic;
  2.  
  3. List<PictureBox> pictBoxes;
  4. List<Image> diceImages;
  5.  
  6. private void Form1_Load(object sender, EventArgs e)
  7. {
  8.     pictBoxes = this.Controls.OfType<PictureBox>().ToList<PictureBox>();
  9.  
  10.     diceImages.Add(Dice_Roll.Properties.Resources.Dice1);
  11.     diceImages.Add(Dice_Roll.Properties.Resources.Dice2);
  12.     //etc.
  13. }
  14.  
  15.  
Now you have to collections that contain your picture boxes and the dice images. All you have to do is set your picture box image to the correct image and you're done.

Expand|Select|Wrap|Line Numbers
  1. ShowDice(int diceNum, int count)
  2. {
  3.     pictBoxes[diceNum].Image = diceImages[count];
  4. }
As HaLo2FrEeEk noted, your collection index (diceNum) probably won't line up correctly with the actual picture boxes, but that doesn't necessarily matter if all you are trying to do is show the results of rolling 12 dice.
Oct 4 '10 #5
GaryTexmo
1,501 Expert 1GB
It looks like you guys have a good handle on working towards a solution so I'll leave it to you; however, I'm going to randomly jump in here with a question!

What is the difference between these two lines?

Expand|Select|Wrap|Line Numbers
  1. pictBoxes = new List<PictureBox>();
  2. pictBoxes = this.Controls.OfType<PictureBox>().ToList<PictureBox>();
The first line is the instantiation I'm used to... I'm guessing that second line does the same thing? Why is it written like that and what does it do? Is there any advantage to the way you wrote it?

Thanks!
Oct 4 '10 #6
Joseph Martell
198 Expert 128KB
I wasn't familiar with that particular bit of code either.

The method OfType is called on the Controls collection. It is a LINQ extension to IEnumerable that returns elements of the collection that are of the specified type.

The second line only works if this refers to a form class (or some other class that contains a Controls collection). It returns an instantiated and populated list collection that contains references to all of the controls on the form of the PictureBox type.
Oct 5 '10 #7
HaLo2FrEeEk
404 256MB
That's why I only declared the pictBoxes variable and didn't instantiate it. Since the OfType<T>() method returns a populated IEnumerable (converted to list using ToList<T>()), you just need to have the variable declared.

I also messed around and figured something out that I'd mentioned in my original post. I had all my picture boxes named "pictureBox##", so I was able to do this (we'll assume that there are 12 picture boxes, like in the OP):

Expand|Select|Wrap|Line Numbers
  1. for(int i = 1; i <= 12; i++) {
  2.   PictureBox pictBox = (PictureBox)this.Controls["pictureBox" + i];
  3.   pictBox.Image = blahblah;
  4.   }
You can see where that's going. It's a faster way of doing it, I think, because you're not creating a list of controls. Also, it keeps things in order.
Oct 5 '10 #8
Joseph Martell
198 Expert 128KB
HaLo2FrEeEk has a good way to do it without creating a separate data structure. The down side to that method is that every time the picture needs to be set the picture box must be found again. A collection does use more memory, but saves time during run-time by not having to search the entire controls collection for the right picture box. The best solution depends on whether you are optimizing for time or space.

Incidentally, whenever using a List or other collection type and you know the number of elements you have beforehand, you can usually make its use slightly more efficient by declaring how many elements it will have up front:

Expand|Select|Wrap|Line Numbers
  1. pictBoxes = new List<PictureBox>(12);
This way the collection is created with 12 spots from the start. This saves time and resources by a) not having to expand the collection's internal memory allotment and b) unused spots are not reserved.

The List class uses an internal array to store its members. As more space is needed the array size is doubled. What is actually happening is a new array is created and the original members copied from the old array to the new one. For our example of a 12 element list the internal array would go from 1, to 2, to 4, to 8, to 16. That is 4 different times a new array must be created and the original values copied over. It also leaves 4 unused elements. By declaring the size at the start, the internal array structure is created with 12 elements. No resizing is necessary and all of the elements will be used.

I think its important to remember that all of the solutions that we are discussing are just shifting the load from one point to another. If you load all of your picture boxes into a collection, by whatever means you choose, then you are emphasizing run-time speed. Referencing the individual picture boxes will be fastest because you have done all of your filtering and searching up front but your memory foot-print and form initialization will be slower. If you find the picture box every time you want to set the image (HaLo2FrEeEk's previous post) your form initialization will be faster and your form slightly smaller because you aren't creating any collections. The individual set operation will be slightly slower because you have to re-find your picture boxes every time.
Oct 5 '10 #9
HaLo2FrEeEk
404 256MB
Either way, I think if the main point of your program is to just roll some dice into 12 picture boxes, overhead really won't be much of a concern. Do whatever is easiest for you, but you now have 2 different, valid ways of achieving what you wanted.
Oct 5 '10 #10
GaryTexmo
1,501 Expert 1GB
Ah, thanks for explaining that. I see it now... your form had a bunch of picture boxes on it already and that just picked them out.

Also, for the record, the performance on a List is pretty quick. When I was doing performance tests on my QuadTree, I threw 100 000 objects into a list in a for loop and my program loaded up in one second. I don't disagree with your base argument, there is indeed some overhead, but I don't believe it's a big deal in this case.
Oct 5 '10 #11
Joseph Martell
198 Expert 128KB
@Gary
I agree, Lists are pretty quick in my experience too. It seems like any time some one uses the word "efficient" in a post it tends to spawn a whole slew of discussions about the intricacies of code structure.

I also think that you are correct: The solutions posted here are more than adequate for the problem in the OP.
Oct 6 '10 #12
GaryTexmo
1,501 Expert 1GB
It seems like any time some one uses the word "efficient" in a post it tends to spawn a whole slew of discussions about the intricacies of code structure.
Haha that made me chuckle, too true :D People need to be careful throwing that word about!

Speaking of efficiency, in regards to my earlier post, is there any difference in efficiency between using the ToList method of getting all the PictureBox controls on a form over just looping through this.Controls? This may be one of those things I need to look into...
Oct 6 '10 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Chris Coho, Jr. | last post by:
Ok, I'll explain the whole problem because there may be several ways to solve this and hopefully someone knows one. What I'm doing is creating a specialty template editor, similar to say a corel...
1
by: Jerry S | last post by:
Hi I wonder if someone can help with this, because there's something I'm not understanding right. I've got a List Array of PictureBoxes. If I call PictureBoxListArray.Clear(), and then...
2
by: beanimanius | last post by:
working with about 100 picture boxes (not very big, 42X8) 1 image list of 5 pictures hopefully 1 context menu how do you program a contex menu so that it knows what picture box you are clicking...
2
by: Bwells | last post by:
Sorry for the legacy question (VB6) but the program I need to implement printing on has not been converted to .Net yet. I have a form with 4 Picture Boxes on it. These boxes are used as a...
1
by: eric_berlin | last post by:
I am writing a multithreaded application that has 6 threads each writing 5 frames per second video bitmaps to a different picture box. I have just found out that only the main UI thread is supposed...
0
by: T Clancey | last post by:
Hi. I'm trying to put together a very simple label designer to add to a project, this will allow users to enter text data. I can DrawSting the data into the picture boxes as required, but I...
1
by: nithu | last post by:
hi frens, i am an fresh graduate..... n also new to vb..... pls help me.... how to display values in text boxes retrieved from db in printable format? any sort of help or...
2
by: lord.zoltar | last post by:
I have a couple of images I'm using to try and pretty up some forms. They are PNG images with transparent parts. I have one of them partly overlaying the other, but my problem is with the...
4
by: robertko2 | last post by:
Hello everyone, This is my first post here, and was hoping someone could lead me on the right track to quality resizing of drawing files like .bmp .jpg etc in VB6 Image or Picture boxes. I'm...
4
by: meko92 | last post by:
How can I display random three texts in a label by clicking a button I want to make a game with 2 players and the second player is the PC. I want the PC to choose one of three word and display it...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.