-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtemplate_method.cpp
More file actions
58 lines (47 loc) · 1.22 KB
/
template_method.cpp
File metadata and controls
58 lines (47 loc) · 1.22 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
#include <iostream>
#include <string>
using namespace std;
// General Algorithm for a Game
class Game {
public:
explicit Game(int number_of_players) : number_of_players(number_of_players) {}
// general implementation
void run() {
start();
while (!have_winner())
take_turn();
cout << "Player " << get_winner() << " wins.\n";
}
protected:
// template methods for turn based games.
virtual void start() = 0;
virtual bool have_winner() = 0;
virtual void take_turn() = 0;
virtual int get_winner() = 0;
int current_player{0};
int number_of_players;
};
// Particular implementation for a Chess game.
class Chess : public Game {
public:
explicit Chess() : Game{2} {}
protected:
void start() override {
cout << "Starting a game of chess with " << number_of_players
<< " players\n";
}
bool have_winner() override { return turns == max_turns; }
void take_turn() override {
cout << "Turn " << turns << " taken by player " << current_player << "\n";
turns++;
current_player = (current_player + 1) % number_of_players;
}
int get_winner() override { return current_player; }
private:
int turns{0}, max_turns{10};
};
int main() {
Chess chess;
chess.run();
return 0;
}