Monday, April 6, 2015

Generate non repeating random numbers for games in actionscript AS3

When creating games, the random number generation is one of the important elements to avoid a monotonous game play experience.

Generally, it is straightforward to create a random number in actionscript AS3 (Simply use the built-in Math.random() function). But the question is, how to generate a list of random numbers, without any repetition? I used to be a PHP programmer. With PHP, it has an elegant approach with just 2 lines:

$numbers = range(m, n); //manually generate an array storing a list of numbers ranging from m to n
shuffle($numbers); //yes, we have it shuffled already~

Unfortunately, we dont have a similar solution in AS3...
Instead, the solution is:

var arrWanted:Array = [m, m+1, m+2, ... , n]; //manually generate an array storing a list of wanted numbers
var arrRandom:Array = new Array();
while(arrWanted.length > 0)
{
   var intRandom:int = Math.random()*arrWanted.length;
   arrRandom.push(arrWanted[intRandom]);
   arrWanted.splice(intRandom,1);
}

The idea is that, from the wanted list of number, we randomly pick any of them, while reducing them at the same time. In the end, we have our arrRandom filled with a list of random numbers.

I realize that this problem has been solved by others. In this post, particularly, i would like to add a real example of using the non-repeating random numbers generation as well.

Generate random non-repeating cards in Big 2 (Big Two) Card Game



Big 2 (Big Two) is a popular Poker Card Game involving 4 players. At the beginning of each round, each player is provided 13 cards (which total up to 52). In reality, the cards are distributed one by one, clock-wise. However, when dealing with the cards distribution in coding, we could simply apply the random numbers generation stated above.

Lets rewind the codes (AS3 part). With a little bit modification, we would have our jobs done easily.

var arrWanted:Array = new Array();
for(var i:int=0;i<52;i++)
{
  arrWanted.push(i);
}
 

var arrRandom:Array = new Array();
while(arrWanted.length > 0)
{
   var intRandom:int = Math.random()*arrWanted.length;
   arrRandom.push(tmpArr[intRandom]);
   arrWanted.splice(intRandom,1);
}

var arrPlayer1:Array = new Array(); 
var arrPlayer2:Array = new Array();
var arrPlayer3:Array = new Array();
var arrPlayer4:Array = new Array();
for(i=0;i<arrRandom.length;i++)
{
  if(i<13)
  {
    arrPlayer1.push(i);
  }
  else if(i<26)
  {
    arrPlayer2.push(i);
  }
  else if(i<39)
  {
    arrPlayer3.push(i);
  }
  else
  {
    arrPlayer4.push(i);
  }
}

At the end, we have our arrays ready. Each array stores a list of 13 numbers which represent the Poker Cards.

No comments:

Post a Comment