【发布时间】:2014-02-05 19:18:02
【问题描述】:
所以这很可能是错误的方法,但我一直在考虑这种方法,但我想不出更好的方法。
我正在和朋友一起开发一款 roguelike 游戏,前端使用 Javascript 和 Canvas,并使用 PHP 将我们的数据(怪物、物品等)存储到 MySQL 数据库中。
我们将比赛场地划分为四个独立的象限。整个游戏场是一个 20 x 20 的正方形,所以我们一直在编写 10 x 10 的地牢象限。这个想法是从其中包含地牢象限代码的数组中获取代码,并以某种方式执行此代码。目前我们有四个正在调用的象限函数,它们在这些象限内绘制环境对象并给它们赋值,但这些函数是硬编码的。我希望能够从数组中随机选择一个值并将该代码放在这些函数中。
我听说过一个名为 eval() 的神秘而充满黑魔法的程序。我需要转向黑暗面还是有更好的方法?
我将包含一些代码,以便您了解基本思想。
////Matrix creation / declaration
var coordinates = new Array(mapWidth);
for (var i = 0; i <mapWidth; i++) {
coordinates[i] = new Array(mapHeight);
}
//sets array to 0 which is not an object
for (var i=0; i<mapWidth; i++) {
for (var j=0; j<mapHeight; j++) {
coordinates[i][j] = 0;
}
}
function quadrantOneLoader()
{
var x = 0;
var y = 0;
for (var i = 0; i < 10; i++)
{
if (i % 2 === 1 && i != 3)
{
coordinates[x + i][y + 1] = new environment();
coordinates[x + i][y + 1].image.src = "images/column.png";
}
else if (i % 2 === 1)
{
coordinates[x + i][y + 1] = new environment();
coordinates[x + i][y + 1].image.src = "images/brokenColumn.png";
}
}
for (var i = 0; i < 10; i++)
{
if (i % 2 === 0 && i !== 8)
{
coordinates[x + i][y + 3] = new environment();
coordinates[x + i][y + 3].image.src = "images/column.png";
}
else if (i % 2 === 0)
{
coordinates[x + i][y + 3] = new environment();
coordinates[x + i][y + 3].image.src = "images/brokenColumn.png";
}
}
for (var i = 0; i < 10; i++)
{
if (i % 2 === 0 && i !== 4)
{
coordinates[x + i][y + 7] = new environment();
coordinates[x + i][y + 7].image.src = "images/column.png";
}
else if (i % 2 === 0)
{
coordinates[x + i][y + 7] = new environment();
coordinates[x + i][y + 7].image.src = "images/brokenColumn.png";
}
}
for (var i = 0; i < 10; i++)
{
if (i % 2 === 1 && i !== 7)
{
coordinates[x + i][y + 9] = new environment();
coordinates[x + i][y + 9].image.src = "images/column.png";
}
else if (i % 2 === 1)
{
coordinates[x + i][y + 9] = new environment();
coordinates[x + i][y + 9].image.src = "images/brokenColumn.png";
}
}
coordinates[x + 1][y + 5] = new environment();
coordinates[x + 1][y + 5].image.src = "images/stocks.png";
coordinates[x + 4][y + 5] = new environment();
coordinates[x + 4][y + 5].image.src = "images/candelabra.png";
coordinates[x + 7][y + 5] = new environment();
coordinates[x + 7][y + 5].image.src = "images/stocks.png";
}
所以基本上 quadrantOneLoader() 函数内的代码将被放置在一个数组中。我想把它注入到这个函数中,让它看起来更像这样:
function quadrantOneLoader()
{
var x = 0;
var y = 0;
quadrants[Math.floor(Math.random()*quadrants.length())];
}
【问题讨论】:
-
如果你必须使用 eval 你做错了什么。请为您的问题添加一些进一步的解释(这些函数中有什么代码?),甚至可能还有一些示例代码 sn-ps 来查看。
-
我不会依赖 eval() ,因为它在未来可能不受支持,并且会带来很多潜在的问题。我不明白为什么你需要执行这样的代码。只需将有关网格的信息传递给页面,并让现有的 javascript 函数使用它来呈现图形。
-
阅读一些关于瓦片地图引擎的理论,尤其是它们是如何保存和加载的。我现在没有找到一些好的教程,但开始这可能已经很有用了:tonypa.pri.ee/tbw/tut01.html 绝对不需要使用 eval!
标签: javascript php mysql arrays eval