How to Write a Simple C++ Game in 15 Minutes

One of the things that have always fascinated me in programming is coding a game. I believe that many programmers take up C++ in order to create their first game. Although there are lots of different things that you need to be knowledgeable of to create a 2d or 3d game, you could actually be writing a small but entertaining c++ game in just a matter of minutes or hours.
In this tutorial, i will be showing you how to create a small console based game. It is a mastermind variant where you are given a number and you are then asked to guess whether the next number is going to be higher or lower. I actually created this game in about 10-15 minutes, so it is actually feasible to write such a small game in a really short period of time. And it is also quite entertaining i must say
#include <iostream> #include <time.h> using namespace std; int main() { cout << "This is a very simple number guessing game. Each time you will be given a number of the range 0-10." << endl; cout << "The objective of the game is to guess whether the next number is going to be higher or not. As simple as that." << endl; cout << "You have the ability to make no more than 3 mistakes before you lose, so guess wisely." << endl << endl; cout << "You are starting with number 5. Is the next number higher(write H) or lower(write L) ?" << endl; int mistakes = 0; int correctGuesses; int prevNum = 5, nextNum; char choice; do { srand ( time(NULL) ); do nextNum = rand() % 11; while (nextNum == prevNum); cin >> choice; if (choice == 'H') { if (prevNum < nextNum) { cout << "Correct ! The new number is " << nextNum << endl; correctGuesses++; } else if (prevNum > nextNum) { cout << "Wrong, you made a mistake ! The new number is " << nextNum << endl; mistakes++; } } if (choice == 'L') { if (prevNum > nextNum) { cout << "Correct ! The new number is " << nextNum << endl; correctGuesses++; } else if (prevNum < nextNum) { cout << "Wrong, you made a mistake ! The new number is " << nextNum << endl; mistakes++; } } prevNum = nextNum; } while(mistakes < 3); cout << "You've made 3 mistakes ! Game is now over !" << endl; cout << "You had " << correctGuesses << " correct guesses before the game was over" << endl; return 0; }
Let’s first execute this and play the game :
This is a very simple number guessing game. Each time you will be given a number of the range 0-10.
The objective of the game is to guess whether the next number is going to be higher or not. As simple as that
You have the ability to make no more than 3 mistakes before you lose, so guess wisely.
You are starting with number 5. Is the next number higher(write H) or lower(write L) ?
H
Correct ! The new number is 8
L
Correct ! The new number is 7
L
Correct ! The new number is 6
L
Correct ! The new number is 4
H
Wrong, you made a mistake ! The new number is 3
L
Correct ! The new number is 1
H
Correct ! The new number is 10
L
Correct ! The new number is 7
L
Correct ! The new number is 4
H
Wrong, you made a mistake ! The new number is 2
H
Wrong, you made a mistake ! The new number is 0
You’ve made 3 mistakes ! Game is now over !
You had 8 correct guesses before the game was over
This game is pretty easy to create as you can see. First of all, we declare the important variables that help us preserve the state of the game. This way, we know how many mistakes the user made and how many correct guesses they had. We utilize a do – while loop to start asking the user for H or L. Then, there is also another do – while that is used to pick a random number ranged from 0 to 10. We use this loop so that we are sure that the next number which is randomly selected is not the same as the previous one. Notice that “rand() % 11” picks our number. % is the mod calculation, which provides us with the remainder of the equation “randomValue / 11”, which is of course a value ranging from 0 to 10.
Then, after we pick the next number, we start checking against this new value and the previous one, based on what the user provided us with as input ( H for higher, L for lower). After the checking is over, we increment the correct or wrong counter and make the current nextNum the new prevNum that is used for the next iteration.
The do – while loop keeps going on till 3 mistakes are made. Of course, you can change that, or better yet declare it to be a constant value. I kept it simple in this example. In the end, we get a report of our ingame progress.
Wasn’t this game development interesting and easy ? Of course, you could take it even further by designing a statistics system that will trace and store your answers, keep highscores and more. I would actually like to get a copy of the program where highscores are included, so if anybody has the will to practice on that and develops it, please send it to me. I will definately publish it here.
Thanks-interesting post and quick .cpp game code.
I am no C expert (!) but this would not compile & run for me without adding:
#include Once added all fine
this program is very simple……but i can’compile………..why?
what is the error that you are getting ?
Mmmm-This comment box doesn’t seem to handle code tags?!
(see my previous post above)
It should be
that is># include cstdlib
….:-)
fuck you this even not working you asshole bitch!!!!!!!!!!!!!!!!!!!!!!!!!!
I am a little confused.
Why was this line included:
prevNum = nextNum;
@Joey : They are simply holders for the previous and next selected numbers. For each new iteration, the prevNum becomes the same as nextNum, in order to restart the whole calculation with the newly selected number.
When i debug it and play the game. The first time i get the answer correctly, it states that there’s a “Run-Time Check Failure #3 – The variable ‘correctGuesses’ is being used without being initialized.” How do i fix this to make it run more smoothly?
Change the line to make it : int correctGuesses = 0;
Luciana Saletta scg1ie:LRi7;vrnoranza regna sovrana anche tra chi non dovrebbe ignorare. Spero, per questi ragazzi, che la stupidità di questo insegnante sia meno contagiosa delle infezioni e delle malattie.
hey, this is a pretty nifty piece of coding, simple to program and keeps entertained for as long as the attention span lasts
This is an awesome basic game. I changed the wrong line so I feel really bad when i guess wrong but it is still really cool
Hi there.. I want to learn c++. I just started yesterday and I have no book or anything, so I just want to learn by doing it. I downloaded Microsoft Visual C++ 2010 Express for free. I don’t know if that programm is any good..
so do I just copy and paste that stuff? And as what do I have to save it so I can play the game? I tried saving it as .cpp put that only made the programm start when I clicked on the file… Do I have to save it as .exe or something.
Please help me!
No
After a few steps, one can guess the correct number. One could re-write this code adding an option for entering the exact number at any step, if one could guess what that exact number is. You could give them only one chance, if player is wrong, he/she loses the game. The way you created the game, anyone will eventually lose this game!
like:
if choice == ‘S’ //’S’ for same number
{
cout << "Yes, the correct answer is " << prevNum << " You won!";
}
Thanks for the program, after debugging the program it finally ran, but the number of corrrect guesses is still wrong, how do i fix it??
I try to cover everything about this in a white paper I did orgianilly for the boost development wiki. It’s available around the net in various forms but the most recent version is at . Hope this helps. Patrick
assuming you don’t get a cploime error of type conversion Then don’t have your language do automatic conversion (Ocaml does not, 1.0/2.0 is a type error). isn’t a good one since it doesn’t actually address #2 And I am saying you are conflating two problems, which don’t necessarily need the same solution. One is the definition of an operation. The other is what to do on the edges of that operation. Separate operators also becomes extremely burdensom with custom types and modifiers. Do unsigned and signed values get different operators? It depends on the goal of your language. Higher level languages tend to only have a few numeric types. Or some languages have typeclasses to deal with this, which gives you one operator but you can only use it in particular contexts. In Ocaml you can also locally import a module, so Float.(1.0/2.0) is the same as 1.0 /. 2.0.
hi!!!! friends this is s d jena from jawahar navodaya vidyalaya , kendrapara reading in class xi and wants to become a computer engineer.so what should i do
@Jena, keep on studying and learn a programming language like C++ or Python for starters
Argh! Is not working! ” ‘srand’ should have a prototype”, same with ‘rand’ and a lot more:11 errors, 3 warnings! What version of c++ you have?
@metalbrain : If i recall correctly, this was written in Visual Studio, but i could be wrong, it’s been a while.
but i executed the program , but it has run time errors !!!
hey what do i put in anmespace and what lib is used to define srand and null
Merely a fast hello as well as appreciate dinsscsiug your ideas on this website. I appeared within your blog once researching exercise and fitness connected issues on Yahoo guess I lost with a few things i was performing! Anyway We will be back the minute once more from the long haul to substantiate out of the blogposts later on. Thanks!
Hey, thought I’d drop by to let you know that I’ve slightly toyed with a high scores system.
The simplest method of implementation is creating a text file (highscores.txt, for example) with 0 in it initially. After the game ends, the following code will check whether or not the guesses are higher than the high score in the text document:
#include //Includes the library for file I/O
…
ifstream checkScore; //Input file pointer
ofstream loadScore; //Output file pointer
…
checkScore.open(“highscores.txt”); //Reads the value from highscores.txt into the checkScore pointer
checkScore >> score; //Saves the value of checkScore to the variable score
if (correctGuesses > score) { //Checks if the number of guesses is higher than the high score
cout << "Congratulations! You now hold the high score!" << endl << endl; //Outputs a message
saveScore.open("highscores.txt"); //Opens highscores.txt for writing and assigns it to saveScore
saveScore << correctGuesses; //Prints the number of guesses to the file highscores.txt
}
@Ryan : That’s a nice one ! Feel free to send me a guest post with that if you like, I will be happy to publish
astaxie 我在使用你的主题Typecho过程中,装好之后就出现如下错误: PHP Fatal error: Using $this when not in object ctxeont in wp-content/themes/trapecho/index.php on line 11″ while reading response header from upstream
Please help me in this…. i am using dev c++..
You have to make a racing game in C++.
There are two players in your program. They play by throwing 3 dices and then moving forward.
Your program should start and ask you to press any key for a toss. After a fair toss, one of the players i.e. player 1 or player 2 starts the game. (use rand and srand function for fair toss)
Your screen must show a red perpendicular line on the right side of the screen i.e. finish line.
Player1*
Player2 *
User must be able to see two players standing at the left side of the screen. (* symbol shows each player).
At the start of the game the players are standing at start line.
The player who wins the toss starts the game and presses a key to throw 3 dices (use rand and srand). If the sum of all three dices is exactly equal to 10 then the player moves one step forward (towards right) and plays again (must use recursion for playing again). If next time again the sum is equal to 10 player moves forward and plays again…
If at any time the sum of three dices is not 10, player who was playing stops playing and other player starts playing and the whole procedure repeats (while or do while loop)until one of them has crossed finish line. After takinYou have to make a racing game in C++.
There are two players in your program. They play by throwing 3 dices and then moving forward.
Your program should start and ask you to press any key for a toss. After a fair toss, one of the players i.e. player 1 or player 2 starts the game. (use rand and srand function for fair toss)
Your screen must show a red perpendicular line on the right side of the screen i.e. finish line.
Player1*
Player2 *
User must be able to see two players standing at the left side of the screen. (* symbol shows each player).
At the start of the game the players are standing at start line.
The player who wins the toss starts the game and presses a key to throw 3 dices (use rand and srand). If the sum of all three dices is exactly equal to 10 then the player moves one step forward (towards right) and plays again (must use recursion for playing again). If next time again the sum is equal to 10 player moves forward and plays again…
If at any time the sum of three dices is not 10, player who was playing stops playing and other player starts playing and the whole procedure repeats (while or do while loop)until one of them has crossed finish line. After taking 30 steps, the player reaches finish line and on the 31st step the player crosses the finishing line
hiii guys its nikki i need a game programing to design a game for my project so is there anyone how help me
hi. i try to run program but it s error that unable to open include file ” iostream” and ‘time.h’ and declaration syntax error and undefined symbol ‘cout’
it should be iostream.h
TRY C++ AND IT WILL WORK
Hey Guys Plz help its urgent!!!!!
In this program why do is used 2 times
Secondly, why prevNum=nextNum!
and if i want to add an option of do you want to play again that how will it be possible?
seeking for a kind reply
Hey ALI, here’s a version that allows replay.
#include
#include
#include
using namespace std;
int main()
{
cout << "This is a very simple number guessing game. Each time you will be given a number of the range 0-10." << endl;
cout << "The objective of the game is to guess whether the next number is going to be higher or not. As simple as that." << endl;
cout << "You have the ability to make no more than 3 mistakes before you lose, so guess wisely." << endl << endl;
cout << "You are starting with number 5. Is the next number higher(write H) or lower(write L) ?" << endl;
int mistakes = 0;
int correctGuesses = 0;
int prevNum = 5, nextNum;
char choice;
enum decis {N,Y};
int replay = 0;
do
{
//cout<<"Please guess the next number"<> choice;
if (choice == ‘H’)
{
if (prevNum < nextNum)
{
cout << "Correct ! The new number is " << nextNum << endl;
correctGuesses++;
cout<<"Please guess the next number"< nextNum)
{
cout << "Wrong, you made a mistake ! The new number is " << nextNum << endl;
mistakes++;
if (mistakes < 3)
cout<<"Please guess the next number"< nextNum)
{
cout << "Correct ! The new number is " << nextNum << endl;
correctGuesses++;
cout<<"Please guess the next number"<<endl;
}
else if (prevNum < nextNum)
{
cout << "Wrong, you made a mistake ! The new number is " << nextNum << endl;
mistakes++;
if (mistakes < 3)
cout<<"Please guess the next number"<<endl;
}
}
if(mistakes == 3)
{
cout << "You've made 3 mistakes ! Game is now over !" << endl;
cout << "You had " << correctGuesses << " correct guesses before the game was over" << endl<<endl;
cout << "Would you like to keep playing? 1 for Yes, any for No" << endl<> replay;
if (replay == 1)
{
mistakes = 0;
cout << "Restarting Game" << endl<<endl;
cout << "Last number was "<< nextNum <<", higher or lower?"<< endl;
}
else
cout<<"Game Over";
}
prevNum = nextNum;
}
while(mistakes < 3);
return 0;
}
OK, I fiqured it out after TWO nights of probing and researching the different errors. There was one library missing in the #include section:
#include
When i added that, it worked!! Try it.
Thats: #include sorry.
Hi Doug,When I first posted a list of six good C++ dlvneopmeet environments I did not know of an Eclipse based package that included everything needed for C++ dlvneopmeet. But this time around I discovered your project then called CDT for Windows(now Wascana), and I am sure that it will fill the void of a good, standalone, Free C++ IDE on (at least) Windows platform. I have a draft post saved on Wascana(using 0.9.2 version) and will post it in a few days.You are doing a great job by packaging everything needed for C++ dlvneopmeet as one application and I hope that, given time, it will be found on most of the C++ developers’ desktops.
code formatted wrong, hope this works
#include
#include
#include
using namespace std;
int main()
{
cout << "This is a very simple number guessing game. Each time you will be given a number of the range 0-10." << endl;
cout << "The objective of the game is to guess whether the next number is going to be higher or not. As simple as that." << endl;
cout << "You have the ability to make no more than 3 mistakes before you lose, so guess wisely." << endl << endl;
cout << "You are starting with number 5. Is the next number higher(write H) or lower(write L) ?" << endl;
int mistakes = 0;
int correctGuesses = 0;
int prevNum = 5, nextNum;
char choice;
enum decis {N,Y};
int replay = 0;
do
{
//cout<<"Please guess the next number"<> choice;
if (choice == 'H')
{
if (prevNum < nextNum)
{
cout << "Correct ! The new number is " << nextNum << endl;
correctGuesses++;
cout<<"Please guess the next number"< nextNum)
{
cout << "Wrong, you made a mistake ! The new number is " << nextNum << endl;
mistakes++;
if (mistakes < 3)
cout<<"Please guess the next number"< nextNum)
{
cout << "Correct ! The new number is " << nextNum << endl;
correctGuesses++;
cout<<"Please guess the next number"<<endl;
}
else if (prevNum < nextNum)
{
cout << "Wrong, you made a mistake ! The new number is " << nextNum << endl;
mistakes++;
if (mistakes < 3)
cout<<"Please guess the next number"<<endl;
}
}
if(mistakes == 3)
{
cout << "You've made 3 mistakes ! Game is now over !" << endl;
cout << "You had " << correctGuesses << " correct guesses before the game was over" << endl<<endl;
cout << "Would you like to keep playing? 1 for Yes, any for No" << endl<> replay;
if (replay == 1)
{
mistakes = 0;
cout << "Restarting Game" << endl<<endl;
cout << "Last number was "<< nextNum <<", higher or lower?"<< endl;
}
else
cout<<"Game Over";
}
prevNum = nextNum;
}
while(mistakes < 3);
return 0;
}
Just cause it’s simple doesn’t mean it’s not super helflup.
62 I’m pretty sure the post just above you answered the question quite clearly.“FB&G is independently owned and operated. ESPN does not dictate how I run the site.”
I’m impressed! You’ve managed the almost impossible.
You sure that was The Gap and not Olsen's General Store? Don't wear a showy bonnet, or Nelly Olsen might try to push you down the hill. She's very competitive. Sorry if these references are foreign; I don't know if you Canadians dig Little House. Either way, your closet sounds both organized and frontier-chic. If I had any prairie skirts in my closet, I'd have to keep it for life just in case I got invited to a square dance. I live in fear of being unprepared for theme parties.
Zapatero tiene una obsesión, el deficit público y le importa un bledo las medidas que tenga que tomar para reducirlo y asà satisfacer a la UE, el FMI y los mercados expeculativos.Es capaz de vender el paÃs al mejor postor para conseguir su objetivo y eliminar de paso lo poco que queda del estado del bienestar y de paso le pone la alfonmbra al Rajoy para que llegue a la Moncloa.Salud, República y Socialismo
Huhu liebe Katrin,vielen Dank für Deine lieben Kommentare.Ich habe mich wirklich sehr gefreut.Du hast hier ein sehr schönes neues Blogdesign.Gefällt mir sehr gut.Deine Karte ist auch klasse geworden, auch wenn Dir non-cute “angeblich” nicht so liegt. Ich wünsche Dir noch einen schönen Tag.Liebe GrüßePaola
hvor er det et fint juletræstæppe,har du mon foret det med noget "tungt" stof sÃ¥ det ligger fast pÃ¥ gulvet? jeg har lavet et tæppe,hvor jeg har syet textil voksdug under , mÃ¥ske en ide du kan bruge en anden gang …
Well it’s still wrong, perhaps a list of formatting options should be on this site.
I’d keep trying but I don’t have the ability to delete my posts.
Why visitors still make use of to read news papers when in this
technological world the whole thing is presented
on net?
i have an error fro srand(time(NULL)); help me what can i do??
Hay!! i can’t complete that
IT will not work untill you add #Include
In your code there is only #include
When you compile written program by you it will definetly show error……..
So, for removing error use #include as in your program…
USE
#Include