Description
Hi, I'm on chapter 8 where you build a battleship game. I have finished the Viewer and Model part without the Controller part. My problem:
I type in the console model.fire("somecell") to make 3 hits and drown a ship, but I keep getting that the ship is sunk on every hit. It never says "Hit!"
My code:
`var view = {
displayMessage: function(msg){
var messageArea = document.getElementById('messageArea');
messageArea.innerHTML = msg;
},
displayHit: function(location){
var cell = document.getElementById(location);
cell.setAttribute("class", "hit");
},
displayMiss: function(location) {
var cell = document.getElementById(location);
cell.setAttribute("class", "miss");
}
};
var model = {
boardSize : 7,
numShips: 3,
shipLength: 3,
shipsSunk: 0,
ships:[
{locations: ["10", "20", "30"], hits: ["", "", ""]},
{locations: ["32","33","34"], hits:["", "", ""]},
{locations: ["63","64","65"], hits:["", "", ""]}
],
fire: function(guess){
for(var i = 0; i < this.numShips; i++) {
var ship = this.ships[i];
var index = ship.locations.indexOf(guess);
if (index >=0) {
//trafiony
ship.hits[index] = "hit";
view.displayHit(guess);
view.displayMessage("Hit!");
if (this.isSunk(ship)){
view.displayMessage("Sunk!");
this.shipsSunk++;
}
return true;
}
}
view.displayMiss(guess);
view.displayMessage("Miss!")
return false;
},
isSunk: function(ship) {
for (var i=0; i < this.shipLength; i++){
if (ship.hits[i] !== "hit") {
return false;
}
return true;
}
}
};
`
I compared the code and it's the same as in the book and don't understand why it won't work. Can you help me?
Btw. this book is awesome. I bought a polish version :)