Question

How can I generate a random whole number between 1-10?

I have not got any code at the moment, and nI had a look on online but couldn't find anything. Furthermore I need it so when you hit a tree it will generate a random number, if it is 6 then it will drop an apple. I have the bit for the hitting the tree but nothing else, here is all my code so far:

var count:Number = 0;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var changeCharacter:Boolean = false;
var still:Boolean = false

HeadBodyLegs1st.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);

stop();
HeadBodyLegs1st.gotoAndStop(1)
Tree.gotoAndStop(1)
HeadBodyLegs1st.gotoAndStop(1)


stage.addEventListener(MouseEvent.RIGHT_CLICK,function():void{});

function fl_MoveInDirectionOfKey(event:Event)
{

if (leftPressed)
{
    HeadBodyLegs1st.x -= 15;
    HeadBodyLegs1st.gotoAndStop(3)
}
if (rightPressed)
{
    HeadBodyLegs1st.gotoAndStop(2)
    HeadBodyLegs1st.x += 15;
}
if (Tree.hitTestObject(HeadBodyLegs1st))
{
    count = count + 100;
    Score.text = (count).toString();
    Tree.gotoAndStop(2)
}

if (still)
{
    HeadBodyLegs1st.gotoAndStop(1)
}

}

function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{

    case Keyboard.LEFT:
    {
        leftPressed = true;
        still = false
        break;
    }
    case Keyboard.RIGHT:
    {
        rightPressed = true;
        still = false
        break;
    }
    case Keyboard.SPACE:
    {
        changeCharacter = true;
        break;
    }
}
}

function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{

    case Keyboard.LEFT:
    {
        leftPressed = false;
        still = true
        break;

    }
    case Keyboard.RIGHT:
    {
        rightPressed = false;
        still = true
        break;
    }
    case Keyboard.SPACE:
    {
        changeCharacter = false;
        break;

    }
}
}

Many thanks if solution is found!

Was it helpful?

Solution

Would the following code achieve the goal?

var random:int = Math.floor(Math.random() * 10) + 1;

Basically Math.random() would generate a number from 0 to 1 (1 excluded), multiply the result from Math.random() would return a number from 0 to 10 (but 10 is excluded).

By doing a Math.floor, that would result a random number from 0 to 9, so adding 1 to it would then result a random number from 1 to 10.

OTHER TIPS

 min + (max - min) * Math.random();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top