2015-10-06 10 views
-1

我只是編程世界的初學者,因此我有一個簡單的問題。是否可以隨機執行函數?如果是這樣,你會怎麼做?這只是一個基於我在另一個論壇上閱讀的主題的好奇心。基本上,討論的是如何爲遊戲生成隨機事件,並且他們評論了某些語言(特別是AS3)中使用的「黑客」。黑客將把函數當作變量來處理。例如:C#中的隨機事件系統。怎麼做?

//Make an array of the functions 
public function makeEarthquake():void{} 
public function causePlague():void{} 
public function spaceZombieAttack():void{} 

//select at random 
var selection:uint = Math.random() * eventArrray.length; 
//Call it 
eventArray[selection](); 

我希望這很清楚。我會很高興能解釋如何隨機調用方法的任何答案。謝謝。

編輯:謝謝你們,所有的答案是有幫助的!

+0

Techically,你_could_有代表的有幾種方法引用的列表,隨機選擇從列表中的項目並調用委託(又名執行方法)。所以是的,理論上這是可能的,但在實踐中,這聽起來非常危險...... – PoweredByOrange

+0

你可以有'列表'並且使用與你的問題相同的邏輯。 –

+0

在C#中它不是一個破解..只需創建一個代表列表(你當然需要所有事件的相同簽名)並從隨機索引中挑選 –

回答

0

這當然是可能的。一個直接的辦法是有代表的一個列表或數組:

在C#中,它看起來是這樣的:(在基本的控制檯應用程序)

class Program 
{ 
    // Create the functions: 
    static void Beep() 
    { 
     Console.Beep(); 
    } 

    static void SayHello() 
    { 
     Console.WriteLine("Hello!"); 
    } 

    // Create the function delegate: 
    private delegate void RandomFunction(); 

    static void Main(string[] args) 
    { 
     // Create a list of these delegates: 
     List<RandomFunction> functions = new List<RandomFunction>(); 

     // Add the functions to the list: 
     functions.Add(Beep); 
     functions.Add(SayHello); 

     // Make our randomizer: 
     Random rand = new Random(); 

     // Call one: 
     functions[rand.Next(0, 2)](); // Random number either 0 or 1 

     // This is just here to stop the program 
     // from closing straight away should it say "Hello" 
     Console.ReadKey(); 
    } 
} 

獲得這些功能有參數變化的數字需要多一點儘管如此,還是要付出更多努

0

你可以有一個List<Action>和隨機選擇它。

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<Action> actions = new List<Action>(); 

     actions.Add(() => Program.MakeEarthquake()); 
     actions.Add(() => Program.CausePlague()); 
     actions.Add(() => Program.SpaceZombieAttack()); 

     Random random = new Random(); 

     int selectedAction = random.Next(0, actions.Count()); 

     actions[selectedAction].Invoke(); 
    } 

    static void MakeEarthquake() 
    { 
     Console.WriteLine("Earthquake"); 
    } 

    static void CausePlague() 
    { 
     Console.WriteLine("Plague"); 
    } 

    static void SpaceZombieAttack() 
    { 
     Console.WriteLine("Zombie attack"); 
    } 
} 
0

您可以創建行動然後選擇一個列表裏面的物品隨機像下面的代碼清單

List<Action> actions = new List<Action>(); 
    actions.Add(() => makeEarthquake()); 
    actions.Add(() => causePlague()); 
    actions.Add(() => spaceZombieAttack()); 
    var random=new Random(); 
    int rndNumber = random.Next(actions.Count); 
    actions[rndNumber].Invoke(); 
0

爲什麼不挑像往常一樣一個隨機數,然後使用常見的函數內的號碼依次調用基於你得到的功能?

pubic void DoRandomThing() 
{ 
    switch(new Random().Next(1,4)) 
    { 
     case 1: 
      makeEarthquake(); 
      break; 
     case 2: 
      causePlague(); 
      break; 
     case 3: 
      spaceZombieAttack(); 
      break; 
    } 
}