Question 8
Back to Exercise
Write an abstract Game whose non-virtual play() runs start → turns until finished → end, calling pure virtual hooks; implement a simple CountdownGame and a NumberGuess game with a fixed guess list.
Solution
#include <iostream>
#include <string>
#include <vector>
class Game {
public:
void play() {
start();
int turn = 0;
while (!finished()) take_turn(++turn);
std::cout << "game over after " << turn << " turns: " << winner() << '\n';
}
virtual ~Game() = default;
protected:
virtual void start() = 0;
virtual bool finished() const = 0;
virtual void take_turn(int turn) = 0;
virtual std::string winner() const = 0;
};
class Countdown : public Game {
int n_ = 0;
void start() override { n_ = 3; std::cout << "countdown: "; }
bool finished() const override { return n_ == 0; }
void take_turn(int) override { std::cout << n_-- << ' '; }
std::string winner() const override { return "liftoff"; }
};
class NumberGuess : public Game {
int secret_ = 0; std::vector<int> guesses_{50, 25, 37, 31}; std::size_t i_ = 0; bool won_ = false;
void start() override { secret_ = 31; std::cout << "guessing:\n"; }
bool finished() const override { return won_ || i_ == guesses_.size(); }
void take_turn(int turn) override {
int g = guesses_[i_++];
std::cout << " turn " << turn << ": " << g << (g == secret_ ? " correct" : g < secret_ ? " too low" : " too high") << '\n';
won_ = g == secret_;
}
std::string winner() const override { return won_ ? "player" : "computer"; }
};
int main() {
Countdown c;
c.play();
NumberGuess g;
g.play();
return 0;
}
countdown: 3 2 1 game over after 3 turns: liftoff guessing: turn 1: 50 too high turn 2: 25 too low turn 3: 37 too high turn 4: 31 correct game over after 4 turns: player
The loop structure is written once in the abstract class; games fill in the protected pure virtual steps (template method pattern).
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!