2013-03-03 75 views
1

是否可以從AS3中的類中取一個隨機常量?如何從課堂上獲得隨機常數?

class Constat 
{ 
    public static const constA:String = "const1"; 
    public static const constB:String = "const2"; 
    ... 

    /** this method must return a random constant */ 
    public static function getRandomConst():String 
    { 
     ------------------------------- 
    } 
} 

回答

2

您可以使用describeType()收集所有在你的類中定義的常量,然後選擇從那裏隨機一個。

public class Constat 
{ 

    public static const constA:String = "const1"; 
    public static const constB:String = "const2"; 

    private static var _constants:Vector.<String>; 


    public static function getRandomConst():String 
    { 
     if(_constants === null) 
     { 
      _constants = new <String>[]; 

      var def:XML = describeType(Constat); 

      for each(var i:XML in def.constant) 
      { 
       _constants.push([email protected]); 
      } 
     } 


     // Select random. 
     var con:String = _constants[ int(Math.random() * _constants.length) ]; 

     return Constat[con]; 
    } 

} 
0

是的,你總是可以將所有的值粘貼到一個數組中並隨機選擇一個。

+0

你能寫出更多的細節嗎?或代碼示例?因爲我沒有找到任何有關如何去做的信息。 – jhard 2013-03-03 10:50:53

+0

你有過數組嗎?這非常簡單。一旦將值添加到數組中,您只需生成一個隨機索引即可從數組中選取一個值。 – mitim 2013-03-03 11:34:04

+0

對不起,也許我不明白你的答案(英語對我來說很難)。我認爲有辦法將這個類轉換爲一個常量數組,然後得到隨機值。 (順便說一句,我剛剛發現如何做到這一點[獲取類的常量](http://stackoverflow.com/questions/11596475/as3-how-can-i-get-an-array-of-a )(但我認爲這個解決方案很慢))在類中存儲具有常量名稱的數組對我來說並不是好的解決方案(如果我現在不支持你的報價)(但工作得很好:) )) – jhard 2013-03-03 12:29:47

0

設置爲常數名稱後跟一個數字。並使用字典方法與Math.random()

試試這個

package { 

    import flash.display.Sprite; 

    public class MyClass extends Sprite 
    { 
     public static const constA:String = "00"; 
     public static const constB:String = "11"; 
     public static const constC:String = "22"; 
     public static const constD:String = "33"; 
     public static const constE:String = "44"; 
     public static const constF:String = "55"; 
     public static const constG:String = "66"; 
     public static const constH:String = "77"; 
     public static const constI:String = "88"; 
     public static const constJ:String = "99"; 
          . 
          . 
          . 

     public function MyClass() 
     { 
      MyClass.test(); 
     } 

     public static function mapped(i:int):String 
     { 
      //65 is A 
      return String.fromCharCode(65+i);     
     } 

     public static function test():void 
     { 
      trace(MyClass["const"+mapped(int(Math.random()*10))]); 
     } 

    } 
} 
+0

感謝您的回答。你的解決方案非常簡單而且很好,但是我的constans的名字是不同的 – jhard 2013-03-03 12:35:44

+0

我編輯過。請檢查。這段代碼優雅。我的想法是映射數字和字母表。 – 2013-03-03 12:49:38

+0

再次感謝你,但你不明白..我寫了constA和constB,但我做了它例如..真正的名字是拉布拉多,羅威納爾等 – jhard 2013-03-03 13:50:05