随机数打印数组(Swift)

时间:2016-01-07 23:39:20

标签: swift random

首先,这是我之前提出的问题所以你看到了我想要做的事情。

  

我们正在尝试制作一款小游戏。我们制作了一种怪物格斗游戏。我们为游戏制作了物品,但我希望它们能够被怪物击落。做了不同的类型,并想知道如何编码以获得项目的丢失机会......如

所以现在我知道这是如何工作的我不得不从我的列表中获取一个随机项目。

所以我真正想要的是获得我的" NormalType"的随机项目。我打印时列出..

protocol NormalType {
    var name: String { get }
}

class knife: NormalType {
    let name = "Knife"
    let Str = 10
}
class sword: NormalType {
    let name = "Sword"
    let Str = 20
}
class katana: NormalType {
    let name = "Katana"
    let Str = 30
}


class RareType {
    class Knife: RareType {
        var Str = 10
        var Hp = 10
    }
    class sword: RareType {
        var Str = 20
        var HP = 15
    }
    class Katana: RareType {
        var Str = 30
        var Hp = 20
    }
}

class LegendaryType {
    class Knife: LegendaryType {
        var Str = 10
    }
    class sword: LegendaryType {
        var Str = 20
    }
    class Katana: LegendaryType {
        var Str = 30
    }
}
var Knife = knife()
var Sword = sword()
var Katana = katana()

var Items: [NormalType] = [Knife, Sword, Katana]
var randomnumber = (arc4random_uniform(2))

print(Items[randomnumber])

1 个答案:

答案 0 :(得分:1)

所以你在这里犯了一个小错误的代码:

您忘记转换为Int:(arc4random_uniform(2))

import UIKit

protocol NormalType {
    var name: String { get }
}

class knife: NormalType {
    let name = "Knife"
    let Str = 10
}
class sword: NormalType {
    let name = "Sword"
    let Str = 20
}
class katana: NormalType {
    let name = "Katana"
    let Str = 30
}



class RareType {
    class Knife: RareType {
        var Str = 10
        var Hp = 10
    }
    class sword: RareType {
        var Str = 20
        var HP = 15
    }
    class Katana: RareType {
        var Str = 30
        var Hp = 20
    }

}

class LegendaryType {
    class Knife: LegendaryType {
        var Str = 10
    }
    class sword: LegendaryType {
        var Str = 20
    }
    class Katana: LegendaryType {
        var Str = 30
    }

}
var Knife = knife()
var Sword = sword()
var Katana = katana()

var Items: [NormalType] = [Knife, Sword, Katana]
var randomnumber =   Int(arc4random_uniform(2))



print(Items[randomnumber])