有没有更好的方法来处理Sprite Kit中的结果逻辑? (迅速)

时间:2018-05-18 08:15:02

标签: swift sprite-kit

我正在尝试处理游戏的结果。但我不确定以下是否正确。该方法正在运行,我正在寻找一种更好的解决方案来计算结果。

func result(a: Int, b: Int, z: Int){
    // a: User/Opponent'answer (Int), b: User/Opponent'answer (Int), z: Correct Answer
    let az = abs(a - z)  //User/Opponent based on GameData.shared.userDetected
    let bz = abs(b - z)  //Opponent/User based on GameData.shared.userDetected

    if GameData.shared.userDedected == true {


        if az == bz {
            print("Draw")

        } else if az < bz {
            print("User won az < az")

        } else if bz < az {
            print("User lost bz < az")

        }
    } else if GameData.shared.userDedected == false {
        if az == bz {
            print("Draw")

        } else if az < bz {
            print("User Lost az < bz")

        } else if bz < az {
            print("User won bz < az")

        }
    }
}

2 个答案:

答案 0 :(得分:1)

检查你是否喜欢它,我没有在compilator上检查它:

func result(a: Int, b: Int, z: Int) -> Bool {
    let az = abs(a - z)  //User/Opponent based on GameData.shared.userDetected
    let bz = abs(b - z)  //Opponent/User based on GameData.shared.userDetected

    let userWon:Bool = (az < bz && GameData.shared.userDedected == true) || (az > bz && GameData.shared.userDedected == false) ? true:false

    if az == bz {
        print("Draw")
        return true
    }

    if userWon == true {
        print("Won")
        return true
    }
    else {
        print("Lost")
        return false
    }
}

答案 1 :(得分:1)

你的代码很好,但是如果你想清理它,你可以这样做:

func result(a: Int, b: Int, z: Int){
    // a: User/Opponent'answer (Int), b: User/Opponent'answer (Int), z: Correct Answer
    let az = abs(a - z) * GameData.shared.userDedected ? 1 : -1  //User/Opponent based on GameData.shared.userDetected
    let bz = abs(b - z) * GameData.shared.userDedected ? 1 : -1  //Opponent/User based on GameData.shared.userDetected

    if az == bz {
        print("Draw")
    } else if az < bz {
        print("User won az < bz")
    } else if bz < az {
        print("User lost bz < az")
    }
}

基本上,基于userDedected的值确定是否应该翻转符号

您也可以这样做:

func result(a: Int, b: Int, z: Int){
        // a: User/Opponent'answer (Int), b: User/Opponent'answer (Int), z: Correct Answer
        let value = (abs(a - z)  - abs(b - z) ) * GameData.shared.userDedected ? 1 : -1  //User/Opponent based on GameData.shared.userDetected

        if value == 0 {
            print("Draw")
        } else if value < 0 {
            print("User won az < bz")
        } else if value > 0 {
            print("User lost bz < az")
        }
    }