-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.cpp
More file actions
88 lines (78 loc) · 2.19 KB
/
Game.cpp
File metadata and controls
88 lines (78 loc) · 2.19 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// /////////////////////////////////////////////////////////
//
// File: clerdle/Game.cpp
// Author: Michael Foster
// Date: 2022.04.29
//
// This class contains game logic.
//
// /////////////////////////////////////////////////////////
#include "Game.h"
//-------------//
#include <vector>
#include <string>
#include "UX.h"
#include "Guess.h"
#include "Puzzle.h"
#define NUM_ROUNDS 6
#define ALLOWED_CHARS "1234567890+-*/="
Game::Game(Puzzle *puzzle, Game::state state) : puzzle_{puzzle}, completedRounds_{0}
{
if (state == Game::testMode) // in test mode, print the answer first
UX::printTestAnswer(this->puzzle_->getAnswer());
this->rounds_.reserve(NUM_ROUNDS);
for (int i = 0; i < NUM_ROUNDS; i++)
{
this->rounds_.push_back(Guess{});
}
std::vector<Guess::GuessChar> chars;
for (auto c : ALLOWED_CHARS)
{
chars.push_back({c, Guess::unknown});
}
this->usedChars_ = Guess(chars.size());
this->usedChars_.set(chars);
this->play();
// record stats here
}
void Game::play()
{
UX::printGameStart(this->puzzle_->getAnswer().length());
for (int i = 0; i < NUM_ROUNDS; i++)
{ // ROUND loop
std::string guess{};
int attempt{};
while (true)
{ // get a guess
guess = UX::promptGuess(bool(attempt));
if (guess.length() == this->puzzle_->getAnswer().length() && Puzzle::verify(guess))
break;
attempt++;
}
this->rounds_.at(i) = this->puzzle_->compare(guess);
auto newChars = this->usedChars_.getVector();
int correctCount{};
for (auto &c : this->rounds_.at(i).getVector())
{
if (c.state == Guess::correct)
correctCount++;
for (auto &c2 : newChars)
{
if (c2.character == c.character)
{
if (c.state == Guess::correct || (c2.state != Guess::nearby && c2.state != Guess::correct))
c2.state = c.state;
break;
}
}
}
this->usedChars_.set(newChars);
this->won_ = correctCount == int(this->rounds_.at(i).getString().length());
this->completedRounds_++;
UX::printRound(i + 1, this->rounds_, this->usedChars_, this->won_ ? i : -1);
if (this->won_)
break;
}
if (!this->won_)
UX::printLoss(this->puzzle_->getAnswer());
}