Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Chapter 8 - Battleship #23

Open
Open
@akyjoon

Description

@akyjoon

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 :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp