This site requires JavaScript, please enable it in your browser!
Greenfoot back
puddle148
puddle148 wrote ...

2017/1/21

For loop to addObjects

puddle148 puddle148

2017/1/21

#
I am trying to add 2 cards on dealer side and 2 on the player this is the code I have tried, the cards are random but only one will show one will show up on the screen each time.
int l = Greenfoot.getRandomNumber(3);
        int p = Greenfoot.getRandomNumber(12);
        String picName;
        //string allows the values and suits to have a image assigned to them
        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 13; y++)
            {
                //the string must include suit card and png on the end to make it the same as the file in greenfoot images file
                //both lines call from the strings created above creating new lines for the addobject
                picName = suits[x] + cards[y] + ".png";
                Crd[x][y] = new Card(suits[x], cards[y], cardvalues[y], picName );

            }
        }
and this just below
 for (int i = 0; i <= 2; i++)
        {
            addObject(Crd[l][p], 220, 500);   
        } 
danpost danpost

2017/1/21

#
First off, in the first two lines, you are omitting an entire suit and one rank. Use '4' and '13' instead of '3' and '12'. Secondly, those same two lines, which are the indices of your array used in the 'for' loop, are outside the for loop and are executed only once. Therefore, the same card is trying to be added to the world for each iteration of the loop. Move the two lines inside the loop before the 'addObject' line.
puddle148 puddle148

2017/1/21

#
Thanks that worked! I need 2 cards to be on the dealer side and 2 on the player side, do I have to make another for loop for this? Also, how do I get the cards to go in a row instead of just on top of one another. I have tried placing for example (50 + 50, 60). I have also tried to add object statement but I get a runtime error.
 for (int i = 0; i <= 1; i++)
        {
              int l = Greenfoot.getRandomNumber(4);
               int p = Greenfoot.getRandomNumber(13);
            //addObject(Crd[l][p], 220 + 60, 500);   
            addObject(Crd[l][p], 230 + 80, 430); 
        } 
danpost danpost

2017/1/21

#
Just adding a constant value changes the placement of all cards. The thing that is different for each card is the iteration counter of the loop. Try:
addObject(Crd[1][p], 230+i*80, 430);
You will need two loops. They can be separate or combined as a double loop (one inside the other).
puddle148 puddle148

2017/1/21

#
Thanks danpost everything is working now!
You need to login to post a reply.