4.9. 模拟骰子
问题
我要模仿掷骰子
解决办法
用NumberUtilities.random( ) 方法产生指定范围的随机数
讨论
用 random( ) 方法产生整数来模拟掷骰子,这在很多游戏中经常用到,这次我们在ActionScript中实现
一般我们产生随机数然后保存它在使用,如果要重新使用存在的随机数,应保存它而不是再产生新的随机数。注意下面两种情况,第一种,dice总是die1和die2的之和:
var die1:uint = NumberUtilities.random(1, 6);
var die2:uint = NumberUtilities.random(1, 6);
var dice:uint = die1 + die2;
下面的情况,dice和die1和die2没有关系,换句话说,即使die1和die2加起来等于7,dice也不会等于它:
var die1:uint = NumberUtilities.random(1, 6);
var die2:uint = NumberUtilities.random(1, 6);
var dice:uint = NumberUtilities.random(1, 6) + NumberUtilities.random(1, 6);
NumberUtilities.random( ) 还可以模拟多边的骰子:
var die1:uint = NumberUtilities.random(1, 15);
下面的例子模拟了一个骰子
package ...{
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.MouseEvent;
import ascb.util.NumberUtilities;
public class NumbersAndMath extends Sprite ...{
var _die:Sprite;
var _value:uint;
public function NumbersAndMath( ) ...{
_die = new Sprite( );
addChild(_die);
_die.addEventListener(MouseEvent.CLICK, rollDie);
rollDie(null);
}
private function rollDie(event:MouseEvent):void ...{
_value = NumberUtilities.random(1, 6);
_die.graphics.clear( );
_die.graphics.lineStyle( );
_die.graphics.beginFill(0xFFFFFF);
_die.graphics.drawRect(0, 0, 50, 50);
_die.graphics.endFill( );
_die.graphics.beginFill(0x000000);
if(_value == 1 || _value == 3 || _value == 5) ...{
_die.graphics.drawCircle(25, 25, 4);
}
if(_value == 2 || _value == 3 || _value == 4 ||
_value == 5 || _value == 6)
...{
_die.graphics.drawCircle(11, 11, 4);
_die.graphics.drawCircle(39, 39, 4);
}
if(_value == 4 || _value == 5 || _value == 6) ...{
_die.graphics.drawCircle(11, 39, 4);
_die.graphics.drawCircle(39, 11, 4);
}
if(_value == 6) ...{
_die.graphics.drawCircle(11, 25, 4);
_die.graphics.drawCircle(39, 25, 4);
}
}
}
}
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.MouseEvent;
import ascb.util.NumberUtilities;
public class NumbersAndMath extends Sprite ...{
var _die:Sprite;
var _value:uint;
public function NumbersAndMath( ) ...{
_die = new Sprite( );
addChild(_die);
_die.addEventListener(MouseEvent.CLICK, rollDie);
rollDie(null);
}
private function rollDie(event:MouseEvent):void ...{
_value = NumberUtilities.random(1, 6);
_die.graphics.clear( );
_die.graphics.lineStyle( );
_die.graphics.beginFill(0xFFFFFF);
_die.graphics.drawRect(0, 0, 50, 50);
_die.graphics.endFill( );
_die.graphics.beginFill(0x000000);
if(_value == 1 || _value == 3 || _value == 5) ...{
_die.graphics.drawCircle(25, 25, 4);
}
if(_value == 2 || _value == 3 || _value == 4 ||
_value == 5 || _value == 6)
...{
_die.graphics.drawCircle(11, 11, 4);
_die.graphics.drawCircle(39, 39, 4);
}
if(_value == 4 || _value == 5 || _value == 6) ...{
_die.graphics.drawCircle(11, 39, 4);
_die.graphics.drawCircle(39, 11, 4);
}
if(_value == 6) ...{
_die.graphics.drawCircle(11, 25, 4);
_die.graphics.drawCircle(39, 25, 4);
}
}
}
}
没有评论:
发表评论