Swift中的逻辑问题

时间:2016-12-19 16:45:14

标签: ios swift if-statement swift3

我在Swift 3中创造了一个小游戏并且越过了游戏。我想要一个警报来显示游戏何时获胜,但我的获胜逻辑出现了一些我看不到的错误。

出于某种原因,警报工作等,但用户可以点击任何地方,即使我已经明确说明了要触摸的地方,它也会出现。所以我试图说的方法是,如果三个图像=彼此,如果不是user = 1,则user = 2.如果user = 1,则触发win警报。但是,无论如何,每当用户触及胜利者时,它就会变为1。任何人都可以阐明为什么会这样吗?

目前仅在水平获胜功能中调用

alert()以节省时间等。

class ViewController: UIViewController {

@IBOutlet var cross: UIImage!
@IBOutlet var nought: UIImage!
@IBOutlet weak var image1: UIImageView!
@IBOutlet weak var image2: UIImageView!
@IBOutlet weak var image3: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    cross = UIImage(named: "Cross.png")
    nought = UIImage(named: "Naught.png")


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
var gamepiece = 1
var whowon = 0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let user = event?.allTouches!.first!
        if image1.frame.contains((touch?.location(in: self.view))!) {
            if user == 1{
                image1.image = cross
                user = 2

                }
            else{
                image1.image = nought
                user=1
            }
        }
        if image2.frame.contains((touch?.location(in: self.view))!) {
            if user == 1{
                image2.image = cross
                user = 2
            }
            else{
                image2.image = nought
                user=1                    
                }
            }
        if tR.frame.contains((touch?.location(in: self.view))!) {
            if user == 1{
                image3.image = cross
                user = 2                    
        }
        else{
            image3.image = nought
            user=1                    
        }
    }

}

func win(){
    if (image1.image == image2.image || image2.image == image3.image){
        whowon = 1
        alert()
    }
    return true
}
func alert(){
    if (whowon == 1){
        let winner = UIAlertController(title: "", message: "Well done.", preferredStyle: .alert)

        let action1 = UIAlertAction(title: "", style: .default) { (alert: UIAlertAction!) -> Void in self.turn.text =  ""
        self.resetBoard()
        }

        let action2 = UIAlertAction(title: "", style: .default) { (alert: UIAlertAction!) -> Void in self.turn.text =  ""
        }

    winner.addAction(action1)
    winner.addAction(action2)        

}

1 个答案:

答案 0 :(得分:1)

这是因为当图像视图中没有图像时,image属性会返回nil

让我们说你在这里放了一个十字架:

x| |
-|-|-
 | |
-|-|-
 | |

注意第二列中的所有图像视图都没有图像?当您比较他们的image属性时,他们都是nil!众所周知,nil等于nil,因此条件成立。要避免这种情况,只需检查其中一个图像视图是否没有图像。 e.g。

(image1.image == image2.image && image2.image == image3.image && image3.image != nil)