How to Write a Number Guessing Game in C++

28 04 2012

Someone on Yahoo Answers had written a number guessing game in C++ for a class and was asking about adding a feature that alerts the player if he had already guessed the number he just entered. His code so far was awful but probably worked well enough for him. He had one goto statement and was counting the number of tries backwards for reasons I can’t imagine. I tried to explain what he should do to make the code easier to read and maintain and how he might add the feature. I wound up deciding to just re-write the whole thing. When I went to submit my answer, Yahoo Answers informed me that it was on break, as in broken. So I’m going to put here where it totally doesn’t belong.

It works using 3 nested do/while loops. The outer most loop contains the game and loops when our player wants to play again. The loop inside that is the game loop and it runs until a game ending condition is met (the player either guesses correctly or gives up). The loop inside that one gets the player’s guess and re-runs if the guess is outside the range of the game or has already been guessed.

The inner-most loop adds the functionality the student was asking for.

// includes go here
using namespace std;

// Let's define our constants
const int MIN_NUMBER = 1;
const int MAX_NUMBER = 100;
const int EXIT_VALUE = -1;

int main()
	// seed the random number generator
	srand((unsigned int)time(NULL));

	// initialize our program variables
	int games = 0;			// counts number of games played
	int wins = 0;			// counts number of games won
	int total_guesses = 0;	// adds total guesses together to calc the average at the end
	char again = 'n';		// will == 'y' or 'Y' if we want to play again

	// Let's save our title as a string so we can reuse it latter and ensure it doesn't change.
	char* title = "Unfrozen Caveman's Stupid Number Guessing Game";

	cout << "*** You are playing " << title << "! ***\n\n";

	do // This loop will exit when we don't want to play the game any more
		// init our per game variables
	// set our target to a random number between MIN_NUMBER AND MAX_NUMBER
		int target = rand() % (MAX_NUMBER-MIN_NUMBER+1) + MIN_NUMBER;

The student’s code had a function to get a random number that wasn’t quite implemented properly. I found it unnecessary (to define an external function), but you can do that if you want. rand() % MAX_NUMBER will give us a random number in the range of 0 and MAX_NUMBER-1 (0 to 99). rand() % (MAX_NUMBER) + MIN_NUMBER will work as long as MIN_NUMBER == 1, but we don’t want our code to break if our constants are changed even if we don’t plan on doing so. If MAX_NUMBER==50 and MIN_NUMBER==25, our random number needs to be constrained by 26 (50-25+1) before 25 is added to ensure the number is within range. I hope that makes sense.

		int guess = 0;				// record our guess
		int guesses = 0;			// count our guesses
		bool game_over = false;		// this will == true when reach an end of game condition ( win or lose)

		// Let's declare and initialize an array to store all of our previous guesses with
		// enough elements to ensure we won't run out. If MAX_NUMBER = 40 and MIN_NUMBER = 20,
		// then we need 40-20+1 = 21 elements to cover the maximum number of guesses possible
		int old_guess[MAX_NUMBER - MIN_NUMBER + 1];
		for (int i=0; i			old_guess[i] = 0;

I hope this makes sense too. Worst case scenario is that our player guesses every single wrong answer before “winning”. In that case we need to have enough elements in our old_guess array to cover every single wrong guess (and his final correct one). We could eliminate the +1 here, but that would necessitate checking later on for this highly unlikely case.

		do // this loop will run until and end of game condition occurs
			bool good_guess = false;

			// This loop ensures that our number is in range and hasn't been guessed already. This
			// loop could easily be another do-while loop, as it has to run at least once
			while(good_guess == false)
				// Explain our range and ask for a guess within it.
				cout << "Enter a number between " << MIN_NUMBER << " and " << MAX_NUMBER << " (-1 to give up): "; 				cin >> guess;

				good_guess = true;

				// If the guess is our exit value, skip the other checks
				if(guess == EXIT_VALUE)
				else if(guess > MAX_NUMBER)
					cout<<guess<<" is higher than the range of this game. Try again."<<endl;
					good_guess = false;
				else if(guess < MIN_NUMBER)
					cout<<guess<<" is lower than the range of this game. Try again."<<endl;
					good_guess = false;
					for (int i=0; i					{
						if (guess == old_guess[i])
							// if the player guesses a number he already tried, he should be verbally abused
							cout << "You already guessed that on guess #" << (i+1) << " you idiot!" << endl;
							good_guess = false;
					} // end for
				} //end if
			} // end while

			// Now that we have a valid guess, let's save it in our old_guess array and increment our counter
			old_guess[guesses] = guess;

			// now for our normal checking
			if(guess==EXIT_VALUE)	// Do we have a quitter on our hands?
				// quitting calls for some verbal abuse
				cout << "*** YOU GOD-DAMNED QUITTER!! ***\n";
				cout << "The number was " << target << endl << endl; 				game_over = true; 			} 			else if (guess > target)	// Did he guess too high?
				cout << guess << " is too high. " << endl;
			else if (guess < target)	// Did he guess too low?
				cout << guess << " is too low. " << endl;

The student’s code did not give “too low” or “too high” hints until the player had guessed five times, drastically reducing the tiny amount of fun present in my (and everyone else’s) version of this game.

			else if (guess == target)	// This could just be an else statement, because all other possibilities have been covered.
				if (guesses == 1)
					cout << "!!!!HOLY HELL!!!! You fucking RAINMANED that shit! Just " << guesses << " guess!\n\n";
					cout << "*** YOU GOT IT!! ***\n It took you "<< guesses <				game_over = true;
				total_guesses += guesses;

I didn’t want the game to say “It took you 1 guesses” if the player happens to nail it (Rainman it) on the first try, so I added a special vulgar message for such a case.

		} while (game_over == false);


		cout << "Would you like to play again? "; 		cin >> again;
		cout << "\n\n";

	} while ((again == 'y') || (again == 'Y'));

The student’s code only permitted the player to play 256 times (a curiously square number). I can only guess that this was intended to be like the Nintendo Wii suggesting you go outside and play after playing with it for several hours. You know, cuz number guessing games are so addictive.

	// lets calculate the average number of guesses it took our player to win
	float average = float(total_guesses) / float(wins);
	cout << "Thanks for playing " << title << endl;
	cout << "You played "<< games <	cout << "with an average of " << average << " guesses per win\n\n";

	cout << "Hit enter to exit.\n\n";

	return 0;

Wasn’t that fun? So, yeah, I’ve been programming computers as a hobby since I was 12 or so. I’ve spent years away from it, but I’ve been getting back into it lately. Feel free to point out anything you don’t like about my code or to ask questions about it or about your own code. If you want to know how to show code on, check out this thing I just learned. You can no longer find this full code without interruption at PASTEBIN, which is where you should go if you need to share code with others on the interwebs for a fairly limited amount of time.

Fat Guy Says What?

7 04 2012

I just got a response to a very old post that I’m still quite proud of, Internet Mind-readers and the Fragile Fat Girl Ego. I don’t remember exactly what I said in that, but I felt really smart at the time.

I am 22 year old male who is 5′ 9″ and weighs about 220 pounds. Yes, I am fat. Recently this (fatter) black girl decided to randomly message me saying “your fat, ugly and not ok”. I sent her a bomb of an intellectual hate mail back and got banned.

That’s exceedingly hilarious. That presumably took place on some dating site, a detail that should be included if you’re telling a story about such an environment. “You’re fat, ugly and not OK” is God-damned funny! This should not bother you or make you upset in any way. If this took place on OKCupid, the proper response would have been to go on the forums and share the experience. Generally, nothing good comes of expressing anger at people on the internet.  If you got that upset, you do, in fact, have a fragile ego of a fat girl, if not worse. That’s pathetic.

I think people who objectively spread negativity at random are immoral cunts (be them guy or girl). Being fat is one thing but causing others pain because that’s a coping mechanism for their ill head that’s worse.

Geezus. I know you’re pretty young, but you’re old enough to learn that you’re thinking like a child. There is no practical reason for passing moral judgement on anyone’s being fat or acting thoughtlessly. You’re doing this so you can compare yourself to her, so you can paint her as the bad guy and yourself as the victim. This is not necessary! The facts speak for themselves! She said something mean to you that hurt your feelings, but you should have immediately recognized her words as meaningless.

And in this person’s mind they do not associate with themselves being fatter than me; their mind defends itself from believing that and they hypocracize and who knows becomes a serial killer of fat men.

Yes, the behavior is clear some sort of defense mechanism or projection or something like that. The only reaction this shit deserves is that you look down at her and laugh at her. If you’re a bit evolved it should give you pause, make you wonder if your own brain is so equipped to fool itself.

In my defense, I have had therapeutic chemical tools for the last 3 years that made me gain 33% of my body’s weight in the process. I was a healthy 155 pounded human being. Now I weigh 220 pounds.

Why do you talk like this? Is English your second language? You should clearly state that you’ve been on some drug that made you fat. This is a common and commonly understood phenomena. You could even say what drug it is! Your privacy is pretty safe here. Nobody knows who you are and nobody cares!

I am confident and content and know I need to lose weight to reduce my hypertension among other things. But I guess my argument stands, pass in nice thoughts you want to communicate to others.

What argument? Maybe you made one in your head, but you haven’t done so in this message. You don’t sound confident or content. If you were, you wouldn’t be so upset about things of no consequence.

You’ll most likely not meet anyone you talk to on the internet because the temptation to falsify info and make fraudulent dating accounts is to be expected.

A lot of people end up in relationships with people they’ve met through the internet, including me. Although, the level of attention most guys get on dating sites is underwhelming, to put it mildly. The numbers are such that fat chicks will confidently reject fat dudes. Have a profile up here or there, but don’t take this shit seriously. Doing so makes you appear desperate (which you clearly are). Don’t take yourself too seriously in your profile, don’t put a lot of energy into contacting girls, have no expection that any of them will ever reply, and for God’s sake don’t get excited if a chick messages you. If you’re going to burn calories meeting women, do so in meatspace. This can help turn you into the kind of dude women find attractive.

And someones profile photos are most likely to be outdated. And peoples sexual orientation is most likely inaccurate, especially in younger crowds.

What the fuck are you talking about? Inaccurate photos are a always possible, and I feel strongly that people should meet as soon as there’s a hint of mutual interest, before you feel like you have anything to lose, when you have no expectations. Of course, you could be the type of person who always has expectations, but having them crushed a few times should put an end to that nonsense. I have no idea what you’re on about regarding sexual orientation. What is in it for anyone to lie about that?

People are testing the waters, and for our audience’s sake lets hope that someone who posted an outdated fat picture loses weight.

Okay. I’ll put that near the bottom of my list of things to hope for. Who cares?

The most important question to ask yourself is: do we want whats best for ourselves vs. Do we want whats best for ourselves and others? Helping others in turn helps you.

That’s not the most important question for me to ask myself. I have a strong desire to attempt in futility to make the world a better place by arguing with idiots and saying things that most people are too God-damned nice to say. I don’t need anyone to talk me into helping others, including people I’ll never meet who I don’t personally care about. If I need anything, I need the opposite. I need to be reminded that I can’t fix the world and that most people are too dumb to ever get it.

Why not ask a fatties you’re attracted to be your work out buddy or better yet, ignore them alltogether.

I’m not attracted to fatties. Nobody is! That’s kind of been my point!

hope I corrected some of your thoughts.

You’re fucking delusional if you think coming to my blog and crying some emotional nonsense at me would get me to think differently. Anyway, you seem like a nice kid who’s mommy lied to him his whole life about him already being good enough. You’re not, and you never were, but you can get better. I’m not even talking about you being fat. Grow up and become a man.

I kind of want to try and help you, but I’m out of gas for now, and I don’t fully understand what your problem is. I honestly don’t know why you’re angry.

The Worst Day for a Dog to Die

1 04 2012

What follows is an actual facebook exchange that took place today between the Unfrozen Caveman and his Cavelady. The names have been changed to protect the innocent, and the grammar has been cleaned up to protect the guilty.

Unfrozen Caveman: Your mom’s dog, Princess* just died

Unfrozen’s Cavelady: haha

[ Cavelady did not like this dog, but I was very surprised to see this response. ]

That’s not nice. Your mom is sad, and Sunshine’s* crying.

OMG. I’m laughing so hard at my desk right now. I’m getting weird looks.

[ Once again, I don’t understand the reaction. She was getting weird looks from me too at this point. This is fascinating now, because I realize that I sort of filtered this out because it didn’t really fit in with my reality. My pattern recognition algorithms failed to make sense of this. At the same time, some part of my brain is working on re-calibrating my own sense of  humor. If she thinks this is funny, maybe I should too? We all do this, though I suspect few are aware of it. ]

She’s in a garbage bag now awaiting burial. Princess, that is…

[ I clearly have a pretty sick sense of humor as it is. ]

Be sure to help my mom lift her into the hole, she’s heavy and mom’s got a bad back.

[ Actually, digging the hole is going to be a pain in the ass ]

Yes, I got her in the bag and we moved it to the shade for now. They’re off to church.


[ I must admit, going to church right after the dog dies is kind of funny, though I’m not sure why. Here I try to address the surprising coldness I keep encountering. ]

I’m happy that I won’t hear her barking, but i’m not THAT happy right now. Your mom’s not happy. Now she’s gonna want a puppy. I wouldn’t be shocked if she came home from church with a puppy

So, how did she die?

It’s a mystery. She went outside, laid down, and died. Heart attack or stroke, it seems. Your moms other dog better not follow suit.

[ This dog was nine years old and about 55 pounds. I had never witnessed a dog death before, so it seemed very odd. I really don’t know why this dog died. She was not overweight, and seemed to be in good shape.

We went on to discuss the new smartphone game that’s all the rage, Draw Something, for a few minutes. You should check it out. It makes me smile a lot.

Then, something happened. I saw the date. I saw that it was the first day of the fourth month. Understand, that it’s early in the morning and I should still be in bed. Gears start turning, some steam comes out my right ear, and it all starts to make sense. My pattern recognition software is suddenly becoming satisfied. ]

So, I just saw what day it is and thought you should know that Princess really is dead, in case you thought that was a joke.

Oh shit.


[ Though I had figured it out, I was still surprised to learn that my suspicions were correct. I wish I could be so clever. I’m still not fully awake. ]

Oh, and I’m pregnant, by the way. I thought about posting that on facebook, but it’s being over used already. Then, I though about cancer, but that might be pushing it.

How about some really weird form of cancer? 

[ After I say this I realize to myself that there is at least one form of cancer for every part of the body that you could imagine there being ever cancer, as hilarious as some organs names may sound to my idiotic ears. Duodenum Cancer, for instance. So I try to split the difference. ]

Like toenail cancer?

Meh, I’m sure it’ll offend someone… and I don’t feel like dealing with that shit storm.

Okay seriously, you have my mom in on the joke too?? God, I’m going to feel like such an asshole if you guys are serious.

That’s hilarious. If you need me to text you a picture of a dead dog…

[ I really didn’t want to send the picture, but I can tell that she can’t commit to believing me or to calling bullshit, and I would really like to end that for her. ]

Your mom went to let the dogs in and Princess wouldn’t come. She was lying there not moving, and I heard it in your mom’s voice that she was scared. She went out there and came back and said, “she’s dead!” If your mom’s in on it, so’s the dog because she wasn’t moving.

[ The thought of a dog pretending to be dead on April Fool’s day as a prank makes me giggle like retard. But no, the dog actually died. ]

Anyway, when she said that, I thought “what? no way, just like that?” So, I checked out the corpse. She had one eye open, one closed, and her tongue was hanging out and had dirt and grass stuck to it.

FUCK… I hope you guys aren’t serious!

This is the worst and/or best day ever for a dog to die.

[ I’m laughing like the King of Idiots at this stage. I decided to share this thought with my facebook friends, keenly aware that her mom isn’t one of them. ]

Wait, there’s no way you would have gotten out of bed before they left for church.
You’re full of shit!

[ This is pretty clever of her. It is unlikely for me to get out of bed before they go to church. But she happens to be wrong. DEAD wrong in this case! Ha! She’s back to calling bullshit!  ]

I need a pickaxe.

You shouldn’t comment on my facebook status.

Why not?

Unless you already called bs on your mom… I wish I was so clever.

I haven’t responded yet.

[ Oh, that is a good thing. ]

At a certain point, when someone calls bs, you have to admit that they’re right.

[ I’m trying to plead my case here, awkwardly declaring that if this were a joke, I would have given up on it by now. But, as I think about it, I’m not even convinced that this is true. As long as doing so remains funny, there’s motivation continue insisting that your lie is true. I’m such a terrible liar now that I can’t convincingly tell the truth. ]

I’ve never been a fan of lying after you’ve been called out on it

Sorry? People like to lay it on thick on April 1st. How the fuck should I know?

I’m not upset.

[ I wasn’t. It’s funny, but she clearly feels bad. ]

I totally didn’t get why you reacted to the news with laughing. It did not occur to me [that it was April 1st] until I said it did.

You sent that message LITERALLY right after my coworker was telling me what her kids did to her this morning before work. I had forgotten, too.

[ I wasn’t clear enough here. She didn’t understand what I meant. ]

Anyway, your mom is actually upset. That’s all I’m saying. This is the funniest thing that’s ever happened on April 1st in my life. I bet this has happened with people too:
-Grandpa died
– :O

Okay, this is so fucked up, I just told my coworker what happened and we are laughing so hard we are crying.

I deleted your comment so your mom doesn’t see it.

Not because the dog died?

[ What? OMG she’s still giving me too much credit! ]

Her and I are not facebook friends. Are you still unsure?

OMG, I’m re-reading this whole exchange. FUCK! There was a time there you didn’t realize today was April 1st!



I know you weren’t BFFs with Princess, but your response to the news of her demise was surprisingly cold. I’m thinking, “I just stuffed a dead dog in a trash bag, why is that funny?”

PLEASE TELL me you know that I would not find this funny on any other day of the year.

Of course! When I said that she died and you responded right away, I didn’t see it but I was sure you either said “wow!” OR “holy shit!” I came back and saw “HAHA.”

That was RIGHT AFTER Madonna*, my co-worker, was telling me about her April fool’s morning.

Tell me!

Oh, nothing too terrible, just fucked with her alarm clock and other silly shit. Then, to get back at her daughter, she jumped on her bed and woke her up shaking her saying “OMG HURRY GET OUT OF BED, YOUR DOG RAN AWAY AND SHE’S HEADING TOWARDS THE MAIN ROAD” and her kid got all upset and shit.

God is hilarious. What a sick bastard!

God is a dick.

* – Those are made up names, but you already knew that.