Sunday, August 7, 2016

"The Same Game": A Simple Game from Start to Finish, Part 1 of 5

Foreword to Same Game

In this five part series, we'll be creating a version of a game called SameGame using the Microsoft Foundation Class library from start to finish. We'll include features beyond the simple removing of blocks in the game. We'll implement an undo/redo subsystem and some user configuration dialogs. We'll show you step by step with not only source code but screenshots how to build a fun game from start to finish and how to use Microsoft's MFC classes. Every article comes with complete source code, so you can build and run the game yourself.
The rules to the SameGame are quite simple, you try to remove all of the colored blocks from the playing field. In order to remove a block the player must click on any block that is next to, vertically or horizontally, another with the same color. When this happens all of the blocks of that color that are adjacent to the clicked block are removed. All of the blocks above the ones removed then fall down to take their place. When an entire column is removed, all columns to the right are shifted to the left to fill that space. The blocks aren't shifted individually but as a column. The game is over when there are no more valid moves remaining. The goal is to end with an empty board in as little time as possible. Some versions of the SameGame use a scoring algorithm that can be implemented as an additional exercise for the user.

Prerequisites

You'll need to have a basic C++ knowledge of functions, recursion, classes, and inheritance. The code was written using Visual Studio 2005 on Windows XP although later versions of Visual Studio should be fine although the screenshots will look slightly different from what you will see. You must use the Standard or Professional edition of Visual Studio; Visual Studio Express cannot be used, because it does not come with MFC.
If you are student, you may be able to get the Professional Version of Visual Studio for FREE from Microsoft DreamSpark.
If you are not a student, and you do not have the full version of Visual Studio, can work through this tutorial using a trial version of Visual Studio.

What You'll Learn

First and foremost, you'll learn some basics of how to create your own game. You'll learn about the Microsoft Foundation Class library and some basic usage and the Document/View architecture paradigm.
Here's an outline of the series, with links to each article:

Why MFC?

MFC is an easy-to-use library, especially for a simple game like the one we want to make. It will make it easy to create an application with a true Windows look-and-feel.

Starting the Same Game Project

In this article we'll be using Visual Studio 2005 to create our game. The following instructions can easily be adapted to all other versions of Visual Studio. First start up Visual Studio and create a new project. The type of project is "Visual C++" -> "MFC" -> "MFC Application".
Next the MFC application wizard will appear. If you do not choose the name SameGame, then the names of your classes will be slightly different than those that appear in this article. This allows you to select quite a few options that the resulting generated code will include. For our simple game we can disable quite a few of these options. The following graphics show which options to select in order to get the project just the way we want it.
Selecting "Single document" allows the application to use the document/view architecture when multiple documents aren't necessary. The last setting of interest on this page is "Use of MFC". The two options are for a shared DLL or as a static library. Using a DLL means that your users must have the MFC DLLs installed on their computer, which most computers do. The static library option links the MFC library right into your application. The executable that is produced will be larger in size but will work on any Windows machine.
Advance through the next three pages, taking the defaults until the following page is displayed.
(If you are using Visual 2010, this screen does not have a "None" option for Toolbars. Just choose "Use a Classic Menu" without checking either toolbar.) A thick frame allows the user to resize the window. Since our game is a static size, un-check this option. A maximize box isn't needed, nor is a status bar or a toolbar. Advancing to the next page will bring you to the "Advanced Features" page.
Turn off printing, ActiveX controls and set the number of recent files to zero. Since we won't actually be loading any files, this option won't be necessary. The last page of the MFC Application Wizard presents you with a list of generated classes.
Four classes that will be generated for you are the basis for the game. The first on the list is the view class, here it is called CSameGameView. I will come back to this class in a minute. The next class in the list is the application class. This class is a wrapper for the entire application and a main function is provided for your application by this class. The base class isn't selectable and must be CWinApp.
The next class in the list is the document class, CSameGameDoc based on the CDocument class. The document class is where all of the application data is stored. Again the base class cannot be changed.
The last class is the CMainFrame class. This CFrameWnd based class is the wrapper class for the actual window. The main frame class contains the menu and the client area view. The client area is where the actual game will be drawn.
Now back to the view class. The base class is a dropdown with a list of views that are generally available, each with its own use and application. The default view type is CView, which is a generic view where all of the display and interaction with the user must be done manually. This is the one that we want to select.
I will quickly go down the list and explain what each view type is used for, just for your information. The CEditView is a generic view which consists of a simple text box. The CFormView allows the developer to insert other common controls into it, i.e. edit boxes, combo boxes, buttons, etc. The CHtmlEditView has an HTML editor built into the view. The CHtmlView embeds the Internet Explorer browser control into the view. The CListView has an area similar to an Explorer window with lists and icons. The CRichEditView is similar to WordPad; it allows text entry but also text formatting, colors and stuff like that. A CScrollView is a generic view similar to CView but allows scrolling. Finally the CTreeView embeds a tree control into the view.
Finishing the MFC Application Wizard will produce a running MFC application. Since we haven't written any code yet it is a very generic window with nothing in it, but it is a fully functioning application all the same. Below is a screenshot of what your generic application ought to look like. To build your application, you can go to the Debug menu, and select Start without Debugging. Visual Studio may prompt you to rebuild the project—select "Yes".
Notice it has a default menu (File, Edit and Help) and an empty client area. Before we get to actual coding I'd like to explain a little about the document/view architecture that is used in MFC applications and how we are going to apply it to our game.

Monday, August 1, 2016

C++0x: The future of C++

What is C++0x?

C++0x was the working name for the new standard for C++, adding many language features that I'll cover in this series on C++11. In September 2011, C++0x was officially published as the new C++11 standard, and many compilers now provide support for some of the core C++11 features.
C++11 includes a wide range of features: major new features like lambda support and "move semantics", usability improvements like type inference through the auto keyword, simplified looping over containers, and many improvements that will make templates easier to write and easier to use. This series on C++11 will cover all of these features and many more.

Should you care about C++11?

Most definitely. C++11 adds many new language features to C++. C++11 should fix many annoyances and reduce the overall verbosity of C++ as well as provide new tools, such as lambda expressions, that increase its overall expressiveness and clarity. Fetaures like move semantics improve the basic efficiency of the language, allowing you to write faster code, and the improvements to the template system make it much easier to write generic code.
The new standard library will also include many new features, including adding multithreading support directly into C++ and improved smart pointers that will simplify memory management for those who aren't already using features like boost::shared_ptr.
I've started using several new C++11 features professionally and I'm loving it. Some of the new features I'm fond of include the new meaning of the auto keyword, simplifications like better handling of right angle brackets in templates, lambda expressions and the new function declaration syntax.

How was C++11 developed?

I can't go on further about C++11 without acknowledging the hard work done by the C++ standards committee--a group of experts from academia and industry who have met many times to work through all the edge cases and design a programming language that can be implemented across multiple platforms by multiple compilers, producing efficient and reasonably maintainable code. The next standard, C++11, looks to be a fantastic addition to the flexibility and power of C++.

What is C++11 about?

Language usability

Having started to use C++11, I'd say that the most fundamental way of looking at it is that it makes C++ a much more usable language. This isn't to say that it makes it a simpler language--there are lots of new features--but it provides a lot of functionality that makes it easier to program. Let's look at one example, the auto keyword.
In C++11, if the compiler is able to determine the type of a variable from its initialization, you don't need to provide the type. For example, you can write code such as
int x = 3;
auto y = x;
and the compiler will deduce that y is an int. This, of course, isn't a shining example of where auto is really useful. Auto really comes into its own when working with templates and especially the STL. Why is that? Imagine working with an iterator:
map<string, string> address_book;
address_book[ "Alex" ] = "webmaster@cprogramming.com";
// add a bunch of people to address_book
Now you want to iterate over the elements of the address_book. To do it, you need an iterator:
map<string, string>::iterator itr = address_book.begin();
That's an awfully long type declaration for something that you already know the type of! Wouldn't it be nice to simply write:
auto itr = address_book.begin();
The code is much shorter, and frankly, I think it's more readable, not less, because the template syntax obscures everything else on that line. This is one of my favorite new features, and I find it eliminates a lot of headaches and hard-to-track-down compiler errors, and just generally saves time without losing expressiveness.

Ranged For Loops

Now, the iterator example is one where C++11 has come up with an even better way of handling this--something called a range-based for loop (which almost every language has nowadays). The idea is so elegant, an example should suffice:
vector<int> vec;
vec.push_back( 10 );
vec.push_back( 20 );

for (int &i : vec ) 
{
        cout << i;
}
All you need to do is give your variable and the range to iterate over (defined as something with iterators available via calls to begin and end--so all STL containers) and you're set! This is a pretty new feature, available as far as I know only in GCC 4.6.
But what if you want to iterate over a map? How do you put in the type for a value stored in a map? With a vector, you know the value is an int. With a map, it's essentially a pair, with .first and .second giving you the key and value. But with auto, we don't need to worry about getting the exact type right, you can simply do this:
for ( auto address_entry : address_book )
{
        cout  << address_entry.first << " < " << address_entry.second << ">" <<endl;
}
Which prints out as:
Alex <webmaster@cprogramming.com>
Isn't that a nice combination of new features in C++11? It feels like it was designed that way :)

Right angle brackets

And I have one more usability improvement for you--in previous versions of the C++ standard, if you wrote a template that had another template:
vector<vector<int> > vector_of_int_vectors;
You had to write a space between the two closing angle brackets. This was not only annoying, but if you did write >> without a space, you'd get obtuse and confusing compiler error messages. The reason for this behavior had to do with an obscure C++ lexer trait called the maximal munch rule. The good news is, you no longer need to worry about it! Say hello to
vector<vector<int>> vector_of_int_vectors;
True, this seems like a small thing, but it's a victory of human code writers over machine tools. Plus it's much less ugly. Compiler support for right-angle brackets is great: GCC since 4.3, MSVC since version 8 (!) and the Intel compiler since version 11.

Mulithreading

For the first time, the C++11 standard will include a memory model and corresponding libraries for multithreading, meaning that you'll be able to write standards-compliant multithreading code. The new standard will provide for all the normal threading functionality, such as threads and thread-local storage and atomic operations. It will also include an interesting set of features, futures and promises. The basic idea of futures and promises is that you can write code that says, "this object, a future, stands for a result that hasn't been computed yet" and the work to compute the value can take place in the background. When the value is needed, you ask the future for it; if the value is ready, you get it; if not, you wait.
I'll go into more depth on mulithreading in a later article in this series.

Lots of other stuff

The number of features in C++11 is incredibly exciting. You can get a taste for what's available on the C++11 page at Wikipedia, and I plan to dive into many of these features in more depth in this series, including:

Compiler Support for C++11

Of course, no language feature matters if it's not available to use, and the good news is that many compilers now support the new C++11 features. The Apache foundation has compiled a very useful list of C++11 language features and the compilers that support them: Compiler Support for C++11. If you're interested in GCC, this page describes the GCC 4.7 support for C++11.
Some compilers, such as GCC, do not automatically enable support for these features--for example, to enable C++11 features, you must compile with -std=c++0x. Nonetheless, they are still valuable if you're working on a project where you can control the choice of compiler and set of language features.

Sunday, July 31, 2016

A step-by-step guide to becoming a C++ programmer...

Want to learn to code? Want to learn C++? Struggling to follow your lecturer or books and tutorials written for experts?
You're not alone.
As a professional C++ developer and former Harvard teaching fellow, I know what you need to know to be a great C++ programmer, and I know how to teach it, one step at a time. I know where people struggle, and how to overcome it. I cover every step of the programming process, including:
  • Getting the tools you need to program and how to use them
  • Basic language features like variables, loops and functions
  • How to go from an idea to code
  • A clear, understandable explanation of pointers
  • Strings, file IO, arrays, references
  • Classes, object oriented programming, and advanced class design
  • Data structures and the standard template library (STL)

Saturday, July 30, 2016

Code Completion Challenge - Guessing Game Solution

Guessing Game Solution
The following program will act as a guessing game in which the user has eight tries to guess a randomly generated number. The program will tell the user each time whether he guessed high or low:
#include <stdlib.h>
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));    
int number=rand()%100; 
int guess=-1;
int trycount=0;
while(guess!=number && trycount<8)

{
cout<<"Please enter a guess: ";
cin>>guess;

if(guess<number)
cout<<"Too low"<<endl;

if(guess>number)
 cout<<"Too high"<<endl;

trycount++;
}
if(guess==number)
cout<<"You guessed the number";
else
cout<<"Sorry, the number was: "<<number;
return 0;
}

Sunday, July 24, 2016

Setting up Code::Blocks and MINGW, A Free C and C++ Compiler, on Windows

By Thomas Carriero 

This tutorial gives you easy-to-follow instructions, with screenshots, for setting up a compiler (the MINGW compiler), a tool that will let you turn the code that you write into programs, and Code::Blocks, a free development environment for C and C++. This tutorial explains how to install Code::Blocks on Windows 2000, XP, Vista or Windows 7. Note: if you're running Linux, go here to learn how to use GCC; if you're on OS X, go here to get set up using Apple XCode.

Step 1: Download Code::Blocks

  • Go to this website: http://www.codeblocks.org/downloads
  • Follow the link to "Download the binary release" (direct link)
  • Go to the Windows 2000 / XP / Vista / 7 section
  • Look for the file that includes mingw in the name. (The name as of this writing was codeblocks-10.05mingw-setup.exe; the 10.05 may be different).
  • Save the file to your desktop. It is roughly 74 megabytes.

Step 2: Install Code::Blocks

  • Double click the installer.
  • Hit next several times. Other setup tutorials will assume you have installed in C:\Program Files\CodeBlocks (the default install location), but you may install elsewhere if you like
  • Do a Full Installation
  • Launch Code::Blocks

Step 3: Running in Code::Blocks

You will be prompted with a Compilers auto-detection window: 

Compiler Auto-Detection Window 

When you get the compiler auto-detection window, just hit OK. Code::Blocks may ask if you want to associate it as the default viewer for C/C++ files--I'd suggest you do. Click on the File menu, and under "New", select "Project..." 

The following window will come up: 

New Project Window 

Click on "Console Application" and hit the "Go" button. 

Click next until you get to the Language Selection Dialog: 

Language selection dialog 

You'll be asked to choose whether you want to use C or C++. If you're not sure, use C++. Otherwise, choose based on the language you are learning. (You can find tutorials here on both C and C++.) 

After clicking "Next", Code::Blocks will then prompt you with where you'd like to save the console application: 

Project Name and Location 

I'd recommend you put it in its own folder, as it may create several files (this is especially true if you create other types of projects). You will need to give your project a name, anything will be fine. 

Clicking "Next" again will prompt you to set up your compiler: 

Compiler Setup 

You don't need to do anything here. Just accept the defaults by hitting "Finish". 

You can now open the main.cpp file on the left: 

Main Editor View (You may need to expand the contents of the "Sources" folder if you don't see main.cpp.) 

At this point, you will have your main.cpp file, which you can modify if you like. For now, it just says "Hello World!", so we can run it as is. Hit F9, which will first compile it and then run it. 

Running Program 

You now have a running program! You can simply edit main.cpp and then hit F9 to compile it and run it again. 

Now that you've finished setting your compiler up, it's time to learn to program: Intro to C++ (or if you're learning C, Intro to C).

Troubleshooting

The most common error people see if things don't work is a message like

"CB01 - Debug" uses an invalid compiler. Probably the toolchain path within the compiler options is not setup correctly?! Skipping..."

First, make sure that you downloaded the right version of Code::Blocks, the one that included MinGW. If that doesn't solve the problem, it is likely a problem with compiler auto-detection. Here's how you can check your current "auto-detected" state. Go to "Settings|Compiler and Debugger...". Then on the left, choose "Global Compiler Settings" (it has a gear icon) and on the right, select the "Toolchain executables" tab. This tab has a "Auto-detect" button that you can use. That might fix the problem--if it doesn't, you can manually fill out the form. Here's a screenshot demonstrating what things look like on my system. Change the path marked "Compiler's installation directory" if you installed to a different location, and make sure everything else is filled in as shown.

Once you've done that, try pressing F9 again to see if you get a running program.

Loops

Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming -- many programs or websites that produce extremely complex output (such as a message board) are really only executing a single task many times. (They may be executing a small number of tasks, but in principle, to produce a list of messages only requires repeating the operation of reading in some data and displaying it.) Now, think about what this means: a loop lets you write a very simple statement to produce a significantly greater result simply by repetition.



One Caveat: before going further, you should understand the concept of C++'s true and false, because it will be necessary when working with loops (the conditions are the same as with if statements). There are three types of loops: for, while, and do..while. Each of them has their specific uses. They are all outlined below. 

FOR - for loops are the most useful type. The syntax for a for loop is 

for ( variable initialization; condition; variable update ) {
  Code to execute while the condition is true
}
The variable initialization allows you to either declare a variable and give it a value or give a value to an already existing variable. Second, the condition tells the program that while the conditional expression is true the loop should continue to repeat itself. The variable update section is the easiest way for a for loop to handle changing of the variable. It is possible to do things like x++, x = x + 10, or even x = random ( 5 ), and if you really wanted to, you could call other functions that do nothing to the variable but still have a useful effect on the code. Notice that a semicolon separates each of these sections, that is important. Also note that every single one of the sections may be empty, though the semicolons still have to be there. If the condition is empty, it is evaluated as true and the loop will repeat until something else stops it. 

Example:
#include <iostream>

using namespace std; // So the program can see cout and endl

int main()
{
  // The loop goes while x < 10, and x increases by one every loop
  for ( int x = 0; x < 10; x++ ) {
    // Keep in mind that the loop condition checks 
    //  the conditional statement before it loops again.
    //  consequently, when x equals 10 the loop breaks.
    // x is updated before the condition is checked.    
    cout<< x <<endl;
  }
  cin.get();
}
This program is a very simple example of a for loop. x is set to zero, while x is less than 10 it calls cout<< x <<endl; and it adds 1 to x until the condition is met. Keep in mind also that the variable is incremented after the code in the loop is run for the first time. 

WHILE - WHILE loops are very simple. The basic structure is 

while ( condition ) { Code to execute while the condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is the same as a for loop without the initialization and update sections. However, an empty condition is not legal for a while loop as it is with a for loop. 

Example:
#include <iostream>

using namespace std; // So we can see cout and endl

int main()
{ 
  int x = 0;  // Don't forget to declare variables
  
  while ( x < 10 ) { // While x is less than 10 
    cout<< x <<endl;
    x++;             // Update x so the condition can be met eventually
  }
  cin.get();
}
This was another simple example, but it is longer than the above FOR loop. The easiest way to think of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block. 

DO..WHILE - DO..WHILE loops are useful for things that want to loop at least once. The structure is
do {
} while ( condition );
Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do..while loop is basically a reversed while loop. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and loop while the condition is true". 

Example:
#include <iostream>

using namespace std;

int main()
{
  int x;

  x = 0;
  do {
    // "Hello, world!" is printed at least one time
    //  even though the condition is false
    cout<<"Hello, world!\n";
  } while ( x != 0 );
  cin.get();
}
Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop will execute once, because it automatically executes before checking the condition.