Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.

Commit 2b5c193

Browse files
author
msanvido
committed
Extend Warship Example
Change the color of each cell once a ship is hit. This makes it easier to see if a ship was sunk.
1 parent 00d795f commit 2b5c193

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

warship/styles.css

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ body {
8484
z-index: 2;
8585
}
8686

87+
.cellShipHit {
88+
opacity: 0.5;
89+
background-color: #00CC00;
90+
z-index: 2;
91+
}
92+
8793
.cellMiss{
8894
opacity: 0.5;
8995
background-color: #008000;

warship/warship.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ class Ship {
2828
isVertical = true;
2929
hits = 0;
3030
element: HTMLElement;
31+
cells: Cell[];
3132

3233
constructor(public size: number) {
3334
this.element = $("<div class='ship'></div>")[0];
@@ -185,6 +186,13 @@ class Board {
185186
}
186187
}
187188

189+
markShipBombed(ship: Ship) {
190+
for (var i = 0; i < ship.size; i++) {
191+
$(ship.cells[i].element).removeClass("cellHit");
192+
$(ship.cells[i].element).addClass("cellShipHit");
193+
}
194+
}
195+
188196
bombCell(cellElem: HTMLElement) {
189197
var cellPos = Cell.parseCellLocation($(cellElem).data("cellLocation"));
190198
var cell = this.cells[cellPos.row][cellPos.column];
@@ -199,6 +207,7 @@ class Board {
199207
var ship = this.ships[cell.shipIndex];
200208
ship.hits++;
201209
if (ship.isSunk()) {
210+
this.markShipBombed(ship);
202211
if (this.allShipsSunk()) {
203212
this.onEvent.call(this, 'allSunk');
204213
} else {
@@ -266,14 +275,16 @@ class Board {
266275
var ship = this.ships[index]
267276
ship.hits = 0;
268277
var cells = ship.getCellsCovered();
278+
ship.cells = []
269279
for (var cell = 0; cell < cells.length; cell++) {
270280
var cellPos = Cell.parseCellLocation(cells[cell]);
271281
var targetCell = this.cells[cellPos.row][cellPos.column];
272282
targetCell.shipIndex = index;
283+
ship.cells.push(targetCell);
273284
}
274285
}
275286

276-
$(this.element).children(".cell").removeClass("cellHit cellMiss").addClass("notBombed");
287+
$(this.element).children(".cell").removeClass("cellHit cellMiss cellShipHit").addClass("notBombed");
277288
}
278289

279290
private allShipsSunk() {

0 commit comments

Comments
 (0)