Kolon E.T.
Kolon E.T.

Reputation: 13

Randomly pick variables and give them one value AS3

I want to make an flash application which picks and gives it one value between four variables randomly. So I wrote this code:

import flash.events.Event;

var max:int = 100;
var red:int = 0;
var yellow:int = 0;
var orange:int = 0;
var blue:int = 0;

function updateChart():void
{
var total:int = red + yellow + orange + blue;
redbar.height = red / total * max;
yellowbar.height = yellow / total * max;
orangebar.height = orange / total * max;
bluebar.height = blue / total * max;

redres_txt.text = String(red);
yellowres_txt.text = String(yellow);
orangeres_txt.text = String(orange);
blueres_txt.text = String(blue);
total_txt.text = "Total: " + String(total);
} 
Vote_Button.addEventListener(MouseEvent.CLICK, onRedClick);
function onRedClick(evt:MouseEvent):void
{
var randomSelector:Array = [red, yellow, orange, blue];
var random:* = randomSelector[Math.floor(randomSelector.length * Math.random())];
random++;
updateChart();
}

This is the whole code. The problem is; when i click the button, the numbers returns to zero and other clicks doesn't affect. The fla file is here if you want to look at it: https://drive.google.com/file/d/0B2f6Y60ccirBamt1RThKV2VqSjg/edit?usp=sharing

Thanks.

Upvotes: 1

Views: 76

Answers (1)

Ivan Chernykh
Ivan Chernykh

Reputation: 42166

Change your onRedClick handler like this:

function onRedClick(evt:MouseEvent):void
{
  var randomSelector:Array = ["red", "yellow", "orange", "blue"];
  var random:String = randomSelector[randomSelector.length * Math.random() | 0];
  this[random]++;
  updateChart();
}

Upvotes: 3

Related Questions