-
Notifications
You must be signed in to change notification settings - Fork 1
/
battleship-ai.js
765 lines (708 loc) · 19.3 KB
/
battleship-ai.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//Ship class
function Ship (name, length) {
this.name = name;
this.shipLength = length;
this.locations = [];
this.hits = [];
}
Ship.prototype.toString = function() {
return this.name;
}
Ship.prototype.clearLocations = function() {
while(this.locations.length != 0) {
this.locations.pop();
}
}
var shipDetails = [
{name: "Carrier", shipLength: 5},
{name: "Battleship", shipLength: 4},
{name: "Submarine", shipLength: 3},
{name: "Cruiser", shipLength: 2},
{name: "Cruiser", shipLength: 2}
]
/*
var Carrier = new Ship("Carrier", 5);
var Battleship = new Ship("Battleship", 4);
var Submarine = new Ship("Submarine", 3);
Carrier.locations = ["00", "01", "02", "03", "04"];
Carrier.hits = [0,0,0,0,0];
Battleship.locations = ["55", "56", "57", "58"];
Battleship.hits = [0,0,0,0];
Submarine.locations = ["97", "87", "77"];
Submarine.hits = [0,0,0];
*/
//Model: keeping the game's state
var model = {
boardSize: 10,
numsShips: 0,
guesses: 0,
fired: [],
ships: [],
//takes a String
fire: function(guess) {
if (this.fired.indexOf(guess) < 0) {
this.fired.push(guess);
model.guesses++;
console.log("Fired at: " + guess);
for (var i = 0; i < this.numsShips; i++) {
var ship = this.ships[i];
var index = ship.locations.indexOf(guess);
if (index >= 0) {
ship.hits[index] = 1;
view.displayHit(guess);
if (this.isSunk(ship)) {
Raymond.sunk.push(ship);
console.log(ship.name + " has been sunk!");
}
console.log("Hit!");
return true;
}
}
view.displayMiss(guess);
console.log("Miss!")
return false;
}
else {
console.log("We have already fired on " + guess + "!");
return false;
}
},
//clears ships
resetShips: function() {
for (var i = 0; i < this.numsShips; i++) {
this.ships[i].clearLocations();
}
guesses = 0;
while (this.fired.length != 0) {
this.fired.pop();
}
},
//check whether ship is sunk
isSunk: function(ship) {
for (var i = 0; i < ship.shipLength; i++) {
if (ship.hits[i] == 0) {
return false;
}
}
return true;
},
allSunk: function() {
for (var i = 0; i < this.numsShips; i++) {
if (!this.isSunk(this.ships[i])) {
return false;
}
}
return true;
},
//calls generateShip
generateShipLocations: function() {
var locations;
var ship;
for (var i = 0; i < this.numsShips; i++) {
ship = this.ships[i];
do {
locations = this.generateShip(ship);
} while (this.collision(locations));
ship.locations = locations;
for (var j = 0; j < ship.shipLength; j++) {
ship.hits.push(0);
}
console.log(ship + ": " + locations);
}
},
//generates a ship and tests whether it collides with another
generateShip: function(ship) {
var direction = Math.floor(Math.random() * 2);
var row, col;
//to keep this in bounds
if (direction === 1) {
//horizontal
row = Math.floor(Math.random() * this.boardSize);
col = Math.floor(Math.random() * (this.boardSize - ship.shipLength));
}
else {
//vertical
row = Math.floor(Math.random() * (this.boardSize - ship.shipLength));
col = Math.floor(Math.random() * this.boardSize);
}
var newShipLocations = [];
for (var i = 0; i< ship.shipLength; i++) {
if (direction === 1) {
newShipLocations.push(row + "" + (col + i));
}
else {
newShipLocations.push((row + i) + "" + col);
}
}
return newShipLocations;
},
//checks whether the locations generated collide with
//coordinates of another ship
collision: function(locations) {
for (var i = 0; i < this.ships.length; i++) {
var ship = this.ships[i];
//goes through array and checks
for (var j = 0; j < locations.length; j++) {
if (ship.locations.indexOf(locations[j]) >= 0) {
return true;
}
}
}
return false;
},
isOver: function() {
for (var i = 0; i < this.ships.length; i++) {
if (!this.isSunk(this.ships[i])) {
return false;
}
}
return true;
},
numberTries: function() {
//to account for boxes that already contain ships
var tries = 0;
var current;
for (var i = 0; i < model.boardSize; i++) {
for (var j = 0; j < model.boardSize; j++) {
current = i + "" + j;
if (document.getElementById(current).classList.contains("hit") || document.getElementById(current).classList.contains("miss")) {
tries++;
}
}
}
return tries;
}
};
//View: visual representation
var view = {
displayShips: function() {
var ship;
var box;
for (var i = 0; i < model.numsShips; i++) {
ship = model.ships[i];
for (var j = 0; j < ship.shipLength; j++) {
box = document.getElementById(ship.locations[j]);
box.setAttribute("class","ship");
}
}
},
displayHit: function(location) {
var box = document.getElementById(location);
box.setAttribute("class", "hit");
},
displayMiss: function(location) {
var box = document.getElementById(location);
box.setAttribute("class", "miss");
},
clearScreen: function() {
var boxt;
for (var i = 0; i < model.boardSize; i++) {
for (var j = 0; j < model.boardSize; j++) {
box = document.getElementById(i + "" + j);
box.setAttribute("class","");
}
}
}
};
//Controller: Glues everything together
var controller = {
Raymond: function() {
Raymond.initialSetUp();
while (!model.isOver()) {
Raymond.play();
}
console.log("Raymond made " + model.guesses);
},
getShips: function() {
//generate the ships and add them to ships
for (var i = 0; i < shipDetails.length; i++) {
var current = shipDetails[i];
var ship = new Ship(current.name, current.shipLength);
model.ships.push(ship);
model.numsShips++;
}
}
};
//Artificial Intelligence
var Raymond = {
Row: 10,
Col: 10,
probabilities: new Array(this.Row),
fired: [],
sunk: [],
//create the initial array; set everything to zero
//go through and calculate initial probabilities
initialSetUp: function () {
for (var i = 0; i < this.Row; i++) {
//declare cols for each row
this.probabilities[i] = new Array(this.Col);
for (var j = 0; j < this.Col; j++) {
this.probabilities[i][j] = 0;
}
}
var currentLength;
//calculating initial probabilities
for (var i = 0; i < this.Row; i++) {
for (var j = 0; j < this.Col; j++) {
for (var k = 0; k < model.ships.length; k++) {
currentLength = model.ships[k].shipLength;
//horizontal
if ((j + currentLength - 1) <= (this.Col - 1)) {
for (var l = 0; l < currentLength; l++) {
this.probabilities[i][j + l]++;
}
}
//vertical
if ((i + currentLength - 1) <= (this.Row - 1)) {
for (var l = 0; l < currentLength; l++) {
this.probabilities[i + l][j]++;
}
}
}
}
}
},
//sets everything to zero
resetProbabilities: function() {
for (var i = 0; i < this.Row; i++) {
for (var j = 0; j < this.Col; j++) {
this.probabilities[i][j] = 0;
}
}
},
//recalculates according to ships left
recalculateProbabilities: function() {
var currentLength;
// recalculate probabilities based on ships left and squares not hit
for (var i = 0; i < this.Row; i++) {
for (var j = 0; j < this.Col; j++) {
if (this.fired.indexOf(i + "" + j) >= 0) {
this.probabilities[i][j] = Number.MIN_SAFE_INTEGER;
continue;
}
for (var k = 0; k < model.ships.length; k++) {
if (this.sunk.indexOf(model.ships[k])) {
continue;
}
currentLength = model.ships[k].shipLength;
//horizontal
if ((j + currentLength - 1) <= (this.Col - 1)) {
for (var l = 0; l < currentLength; l++) {
this.probabilities[i][j + l]++;
}
}
//vertical
if ((i + currentLength - 1) <= (this.Row - 1)) {
for (var l = 0; l < currentLength; l++) {
this.probabilities[i + l][j]++;
}
}
}
}
}
},
//guess: need to randomise ties
guess: function() {
var maxValue = Number.MIN_SAFE_INTEGER;
var maxLocation = 0;
for (var i = 0; i < this.Row; i++) {
for (var j = 0; j < this.Col; j++) {
if (this.probabilities[i][j] > maxValue) {
//this currently chooses the first max tile
maxValue = this.probabilities[i][j];
maxLocation = i + "" + j;
}
}
}
//returns string
console.log("Current max: " + maxValue);
return maxLocation;
},
//update probabilities array after each shot
//remove even if hit because hunt mode will sink ship
updateProbabilities: function(location) {
//console.log(location);
//console.log("We update probabilities!");
var location = parseInt(location);
var currentLength;
var row = Math.floor(location / 10);
var col = location % 10;
var start;
//console.log(row);
//console.log(col);
for (var i = 0; i < model.ships.length; i++) {
currentLength = model.ships[i].shipLength;
//horizontal
for (var j = 0; j < currentLength; j++) {
start = col - j;
if ((start >= 0) && ((start + currentLength - 1) <= (this.Col - 1))) {
for (var k = 0; k < currentLength; k++) {
this.probabilities[row][start + k]--;
//console.log("updating!");
}
}
}
// vertical
for (var j = 0; j < currentLength; j++) {
start = row - j;
if ((start >= 0) && ((start + currentLength - 1) <= (this.Row - 1))) {
for (var k = 0; k < currentLength; k++) {
this.probabilities[start + k][col]--;
//console.log("updating!");
}
}
}
}
this.probabilities[row][col] = Number.MIN_SAFE_INTEGER;
},
//used in conjunction with huntMode2
isShip: function(location) {
var ship;
for (var i = 0; i < model.numsShips; i++) {
if (model.ships[i].locations.indexOf(location) >= 0) {
ship = model.ships[i];
}
}
return ship;
},
//targets and hits all adjacent squares till the ship is sunk
huntMode2: function(location) {
var row;
var col;
var location;
var targets = [];
var locations = [];
var toBeUpdated = [];
toBeUpdated.push(location);
locations.push(location);
var ship = this.isShip(location);
while (!model.isSunk(ship)) {
location = locations.pop();
row = Math.floor(location/10);
col = location % 10;
if ((row - 1) >= 0) {
targets.push((row - 1) + "" + col);
}
if ((row + 1) <= (this.Row - 1)) {
targets.push((row + 1) + "" + col);
}
if ((col - 1) >= 0) {
targets.push(row + "" + (col - 1));
}
if ((col + 1) <= (this.Col - 1)) {
targets.push(row + "" + (col + 1));
}
var current;
innerLoop: {
for (;targets.length != 0;) {
current = targets.pop();
if (this.fired.indexOf(current) < 0) {
toBeUpdated.push(current);
this.fired.push(current);
if (model.fire(current)) {
console.log("NEW TARGET!");
locations.push(current);
break innerLoop;
}
}
}
}
}
while (toBeUpdated.length !== 0) {
this.updateProbabilities(toBeUpdated.pop());
}
this.resetProbabilities();
this.recalculateProbabilities();
},
//uses probability to target till the ship is sunk
huntMode3: function(location) {
var row;
var col;
var current;
var ship;
var length;
var currentSunk = this.sunk.length;
var numberOfHits = 0;
var hits = [];
var probabilities = [];
var toBeUpdated = [];
var locations = [];
var firedToBeUpdated = [];
hits.push(location);
firedToBeUpdated.push(location);
locations.push(location);
toBeUpdated.push(location);
//initialise the probabilities; set all to zero
for (var i = 0; i < this.Row; i++) {
//declare cols for each row
probabilities[i] = new Array(this.Col);
for (var j = 0; j < this.Col; j++) {
probabilities[i][j] = 0;
}
}
//continue until we sink one ship
while (this.sunk.length === currentSunk) {
//console.log("hunting");
//update if there is a need to; after a hit
if (locations.length != 0) {
this.printProbabilities1(probabilities);
current = locations.pop();
row = Math.floor(current/10);
col = current % 10;
//check if location can support a ship, and update if it can
for (var i = 0; i < model.numsShips; i++) {
ship = model.ships[i];
//if ship has been sunk, we ignore its possibility
if (this.sunk.indexOf(ship) >= 0) {
continue;
}
length = ship.shipLength - numberOfHits;
//check if location has already been hit
//vertical
for (var j = 0; j < length; j++) {
//console.log("length: " + length);
//console.log("j: " + j);
//check if it is within the square
if (((row + j) < this.Row) && ((row + j - length + 1) >= 0)) {
//check and update if possible
if (this.huntCheckPossibleVertical((row + j), col, length)) {
//console.log("hit add vertical: " + (row + j) + col);
this.huntUpdatePossibilitiesVertical(row + j, col, probabilities, current,length);
}
}
}
//horizontal
for (var j = 0; j < length; j++) {
//check if it is within the square
if (((col + j) < this.Col) && ((col + j - length + 1) >= 0)) {
//check and update if possible
if (this.huntCheckPossibleHorizontal(row, (col + j), length)) {
//console.log("hit add horizontal: " + row + + (col + j));
this.huntUpdatePossibilitiesHorizontal(row, (col + j), probabilities, current, length);
}
}
}
}
//set hit to minimum
probabilities[row][col] = -1000;
this.printProbabilities1(probabilities);
}
//choose probability to fire
current = this.guessHunt(probabilities);
//console.log(current);
toBeUpdated.push(current);
//if hit we update the probabilities
if (model.fire(current)) {
hits.push(current);
locations.push(current);
numberOfHits++;
firedToBeUpdated.push(current);
}
else {
//update for misses
this.fired.push(current);
this.huntUpdateMisses(probabilities, current, hits);
}
}
//update hit locations in global fired
while (firedToBeUpdated.length !== 0) {
this.fired.push(firedToBeUpdated.pop());
}
//update all shots in global probabilities
while (toBeUpdated.length !== 0) {
this.updateProbabilities(toBeUpdated.pop());
}
},
//guess: for hunt mode
guessHunt: function(probabilities) {
var maxValue = Number.MIN_SAFE_INTEGER;
var maxLocation = 0;
for (var i = 0; i < this.Row; i++) {
for (var j = 0; j < this.Col; j++) {
if (probabilities[i][j] > maxValue) {
//this currently chooses the first max tile
maxValue = probabilities[i][j];
maxLocation = i + "" + j;
}
}
}
//returns string
console.log("Hunt - current max: " + maxValue);
return maxLocation;
},
//update misses
huntUpdateMisses: function(probabilities, location, hits) {
this.printProbabilities1(probabilities);
var row = Math.floor(location / 10);
var col = location % 10;
var length = 0;
var start;
console.log("row: " + row);
console.log("col: " + col);
for (var i = 0; i < model.numsShips; i++) {
if (Raymond.sunk.indexOf(model.ships[i]) < 0 && model.ships[i].shipLength > length) {
length = model.ships[i].shipLength;
}
}
console.log(length);
//down vertical
if (hits.indexOf((row - 1) + "" + col) >= 0) {
for (var i = 1; i < length; i++) {
if((row + i) < this.Row) {
probabilities[row + i][col] = -1000;
console.log("down");
}
}
}
//up vertical
else if (hits.indexOf((row + 1) + "" + col) >= 0) {
console.log('here');
for (var i = 1; i < length; i++) {
console.log(row - i);
if((row - i) >= 0) {
probabilities[row - i][col] = -1000;
console.log("up");
}
}
}
//right horizontal
else if (hits.indexOf(row + "" + (col - 1)) >= 0) {
for (var i = 1; i < length; i++) {
if((col + i) < this.Col) {
probabilities[row][col + i] = -1000;
console.log("right");
}
}
}
//left horizontal
else if (hits.indexOf(row + "" + (col + 1)) >= 0) {
for (var i = 1; i < length; i++) {
if((col - i) >= 0) {
probabilities[row][col - i] = -1000;
console.log("left");
}
}
}
probabilities[row][col] = -1000;
//console.log("hello");
this.printProbabilities1(probabilities);
},
//check if location can accomodate ship, takes a location, and an int
//these take increasing locations
huntCheckPossibleVertical: function(row, col, length) {
//go through probability array and check if there is a spot already fired on
//note we skip the original location as it has already been fired upon
//vertical
for (var i = 1; i < length; i++) {
//console.log((row - i) + "" + col);
//check if already hit
if (this.fired.indexOf((row - i) + "" + col) >= 0) {
//console.log("hunt check vertical: " + (row - i) + col);
return false;
}
}
return true;
},
//these take increasing locations
huntCheckPossibleHorizontal: function(row, col, length) {
//go through probability array and check if there is a spot already fired on
//note we skip the original location as we first check
//horizontal
for (var i = 1; i < length; i++) {
//console.log(row + "" + (col - i));
//check if already hit
if (this.fired.indexOf(row + "" + (col - i)) >= 0) {
//console.log("hunt check horizontal: " + row + (col - i));
return false;
}
}
return true;
},
//takes increasing locations: when hit
huntUpdatePossibilitiesVertical: function(row, col, probabilities, location, length) {
for (var i = 0; i < length; i++) {
//console.log("Update" + (row - i) + "" + col);
if (((row - i) + "" + col) === location) {
continue;
}
probabilities[row - i][col]++;
//console.log("Update probability " + probabilities[row - i][col]);
}
},
//takes increasing locations: when hit
huntUpdatePossibilitiesHorizontal: function(row, col, probabilities, location, length) {
for (var i = 0; i < length; i++) {
//console.log(row + "" + (col - i));
if ((row + "" + (col - i)) === location) {
//console.log("hello");
continue;
}
probabilities[row][col - i]++;
}
},
//play the Game: Raymond calculate the probabilities and takes a guess, updating if he misses
play: function() {
var hit;
var location;
location = this.guess();
hit = model.fire(location);
//this.fired.push(location);
if (hit && Raymond.sunk.length != model.numsShips) {
this.huntMode3(location);
}
else {
this.fired.push(location);
this.updateProbabilities(location);
}
},
fire1: function(location) {
var hit;
//var location;
//location = this.guess();
hit = model.fire(location);
//this.fired.push(location);
if (hit && Raymond.sunk.length != model.numsShips) {
this.huntMode3(location);
}
else {
this.fired.push(location);
this.updateProbabilities(location);
}
},
//check the probabilities array
printProbabilities: function() {
for (var i = 0; i < this.probabilities.length; i++) {
var current = "";
for (var j = 0; j < this.probabilities[i].length; j++) {
//current = current + this.probabilities[i][j] + " ";
console.log((i * 10 + j) + " "+ this.probabilities[i][j]);
}
console.log(current);
}
},
printProbabilities1: function(probabilities) {
var current = "";
for (var i = 0; i < probabilities.length; i++) {
for (var j = 0; j < probabilities[i].length; j++) {
//current = current + this.probabilities[i][j] + " ";
current += probabilities[i][j] + " ";
}
current += "\n";
}
console.log(current);
},
lookUp: function(location) {
var row = Math.floor(location / 10);
var col = location % 10;
return this.probabilities[row][col];
}
};
//event handlers
function init() {
controller.getShips();
model.generateShipLocations();
view.displayShips();
controller.Raymond();
//tester();
}
window.onload = init;