Sam February 2016

remove matching images from two Arrays

I'm making a snap game were I'm trying to remove two images from an array so they don't reappear again when first random card and second random card match. Is there any way I can do this? Thanks

var cardNamesArray: [String] = ["sad", "sleepy","angry"]

var cardNamesArray2: [String] = ["triste", "cansado","enfadado"]

Generates a random card for the first Array

   firstRandomNumber = Int (arc4random_uniform(3))
   let firstCardString:String = self.cardNamesArray[firstRandomNumber]
   self.FirstCardImageView.image = UIImage(named: firstCardString)

Generates a random card for the second Array

   SecondRandomNumber = Int (arc4random_uniform(3))
   let SecondCardString:String = self.cardNamesArray2[SecondRandomNumber]
   self.SecondCardImageView.image = UIImage(named: SecondCardString)

If they match player score 1 point

        @IBAction func SnapButtonTapped(sender: UIButton) {

        if firstRandomNumber == SecondRandomNumber {

        print("index match")

        self.playerScore += 1
        self.playerScoreLabel.text = String(self.playerScore

    }

Answers


Sohil R. Memon February 2016

Why don't you try to remove images from an Array itself. Once the random number matches, you can do that!

if firstRandomNumber == SecondRandomNumber {

    print("index match") 
    self.playerScore += 1
    self.playerScoreLabel.text = String(self.playerScore
    cardNamesArray.removeAtIndex(firstRandomNumber)
    cardNamesArray2.removeAtIndex(SecondRandomNumber)

    if cardNamesArray.count == 0 && cardNamesArray2.count == 0{
        print("User Won")
    }else{
        print("Continue Playing")
    }
}

Crash Update:

Replace the below two lines in your code with mine

firstRandomNumber = Int (arc4random_uniform(UInt32(cardNamesArray.count)))

SecondRandomNumber = Int(arc4random_uniform(UInt32(cardNamesArray2.count)))


TechBee February 2016

You may use a dictionary object in the Array.

Instead of

var cardNamesArray: [String] = ["sad", "sleepy","angry"]

You may use

Class CardItem{

   var name = ""
   var isDisplayed:Boolean?

}

And now

var cardNamesArray: [CardItem] = [CardItem(name:"sad",isDisplayed:false), CardItem(name:"sleepy",isDisplayed:false),CardItem(name:"angry",isDisplayed:false)]

Here is your random chunk:

SecondRandomNumber = Int (arc4random_uniform(3))

var uniqueItem = self.cardNamesArray2[SecondRandomNumber]

let SecondCardString:String = uniqueItem.name

self.SecondCardImageView.image = UIImage(named: SecondCardString)

uniqueItem.isDisplayed = true

So when you next time generate random number just check item's isDisplayed property.

Regards

Post Status

Asked in February 2016
Viewed 1,981 times
Voted 6
Answered 2 times

Search




Leave an answer