Old snake under modern Wind32 SDK

Submitted on: 1/2/2015 10:42:00 AM
By: Alex Rest (from psc cd)  
Level: Intermediate
User Rating: By 5 Users
Compatibility: Microsoft Visual C++
Views: 644
     I created this program as example of Win32 SDK using for my students.

This article has accompanying files


Old snake under modern Wind32 SDK

Old snake under modern Wind32 SDK

O. Reshta

This article would be useful for students that studing IT technology and programming.
This article for you if you want to know little more about

  • Win32 SDK using,
  • Graphics and sounds output,
  • Dynamic process modeling,
  • Visual C++ and C++ using,
  • OOA / OOD principles.

The article is based on BSSnake cpp sources. You can find whole VC++ v6.0 project on the site The article includes exercises tasks.

Probably, themes of the article would be difficult for you if don't know C++ language and never wrote programs under Windows using Microsoft VC++.

Win SDK or MFC

Usually we use MFC while programming enterprise - level projects. But it is not a rule that we must to use it always. I think that you must prefer SDK if
  1. you don't use document/view architecture, splitting windows, toolbars, serialization process;
  2. you don't use other libraries that use MFC.

If you want to create a small utility program or a puzzle game then using SDK would be much wise solution. Time that you spend to program will be same, exe file will be much shorter, and program installation process will be cleaner. While you distribute MFC-Based project you must build it with static MFC libraries ore distribute project with MFC dlls. There is no any warranty that your customer has dlls for your program. Old MFC-Based programs must work with new MFC versions. They must but don't do it always. Your customer will be very glad if after installing your project some his old software products will begin hang up.

Either you use SDK or don't you must know it good. A big part of MFC is SDK interface only. The most MFC window functions are same as SDK. Difference is very small. CWnd class stores window handle and you must not use it as the first parameter of function. CDC class stores DC handle and most of graphic objects are same as SDK functions. CRect is based on RECT structure, etc. There are good container classes as CArray, CList, CMap, CString in MFC. But you can easy change them by STL classes. STL much shorter and is a part of C++ standard. It is multiplatform library. There are some SDK functions that are absent in MFC and you use them direct from your code. So, good Windows programmer must know SDK. The best way to know something is a project creating. If you use VC++ and never used clean SDK try to write some program and you would see that you begin understand MFC solutions much better. To understand how SDK project works you can look at BSSnake sources. They are short enough.

Snake game

The game rules are very plane. Snake moves in the window with some speed. You can turn it left/right. If the snake eats a mouse it grows. If snake eats hedgehog, its body or window border it dies. The speed of snake is growing. Your task is to live as long as it possible. Score is a function of snake length.

BSSnake solutions

OOP model of this project is very simple. There are no such things as inheritance, polymorphism, abstract classes and RTTI here. I didn't want to write classic OOP program according all rules that I used in the big projects. I was trying to make shot and clean program. If you are beginner in C++ this code is for you! All main games classes are placed in two files Game.h and Game.cpp. They are short enough for easy understanding.
Imagine yourself a beginner that makes this snake project. He will create Snake class and put in it data that describe a snake. For example, some snake units with (x,y) coordinates. Than he will create method Grow() that will add new unit to snake. Then he will make method Move(), that change all coordinates of all units. Then he will understand that the array is bad solution for snake body storing because every addition will recreate whole array and he will replace the array by list. Then he will find that Snake.Draw() method that redraw all snake units is working too slowly when number of units overload some dozens. At last he will use DirectX to speed up graphic operations.
I did not so. My snake is not owner of its body! Actually we must not move all Snake. We can move and redraw only the tail and the head. Other body units are not changed. So speed of our solution is not depends from snake length. All information that I need to snake control is storing in the game field cells. Snake object remembers only its head and tail coordinates. While head is moving it writes moving direction to its field cell so we have track to tail moving and tail always gets direction that it needs from cell of game field.
The game field is a matrix of Cells. A Cell stores direction and its type and nothing more. Its pixel coordinates can be counted easy. Cell also draw itself using bitmap drawing function BitBlt. Bitmap is static member of Cell class and all cells share it.
PlayBox class controls field objects and cells drawing. All process is execute by CPlayBox::NextTimeStep(). This method is cold every time step. It calls mice generator and snake moving.
To stop the game I use try/catch/throw mechanism. There are three events that must stop a game and they occur on the second level under situation handle. It would be boring to use BOOL return type to process these events.

System solutions

The project was creating by Visual Studio(V6.0) Win32 Application wizard. My changes are very small. I use global object gEngine to encapsulate all windows message and time tick execution. I always do so because I don't like long switch constructions.
For time tick generator I did not use WM_TIMER window message because it has low priority. I replaced GetMessage() function, that was waiting thread messages, by PeekMessage() that was not stopping the program. So I created something as OnIdele() method of MFC application class. You would be very surprised if will try testing your system resources. The snake eats 100% of processor! Do not afraid. It is only joke of Microsoft. The program has normal priority and all other process receive their processor ticks. But other process is sleeping if have not any to do. Opposite BSSnake executes its own timer.

WinMain Message loop looks so :

while (1)
if(!PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
// OR: there are no any message. OnIdle;-)

if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))

if(msg.message == WM_QUIT){

Standard Win32 Application wizard generate a project that cannot use ASSERT macros. I take this macros from MFC and make him working. It stops later then it must stop but you can see and test the program stack as you do it using MFC.

Insert this strings into stdafx.h and ASSERT macros begins to work (but so-so)


Appendix - Exersices

Symbol (*) marks difficult tasks.

A. (OOA/OOD exercise)

  1. Create OOA/OOD documents for this project.
  2. Create class diagram of BSSnake project using Rational Rose ore other case tools.

B. (C++ exercises)

  1. Memory allocation. Make dynamic memory allocation of cells array using operator new. Don't forget to destroy it while program is finished.
  2. (*) Make CellBase abstract class and its children for every kind of cell units. Store base class object pointers or references in the field array. Use virtual function Draw() to draw every unit. Use dynamic_cast operator to test what kind of cell is placed in front of snake.
  3. (*) Create abstract class CVictim and its child CMouse and CHedgehog. Try to use them instead CMouse class.
  4. Make field class with static array of cells. Inherit it by all classes that need. It is a good solution to remove global array of cells.
  5. Every cell store cell type and direction as 32 bit integer. Use bit fields for storing this information. It makes game field array much shorter. How much?
  6. There are a lot of inline functions in a project. Why we use inline functions? Why many software firms forbid its programmers to use them? Replace all inline functions by normal class member functions. Did it make the snake slowly? Did project become cleaner and easier for modifications?

C. (Game improving exercises)

  1. Make options dialog. Make game field size and start speed as option.
  2. Make screen center align of game window.
  3. Make background as bitmap.
  4. Make opening background. A background picture opens only in cells where a snake was.
  5. Include mid files player.
  6. Store options in the Win register.
  7. Make pause key.
  8. Make some new victims.
  9. (*) Make victims that can walking in the field.
  10. (*) Make some concurrent snakes. Player controls one snake computer controls other.
  11. Smooth snake moving. This time snake jumps every step to next cell. Make moving from pixel to pixel.

D. (System programming exercises)

  1. Try find solution of timer tick that not use 100% of processor.

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come out every day, so no prevention program can catch 100% of them. For your own safety, please:
  1. Re-scan downloaded files using your personal virus checker before using it.
  2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

If you don't have a virus scanner, you can get one at many places on the net

Other 2 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.