Shuffle Array, Splice Array. Action script 2

[亡魂溺海] 提交于 2019-12-13 06:19:16

问题


Good afternoon programmers. I am trying to create a game in action script 2. the concept is that the game randomly picks an object. The player has to get the object, then the game calls out a different random object. (these objects are in an array).

static private var oneArray:Array = new Array("milk","cheese","bread");
static private var randomItem:String = oneArray[Math.floor(Math.random() * oneArray.length)];

So you can see I've done this. Now the game will display the text;

    _root.hud.getItem.text = randomItem;

From the code above you can see that the text field will pick a randomeItem from that array.

    if (randomItem == ("milk"))
    {
        if (_root.milk.hitTest(_root.player._x + 60, _root.player._y - 60, true) || _root.milk.hitTest(_root.player._x - 60, _root.player._y - 60, true)) 
        {
            trace("got milk");
            _root.milk.gotoAndStop(2);
        }
    }

The code you see above means that if the text field displays "milk" and if the player touches the milk, then the milk goes away.

Now when the collision is true, I want the textfield to display another random item from the array, but I don't want the same name to appear. I've tried splicing milk from the array but the textfield still displays the text "milk".

It doesn't update basically.

I've tried my best, and sorry if the information provided above isn't the best. Can someone please help me. Thank you.


回答1:


Swap last and random selected item in oneArray, and decrease random multiplier(len) so the last item(previously random selected) will never bother again.

private var oneArray:Array = new Array("milk","cheese","bread");
private var len:int = oneArray.length - 1;
private var rand:int;
private var randomItem:String;

select random item

rand = Math.floor(Math.random() * len);
randomItem = oneArray[rand];
_root.hud.getItem.text = randomItem;

the collision is true

var item:String = oneArray[rand];
oneArray[rand] = oneArray[len];
oneArray[len] = item;
len--;

if (len < 0) { 
    //goto next level
}
else {
   // and select random item again
}


来源:https://stackoverflow.com/questions/22199912/shuffle-array-splice-array-action-script-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!