Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Filtering an Array

Status
Not open for further replies.
Alright, I'm guessing the guys in the irc are a bit tired of my useless scripting rants, so I've decided to get help in the forum, this time. I really want to filter an array into an all new array.

for example: array = [0,0,0,0,1,1,1,1,2,2,2,2] (array[0...3] = 0, array[4...7] = 1, array[8...11] = 2)
If I wanted a new array that only held the number 1, for example, I'd need the array not to start at 4 and end at 7, but to start at 0 and end at 3.

another example is: array = [1,0,1,2,0,1,2,0,0,2,2,1] If I needed a new array with only 1's It would be the same as the first example.


Alright if you don't understand that, I'll give you an example from my failed attempts:

Code:
        cards = @actor.deck[@deck_index].cards.clone
        magic_cards = []
        for i in 0...cards.size
          if cards[i][2] != "Magic"
            cards[i] = nil
          end
        end
        cards.compact
        magic_cards = cards.clone
        for i in 0...magic_cards.size
          draw_card_graphic(magic_cards[i], 2, 2, i)
        end

You see, I know why this wouldn't work, but I don't know how to fix it. The this wouldn't work is because magic_cards retains the same index as the cards that are cloned.

Now, you should know my problem. I'd really like some help with this.
 

Eilei

Sponsor

Use the array.select method; something like this:

Code:
        magic_cards = @actor.deck[@deck_index].cards.select {|card| card[2] == "Magic"}

        for i in 0...magic_cards.size
          draw_card_graphic(magic_cards[i], 2, 2, i)
        end
 
Status
Not open for further replies.

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top