Search code examples
iosarraysswiftxcodeuiimageview

make comparisons between 2 dice toss in an IOS app


I have an app with 2 image views. each one randomly displays an image of a dice face (from 1 to 6), the end results looks like the simulation of a dice toss for a player and for the computer.

it looks like this :

enter image description here

I have an array that contains the names for each image that is displayed : let des: Array = ["one", "two", "three", "four", "five", "six"]

I also have a function that randomizes the image that is displayed for the 2 players

        UIView.animate(withDuration: 0.5) {
            self.dicePlayer.image = UIImage(named: self.des.randomElement() ?? "one")
            self.diceComputer.image = UIImage(named: self.des.randomElement() ?? "two")

        }
        // on appelle la fonction qui gere les scores
        gestionDesScores()
    } 

I would like to make comparison between those 2 tosses (i.e : if player one dice toss is superior to player 2 toss, then the player wins and vice versa).


Solution

  • I would recommend storing the two tosses as human readable Int values. Add these properties to your class:

    var playerToss = 1
    var computerToss = 1
    

    Then modify your function like this:

    func lancerDeDes() {
        self.playerToss = Int.random(in: 1...6)
        self.computerToss = Int.random(in: 1...6)
    
        UIView.animate(withDuration: 0.5) {
            // subtract 1 because des array is indexed 0...5 not 1...6
            self.dicePlayer.image = UIImage(named: self.des[self.playerToss - 1])
            self.diceComputer.image = UIImage(named: self.des[self.computerToss - 1])
    
        }
        // on appelle la fonction qui gere les scores
        gestionDesScores()
    } 
    

    Then you can just compare playerToss and computerToss directly:

    if self.playerToss > self.computerToss {
        // the player wins!
    }
    

    Storing the values as Int will aid you in debugging in addition to making the comparison easier.


    Magic Numbers

    In your program, I think it is clear what 6 represents. In general though it is wise to avoid magic numbers (uncommented numbers) in your code. So you could write the rolls as:

    self.playerToss = Int.random(in: des.indices) + 1
    self.computerToss = Int.random(in: des.indices) + 1
    

    By using des.indices to obtain the range 0...5 from the des array, you ensure that the code would work correctly even if the number of values in the des array changed.

    I personally would still store the rolls in the range 1...6 for debugging purposes, but you could avoid the + 1 and - 1 by storing the rolls in the range 0...5.