我使用raphael.js作为我的战舰游戏的视觉界面。我有一个名为createCanvas()的函数,它创建一个网格(10x10)。这样,用户可以看到瞄准的位置。问题是,在游戏代码(放入坐标等)完成之后,网格才会出现。有谁知道如何解决这个问题?
这里是entire code。下面是createCanvas()和game()的代码。
function createCanvas() {
$(function() {
var canvas = Raphael(0, 0, 2000, 2000);
for(var i = 0; i != (BOARD_WIDTH); i++) {
canvas.text((60+70*i), 15, i+1);
}
for(var i = 0; i != (BOARD_HEIGHT); i++) {
canvas.text(15, (60+70*i), i+1);
}
for(var i = 0; i != (BOARD_WIDTH+1); i++) {
canvas.path( "M" + (25+(70*i)) + ",25 L" + (25 + (70*i)) + ",725" );
}
for(var i = 0; i != (BOARD_HEIGHT+1); i++) {
canvas.path( "M25," + (25+(70*i)) + " L725," + (25+(70*i)) );
}
});
}
function game(){
inputArray = [4,3,2];
var boats = randomBoats(inputArray);
var currentBoat = 0;
var sunkenBoat = 0;
var numberOfTurns = 0;
while(sunkenBoat !== inputArray.length ) {
var hit= false;
var target = "(" + prompt("Enter targetcoordinate (x,y)") + ")";
var targetString = target.replace(/\s+/g, '');
for(var i = 0; i !== inputArray.length; i++) {
for(var j = 0; j !== boats[i].usedPositions().length; j++) {
console.log(targetString)
if(targetString === boats[i].usedPositions()[j].toString()) {
hit = true;
boats[i].hits[j] = 1;
console.log(boats[i].hits);
currentBoat = boats[i];
fillSquare(targetString, "red");
break;
}
}
}
console.log(currentBoat.hits);
console.log(allEquals(currentBoat.hits, 1));
if(hit)
alert ("Hit!");
else {
fillSquare(targetString, "blue");
alert ("Miss!");
}
if(allEquals(currentBoat.hits, 1)) {
alert("Boat with length " + currentBoat.hits.length + " has sunken!");
sunkenBoat++;
}
numberOfTurns++
}
alert("You've won! You did it in " + numberOfTurns + " turns.")
}
在我的代码中,我致电
createCanvas();
game();
所以我认为首先绘制画布......
答案 0 :(得分:1)
问题是While循环。你没有给任何其他机会进入并做任何事情。这将尽可能快地四处走动,直到你完成为止。
您应该尝试在页面上放置一个输入框,然后检测关键事件以查找输入键。
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
这样你以后需要的动画和其他东西可以在不被阻挡的情况下运行,你不会像疯了一样烧掉CPU周期,而只检查用户实际输入值时的命中
然后你甚至可以在画布上写一些代码显示“Hit”或“Miss”(可能是动画的),这样你就可以删除所有不断弹出的警告和消息框。