LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Abstract Class Programs · Question 8

Turn-based game skeleton with an abstract class in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
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
main.cpp
#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;
}

Output Verified by compiling and running

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links