编辑代码

func displayArrayGraph(){
    let myView1 = self.view.viewWithTag(2001) as! UIImageView
    let myView2 = self.view.viewWithTag(2002) as! UIImageView
    myView1.backgroundColor = .darkGray
    myView2.backgroundColor = .darkGray
    let h = myView1.frame.size.height
    let w = myView1.frame.size.width
    let padding : CGFloat = 5
    let margin : CGFloat = 10
    let grid_w= (w - margin * 2 - padding * CGFloat(cols- 1)) / CGFloat(cols)
    let grid_h= (h - margin * 2 - padding * CGFloat(rows- 1)) / CGFloat(rows)
    for i in 0..<rows{
        for j in 0..<cols{
            let x = margin + CGFloat(j) * (grid_w + padding)
            let y = margin + CGFloat(i) * (grid_h + padding)
            let rect = CGRect(x: x,y:y, width: grid_w,height:grid_h)
            let fileName1 = iv1[i* cols+ j]
            let img1 = UIImage(named:fileName1)
            let imgView1 = UIImageView(frame: rect)
            imgView1.image = img1
            imgView1.backgroundColor = .yellow
            myView1.addSubview(imgView1)
            let fileName2 = iv2[i* cols+ j]
            let img2 = UIImage(named:fileName2)
            let imgView2 = UIImageView(frame: rect)
            imgView2.image = img2
            imgView2.backgroundColor = .yellow
            myView2.addSubview(imgView2)
        }
    }
}


func displayArrayGraphButton(){
let myviewl = self.view viewWithTag(2001) as! UIImageview 
let myview2 = self.view.viewWithTag(2002) as! UIImageview 
myview1.backgroundColor = .darkGray 
myView2.backgroundColor= .darkGray
myViewl.isUserInteractionEnabled = true 
myView2.isUserInteractionEnabled = true
let h = myView1.frame.size.height 
let w = myViewl.frame.size.width
let padding :CGFloat= 5 
let margin : CGFloat= 10
let grid w=(w- margin * 2 - padding * CGFloat(cols - 1))/ CGFloat(cols) 
let grid h=(h- margin* 2- padding* CGFloat(rows- 1))/ GFloat(rows)
for i in o..<rows {
for j in o..<cols {
let x= margin + CGFloat(j) * (grid w+ padding) 
let y = margin + CGFloat(i)*(grid h + padding)
let rect = CGRect(x: x y:y , width: grid_w, height: grid_h)
let fileNamel = iv1[i* cols+ j]
let img1= UIImage(named: fileName1) 
let btn1 = UIButton(frame: rect) 
btnl.setImage(imgl, for:.normal) 
btn1.backgroundColor=.yellow
 btnl.tag = i* cols+ j + 4000
btn1.addTarget(self, action: #selector(buttonCheck( :)),for.touchUpInside)
myView1.addSubview(btn1)
let fileName2 = iv2[i* cols+ j]
let img2 = UIImage(named: fileName2) 
let btn2 = UIButton(frame: rect) 
btn2.setImage(img2, for:.normal) 
btn2.backgroundColor=.yellow 
btn2.tag = i* cols+ j + 5000
btn2.addTarget(self, action: #selector(buttonCheck(_:)),for:.touchUpInside)
myView2.addSubview(btn2)
         }
     }
}


@objc func buttonCheck(_ sender : UIButton){
let tipsLabel = self view viewwithTag(1001) as! UILabel 
let tag = sender.tag 
if tag >= 5000 {
let row = Int ((tag - 5000) / cols)
let col = tag - 5000 - cols * row 
print("Bottom(\(row),\(col))")
tipsLabel.text = "Bottom(\(row),\(col))"
}
 else if tag >= 4000 { 
 let row = Int ((tag - 4000) / cols) 
 let col = tag - 4000 - cols * row 
print("Top(\(row),\(col))")
tipsLabel.text = "Top(\(row),\(col))"
}
else {
print ("Button.tag=\ (sender.tag)")
tipsLabel.text = "Button.tag=\(sender.tag)"
    }
}


func distractorCreate(mount:Int){
for in 0..<mount {
let col = Int(arc4random()) % cols 
let row = Int(arc4random()) % rows

cords.append((row,col))
let index = Int(arc4random()) % images.count
iv1[cols* row + col] = images[index] 
iv2[cols* row + col] = images[index]

    }
}


let rows = 8 
let cols = 8
var ivl : Array<string> = [] 
var iv2 : Array<string> = []
var cords : Array<(Int,Int)> = []
let images : Array<String> = ["bird","bee", "flower" , "mogu"]


func differenceCreate(mount:Int){
for_ in 0..<mount {
let col = Int(arc4random()) % cols 
let row = Int(arc4random()) % rows

errorCords.append((row,col))
let index = Int(arc4random()) % images.count
let which = Int(arc4random()) % 2

if which == 0 {
ivl [cols* row + col] = images[index]
}
else {
  iv2[cols* row + col] = images[index]
        }
    }
}


@objc func buttonCheckMusic(_ sender : UIButton){
let tipsLabel = self.view.viewwithTag(1001) as! UILabel 
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)
}
if result.count >= 1 {
    let path = Bundle.main.path(forResource:"birdsound",ofType:"m4a")
let url = URL(fileURLWithPath: path!)
soundPlayer= try? AVAudioPlayer(contentsof:url) 
soundPlayer.play()
tipsLabel.text="不同找到: (\(row),\(co1))"
}
else{
let path = Bundle.main.path(forResource: "error", ofType:"m4a")
let url = URL(fileURLWithPath: path!)
soundPlayer= try? AVAudioPlayer(contentsOf:url)

soundplayer.p lay()
tipsLabel.tex t = "找错啦: (\(row),\(col))"
    }
}


func getCurrentTimeStamp() -> Int {
let now= Date()
let timeInterval : TimeInterval = now timeIntervalsince1970 
return Int(timeInterval)

func timeElapse() {
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true){
(timer) in
let timestamp= self.getCurrentTimeStamp()
let pastPeriod = timestamp- self.beginTimestamp 
let countDown = self.GamePeriod - pastperiod self.TimeCost= pastPeriod
if countDown <= 0 || self.GameOver {
self.GameOver= true
let tipsLabel = self.view.viewWithTag(1001) as! UILabel 
tipsLabel.text ="游戏结束,共消耗时间\(self.TimeCost)秒" 
timer.invalidate(){
}

let tipsLabel =. self.view.viewWithTag(1002) as! UILabel 
DispatchQueue.mai in.async {
tipsLabel.text	="您消耗\(pastPeriod) 秒,倒计时\(countDown)秒"
        }
    }
}


@objc func buttonCheckMusicTimer(_ sender: UIButton) {
if GameOver {return}
let tipslabel - self.view.viewwithTag(1001) as! UILabel 
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: "birdsound",ofType:"m4a") 
let url= URL(fileURLWithPath: path!)
soundPlayer= try? AVAudioPlayer(contentsOf:url) 
soundPlayer.play()
tipsLabel.text="不同找到:(\(row)\(col)),还剩\(errorCords.count)个"
if errorCords.count <= o {
GameOver = true
tipsLabel.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.play()
tipsLabel.text ="找错啦:(\(row),\(col))"
    }
}


func displayArrayGraphButtonTips(){ 
let myViewl = self view viewwithTag(2001) as! UIImageview 
let myView2 = self view viewWithTag(2002) as! UIImageView 
myViewl backgroundColor=.darkgray 
myView2.backgroundColor=.darkGray 
myViewl.isUserInteractionEnabled = true 
myView2.isUserInteractionEnabled = true
let h= myViewl.frame.size.height 
let w= myView1.frame.size.width

let padding : CGFloat = 5 
let margin : CGFloat = 10
let grid_w = (w- margin* 2- padding* CGFloat(cols- 1)) / CGFloat(cols)
let grid_h = (h- margin * 2 - padding * CGFloat(rows- 1)) / CGFloat(rows)
for i in 0..<rows {
    for j in o..<cols {
        let x = margin + CGFloat(i) * (grid_w + padding) 
        let y = margin + cGFloat(i)*(grid_h + padding)
let rect= CGRect(x: x, y:y , width: grid w, height: grid_h)
 
let fileNamel = iv1[i* cols+ j] 
let tagl = i* cols+ j + 5000
addButton(view: myViewl, rect: rect,fileName: fileNamel,tag:tagl)
 
let fileName2= iv2[i* cols+ j] 
let tag2 = i* cols+ j + 4000
addButton(view: myView2, rect: rect,fileName:fileName2,tag:tag2)
        }
    }

}


func addButton(view:UIView,rect:CGRect,fileName:String,tag:Int){
let img = UIImage(named: fileName) 
let btn = UIButton(frame: rect) 
btn.setImage(img, for:.normal)
var mytag = tag 
if mytag>= 5000 {
    mytag -= 5000
}
else if mytag >= 4000 {
    mytag -= 4000
}
let row = Int (mytag / cols) 
let col = mytag - cols * row

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

if result.count >= 1 && TipsFlag {
    btn.backgroundColor=.blue
}
else {
btn.backgroundcolor = .yellow
}
btn.tag= tag
btn.addTarget(self, action: #selector(buttonCheckMusicTimer (_:)),for:.touchupInside)
view.addsubview(btn)
}
@IBAction func onTips(_ sender : UIButton){
TipsFlag=! TipsFlag
displayArrayGraphButtonTips()
}

@IBAction func onBegin(_sender : UIButton){

GameOver= false

beginTimestamp= getCurrentTimeStamp()
timeElapse() 
initGame()
distractorCreate(mount:5) 
differenceCreate(mount:3)
displayArrayGraphButtonTips()
}


func addButton (view:UIView,rect:CGRect,fileName:String,tag;Int){

}
let img - UIImage(named: fileName) 
let btn = UIButton(frame: rect) 
btn.setImage(img, for: .normal)
var mytag= tag
if mytag >= 5000 {
mytag-= 5000
}
else if mytag >= 4000 {
mytag-= 4000
}
let row = Int (mytag / cols) 
let col = mytag - cols * row
let result = errorCords.filter {
    $0--(row,col)
}

if result.count >= 1 && TipsFlag {
    btn.backgroundColor=.blue 
    btn.tag- tag
    btn.addTarget(self,action: #selector(buttonCheckMusicTimer(:)),for:.touchUpInside)
    view.addsubview(btn)
}

let resultl = cords.filter {
$0== (row,col)
}

if resultl.count>= 1{
btn.tag= tag
btn.addTarget(self,action: #selector(buttonCheckMusicTimer (_:)),for:touchupInside)
view.addSubview(btn)
}

 
func removeAllSubViews(view:UIView){
    if view.subviews.count>0 {
    view.subviews.forEach({$0.removeFromSuperview()})
     }
}

@IBAction func onTips(_ sender : UIButton){
TipsFlag=! TipsFlag
displayArrayGraphButtonTips()
}
@IBAction func onBegin( sender : UIButton){
    GameOver= false
beginTimestamp= getcurrentTimeStamp()
timeElapse() 
initGame()
distractorCreate(mount:10) 
differenceCreate(mount:8)
displayArrayGraphbuttonTips()
}

@IBAction func onNext(_ sender :UIButton){
GameOver= true 
TipsFlag= false
let myViewl = self.view.viewWithTag(2001) as! UIImageview 
let myView2 = self view viewWithTag(2002) as! UIImageView CurrentBackground += 1
if CurrentBackground>4 {
CurrentBackground = 1
}
let image = UIImage(named: "back0\(CurrentBackground)")! 
myView1.image= image 
myView2.image= image
removeAllSuk oViews(view: myView1) 
removeallSuk oViews(view: myView2)