I am making a game that when you click on the Monster your score gets +1. But when your score goes over 1000 I would like it like this 1,000 rather than 1000. I am not sure how to do this as I have not learnt much action script. I have embed number and punctuation into the font. Here is my code so far:
var score:Number = 0;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
Monster.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler);
function fl_TapHandler(event:TouchEvent):void
{
score = score + 1;
Taps_txt.text = (score).toString();
}
Help will greatly appreciated.
You can do like that:
function affScore(n:Number, d:int):String {
return n.toFixed(d).replace(/(\d)(?=(\d{3})+\b)/g,'$1,');
}
trace(affScore(12345678, 0)); // 12,345,678
This may not be the most elegant approach, but I wrote a function that will return the string formatted with commas;
public function formatNum(str:String):String {
var strArray:Array = str.split("");
if (strArray.length >= 4) {
var count:uint = 0;
for (var i:uint = strArray.length; i > 0; i--) {
if (count == 3) {
strArray.splice(i, 0, ",");
count = 0;
}
count++;
}
return strArray.join("");
}
else {
return str;
}
}
I tested it on some pretty large numbers, and it seems to work just fine. There's no upper limit on the size of the number, so;
trace (formatNum("10000000000000000000"));
Will output:
10,000,000,000,000,000,000
So in your example, you could use it thusly;
Taps_txt.text = formatNum(String(score));
(This is casting the type implicitly rather than explicitly using toString();, but either method is fine. Casting just looks a little neater in function calls)
Use the NumberFormatter class:
import flash.globalization.NumberFormatter;
var nf:NumberFormatter = new NumberFormatter("en_US");
var numberString:String = nf.formatNumber(1234567.89);
trace("Formatted Number:" + numberString);
// Formatted Number:1,234,567.89
To show the score with comma, you can do like this : ( comments are inside the code )
var score:Number = 0;
var score_str:String;
var score_str_len:int;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
Monster.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler);
function fl_TapHandler(event:TouchEvent):void
{
score = score + 1;
score_str = score.toString();
score_str_len = score_str.length;
// here you can use score > 999 instead of score_str_len > 3
Taps_txt.text =
score_str_len > 3
// example : 1780
// score_str_len = 4
// score_str.substr(0, 4 - 3) = 1 : get thousands
// score_str.substr(4 - 3) = 780 : get the rest of our number : hundreds, tens and units
// => 1 + ',' + 780 = 1,780 : concatenate thousands + comma + (hundreds, tens and units)
? score_str.substr(0, score_str_len-3) + ',' + score_str.substr(score_str_len-3)
: score_str
;
// gives :
// score == 300 => 300
// score == 1285 => 1,285
// score == 87903 => 87,903
}
EDIT :
To support numbers greater than 999.999, you can do like this :
function fl_TapHandler(event:MouseEvent):void
{
score = score + 1;
score_str = score.toString();
Taps_txt.text = add_commas(score_str);
}
function add_commas(nb_str:String):String {
var tmp_str:String = '';
nb_str = nb_str.split('').reverse().join('');
for(var i = 0; i < nb_str.length; i++){
if(i > 0 && i % 3 == 0) tmp_str += ',';
tmp_str += nb_str.charAt(i);
}
return tmp_str.split('').reverse().join('');
/*
gives :
1234 => 1,234
12345 => 12,345
123456 => 123,456
1234567 => 1,234,567
12345678 => 12,345,678
123456789 => 123,456,789
1234567890 => 1,234,567,890
*/
}
Hope that can help you.
Related
I'm looking for a tip for a AS3 script, have no idea how to start there
Button, if clicked the function is executed, which outputs a predefined value as the cross sum of a number string.
Example:
Cross sum should be 10
By clicking on the button, the function generates the number 55 or 82 or 37 or 523, ie numbers with the cross sum 10
An alternative way using % (modulo) instead of a string. You could write that into one line like this:
while (sum != 0) { qsum += sum % 10; sum /= 10; }
The trick is that modulo will give us only the last digit of the longer number, then we divide by 10 to trim off that last number (from longer) and we re-read a newer ending digit of the long number.
Example:
Long num = 1234, so each trim gives, 4 then 3 then 2 then 1 and we'll sum them up each time.
usage:
myInt = cross_sum(50); //makes myInt hold answer result of function (where ExpectedValue input is 50).
and the supporting function...
function cross_sum( ExpectedValue: int ) : int
{
var rand :int = Math.floor(Math.random() * 100000000000)
var sum :int = Math.abs( rand );
var qsum :int = 0;
while (sum != 0)
{
qsum += sum % 10; //get last digit of sum...
sum /= 10; //trim down sum by 1 digit...
}
if ( qsum == ExpectedValue ) { return rand; } //# stop here and give back "rand" as answer result.
else { cross_sum( expectedValue ); } //# else if wrong, try again...
}
Got it now.....
the function calculates a number, with the crosssum 50
function berechnen() {
var rand = Math.floor(Math.random() * 100000000000)
var sum = String(rand)
var qsum = 0;
for (var i = 0; i < sum.length; i++) {
qsum += Number(sum.charAt(i));
}
if (qsum == 50) {
summe.text = String(sum);
} else {
berechnen()
}
}
I wanted to create the ability to have "random" (pseudo-random) colors generated and came up with this code intended to create all and any color.
I'm very new to programming and wanted to see if anyone on S.O. had any comments or criticisms, the code works great. Only problem is the colors occasionally being too similar making it difficult to differentiate bewteen them.
I know this is likely a very brute force fashion of coding but its what I thought of.
Hexidecimal generator
public class colorGenerator
{
public var color:int;
private var randomnumber:Number;
private var first:String = "";
public function colorGenerator():void
{
var colorstring:String = "0x";
var transfer:String = "0x";
for ( var i:uint = 0; i < 6; i++)
{
randomhex();
colorstring += first;
}
transfer = colorstring;
color = int(transfer);
}
public function randomhex():void
{
randomnumber = Math.random();
if ( -1 < randomnumber < ((.99 / 16) * 1))
first = "0";
else if ( ((.99/16)*1) < randomnumber < ((.99/16)*2))
first = "1";
else if ( ((.99/16)*2)< randomnumber < ((.99/16)*3))
first = "2";
else if ( ((.99/16)*3)< randomnumber < ((.99/16)*4))
first = "3";
else if ( ((.99/16)*4)< randomnumber < ((.99/16)*5))
first = "4";
else if ( ((.99/16)*5)< randomnumber < ((.99/16)*6))
first = "5";
else if ( ((.99/16)*6)< randomnumber < ((.99/16)*7))
first = "6";
else if ( ((.99/16)*7)< randomnumber < ((.99/16)*8))
first = "7";
else if ( ((.99/16)*8)< randomnumber < ((.99/16)*9))
first = "8";
else if ( ((.99/16)*9)< randomnumber < ((.99/16)*10))
first = "9";
else if ( ((.99/16)*10)< randomnumber < ((.99/16)*11))
first = "A";
else if ( ((.99/16)*11)< randomnumber < ((.99/16)*12))
first = "B";
else if ( ((.99/16)*12)< randomnumber < ((.99/16)*13))
first = "C";
else if ( ((.99/16)*13)< randomnumber < ((.99/16)*14))
first = "D";
else if ( ((.99/16)*14)< randomnumber < ((.99/16)*15))
first = "E";
else if ( ((.99/16)*15)< randomnumber < 2)
first = "F";
}
}
I then just assign the hexidecimal value to a variable in another class
var acolor:colorGenerator = new colorGenerator;
var COLOR:uint = acolor.color
Thanks for any comments!
This should work as well.
Math.random() * 0xFFFFFF;
Not tested but this should be more "random":
var red : int = Math.floor(Math.random()*255);
var green : int = Math.floor(Math.random()*255);
var blue : int = Math.floor(Math.random()*255);
var color : int = red << 16 | green << 8 | blue;
i have to handle unique names and save it in db like -
If name already exists, find the smallest number you can append to the name to save it as a unique name.
For example:
If username Scott already exists, save as Scott(1). If Scott(1) already exists, save as Scott(2). Etc.
i am using c# and sql server 2010
any great ideas ?
figured that out - but appreciate improvements
var seprator = "scott";
var list = new List<string>();
list.Add("scott");
list.Add("scott(1)");
list.Add("scott Alex");
list.Add("scott (4)");
list.Add("scott(xxx)");
list.Add("scott(250)");
list.Add("scott(12s)");
list.Add("scott(123)x");
list.Add("Scott caps");
list.Add("Alex Scott caps");
list.Add("xxxscottmmm");
var numberList = new List<int>();
foreach (var v in list)
{
var parts = Regex.Split(v, seprator, RegexOptions.IgnoreCase);
if (parts.Length > 1) //(1) Alex (4) (xxx) (250) (12s) (123)x caps caps
{
var secondPart = parts[1].Trim();
if (secondPart.StartsWith("(") && secondPart.EndsWith(")")) // (1) (4) (xxx) (250) (12s)
{
var valuebetweenbraces = secondPart.Substring(1, secondPart.Length - 2); //1 4 xxx 250 12s
int number;
var isNumber = int.TryParse(valuebetweenbraces, out number);
if (isNumber)
{
numberList.Add(number);
}
}
}
}
int maxValue = 0;
if (numberList.Count > 0)
maxValue = numberList.Max() + 1;
else
maxValue = maxValue + 1;
Response.Write(seprator + "(" + maxValue + ")");
Im trying to make a multidimensional array but I obtain an error ("TypeError: Error #1010: A term is undefined and has no properties.").
var matriz:Array = new Array();
for(var p:Number = 0; p<2;p++ ){
for(var q:Number = 0; q<2;q++ ){
matriz[p][q] = 0;
}
}
what am I doing wrong?
Thanks in advance!
You need to create an array within matriz[p] before you can add an array (or anything else) into it.
You can achieve what you're attempting without errors like this:
var matriz:Array = [];
for(var p:Number = 0; p<2; p++)
{
// Create an array at matriz[p] if undefined.
if(matriz[p] == undefined) matriz[p] = [];
for(var q:Number = 0; q<2; q++)
{
matriz[p][q] = 0;
}
}
Essentially you were trying to do the same as this:
var object:Object = {};
object.nonexistantProperty.value = 10;
What Marty has said is correct, however I prefer removing the if condition and changing the code to the following:
var matriz:Array = [];
for(var p:Number = 0; p<2; p++) {
matriz[p] = [];
for(var q:Number = 0; q<2; q++) {
matriz[p][q] = 0;
}
}
public class cArray
{
private var DIM1CAP:uint=0;
private var DIM2CAP:uint=1;
private var DIM3CAP:uint=2;
private var DIM4CAP:uint=3;
private var DIM5CAP:uint=4;
public function cArray():void
{
// avoid the noid
}
// returns empty array of args.length dimensions
// 1st argument is dim 1 capacity; 2nd is dim 2, etc.
public function getArray ( ... args ):Array
{
var arr = new Array();
if ( paramsNotValid(args) )
{
return null;
}
switch (args.length)
{
case 2:
arr = get2DArray ( args[0], args[1] );
break;
case 3:
arr = get3DArray ( args[0], args[1], args[2] );
break;
case 4:
arr = get4DArray ( args[0], args[1], args[2], args[3] );
break;
case 5:
arr = get5DArray ( args[0], args[1], args[2], args[3], args[4] );
break;
default:
break;
}
return arr;
}
// returns empty 2d array of parameter specified capacity
private function get2DArray ( _1stDimCapacity:uint, _2ndDimCapacity:uint ):Array
{
var arr2d:Array = [];
var arr1d = new Array();
for ( var i:uint=0; i<_1stDimCapacity; i++ )
{
arr1d[_2ndDimCapacity-1] = undefined;
arr2d.push(arr1d);
arr1d = new Array();
}
return arr2d;
}
// returns empty 3d array of parameter specified capacity
private function get3DArray ( dim1Cap:uint,
dim2Cap:uint,
dim3Cap:uint ):Array
{
var arr3d = new Array();
for ( var i:uint=0; i<dim1Cap; i++ )
{
arr3d.push ( get2DArray ( dim2Cap, dim3Cap ) );
}
return arr3d;
}
// returns empty 4d array of parameter specified capacity
private function get4DArray ( dim1Cap:uint,
dim2Cap:uint,
dim3Cap:uint,
dim4Cap:uint):Array
{
var arr4d = new Array();
for ( var i:uint=0; i<dim1Cap; i++ )
{
arr4d.push ( get3DArray ( dim2Cap, dim3Cap, dim4Cap ) );
}
return arr4d;
}
// returns empty 5d array of parameter specified capacity
private function get5DArray ( dim1Cap:uint,
dim2Cap:uint,
dim3Cap:uint,
dim4Cap:uint,
dim5Cap:uint):Array
{
var arr5d = new Array();
for ( var i:uint=0; i<dim1Cap; i++ )
{
arr5d.push ( get4DArray ( dim2Cap, dim3Cap, dim4Cap, dim5Cap ) );
}
return arr5d;
}
//////////////////////////////////////////////////////
private function paramsNotValid ( args:Array ):Boolean
{
if ( args.length<2 || args.length>5 )
{
return true;
}
for ( var i:uint=0; i<args.length; i++ )
{
if ( ! ( args[i]>0 ) )
{
break;
}
}
if ( i < args.length )
{
return true;
}
return false;
}
}
}
public class cMain extends MovieClip
{
var cArr:cArray = new cArray;
public function cMain():void
{
var arr2d:Array;
var arr3d:Array;
var chessBrd_4d:Array;
var arr5d:Array;
// capacity of 10 games; 150 moves/gm; white's mv or black's;
// - piece positions; move in chess notation (index 32 of
// - last dimension); commentary (index 33 of last dimension)
chessBrd_4d = cArr.getArray(10,150,2,34);
// adding data
// - 4th game, 8th move, white's move, positions of pieces
chessBrd_4d[3][7][0][0] = 'd8';
chessBrd_4d[3][7][0][1] = 'b1';
// ...
// - positions of pieces up to last one
// ...
// - last piece pos
chessBrd_4d[3][7][0][31] = 'captured';
// - actual move in chess notation
chessBrd_4d[3][7][0][32] = 'nC4';
// - annotation
chessBrd_4d[3][7][0][33] = 'blocks b pawn, ' +
'opens diag for c1 bishop, ' +
'Justin Beiber is a putz, ' +
'the president is liar'
trace ( 'piece 0 is on square ' + chessBrd_4d[3][7][0][0]);
trace ( 'piece 1 is on square ' + chessBrd_4d[3][7][0][1]);
trace ( ' ... ' )
trace ( 'piece 31 has been ' + chessBrd_4d[3][7][0][31]);
trace ( 'move: ' + chessBrd_4d[3][7][0][32]);
trace ( chessBrd_4d[3][7][0][33]);
/*
trace results:
piece 0 is on square d8
piece 1 is on square b1
...
piece 31 has been captured
move: nC4
blocks b pawn, opens diag for c1 bishop,
Justin Beiber is a putz, the president is liar
*/
/*
trace ( chessBrd_4d.length ); = 10
trace ( chessBrd_4d [ 2 ].length ); = 150
trace ( chessBrd_4d [ 2 ] [ 4 ].length ); = 2
trace ( chessBrd_4d [ 2 ] [ 4 ] [ 1 ].length ); = 34
trace ( chessBrd_4d [ 2 ] [ 4 ] [ 0 ] .length); = 34
*/
}
}
If I am getting a random number, how do I increase my chances of making that random number to be even. I am not looking to make it even every time. I am just looking to generate a random number say... %70 of the time or %90 of the time.
private function randNum (high, low) {
return Math.floor(Math.random() * (1+high-low)) + low;
}
Would I pass in a greater range of numbers to this function? Or would I have to scrap this function altogether?
Thank you
private function randNum (high : Number, low : Number) : int
{
var even : Boolean = Math.random() < 0.7; //set probability of even number here
var rand : int = Math.floor(Math.random() * (1+high-low)) + low;
if (even)
while (rand % 2 != 0)
rand = Math.floor(Math.random() * (1+high-low)) + low;
else
while (rand % 2 != 1)
rand = Math.floor(Math.random() * (1+high-low)) + low;
return rand;
}
Test:
var even : int = 0;
var odd : int = 0;
for (var i : int = 0; i < 100000; i++)
{
var a : int = randNum(1, 20);
if (a % 2 == 0)
even++;
else
odd++;
}
trace(even, odd);
Output:
[trace] 69869 30131
A little too late ;) but another one with no loop and using bit masking operation :
ret & -2 will make your number even, then depending on the result of (Math.random() >= evenProbability) you set the lower bit to be 1 to give an odd number
function randomRange(low:int, high:int, evenProbability:Number = 0.5):int{
var ret:int = int( Math.random() * ( 1 + high - low ) ) + low
return ( ret & -2 ) | int( Math.random() >= evenProbability )
}
Here a live test with wonderfl : http://wonderfl.net/c/9IHx