how could i keep track of subscripts of an array so they cant be used again?

edited January 2016 in How To...

I have to make a game to play war and it cant use the same cards twice in the same game. I have everything set and playing the game but the cards just randomly generate and cycle through the cards available. I am using an array to produce the cards because that's the point of the project. how would i go about telling the computer to not use a subscript in an array that has already been played. If you can give any advice I would appreciate it. Thank you.

Tagged:

Answers

  • Answer ✓

    Hi, I'll try to answer to the best of my (limited) knowledge. I hope I understand the problem. Use a second array or a two-dimensional array to keep track of which cards have been used. Disadvantage: Theoretically it would be possible that "scanning" the array for an unused card would take infinite time. Better method: Imitate a real deck of cards which are then drawn in sequence. Shuffle the array/deck before drawing the cards. I found this forum thread:

    http://forum.processing.org/one/topic/i-made-a-shuffle-for-arrays.html which mentions http://en.wikipedia.org/wiki/Fisher–Yates_shuffle

    HTH! Regards, fluxmov

  • edited November 2013 Answer ✓

    @rauhaus has got the right idea but it is possible to avoid the need to shuffle the deck.

    This code demonstrates what is happening. The nbrUsed not only keeps thrack of the number of cards used but also the array index for the next card to be used. The method getCard picks a random card from the 'unused' cards swaps it with the next card to deal and then retuns that card, increasing the nbrUsed variable at the same time. Each time you run this sketch you should get a random sequence without repeats.

    int[] deck = new int[10];
    int nbrUsed = 0;
    int cardValue = -1;
    
    void setup() {
      // create the deck
      for (int i = 0; i < deck.length; i++)
        deck[i] = i;
    
      // Deal out the deck in random order without repeating
      for (int i = 0; i < deck.length; i++) {
        cardValue = getCard();
        print(cardValue + "  ");
      }
      println();
    }
    a
    
    public int getCard() {
      int cardPos = (int)random(nbrUsed, deck.length);
      // Sawp the next card with one not used
      int temp = deck[nbrUsed];
      deck[nbrUsed] = deck[cardPos];
      deck[cardPos] = temp;
      return deck[nbrUsed++];
    }
    
  • This helps a bit. ill have to work something like this into mine. i just have to edit it to rework it to work with mousePressed. thank you.

  • edited November 2013

    Side note: for me, subscript is the little numbers used in chemical notations, like H2O or CO2. (It doesn't work on this forum? Oh, I see, there is a vertical-align: baseline; style on all HTML elements! Dumb... Worked around by restoring the default align on my <sub> tags!)

    In arrays, we rather talk about indexes.

Sign In or Register to comment.