Programming Dice Games in C++: An Introduction to C++ Programming

Mike McMillan
3 min readDec 6, 2023
Photo by Danial Igdery on Unsplash

In this article series I’m going to teach C++ programming by learning how to write programs to play dice games. I picked dice games because they are fun, they are easy to simulate with a computer program, and the dice games we are going to learn use all the techniques covered in a first course in computer programming.

Let me show you a simple example of a dice game (simplified somewhat) written in C++. This dice game involves two dice. Each player starts with 20 points. The game runs by each player rolling both dice. If the sum of the two dice rolls is even, the sum is added to the player’s pot. If the sum of the two rolls is negative, the sum is subtracted from the player’s pot. The first player to lose all their points is the loser of the game.

Here’s the program that simulates this game:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
srand(time(0));
int player1 = 20;
int player2 = 20;
int die1, die2;
while (player1 >= 0 && player2 >= 0) {
// Player 1 rolls
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
int sum = die1 + die2;
if (sum % 2 == 0) {
player1 = player1 + sum;
}
else {
player1 = player1 - sum;
}
cout << "Sum of player 1 roll: " << sum <<…

--

--

Mike McMillan

Mike McMillan writes about computer programming and running. See more of his writing and courses at https://mmcmillan.gumroad.com.