从两个阵列中删除匹配的图像

时间:2016-02-08 11:46:33

标签: arrays swift

我正在制作一个快照游戏,我正在尝试从阵列中删除两个图像,这样当第一张随机卡和第二张随机卡匹配时,它们不会再次出现。有什么方法可以做到这一点吗?感谢

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

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

为第一个数组生成随机卡

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

为第二个数组生成随机卡

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

如果他们匹配球员得分1分

        @IBAction func SnapButtonTapped(sender: UIButton) {

        if firstRandomNumber == SecondRandomNumber {

        print("index match")

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

    }

2 个答案:

答案 0 :(得分:1)

为什么不尝试从阵列本身删除图像。一旦随机数匹配,你就可以做到!

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")
    }
}
  

崩溃更新:

用我的代码替换代码中的以下两行

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

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

答案 1 :(得分:1)

您可以在数组中使用字典对象。

而不是

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

您可以使用

Class CardItem{

   var name = ""
   var isDisplayed:Boolean?

}

现在

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

这是你的随机块:

SecondRandomNumber = Int (arc4random_uniform(3))
  

var uniqueItem = self.cardNamesArray2 [SecondRandomNumber]

     

让SecondCardString:String = uniqueItem.name

self.SecondCardImageView.image = UIImage(名称:SecondCardString)

  

uniqueItem.isDisplayed = true

因此,当您下次生成随机数时,只需检查项目的isDisplayed属性。

此致