Today we are going to develop a fully functional image recognition game using JavaScript. JavaScript is the best fit choice since it is a web-based game. The game is totally based on event handling and event objects.
今天,我们将使用JavaScript开发功能全面的图像识别游戏 。 JavaScript是最适合的选择,因为它是基于Web的游戏。 游戏完全基于事件处理和事件对象 。
Code files
代码文件
1) battleship.js
1)Battleship.js
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,
shipsSunk: 0,
shipLength: 3,
generateShipLocations: function() {
var locations;
for (var i = 0; i < this.numShips; i++) {
do {
locations = this.generateShip();
} while (this.collision(locations));
this.ships[i].locations = locations;
}
},
generateShip: function() {
var direction = Math.floor(Math.random() * 2);
var row, col;
if (direction === 1) {
row = Math.floor(Math.random() * this.boardSize);
col = Math.floor(Math.random() * (this.boardSize - this.shipLength));
} else {
row = Math.floor(Math.random() * (this.boardSize - this.shipLength));
col = Math.floor(Math.random() * this.boardSize);
}
var newShipLocations = [];
for (var i = 0; i < this.shipLength; i++) {
if (direction === 1) {
newShipLocations.push(row + "" + (col + i));
} else {
newShipLocations.push((row + i) + "" + col);
}
}
return newShipLocations;
},
collision: function(locations) {
for (var i = 0; i < this.numShips; i++) {
var ship = model.ships[i];
for (var j = 0; j < locations.length; j++) {
if (ship.locations.indexOf(locations[j]) >= 0) {
return true;
}
}
}
return false;
},
ships: [{
locations: [0, 0, 0],
hits: ["", "", ""]
}, {
locations: [0, 0, 0],
hits: ["", "", ""]
}, {
locations: [0, 0, 0],
hits: ["", "", ""]
}],