I’m working on a simple game and I need some help to improve my code
So here’s the game:
Some square show and hide randomely for a few seconds and you have to clic on them.
I use RaphaelJS to draw the square and a few of JQuery ($.each() function)
I work in a div, that’s how I draw my squares (6 squares), x y are random numbers.
var rec1 = paper.rect(x, y, 50, 50).attr({
fill: "blue",});
Can I use for() to build my squares with a different var name for each one ?
I try with var = varName+i but it didn’t work.
To hide and show the square I use two functions call with two setTimeout:
function box1() {rec1.show();}
function hidebox1() {rec1.hide();}
var time1 = setTimeout(box1, 1000);
var time1 = setTimeout(hidebox1, 2000);
I know it looks crappy…
I’m sure there is a way to use a toggle, or something more fancy to do that if you could help me finding it 🙂 Because right now I have to do that for every square…
Thanks a lot for your help.
Your instinct to try to use
varNameplus someito identify whichvarNameyou want is spot on, and JavaScript (like most languages) has that idea built in through what’s called an array.A simple one looks something like this:
With that array, you can access
foo[0]which is1, orfoo[3]which is309.Note two things: First, we identify which element of the array we want using square brackets. Second, we start counting at 0, not 1.
You can create an empty array like
var varName = [];and then add new elements to it usingvarName.push( newValueToPutIn );With those tools, you can now get at what you wanted. Now you can do something like:
And
recs[0]andrecs[1]and so forth will refer to your various boxes.