AS3:如何生成10到20之间的随机数

时间:2014-07-26 14:10:05

标签: actionscript-3 flash

我一直在尝试在Flash中生成一个随机数。我一直在看视频并复制它们,但是当我点击按钮时,文本框中的数字不会出现。

以下是我在air ios游戏中编写的代码:

import flash.events.MouseEvent;
//creating the  vars
var difficulty;

//listening for the play button to be clicked
play_button.addEventListener(MouseEvent.CLICK, letsgotoframe2);


//and after the listening what do the computer do!
function letsgotoframe2(event:MouseEvent):void
{
    gotoAndStop(2)
    }



//listening for the easy button to be clicked
Easy_button.addEventListener(MouseEvent.CLICK,letsgoeasy)






//what  will it do when it is clicked
function letsgoeasy(e:MouseEvent):void{
    difficulty = 1;
   var rand = (Math.random()*20)
   txt.text = String (rand);
   gotoAndStop(rand);
}

PS:抱歉结构不好这是我的第一篇文章!

3 个答案:

答案 0 :(得分:3)

这将为您提供0到10之间的数字(包括):

Math.floor( Math.random() * 11 )

现在,只需添加10即可,您将得到10到20之间的数字:

10 + Math.floor( Math.random() * 11 )

我假设你想要整数。如果你想要实数,删除Math.floor并将11改为10(你的上限不会是20,不过,我将是19,99等)

答案 1 :(得分:0)

这是一个函数,它将为您提供min和max之间的随机整数:

function random(min:int = 0, max:int = int.MAX_VALUE):int
{
    if (min == max) return min;
    if (min < max) return min + (Math.random() * (max - min + 1));
    else return max + (Math.random() * (min - max + 1));
}

var r = random(10, 20);

答案 2 :(得分:0)

如果没有看到.FLA中时间轴的组成,就很难诊断出您遇到的这个问题,因为您的代码可能会出现一些导致此问题的事情。

<强>的问题:

  1. 由于尚未提供时间轴的结构,因此我无法假设您已在第10帧到第20帧的时间轴上正确设置了实例名称为txt的TextField。我'我只是假设第20帧是最大的,因为你问我们10到20之间的随机数。
  2. 调用Math.random()函数会产生实数,而不是整数。因此,在int中使用该值之前生成一个随机数而不将其转换为gotoAndStop将是一个问题。
  3. 因此,为了解决这些问题,我建议如下:

    1. 确保您的TextField确实存在于第10帧到第20帧的时间轴上。这可以通过两种方式之一完成。第一个是查看时间轴并确保TextField存在的图层,帧数在10到20之间。或者您只需检查第10帧到第20帧,看看TextField是否存在于这些帧上。同样,如果没有看到您的时间轴结构,我们很难确定这些部分是否设置正确。
    2. 您需要将随机数转换为int才能在gotoAndStop声明中正确使用。
    3. 这是您的代码,经过修改以修复播放问题;但是,您必须手动检查TextField的存在:

      import flash.events.MouseEvent;
      //creating the  vars
      var difficulty;
      
      //listening for the play button to be clicked
      play_button.addEventListener(MouseEvent.CLICK, letsgotoframe2);
      
      
      //and after the listening what do the computer do!
      function letsgotoframe2(event:MouseEvent):void
      {
          gotoAndStop(2);
      }
      
      //Easy Button Handler
      function letsgoeasy(e:MouseEvent):void{
         difficulty = 1;
         var rand:int = Math.floor( (Math.random()*11) + 10 );
         txt.text = String (rand);
         gotoAndStop(rand);
      }
      
      //Create listener for the easy button
      Easy_button.addEventListener(MouseEvent.CLICK,letsgoeasy)
      
相关问题