jeudi 27 avril 2017

Bool doesn't return correctly (Swift 3.0)

I'm pretty much new to programming and I want to learn Swift 3.0.

I've been trying to write my own TicTacToe-Game but somehow the bool return doesn't work the way I want when I check for a winner...

The CheckWin() function looks like this:

func CheckWin() -> Bool
{
if button1.titleLabel?.text == button2.titleLabel?.text && button2.titleLabel?.text == button3.titleLabel?.text && button1.titleLabel?.text != ""
{
return true
}
else
{
return false
}
//and so on...

my Problem is, when I click on a Button it fills the Button with an "X" or an "O" and afterwards i call the CheckWin() function via an if-statement but it sets the Labeltext to "Won!" after the NEXT time i click on a button. Instead of immediately checking it and setting the Labeltext to "Won!".

@IBAction func buttonClick(_ sender: UIButton)
{
    if sender.titleLabel?.text == ""
    {
         if player%2==0
         {
              sender.setTitle(playerx, for: UIControlState.normal}
              player += 1  //Adds 1 to the variable player
              turn += 1    //Adds 1 to the variable turn (to check later for a draw)
         }
         else
         {
              sender.setTitle(playero, for: UIControlState.normal)
              player += 1
              turn += 1
         }
    }
    if CheckWin()
    {
    label.text = "Won!"
    }
}

I appreciate any help/tips! Thanks in advance!

(By the way, I know that it's not such a good idea to create an outlet for each Button, but at first I just want to get this thing working before I start improving) :)

Aucun commentaire:

Enregistrer un commentaire