Debian Codegraph @

tests/inputs/warship.ts

raw
1 // https://github.com/guidobouman/typescript/blob/master/samples/warship/warship.ts
2 /// <reference path="jquery.d.ts" />
3 /// <reference path='jqueryui.d.ts' />
4
5 class Cell {
6 shipIndex: number;
7 hasHit: boolean;
8 element: HTMLElement;
9
10 constructor(public row: number, public column: number) {
11 this.element = $("<div class='cell notBombed'></div>")[0];
12 }
13
14 // Parse a cell location of the format "row,column"
15 static parseCellLocation(pos: string) {
16 var indices: string[] = pos.split(",");
17 return { 'row': parseInt(indices[0]), 'column': parseInt(indices[1]) };
18 }
19
20 // Return the cell location of the format "row,column"
21 cellLocation() {
22 return "" + this.row + "," + this.column;
23 }
24 }
25
26 class Ship {
27 column = 0;
28 row = 0;
29 isVertical = true;
30 hits = 0;
31 element: HTMLElement;
32
33 constructor(public size: number) {
34 this.element = $("<div class='ship'></div>")[0];
35 }
36
37 updatePosition(row: number, column: number, vertical: boolean) {
38 this.row = row;
39 this.column = column;
40 this.isVertical = vertical;
41 this.updateLayout();
42 }
43
44 updateLayout() {
45 var width = "9.9%";
46 var height = "" + (this.size * 9.9) + "%";
47 this.element.style.left = "" + (this.column * 10) + "%";
48 this.element.style.top = "" + (this.row * 10) + "%";
49 this.element.style.width = this.isVertical ? width : height;
50 this.element.style.height = this.isVertical ? height : width;
51 }
52
53 flipShip() {
54 this.isVertical = !this.isVertical;
55 if (this.isVertical) {
56 if (this.row + this.size > 10) {
57 this.row = 10 - this.size;
58 }
59 } else {
60 if (this.column + this.size > 10) {
61 this.column = 10 - this.size;
62 }
63 }
64 this.updateLayout();
65 }
66
67 getCellsCovered() {
68 var cells: string[] = [];
69 var row = this.row;
70 var col = this.column;
71 for (var i = 0; i < this.size; i++) {
72 cells.push(row.toString() + "," + col.toString());
73 if (this.isVertical) {
74 row++;
75 } else {
76 col++;
77 }
78 }
79 return cells;
80 }
81
82 isSunk() {
83 return this.hits === this.size;
84 }
85 }
86
87 class Board {
88 ships: Ship[];
89 cells: Cell[][]; // Indexed by [rows][columns]
90 playerTurn = false; // Set to true when player can move
91 onEvent: Function; // Callback function when an action on the board occurs
92 shipSizes = [5, 4, 3, 3, 2];
93
94 private positioningEnabled: boolean; // Set to true when the player can position the ships
95
96 constructor(public element: HTMLElement, playerBoard: boolean = true) {
97 this.positioningEnabled = playerBoard;
98 this.cells = [];
99 this.ships = [];
100 var cell: Cell = null;
101
102 // Create the cells for the board
103 for (var row = 0; row < 10; row++) {
104 this.cells[row] = [];
105 for (var column = 0; column < 10; column++) {
106 cell = new Cell(row, column);
107 this.cells[row][column] = cell;
108 element.appendChild(cell.element);
109 $(cell.element).data("cellLocation", cell.cellLocation());
110 if (playerBoard) {
111 $(cell.element).droppable({
112 disabled: false,
113 drop: (event, ui) => {
114 var shipElement = <HTMLElement>ui.draggable[0];
115 var shipIndex: number = $(shipElement).data("shipIndex");
116 var ship = this.ships[shipIndex];
117 var shipX = Math.round(shipElement.offsetLeft / cell.element.offsetWidth);
118 var shipY = Math.round(shipElement.offsetTop / cell.element.offsetHeight);
119 ship.updatePosition(shipY, shipX, ship.isVertical);
120 }
121 });
122 }
123 }
124 }
125
126 var referenceCell = $(cell.element);
127 for (var i = 0; i < this.shipSizes.length; i++) {
128 var ship = new Ship(this.shipSizes[i]);
129 this.ships[i] = ship;
130 ship.updatePosition(i, 0, false);
131 if (playerBoard) { // Show the ships for positioning.
132 this.element.appendChild(ship.element);
133 ship.updateLayout();
134 $(ship.element).data("shipIndex", i).draggable({
135 disabled: false,
136 containment: 'parent',
137 // Reduce size slightly to avoid overlap issues blocking the last cell
138 grid: [referenceCell.width() * 0.99 + 2, referenceCell.height() * 0.99 + 2],
139 cursor: 'crosshair'
140 }).click((evt: JQueryEventObject) => {
141 if (this.positioningEnabled) {
142 var shipIndex: number = $(evt.target).data("shipIndex");
143 this.ships[shipIndex].flipShip();
144 }
145 });
146 }
147 }
148
149 $(window).resize((evt) => {
150 $(this.element).children(".ship").draggable("option", "grid", [referenceCell.width() * 0.99 + 2, referenceCell.height() * 0.99 + 2]);
151 });
152
153 if (!playerBoard) {
154 // Computer board, this is where the player clicks to bomb
155 $(element).click((evt: JQueryEventObject) => this.onCellClick(evt));
156 }
157 }
158
159 set dragAndDropEnabled(val: boolean) {
160 var cells = $(this.element).children(".cell");
161 var ships = $(this.element).children(".ship");
162
163 this.positioningEnabled = val;
164 ships.draggable("option", "disabled", !val);
165 cells.droppable("option", "disabled", !val);
166 }
167
168 static getRandomPosition() {
169 return {
170 "row": Math.floor(Math.random() * 10),
171 "column": Math.floor(Math.random() * 10),
172 "vertical": (Math.floor(Math.random() * 2) === 1)
173 }
174 }
175
176 onCellClick(evt: JQueryEventObject) {
177 var x = <HTMLElement>evt.target;
178 if ($(x).hasClass("cell") === false) {
179 return;
180 }
181 if (!this.playerTurn) {
182 this.onEvent.call(this, 'click');
183 }
184 if (this.playerTurn) { // May be updated by prior onEvent call, so check again
185 this.bombCell(x);
186 }
187 }
188
189 bombCell(cellElem: HTMLElement) {
190 var cellPos = Cell.parseCellLocation($(cellElem).data("cellLocation"));
191 var cell = this.cells[cellPos.row][cellPos.column];
192
193 if (cell.hasHit) {
194 return; // Already been clicked on
195 }
196 cell.hasHit = true;
197 if (cell.shipIndex >= 0) { // Has a ship
198 $(cellElem).removeClass("notBombed");
199 $(cellElem).addClass("cellHit");
200 var ship = this.ships[cell.shipIndex];
201 ship.hits++;
202 if (ship.isSunk()) {
203 if (this.allShipsSunk()) {
204 this.onEvent.call(this, 'allSunk');
205 } else {
206 this.onEvent.call(this, 'shipSunk');
207 }
208 } else {
209 this.onEvent.call(this, 'hit');
210 }
211 } else {
212 $(cellElem).removeClass("notBombed");
213 $(cellElem).addClass("cellMiss");
214 this.onEvent.call(this, 'playerMissed');
215 }
216 }
217
218 randomize() {
219 var shipCount = this.ships.length;
220 do {
221 for (var shipIndex = 0; shipIndex < shipCount; shipIndex++) {
222 var pos = Board.getRandomPosition();
223 this.ships[shipIndex].updatePosition(pos.row, pos.column, pos.vertical);
224 }
225 } while (!this.boardIsValid());
226 }
227
228 boardIsValid() {
229 // Check if any ships overlap my checking their cells for duplicates.
230 // Do this by putting into a flat array, sorting, and seeing if any adjacent cells are equal
231 var allCells: string[] = [];
232 for (var i = 0; i < this.ships.length; i++) {
233 allCells = allCells.concat(this.ships[i].getCellsCovered());
234 }
235 allCells.sort();
236 var dups = allCells.some(function (val, idx, arr) { return val === arr[idx + 1]; });
237
238 // See if any ship cells are off the board
239 var outOfRange = allCells.some(function (val: string) {
240 var pos = Cell.parseCellLocation(val);
241 return !(pos.column >= 0 && pos.column <= 9 && pos.row >= 0 && pos.row <= 9);
242 });
243 if (dups || outOfRange) {
244 return false;
245 } else {
246 this.updateCellData();
247 return true;
248 }
249 }
250
251 chooseMove() {
252 do {
253 var pos = Board.getRandomPosition();
254 var cell = this.cells[pos.row][pos.column];
255 } while (cell.hasHit);
256 this.bombCell(cell.element);
257 }
258
259 private updateCellData() {
260 for (var i = 0; i < 100; i++) {
261 var x = this.cells[Math.floor(i / 10)][i % 10];
262 x.hasHit = false;
263 x.shipIndex = -1;
264 }
265
266 for (var index = 0; index < this.ships.length; index++) {
267 var ship = this.ships[index]
268 ship.hits = 0;
269 var cells = ship.getCellsCovered();
270 for (var cell = 0; cell < cells.length; cell++) {
271 var cellPos = Cell.parseCellLocation(cells[cell]);
272 var targetCell = this.cells[cellPos.row][cellPos.column];
273 targetCell.shipIndex = index;
274 }
275 }
276
277 $(this.element).children(".cell").removeClass("cellHit cellMiss").addClass("notBombed");
278 }
279
280 private allShipsSunk() {
281 return this.ships.every(function (val) { return val.isSunk(); });
282 }
283 }
284
285 class Game {
286 static gameState = { begin: 0, computerTurn: 1, playerTurn: 2, finished: 3 };
287 static msgs = {
288 gameStart: "Drag your ships to the desired location on your board (on the right), then bomb a square on the left board to start the game!",
289 invalidPositions: "All ships must be in valid positions before the game can begin.",
290 wait: "Wait your turn!",
291 gameOn: "Game on!",
292 hit: "Good hit!",
293 shipSunk: "You sunk a ship!",
294 lostShip: "You lost a ship :-(",
295 lostGame: "You lost this time. Click anywhere on the left board to play again.",
296 allSunk: "Congratulations! You won! Click anywhere on the left board to play again."
297 };
298
299 state = Game.gameState.begin;
300 playerBoard: Board;
301 computerBoard: Board;
302
303 constructor() {
304 this.updateStatus(Game.msgs.gameStart);
305 this.playerBoard = new Board($("#playerBoard")[0]);
306 this.computerBoard = new Board($("#computerBoard")[0], false);
307 this.computerBoard.randomize();
308 this.playerBoard.randomize();
309 this.playerBoard.dragAndDropEnabled = true;
310 this.computerBoard.onEvent = (evt: string) => {
311 switch (evt) {
312 case 'click': // The user has click outside a turn. Action depends on current state
313 switch (this.state) {
314 case Game.gameState.begin:
315 this.startGame();
316 break;
317 case Game.gameState.computerTurn: // Not their turn yet. Ask to wait.
318 this.updateStatus(Game.msgs.wait);
319 break;
320 case Game.gameState.finished: // Start a new game
321 this.computerBoard.randomize();
322 this.playerBoard.randomize();
323 this.playerBoard.dragAndDropEnabled = true;
324 this.updateStatus(Game.msgs.gameStart);
325 this.state = Game.gameState.begin;
326 break;
327 }
328 break;
329 case 'playerMissed':
330 this.computersTurn();
331 break;
332 case 'hit':
333 this.updateStatus(Game.msgs.hit);
334 this.computersTurn();
335 break;
336 case 'shipSunk':
337 this.updateStatus(Game.msgs.shipSunk);
338 this.computersTurn();
339 break;
340 case 'allSunk':
341 this.state = Game.gameState.finished;
342 this.computerBoard.playerTurn = false;
343 this.updateStatus(Game.msgs.allSunk);
344 break;
345 }
346 };
347 this.playerBoard.onEvent = (evt: string) => {
348 switch (evt) {
349 case 'playerMissed':
350 case 'hit':
351 this.computerBoard.playerTurn = true;
352 break;
353 case 'shipSunk':
354 this.updateStatus(Game.msgs.lostShip);
355 this.computerBoard.playerTurn = true;
356 break;
357 case 'allSunk':
358 this.updateStatus(Game.msgs.lostGame);
359 this.computerBoard.playerTurn = false;
360 this.state = Game.gameState.finished;
361 break;
362 }
363 };
364 }
365
366 private computersTurn() {
367 this.computerBoard.playerTurn = false;
368 this.state = Game.gameState.computerTurn;
369 setTimeout(() => {
370 this.playerBoard.chooseMove();
371 }, 250);
372 }
373
374 private startGame() {
375 if (this.playerBoard.boardIsValid()) {
376 this.state = Game.gameState.playerTurn;
377 this.playerBoard.dragAndDropEnabled = false;
378 this.computerBoard.playerTurn = true;
379 this.updateStatus(Game.msgs.gameOn);
380 }
381 else {
382 this.updateStatus(Game.msgs.invalidPositions);
383 }
384 }
385
386 private updateStatus(msg: string) {
387 $("#status").slideUp('fast', function () { // Slide out the old text
388 $(this).text(msg).slideDown('fast'); // Then slide in the new text
389 });
390 }
391 }
392
393 $(new Function("var game = new Game();"));