forked from R3DHULK/cpp-for-gamers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mastermind.cpp
105 lines (98 loc) · 2.9 KB
/
mastermind.cpp
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;
const int CODE_LENGTH = 4; // Length of the secret code
const int NUM_COLORS = 6; // Number of possible colors
const int MAX_GUESSES = 10; // Maximum number of guesses allowed
// Function to generate a random code
vector<int> generateCode()
{
vector<int> code(CODE_LENGTH);
srand(time(NULL));
for (int i = 0; i < CODE_LENGTH; i++)
{
code[i] = rand() % NUM_COLORS;
}
return code;
}
// Function to get a guess from the player
vector<int> getGuess()
{
vector<int> guess(CODE_LENGTH);
cout << "Enter your guess (0-" << NUM_COLORS - 1 << ") separated by spaces: ";
for (int i = 0; i < CODE_LENGTH; i++)
{
cin >> guess[i];
}
return guess;
}
// Function to compare the guess to the secret code and return the number of exact and partial matches
void checkGuess(const vector<int> &code, const vector<int> &guess, int &numExactMatches, int &numPartialMatches)
{
numExactMatches = 0;
numPartialMatches = 0;
vector<bool> codeUsed(CODE_LENGTH, false);
vector<bool> guessUsed(CODE_LENGTH, false);
// Count exact matches
for (int i = 0; i < CODE_LENGTH; i++)
{
if (code[i] == guess[i])
{
numExactMatches++;
codeUsed[i] = true;
guessUsed[i] = true;
}
}
// Count partial matches
for (int i = 0; i < CODE_LENGTH; i++)
{
if (!codeUsed[i])
{
for (int j = 0; j < CODE_LENGTH; j++)
{
if (!guessUsed[j] && code[i] == guess[j])
{
numPartialMatches++;
guessUsed[j] = true;
break;
}
}
}
}
}
// Function to print a vector
void printVector(const vector<int> &vec)
{
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
}
int main()
{
vector<int> code = generateCode();
cout << "Welcome to Mastermind!" << endl;
cout << "Guess the secret code (0-" << NUM_COLORS - 1 << ") in " << MAX_GUESSES << " or fewer tries." << endl;
for (int guessNum = 1; guessNum <= MAX_GUESSES; guessNum++)
{
cout << endl
<< "Guess #" << guessNum << ":" << endl;
vector<int> guess = getGuess();
int numExactMatches, numPartialMatches;
checkGuess(code, guess, numExactMatches, numPartialMatches);
cout << "Result: ";
printVector(guess);
cout << " - " << numExactMatches << " exact matches, " << numPartialMatches << " partial matches" << endl;
if (numExactMatches == CODE_LENGTH)
{
cout << "Congratulations! You guessed the code in " << guessNum << " tries." << endl;
return 0;
}
}
cout << "Sorry, you ran out of guesses. The secret code was: ";
printVector(code);
cout << endl;
return 0;
}