我正在尝试制作一个简单的回合制双人游戏(如富裕)作为即将开展的项目的练习。在尝试确保同一网格磁贴上没有字符重叠时,我尝试创建一个验证器函数,我可以为生成中的每个字符调用(随机生成的位置),这样我就不会在相同的脚本中进行微小的更改每个角色部分。我的原始代码(没有函数)在上面,最近的尝试(有一些上下文)如下:
function bTeamCharGen() {
var a = 10;
var b = 15;
var c = 0;
var d = 5;
var bTeamLead = document.createElement("img");
bTeamLead.src = "images/transp_img.gif";
bTeamLead.height = "38";
bTeamLead.width = "38";
bTeamLead.className = "lead";
bTeamLead.id = "bLead";
genStartPos();
var curr = document.getElementById("gridBlock_" + i + "_" + j);
if (curr.hasChildNodes()) {
while (curr.hasChildNodes()) {
genStartPos(a, b, c, d);
}
}
document.getElementById("gridBlock_" + i + "_" + j).appendChild(bTeamLead);
document.getElementById("bLead").style.background = "url('images/eirika_1_1.gif') 0 0";
document.getElementById("bLead").style.backgroundRepeat = "no-repeat";
//commented out basic structure for further characters here
}
这是其中一个字符的原始代码。以下是我目前所得到的(仍有未捕获的TypeError):
var i, j;
//functions to generate grid and background
function genStartPos(minX, maxX, minY, maxY) {
i = Math.floor(Math.random() * (maxX - minX + 1) + minX);
j = Math.floor(Math.random() * (maxY - minY + 1) + minY);
}
function validStartPos() {
genStartPos();
var curr = document.getElementById("gridBlock_" + i + "_" + j);
if (curr.hasChildNodes()) {
while (curr.hasChildNodes()) {
genStartPos(a, b, c, d);
}
}
}
function bTeamCharGen() {
var a = 10;
var b = 15;
var c = 0;
var d = 5;
var bTeamLead = document.createElement("img");
bTeamLead.src = "images/transp_img.gif";
bTeamLead.height = "38";
bTeamLead.width = "38";
bTeamLead.className = "lead";
bTeamLead.id = "bLead";
validStartPos();
document.getElementById("gridBlock_" + i + "_" + j).appendChild(bTeamLead);
document.getElementById("bLead").style.background = "url('images/eirika_1_1.gif') 0 0";
document.getElementById("bLead").style.backgroundRepeat = "no-repeat";
//commented out basic structure for further characters here
}
function initialise() {
makeGrid();
setBackground();
bTeamCharGen();
rTeamCharGen();
}
这有点长而且笨拙,因为我还在试图把它连接起来,但其他一切都有效,直到我这样做。我将初始化函数称为正文的onload,而<script>
位于<head>
之内,因为我在<body>
中将其置于早期时遇到了问题。
答案 0 :(得分:0)
我不确定,但是...我认为你在"gridBlock_" + i + "_" + j
为undefined
时尝试获取元素
您在没有任何参数的情况下调用genStartPos()
。因此,您的i
和j
未定义,因此您使用元素ID字符串。
如果您无法将变量传递给genStartPos()
,则需要为maxX,maxY ...设置一些默认值。
PS,当a,b,c,d未定义时,你也会调用genStartPos(a, b, c, d)
。或许这可能不是你展示的所有代码