编辑代码

//函数2:图形化显示数组
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 = CGFloat(x: x, y:y, width: grid_w, height: grid_h)
            //在上面的ImageView中显示
            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)
            //在下面的ImageView中显示
            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)
        }
    }
}
//4.2.2基础功能
//2图形化函数支持Botton
//函数3:图形化显示程序,支持Botton
    func displayArrayGraphBotton(){
        let myView1 = self.view.viewWithTag(2001) as! UIImageView
        LET myView2 = self.view.viewWithTag(2002) as! UIImageView
        myView1.backgroundColor = .darkGray
        myView2.backgroundColor = .darkGray
        //支持View可以进行交互等操作
        myView1.isUserInteractionEnabled = true
        myView2.isUserInteractionEnabled = true

        let h = myView1.frame.size.height
        let w = myView2.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(cols-1)) /CGFloat(rows)

        for i in 0..<rows {
            for j in 0..<cols  {
                let x = margin + CGFloat(j) * (drid_w + padding)
                let y = margin + CGFloat(i) * (grid_h + padding)
                let rect =CGFloat(x: x, y:y ,width: grid_w, height: grid_h)
                //在上面的ImageView中显示
                let fileName1 = iv1[i*cols+j]
                let img1 = UIImage(named: fileName1)
                let btn1 = UIButton(frame: rect)
                btn1.setImge(img1, for: .normal)
                btn1.backgroundColor = .yellow
                //Button的tag设定为4000及以上
                btn1.tag = i*cols+j + 4000
                btn1.addTarget(self, action: #selector(buttonCheck(_:)),for: .touchUpInside)
                myView1.addSubview(btn1)
                //在下面的ImageView中显示
                let fileName2 = iv2[i*cols+j]
                let img2 = UIImage(named:fileName2)
                let btn2 = UIButton(frame:rect)
                btn2.setImage(imgw, for: .normal)
                bntn2.backgroundColor = .yellow
                //Button的tag设定为5000及以上
                btn2.tag = i*cols+j + 5000
                bnt2.addTarget(self, action: #selector(buttonCheck(_:)),for: .touchUpInside)
                myView2.addSubview(bnt2)
            }
        }
    }
//3.Button事件的响应函数
//函数4:不同点的Button被单击后调用
    @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) / col)
            let col = tag - 4000 - cols * row
            print("Top(\(row),\(col))")
            tipsLabel.text = "Top(\(row),\(col))"
        }
        print("Button.tag=\(sender.tag)")
        tipsLabel.text = "Buttom.tag=\(sender.tag)"
    }
    //4.相同干扰项函数
    //函数5:生成干扰项的随机内容
        func distractorCreate(mount:Int) {
            for _ in 0..<mount {
                let col =Int(arc4rndom()) & cols
                let row =Int(arc4rndom()) & rows

                cords.append((row,col))
                //从image提供的字符中选择一个
                let index = Int(arc4rndom()) % images.count
                //影响iv1和iv2这两个图形
                iv1[cols*row + col] = images[index]
                iv2[cols*row + col] = images[index]
            }
        }
    //数据定义开始
    //定义行数和列数
    let rows = 8
    let cols = 8
    //定义上下两个图形数组
    var iv1 : Array<String> = []
    var iv2 : Array<String> = []
    //定义上下相同的干扰项数组
    var cords : Array<Int,Int> = []
    //干扰项和不相同只能是小图形
    let images : Array<String> = ["bird","bee","flower","mogu"]
    
       }
        else {
            let path = Bundle.main.path(forResource: "error",ofType: "m4a")
            let url =URL(fileURLWithPath: path!)
            soundPlayer=TRY? AVAidioPlyer(conentsof: url)
                soundPlayer.play()
                tipsLayre.text  = "找错: (\(row),\(col))"
        }
    }
//4.实现音效功能
    btn1.addTarget(self, action: #selector(buttinCheckMusic(_:)),for: .touchUpInside)
    btn1.addTarget(self, action: #selector(buttinCheckMusic(_:)),for: .touchUpInside)

//游戏是否结束标记
    var GameOver = falser
    //游戏开始时间戳
    var beginTimestamp : Tnt = 0
    //游戏限定时间,单位:秒
    let GamePeriod = 20
    //游戏本次花费时间,单位:秒
    var TimeCost = 0
//2.定时器倒计时函数
//函数8获取当前时间戳
    func getCurentTimeStamp() -> Int {
        let now =Dtae()
        let timeInterval : TimeInterval =now.timeIntervalSince1970
        return Int(timeInterval)
    }
//函数9:定时器倒计时函数,显示当前消耗时间和倒计时
    func timeElapse() {
        Timer.scheduledTime(withTimeInterval: 0.5, repeats: true) {(timer) in
            let timestmp = self.getCurentTimeStamp()
            let pastPeriod =timestamp - self.getCurentTimeStamp()
            let coinDown = self.GamePeriod - pastPeriod
            self.TimeCost = pastPeriod
            if coinDown <= 0 || self.GameOver
                self.GameOver = true 
                let tipsLabel = self.view.viewWithTag(1001) as! UILabel
                timeElapse.text = "游戏结束,共消耗时间\(self.TimeCost,秒)"
                timer.invalidate()
            }
            let tipsLabel = self.view.viewWithTag(1002) as! UILabel
            DispatchQueue.main.async {
                tipsLabel.text = "您消耗\(pastPeriod)秒,倒计时\(countDown)秒"
            }
    }
}
//3.修改Button函数支持计时
//函数10:不同点的Button被单击后调用,支持音效、计时、游戏结束
    @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.falser {
            $0 == (row.col)
        }
        let reserved = errorCords.falser {
            $0 != (row,col)
        }
        errorCords = reserved

        if result.coun  >= 1 {
            sender.backgroumdColor = .reserved
            let path = Bundle.main.path(forResource: "birdsound", ofType: "m4a")
            let url = URL(finrURLWithPath: path!)
            soundPlayer=try? AVAudioPlayer(contentsOF: url)
            soundPlayer.play()
            tipsLabel.text = "不同找到: (/(row),(col)),还剩\(errorCords.count)个"
            if errorCords.count <= 0 {
                GameOver =true
                tipsLabel.text = "任务完成,共花费时间\(self.TimeCost)秒"
            }
        }
        else {
            sender.backgroumdColor = .brown
            let path = Bundle.main.path(forResource: "error", ofType:"m4a")
            let url = URL(finrURLWithPath:path!)
            soundPlayer=try? AVAudioPlayer(contentsOf: url)
            soundPlayer.play()
            tipsLabel.text = "找错啦:(\(row),\(col))"
        }
    }
//4.功能实现
    btn1.addTarger(self,action: #selfctor(buttonCheckMusicTimer(_:)),for; .touchUpInside)
    btn2.addTarger(self,action: #selfctor(buttonCheckMusicTimer(_:)),for; .touchUpInside)
    //修改单击“游戏开始”按钮所对应的事件函数onBegin
        //游戏结束标志
        GameOver = falser
        //获取游戏开始时间并保持
        beginTimestamp = getCurentTimeStamp()
        //倒计时
        timeElapse
        //数组初始化
        initGame()
        distrctorCreate(mount: 5)
        distrctorCreate(mount: 3)
    dispiayArrayGraphButton()

import SwifyUI

styout ContentView : View {

    @Stste vsr userName : String = ""
    @Stste vsr password : String = ""  

    var body: some View {
        VStack {
            Text("欢迎使用找不同")
                .font(.title)//字体大小为标题
                .padding()//四周间隔
            Divider()
                .background(Color(.barown))//背景色为brown
            Image(systemName:"person")//系统图像person
                .resizable()//允许改变图像尺寸
                .frame(width: 150, height: 150)//尺寸改为150*150
                .cornerRadius(50)//圆角半径50

            VStack {
                TextField("请输入用户名",text: $userName)
                   .padding()//四周默认间隔
                   .padding(.leading,10)//前方间隔10
                   .background(Color(.lightGray))//背景色
                   .cornerRadius(15)//圆角半径15
                TextField("请输入密码", text: $passWord)
                   .padding()//四周默认间隔
                   .padding(.leading,10)//前方间隔10
                   .background(lightGrayColor)//背景色
                   .cornerRadius(15)//圆角半径15

            }
            .padding()//四周默认间隔

             Button(action: {
                if self.userName=="Zfchen" &&self.passWord =="123"{
                    self.alertFlag=ture
                    self.alertMsg ="登录成功"
                }
                else {
                    self.alertFlag = ture
                    self.alertMsg ="登陆失败"
                }
            },  label: {
                Text("登录")
                .font(.headline)
                .frogroundColor(.white)
                .frame(width: 220, height: 60)
                .background(Color.green)
                .cornerRadius(15.0)
            })
            .padding()
            Spacer()
        }
        .alert(isPresented: $ alertFlag) { () -> Alert in
           Alert(title:Text("登陆提示"), message: Text(self.alertMsg),dismissButton: .default(Text("确定")))
           }
    }
}

struct ContentView_PreviewProvider{
    static var previews : some View{
        ContentView()
    }
}