OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 /** A boat in the grid. */ | |
6 class Boat { | |
7 final int startX; | |
8 final int startY; | |
9 final bool horizontal; | |
10 final int length; | |
11 int hitCount = 0; | |
12 | |
13 Boat(this.startX, this.startY, this.horizontal, this.length) {} | |
14 | |
15 bool get sunk() => length == hitCount; | |
16 } | |
17 | |
18 /** Represents a grid configuration. */ | |
19 class BoatGrid { | |
20 List<List<Boat>> boatMap; | |
21 | |
22 BoatGrid() : boatMap = new List(Constants.SIZE) { | |
23 for (int i = 0; i < Constants.SIZE; i++) { | |
24 boatMap[i] = new List(10); | |
25 } | |
26 } | |
27 | |
28 void placeBoats(List<Boat> boats) { | |
29 for (int b = 0; b < boats.length; b++) { | |
30 Boat boat = boats[b]; | |
31 for (int i = 0; i < boat.length; i++) { | |
32 int x = boat.startX + (boat.horizontal ? i : 0); | |
33 int y = boat.startY + (boat.horizontal ? 0 : i); | |
34 boatMap[x][y] = boat; | |
35 } | |
36 } | |
37 } | |
38 | |
39 List<int> shoot(GridState state, int x, int y) { | |
40 assert(x >= 0); | |
41 assert(y >= 0); | |
42 assert(x < Constants.SIZE); | |
43 assert(y < Constants.SIZE); | |
44 assert(state.valueAt(x, y) == null); // repeated shot | |
45 Boat b = boatMap[x][y]; | |
46 if (b == null) { | |
47 state.miss(x, y); | |
48 return const [Constants.MISS]; | |
49 } else { | |
50 state.hit(x, y); | |
51 b.hitCount++; | |
52 return b.sunk ? [Constants.SUNK, b.length] : const [Constants.HIT]; | |
53 } | |
54 } | |
55 } | |
56 | |
57 /** Represents the current state of a boat grid. */ | |
58 class GridState { | |
59 List<List<int>> cells; | |
60 | |
61 GridState() | |
62 : cells = new List(Constants.SIZE) { | |
63 for (int i = 0; i < Constants.SIZE; i++) { | |
64 cells[i] = new List(10); | |
65 } | |
66 } | |
67 | |
68 int valueAt(int x, int y) => cells[x][y]; | |
69 | |
70 void miss(int x, int y) { | |
71 cells[x][y] = Constants.MISS; | |
72 } | |
73 | |
74 void hit(int x, int y) { | |
75 cells[x][y] = Constants.HIT; | |
76 } | |
77 | |
78 void pending(int x, int y) { | |
79 cells[x][y] = Constants.PENDING; | |
80 } | |
81 | |
82 void clear(int x, int y) { | |
83 cells[x][y] = null; | |
84 } | |
85 } | |
86 | |
87 | |
88 /** Static constants used by the game. */ | |
89 class Constants { | |
90 static final SIZE = 10; | |
91 static final MISS = 1; | |
92 static final HIT = 2; | |
93 static final SUNK = 3; | |
94 static final PENDING = 4; | |
95 | |
96 Constants() {} | |
97 } | |
OLD | NEW |