In this C++ “Bins & Matches” game, two players take turns removing matches from five available bins, until the last match is removed. The player that removes the last match loses the game! When choosing a bin, players must make sure to enter a number 1 through 5. When choosing the number of matches, players must ensure their input is between 1 and the total number of matches in that bin. The program checks for invalid inputs to enforce those rules.
Here is what the game looks like when running:
(It continues on like that until all matches are removed...)
And, here is the code!
#include <iostream>
#include <array>
using namespace std;
void removeMatches(int bins[], int binChoice, int numMatches) {
bins[binChoice - 1] -= numMatches;
}
// Asks the player to select their bin/match choices. Returns false if any choices are invalid
bool askInput(int bins[], int numBins, int player) {
int binChoice;
int numMatches;
printf("It's player %d's turn.\n",player);
// Select bin and check if it is valid:
printf("Select a bin (number between 1 and %d).\n", numBins);
cin >> binChoice;
if(binChoice < 1 || binChoice > numBins) {
return false;
};
// Select matches and check if it is valid:
printf("How many matches would you like to remove from the bin?\n");
cin >> numMatches;
if(numMatches < 1 || numMatches > bins[binChoice-1]) {
return false;
}
removeMatches(bins, binChoice, numMatches);
return true;
}
// Displays the list of bins and their match quantities
void displayGame(int bins[], int numBins) {
printf("The Bins:\n");
for (int i = 0; i < numBins; i++) {
printf(" %d ", bins[i]);
}
printf("\n");
for (int i = 0; i < numBins; i++) {
printf("|_| ", bins[i]);
}
printf("\n");
}
// Checks if any bins are empty
bool isGameOver(int bins[], int numBins) {
for (int i = 0; i < numBins; i++) {
if(bins[i] > 0) {
return false;
}
}
return true;
}
int switchPlayer(int player) {
int ret;