Creating Mancala in C++

Mancala is a board game first developed in Egypt, according to its history as found in Ultra Board Games. The game has many names and was first introduced in the United States as Chuba. Mancala is an Arabic name that is based on the movement of the stones. It is a good game to develop in a computer language as it forces the user to use many important features of each language in order to efficiently program the game. In my C++ classes, I break the develop of this code into multiple sections. The first covers writing functions to print a varying length solid line and to print a varying length dotted lines using the characters ‘ ‘ and ‘*’. The second section adds the pit numbers and the stones in each pit. The board has six indentations on either player side and two larger indentations at the end, called Mancalas. The general purpose is to trap as many stones in your own Mancala as possible. The names for the indentations and playing pieces vary quite a bit. For this discussion and my example, I use “pit” for each indentation and “stone” for each playing piece. All of the code is shown in the following videos. I decided to not put in any of the code here (besides the array definition, because students learn so much more by typing the code themselves. The array line for the board’s pits is:

int board[] = { 4,4,4,4,4,4,0,4,4,4,4,4,4,0 };

Each player’s pits are initially filled with four stones each. The two Mancalas are left empty. The pits 0-5 are player 1’s side and pit 6 is player 1’s Mancala. The pits 7-12 are player 2’s side and pit 13 is player 2’s Mancala.

This will create the board. The next code that needs to be written is to create the rules for two players to play the game. The rules are fairly simple after the board is set up with four stones in each of the payers’ six pits.

Adding Moves to the Mancala Game

  1. The two players decide who goes first.
  2. The first player picks up all of the stones in one of their six pits.
  3. They place the stones one at a time in each of the subsequent pits (going counterclockwise) until they run out of stones. Stones can be dropped in their own Mancala, but not in the opponent’s Mancala.
  4. If the last stone lands in their own Mancala, they are able to go again.
  5. If the last stone lands in an empty pit on their own side and there are stones opposite that pit, the stone in the player’s pit and all stones in the opposite pit are captured and placed in the player’s Mancala.
  6. Once all the pits are empty on one side, the other player removes all the stones from their pits and puts them into their own Mancala.
  7. The winner has the most stones.

There are a few variations of rules, but these are the rules that are included in this demonstrations. Mancala is a good way to learn simple mathematics. The Spruce Craft has an interesting introduction to Mancala.

The game still needs to have a capture function written as well as a quick check to see who won. Thank you for looking at this page.

Add Capture of Stones Rule

If you have enough stones to go completely around the board and land the last stone in an empty pit, you are able to take your own stone and all the stones in the opposite pit on your opponent’s side and place all of them in your own Mancala. The interesting fact is that all opposing pits when added to the current player’s landing pit add up to twelve. This makes calculating the opponent’s pit easy. Since this is an easy calculation, I am also adding looping to this example so the users can play multiple games instead of having to restart the process for each game. Because multiple games are now allowed, I am also statistics to the program.

Adding File Input/Output

Once the game has been completed, it is time to start saving the scores to a file. This is done with the include files <fstream> and <sstream>. Both must be added to your include section of the program:

#include <fstream>
#include <sstream>

To read or write to a file, the file must be opened. To prevent memory leaks, be sure to close the file after you have completed your use of the file. Memory leaks are where a connection to a file is kept open and never closed. If the code does this repeatedly, new connections with that file will continue to be opened and none closed. It may be slow, but over time the size of the executable file will continue to grow until it eventually will run out of allocated space. A read from a file would be something like:

ifstream inputFile;
string fileName = "mancala.txt", userName;
int games, wins, losses, ties;
// print Headers for printing out file.
cout << "Name\tGames\tWins\tLosses\tTies" << endl;
// read the information from the file.;        // Try to open
if(inputFile) {                  // If the file was able to be opened, read
    while (input >> userName >> games >> wins >> losses >> ties;) {
       cout << "The line is: " << userName << "\t" << games << "\t" << wins
            << "\t" << losses << "\t" << ties << endl;
inputFile.close();               // Close the file.


When writing a program, it is good to know what needs to be done and design a program that implement those goals. The purpose of this addition is to hold the scores of all the players who have ever played this game. There are three ways we could preceed.

  1. Have one file which keeps all entries. If the same person plays another game, a new line will be added with this information at the end of the file. This will leave multiple copies of the same person’s scores saved with their score each time they played. In reading, the last entry for each player must be read.
  2. Have one file for each player. This is the easiest implementation and is shown in the Adding File Input and Output page.
  3. Store all the players’ names and scores in one file. When starting a new game, the file storing the players’ information and storing all but the current players’ information in a backup file. If a player’s name is not found, all the parameters are initialized to their beginning values. At the end of the games, the backup file is read and the information is put back into the primary file. The two players’ information is added at the end of the file.

Option 3 is what is being implemented in this example. A brief description of what went into the design is in the following video.

Implementing the Design

This example’s code is explained in the following video.

Adding Color and a Player Structure

To make even a console application easier to use, adding color to the game makes the stones more visible. I am including the header file with the color information and a player structure. The player structure is to gather all of the information related to each player, like low pit number and high pit number so that it is all in one place. There is a more thorough description of structures in a separate C++ subpage. The header file I am using is:

#pragma once
/* Player.h
 * Wayne Cook
 * 28 October 2020
 * Purpose:
 *		Create a structure for the required variables for each Mancala player.
 *		Add some color to the game.
 * Modified: 1 November 2020
 *		Add background ANSI Color Definitions to make the Mancala's more distinct

#ifndef __Player__
#define __Player__
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <windows.h>			// Font information for a window
using namespace std;

// Include ANSI Bright Color definitions
#define ANSI_COLOR_BLACK		"\x1b[90m"
#define ANSI_COLOR_RED			"\x1b[91m"
#define ANSI_COLOR_GREEN		"\x1b[92m"
#define ANSI_COLOR_YELLOW		"\x1b[93m"
#define ANSI_COLOR_BLUE			"\x1b[94m"
#define ANSI_COLOR_MAGENTA		"\x1b[95m"
#define ANSI_COLOR_CYAN			"\x1b[96m"
#define ANSI_COLOR_WHITE		"\x1b[97m"
// Include ANSI general color control
#define ANSI_COLOR_BRIGHT		"\x1b[1m"
#define ANSI_COLOR_RESET		"\x1b[0m"
// Include ANSI Bright Background definitions
#define ANSI_BACKGROUND_BLACK	"\x1b[100m"
#define ANSI_BACKGROUND_RED		"\x1b[101m"
#define ANSI_BACKGROUND_GREEN   "\x1b[102m"
#define ANSI_BACKGROUND_YELLOW  "\x1b[103m"
#define ANSI_BACKGROUND_BLUE    "\x1b[104m"
#define ANSI_BACKGROUND_MAGENTA "\x1b[105m"
#define ANSI_BACKGROUND_CYAN    "\x1b[106m"
#define ANSI_BACKGROUND_WHITE   "\x1b[107m"
/* struct Player
 * structs must be declared in the header file or too many errors occur.
 * includes important information about each player
 * Fields:
 *		string name - Player's name
 *		string firstName - student first name
 *		wins,				// Games won
 *		losses,				// Games lost
 *		ties,				// Tie games played
 *		lowPit,				// Low Pit for each player
 *		highPit;			// High Pit for each player
struct Player {
	string name = "Player";			// Player's name
	int games = 0,				// Games played
		wins = 0,			// Games won
		losses = 0,			// Games lost
		ties = 0,			// Tie games played
		mancala = 0,			// Mancala for each player
		lowPit = 0,			// Low Pit for each player
		highPit = 0;			// High Pit for each player

To add color and use the structure, copy the above header and see the video below.

Now that I have the player data defined in a “struct” I can now reduced the code that accesses the variables moved to reside in the Player structure. I reduced the code by removing the two printPlayer routines and replaced them with one void printPlayerLines(int player) routine. This removed 77 lines of code and comments and replaced them with 34 lines of code and comments. A nice savings, The following video describes what was done:

One Response to Creating Mancala in C++

  1. Stuckert says:

    As I website possessor I believe the content material here is real wonderful, thankyou for your efforts.

I would enjoy hearing from you.

This site uses Akismet to reduce spam. Learn how your comment data is processed.