Matching pennies is a two-player game of independent heads-or-tails choices. One player wins when the choices differ; the computer wins when it predicts a match. section 8.0
A small playable version needs to:
- Read only 0 or 1 from the player, treating other input as a request to stop. section 8.1
- Generate the computer's choice with a random generator and uniform distribution. section 8.1
- Compare choices, count player wins and turns, and report statistics when play ends. section 8.1
The random version gives the computer roughly half the wins on average. A predictive version instead records recent outcomes and whether the player's choice stayed the same or changed. section 8.0 section 8.2
Learning a predictable pattern
If a player always chooses heads, the recent-choice states eventually show repeated Same choices, allowing the machine to predict the next choice. Alternating every turn produces the corresponding Change pattern. section 8.2
Listing 8.2 A pennies game
#include <random>
void pennies_game()
{
int player_wins = 0; #1
int turns = 0; #1
std::mt19937 gen{ std::random_device{}() }; #2
std::uniform_int_distribution dist(0, 1); #2
std::cout << "Select 0 or 1 at random and press enter.\n"; #2
std::cout << "If the computer predicts your guess it wins.\n"; #2
while (true) #2
{ #2
const int prediction = dist(gen); #2
auto input = read_number(std::cin); #3
if (!input) #4
{ #4
break; #4
}
const int player_choice = input.value();
++turns; #5
std::cout << "You pressed " << player_choice #5
<< ", I guessed " << prediction << '\n'; #5
if (player_choice != prediction) #5
{ #5
++player_wins; #5
}
}
std::cout << "you win " << player_wins << '\n'
<< "I win " << turns - player_wins << '\n';
}
Use the complete pennies-game listing to inspect the input, random generation, loop, prediction, comparison, and statistics together. section 8.1
