简单的javascript游戏,隐藏/显示随机方块
我正在开发一个简单的游戏,我需要一些帮助来改进我的代码
所以这是游戏:
一些方块随机显示和隐藏几秒钟,你必须点击它们。 我使用RaphaelJS来绘制正方形和一些JQuery($.each()函数)
我在div中工作,这就是我绘制正方形(6个正方形)的方式,xy是随机数。
var rec1 = paper.rect(x, y, 50, 50).attr({
fill: "blue",});
我可以使用 for() 来构建每个方块并使用不同的变量名称吗? 我尝试使用 var = varName+i 但它不起作用。
为了隐藏和显示方块,我使用两个函数调用两个 setTimeout:
function box1() {rec1.show();}
function hidebox1() {rec1.hide();}
var time1 = setTimeout(box1, 1000);
var time1 = setTimeout(hidebox1, 2000);
我知道它看起来很糟糕...
我确信有一种方法可以使用切换,或者如果你能帮忙的话,可以使用更奇特的方法来做到这一点我找到了:)因为现在我必须对每个方块都这样做...
非常感谢您的帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您尝试使用
varName
加上一些i
来识别您想要的varName
的本能是正确的,JavaScript(像大多数语言一样)具有这一点通过所谓的数组内置的想法。一个简单的看起来像这样:
使用该数组,您可以访问
foo[0]
(即1
),或foo[3]
(即1
)是309
。请注意两件事:首先,我们使用方括号来标识我们想要的数组元素。其次,我们从 0 开始计数,而不是 1。
您可以创建一个空数组,例如
var varName = [];
,然后添加新元素使用varName.push( newValueToPutIn );
使用这些工具,您现在可以获得您想要的东西。现在您可以执行以下操作:
recs[0]
和recs[1]
等等将引用您的各个框。Your instinct to try to use
varName
plus somei
to identify whichvarName
you 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.对于第一个问题,数组是最佳选择。
对于第二部分,您可以将正方形及其显示/隐藏内容封装到一个新的匿名对象中,如下所示:
For the first question, an array is the way to go.
For the second part, you could encapsulate the square and its show/hide stuff into a new anonymous object, like this: