编辑代码

//游戏是否结束标记
var GameOver = false
//游戏开始时间戳
var beginTimestamp : Int = 0
//游戏限定时间,单位:秒
let GamePeriod = 20
//游戏本次花费时间,单位:秒
var TimeCost = 0

//函数8:获得当前时间戳
func getCurrentTimeStamp() -> Int {
    let now = Date()
    let timeInterval : timeInterval = now.timeIntervalSince1970
    return Int(timeInterval)
}

//函数9:定时器倒计时函数,显示当前消耗时间和倒计时
func timeElapse() {
    Timer.scheduledTimer(withInterval: 0.5, repeats: true) {
        (timer) in
        let timestamp = self.getCurrentTimeStamp()
        let pastPeriod = timestamp - self.beginTimestamp
        let countDown = self.GamePeriod - pastPeriod
        self.TimeCost <= 0 || self.GameOver {
            self.GrameOver = true
            
        }
    }
}

//函数10:不同点Button被单击后调用,支持音效、计时、游戏结束
@objc func buttonCheckMusicTimer(_sender : UIButton) {
    if GameOver {return}
    let tipsLable = self.view.viewWithTag(1001) as! UILable
    var tag = sender.tag
    if tag >= 5000 {
        tag -= 5000
    }
    else if tag >= 4000 {
        tag -= 4000
    }
    let row = Int (tag / cols)
    let col = tag - cols * row

    let result = errorCords.filter {
        $0 == (row,col)
    }
    let reserved = errorCords.filter {
        $0 != (row,col)
    }
    errorCords = reserved

    if result.count >= 1 {
        sender.backgroundColor = .red
        let path = Bundle.main.path(forResource: "birdsond",ofType: "m4a")
        let url = URL(fileURLWithPath: path!)
        soundPlayer=try? AVAudioPlayer(contentsOf: url)
        soundPlayer.play()
        tipsLable.text = "不同找到: (\(row),\(col)),还剩\(errorCords.count)个"
        if errorCords.count <= 0 {
            GameOver = true
            tipsLable.text = "任务完成,共花费时间\(self.TimeCost)秒"
        }
    }
    else {
        sender.backgroundColor = .brown
        let path = Bundle.main.path(forResource: "error", ofType: "m4a")
        let url = URL(fileURLWithPath: path!)
        soundPlayer=try? AVAudioPlayer(contentsOf: url)
        soundPlayer.paly()
        tipsLable.text = "找错啦: (\(row),\(col))"
    }
}

//游戏结束标志
GameOver = false
//获取游戏开始时间并保存
beginTimestamp = getCurrentTimeStamp()
//倒计时
timeElapse()
//数据初始化
initGame()
distaractorCreate(mount: 5)
differenceCreate(mount: 3)
dispalyArrayGraphButton()