Reputation: 416
I'm using raphael.js as a visual interface of my Battleship game. I have a function called createCanvas() which creates a grid (10x10). That way the user can see where to aim. The problem is, the grid doesn't appear until after the code of the game (putting in coordinates etc) has finished. Anyone know how to solve this?
Here's the entire code. Below, the code of createCanvas() and of 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.")
}
In my code I call
createCanvas();
game();
so I would think the canvas is drawn first...
Upvotes: 0
Views: 189
Reputation: 6373
The issue is the While loop. You're not giving anything else a chance to get in and do anything. This will just keep going around and around as fast as possible until you're done.
You should take a stab at putting a Input box on the page and and detecting key events looking for the enter key with something like this.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
That way the animations and other stuff your're going to need later can run without being blocked, you don't burn CPU cycles like crazy, and you only check for a hit when the user has actually entered a value
Then you will maybe even write some code display "Hit" or "Miss" on canvas (may be animated) and that way you can remove all the alert and message boxes that keep popping up.
Upvotes: 1