-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgameServer.cpp
More file actions
65 lines (53 loc) · 1.82 KB
/
Copy pathgameServer.cpp
File metadata and controls
65 lines (53 loc) · 1.82 KB
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
#include "gameCommon.hpp"
#include "gameServer.hpp"
namespace Game::Server {
PlayerBoard::PlayerBoard(int boardWidth, int boardHeight)
: width(boardWidth), height(boardHeight) {}
bool PlayerBoard::AddShip(const Game::Ship& ship) {
for (const auto& pos : ship.squares) {
if (pos.x < 0 || pos.x >= width || pos.y < 0 || pos.y >= height) {
return false;
}
}
for (const auto& existingShip : ships) {
for (const auto& pos : existingShip.squares) {
for (const auto& newShipPos : ship.squares) {
if (pos.x == newShipPos.x && pos.y == newShipPos.y) {
return false;
}
}
}
}
ships.push_back(ship);
return true;
}
bool PlayerBoard::TakeShot(Game::Coords pos) {
for (auto& ship : ships) {
for (size_t i = 0; i < ship.squares.size(); ++i) {
if (ship.squares[i].x == pos.x && ship.squares[i].y == pos.y) {
ship.hits[i] = true;
shots.push_back(Game::Shot(pos, true));
return true;
}
}
}
shots.push_back(Game::Shot(pos, false));
return false;
}
bool PlayerBoard::Shoot(Game::Coords pos, PlayerBoard& other) {
if (pos.x < 0 || pos.x >= width || pos.y < 0 || pos.y >= height) {
return false;
}
return other.TakeShot(pos);
}
bool PlayerBoard::IsDead() {
for (const auto& ship : ships) {
for (const auto& hit : ship.hits) {
if (!hit) {
return false;
}
}
}
return true;
}
}