简单的JavaScript游戏,隐藏/显示随机正方形 [英] Simple javascript game, hide / show random square

查看:103
本文介绍了简单的JavaScript游戏,隐藏/显示随机正方形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的游戏,需要一些帮助来改进我的代码

I'm working on a simple game and I need some help to improve my code

这就是游戏:

一些正方形显示并随机隐藏几秒钟,您必须保持对它们的关注. 我使用RaphaelJS绘制正方形和一些JQuery($.each()函数)

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)

我在div中工作,这就是我绘制正方形(6个正方形)的方式,x y是随机数.

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",});

我可以使用for()来为每个正方形使用不同的var名称吗? 我尝试使用var = varName + i,但是没有用.

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.

为了隐藏和显示正方形,我使用了两个带有两个setTimeout的函数:

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...

我敢肯定,有一种方法可以使用切换开关,或者如果您可以帮助我找到它的话,可以尝试其他方法:)因为现在我必须为每个正方形执行此操作...

非常感谢您的帮助.

推荐答案

您的直觉尝试使用varName加上一些i来识别所需的varName和JavaScript(与大多数语言一样)这个想法是通过 array 内置的.

Your instinct to try to use varName plus some i to identify which varName 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:

var foo = [1, 5, 198, 309];

使用该阵列,您可以访问foo[0](即1)或foo[3](即309).

With that array, you can access foo[0] which is 1, or foo[3] which is 309.

请注意两件事:首先,我们使用方括号标识要数组的哪个元素.其次,我们从 0 而不是1开始计数.

Note two things: First, we identify which element of the array we want using square brackets. Second, we start counting at 0, not 1.

您可以创建一个像var varName = [];这样的空数组,然后使用varName.push( newValueToPutIn );

You can create an empty array like var varName = []; and then add new elements to it using varName.push( newValueToPutIn );

有了这些工具,您现在可以实现所需的功能.现在您可以执行以下操作:

With those tools, you can now get at what you wanted. Now you can do something like:

var recs = [];
for(var i = 0; i < 100; i++) {
    var rec = paper.rect(x, y, 50, 50).attr({fill: 'blue'});
    recs.push(rec);
}

然后recs[0]recs[1]等将引用您的各个框.

And recs[0] and recs[1] and so forth will refer to your various boxes.

这篇关于简单的JavaScript游戏,隐藏/显示随机正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆