编辑代码


//4.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 = myViewl.frame. size.width

    let padding: CGFloat = 5
    let margin : CGFloat = 10

    //计身每个格于的高度和笕度
    let grid_w = (w - margin * 2 - padding * CGFloat (cols-1)) / CGPloat (cols)
    let grid_h = (h - margin * 2 - padding * CGrloat (rows-1)) / CGFloat (rows)

    for i in 0..<rows{
        for J in 0..<cols{
            let × = 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)
            
            //在上面的Imageview 中显
            let fileNamel = iv1 [i*cols+j].
            let img1 = UIImage (named: fileName1)
             Let imgView1 = UIImageView (frame: rect)
            imgView1.image = img1
            imgView1.backgroundColor = .yelLow
            myView1.addSubview(imgViewl)
            //在下面的Imageview 中显示
            Let fileName2 = iv2 [i*coIs+j]
            let img2 = UIImage (named: fileName2)
            let imgView2 = UIImageView (frame: rect)
            imgView2.image = img2
            imgView2.backgroundColor = .yellow
            myView2.addSubview (imgView2)
        }
    }
}


//4.2.2基础功能


//2图形化函数支持Button
//函数3:图形化显程序,支持Button
func displavArrayGraphButton () {
    let myView1 = self.view.viewWithTag (2001) as! UIImageView
    let myView2 = self.view.viewWithTag (2002) as! UIImageView
    myView1.backgroundColor = .darkGray
    myView2.backgroundcolor = .darkGray
    //支持View 可以进行交互等操作
    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 0..<cols {
            let x = margin + CGFloat (j) * (grid w + padding)
            let y = margin + CGFloat (i)* (grid h + padding)
            Iet rect = CGRect (x: x, y:y , wiath: grid_w, height: grid_h)
            // 在上面的Imageview 中显示
            let fileNamel = iv1 [i*cols+j]
            let img1 = UIImage (named: fileName1)
            let btn1 = UIButton (frame: rect)
            btn1.setImage (img1, for: .normal)
            btnl.backgroundcolor = .ye11ow
            //Button的tag 设定为 4000及以上
            btnl.tag =i*cols+i+4000
            btn1.addlarget (self, action: #selector (buttonCheck (_:)), for: .touchUpInside)
            myView1.addSubview (btnl)
            //在下面的Imageview 中並示
            let fileName2 = iv2 [i*cols+j]
            Let img2 = UIImage (named : fileName2)
            let btn2 = UIButton (frame: rect)
            btn2.setImage (img2, for: .normal) 
            btn2.backgroundcolor = .yellow
            //Button的tag设定为5000及以上
            btnz.tag = i*cols+j + 5000
            btn2.addTarget (self, action: #selector (buttoncheck _: )) ,for: .touchUpInside
            myView2.addSubview (btn2)
        }
    }
}



//Button事件的响应函数


//函数4:不同点的Button被单击后调用
@obic func buttoncheck (_ sender : UIButton) {
    let tipsLabel = self.view .viewwithTag (1001) as! UILabel
    let tag = sender.tag
    if tag >= 5000 {
        let row = Int ((tag = 5000) / co1s)
        1et co1 = tag - 5000- cols * row
        print ("Bottom (\ (row), \ (col)) ")
        tipsLabel.text = "Bottom (\ (row), \ (col)) "
    }
    else if tag >= 4000{
        let row = Int((tag - 4000)/ co1s)
        let col = tag - 4000 - co1s * row
        print ("Top (\ (row), \ (col)) ")
        tipsLabel.text = "Top (\ (row) , \ (col) ) "
    }
    else {
        print ("Button.tag=\ (sender.tag) ")
        tipsLabel.text = "Button.tag=\ (sender. tag)"
    }
}



//相同干扰项函数

//函数5:生成干扰项的随机位置和随机内容
    func distractorCreate (mount: Int) {
        for _ in 0..<mount {
        let col = Int (arc4random () ) % cols
        let row = Int (arc4random () ) % rows

        cords .append ( (row, col))

        // 从images 提供的字符中选择一个

        let index = Int (arc4random () ) % images.count

        //影响iv1和iV2这两个图形

        ivl [cols*row + col] = images [index]
        iv2 [cols*row + col] = images [index]
    }
}


//新增定义数据

//定义数据开始--
//定义行数和列数
    let rows = 8
    let co1s = 8
//定义上下两个图形组
    var ivl : Array<string> = []
    var iv2 : Array<string> = []
//定义上下相同的千扰项数组
    var cords : Array< (Int, Int)> = []
// 千扰项和不同项只能是小图形
    let images : Array<string> = ["bird", "bee", "flower", "mogu"]
//数据定义结束--



//4.2.3音效功能


//函数6:生成不同项的随机位置和随机内容
    func differencecreate (mount: Int) {
        for _ in 0..<mountt {
        let col = Int (arcarandom ()) % COls
        let row = Int (arcArandom ()) & rows

        errorcoras.append ( (row, col))
        //人images 提供的字符中选择一个
        let index = Int (arc-random ( )) % images.count
        // 选择上面图形,还是下面图形?
        let which = Int (arc4random ( )) % 2
        //影响iV1和iv2这两个图形
        if which == 0 {
            iv1 [cols*row + col] = images [index]
        }
        else{
            iv2 [cols*row + col] = images [index]
        }
    }
}



//修改Button函数支持音效

// 函数7:不同,点的Button 被单击后调用,支持音效
    @objc func buttonCheckMusic (_ sender : UIButton) {
        let tipsLabel = self.view.viewnithTag (1001) as! UILabel
        var tag = sender.tag
        if tag >= 5000 1
            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="不同找到:(1(row),1(co1))"
        }
        else {
            let path = Bundle. main.path (forResource: "error", ofType:"m4a")
            let url = URL (fileURLWithPath: path!)
            soundPlayer=try? AVAudioPlayer (contentsOf: url)
            soundPlayer.play()
            tipsIabel.text = "找错啦:(\(row) , \(co1))"
        }
    }
//


//4.2.4计时功能
//定时器倒计时函数

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

//函数9:定时器倒计时 涵数,显示当前消耗时间和倒计时
func timeELapse() {
    Timer .scheauledlimer(withrimeInterva_: 0.5, repeats : true) { (timer) in
    let timestamp = self.getCurrentlimestamp ()
    let pasteriod = timestamp - self.beginlimestamp
    let countDown = self.GamePeriod - pastPeriod
    self.TimeCost = pastPeriod
    if countdown <= O || sell.GameOver{
        self.GameOver = true
        let tipsLabel = self.view.viewWithTag (1001) as! UILabel
        tzpSLabeL.text = "游戏结束,共消耗时间\ (self.Timecost)秒"
        timer.invalidate ()
    }
        let tipsLabel = self.view.viewwithTag (1002) as! UILabel
        DispatchQueue .main.async{
            tipsLabel.text="您消耗\(pastPeriod)秒,倒计时\(countDown)秒"
        }
    }
}

//修改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.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 ()
        tipsIabei.text= "不同找到:(\(IOW),\(COL)),还剩\(errOrCords.count)个"
        if errorcords.count <= 0 {
            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 ()
        tipstabel.text = ⋯ "找错啦:(\(row),\(co1))"
    }
}

//4.2.5游戏提示和关卡
//函数11:图形化显示程厅,支持 Button,支持提示功能
func dispLayArrayGraphButtonlips() {
    Let myViewl = self.view .viewWithTag (2001) as! UIImageView
    Let myView2 = self.view.viewWithTag (2002) as! UlImageView
    myViewl.backgroundColor = .darkGray
    myView2.backgroundColor = .darkGray
    //支持View可以进行交互等操作
    myView1.isUserInteractionEnabled = true
    myview2.isUserInteractionEnabled = true

    let h = myView1.frame.size.height
    let w = myView1.frame.size.width

    let padding: CGFloat = 5
    let margin: CGFloat = 10

    //计算每个格子的高度和宽度
    let gria_w = (w - margin * 2 - padding * CGFloat(cols-1)) / CGFloat (cols)
    let grid h = (h - margin * 2 - padding * COPloat (rows-1)) / COFIas (rows)
    for i in 0..<rows {
        for j in 0..<cols {
        let x a margin + cGEloat (j)* (grid_ w + paddino)
        let y = margin + cGFloat (i)* (grid_h + padding)
        let reot = ceRect (x: x, y:y , wiath: gria w, height: grid b)

        //在上面的Imageview 中显示
        let fileNamel = iv1 [i*colst+j]
        let tag1 = i*cols+j + 5000
        addButton (view: myViewl, rect: rect, fileName: fileNamel,tag: tag1)

        //在下面的Imageview 中显示
        let fileName2 = iv2ri*cols+i1
        let tag2 = i*cols+j + 4000
        addButton (view: myView2,rect: rect, fileName : fileName2,tag: tag2)
        }
    }
}
// 函数 12:View 上面添加 Button 的函数,提示功能,用于减少代码数量
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 {0
        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 ()
}


//关卡设置

    //函数12:View上面添加Button的函数,提示功能,用于减少代码数量
func addButton (view: UIView, rect:CGRect, tileName : 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 resulti = cords.filter {
        $0 == (row, col)
    }
    if resulti.count >= 1 {
        btn.tag = tag
        btn.addTarget (self, action: #selector (buttonCheckMusicTimer (_:)),for: touchUpInside)
        view.addSubview (btn)
    }
}

//函数13:移除所有子控件
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 mviewl = self. view. viewWithTag (2001) as! UIImageview
    let mwView2 = self. view.viewwithTag (2002) as! UlImageView
    CurrentBackground += 1 
    if CurrentBackground > 4 {
        CurrentBackground = 1
    }
    let image = UIImage (named: "back0\(CurrentBackground)") !
    myView1.image = image
    myView2.image = image
    removeAllSubViews(views: myiew1)
    removeAllSubViews(view: myView2)
}


//4.3.2登录界面的实现

//
// ContenView.swift
// LoginsSwiftUI
//
// Creat by zhifeng Chen on 2020/8/1
// Copright 2020 zhifeng Chen. All rights reserved.
//

import SwiftUI

struct ContentView : View {

    @State var userName : String = ""
    @State var passWord : String = ""

    var body: some View {
        vstack {
            Text ("欢迎使用找不同" )
                .font (.title)// 字体大小カ栐題
                .padding() // 四周同隔
            Divider()
                .background (Color (.brown))// 背景色力 brown
            Image (systemName:"person")// 系統圏像 person
                .resizable()// 允许政变图像尺寸
                .Erame (width: 150, height: 150)//尺寸政力 150+150
                .cornerRadius (50)// 園角半径 50

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

            .Button (action:{
                print("被点击了。..")
            },label: tText {("登录")})
                .padding ()
            Spacer ()
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

//登录界面

import SwiftUI

let lightGrayColor = Color (red: 239.0/255.0, green: 243.0/255.0, blue:244.0/255.0, opacity: 1.0)
    
struct ContentView:View {

    //保存输入的用戸名
    @State var userName : String = ""
    //保存输入的密码
    @State var passWord : String = ""
    //是否需要弹出Alert窗口
    @State private var alertFlag : Bool = false
    //弹出窗口里面的具体内容
    @State private var alertMsg : String = ""
    var body: some View {
        VStack {
            Text("欢迎使用找不同")
                .font(-tit1e)// 字体大小为标题
                .padding ()// 四周间隔
            Divider ()
                .background (Color (.brown))// 背景色为brown
            Image ("back02")//图片back02.png
                .resizable()//允许修改图像尺寸
                .frame (width:150, height:150//尺才改为 150*150
                .cornerRadius (150)//圆角半径 50

            VStack {
                Textpiela("请输入用户名",text:suserName)
                    .padding (// 四周默认间隔
                    .padding (.leading, 10// 前方问隔10
                    .background (lightGravcolor)// 背景色
                    .cornerRadius (15)//圆角半径 15
                Taxtpield ("请输入密码",text:$passnord)
                    .padding ()//四周默认间隔
                    .padding (.leading, 10)// 前方间隔 10
                    .background (1ightGrayColor)// 背景色
                    .cornerRadius (15)//圆角半径15
            }
            padding () //四周默认间隔

            Button (action: {
                if self.userName=="Zfchen" && self.password== "123" {
                    self.alertFlag = true
                    self.alertMsg= "登录成功"
                }
                else {
                    self.alertFlag = true
                    self.alertMsg ="登录失败"
                }
            },label: {
                Text(" 登录")
                    .font (.headline)
                    .foregroundColor (.white)
                    .frame (width: 220, height: 60) 
                    .background (Color.green) 
                    .cornerRadius (15.0)
            })
            .padding ()
            Spacer ()
        }
        .alert(ispreseented: $alertFlag) { () -> Alert in
            Alert(title: Text("登陆提示"), message: Text(self.alertMsg),dismissButton: .default(Test("确定")))
        }
    }
}
struct Contentview_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}