Click here to Skip to main content
Click here to Skip to main content

Snake Game in a Win32 Console

By , 5 Jun 2010
 

Introduction

The Snake game is a widespread game. It has been done a million times, and is playable on any device. Variants of snake run on things like cellphones to mainframes and Snake has been written in most of the major programming languages, from BASIC, C/C++, Pascal, Java, C# to whatever. Today we are going to take a look at a Snake game that is written in C/C++ and is designed to run in a Win32 console using text characters.

So, what is the Snake and how does it all work? Our Snake is simply a text character that traverses within specified boundaries on the screen gobbling up apples that are randomly placed within that specified boundary. Our snake compares its x y location to that of the apples to see if there has been a collision, i.e., if our snake has eaten up the apple. If so, that apple is removed, and a new apple is randomly placed within the specified boundary, and our snake gets 
a body transplant, it is enlongated. All we need is to do is simply process the keyboard commands from the user and draw the snake. We will use the <LEFT>, <RIGHT>, <UP> and <DOWN> keys to steer the snake.

So let's get going.

We begin as usual by creating a project and a class, then we continue further on by embodying the class with members. We choose not to define and embody our member functions in the header file, we will just put the prototyes in a separate file.

The project files are:

CSnake_main.cpp The main file
CSnake.cpp The class definition and method body file
CSnake.h The class declaration file

We will put the declaration of the variables, prototyes and function headers in CSnake.h.

class CSnake
{
	public:

		int snakeXLocation[201];
		int snakeYLocation[201];
		int color_background, color_border  , color_apple , 
				color_normal , color_snake ;  //  colors
		int snake, prvSnake, snake_Enlongment ;
		int randomX, randomY, apple ;
		int level ;
		int score ;
		char playAgain;

		int i, j;
		int centerX, centerY;
		int x, y, oldX, oldY;
		int lines, columns;
		char c;
		int direction, difficulty;

	public:
		CSnake();
		CSnake( int i);
		~CSnake();

	public:

	   void Settings();
	   void Game_Main();
	   void game_Canvas();
	   void initsnake();
	   void check_collision();
	   void keyPressed();
	   void Display_snake();
	   void check_Snake_Location();
	   void Create_Apples();
	   void Check_Apples();
	   void Remove_Apple();
	   void Game_Over();
	   void Display();

		void gotoxy(int x, int y);
		void clrscr();
		void setcolor(WORD color);
		void clrbox(unsigned char x1,unsigned char y1,
			unsigned char x2,unsigned char y2,unsigned char bkcol);
		void box(unsigned x,unsigned y,unsigned sx,unsigned sy,
			unsigned char col,unsigned char col2,char text_[]);
		void putbox(unsigned x1,unsigned y1,unsigned x2,unsigned y2,
			unsigned char texcol,unsigned char frcol,
			unsigned char bkgcol,char bheader[]);
};

And bring Snake to life in CSnake.cpp.
Now let's have a look at some vital methods that are contained in CSnake.cpp.

The Create_Apples() Method

The Create_Apples() method creates a new apple and randomly places it within the specified boundaries.

/***************************
 *   create apples         *
****************************/
void CSnake::Create_Apples()
{
   setcolor(color_apple);
   randomX= ( rand()% columns )+ centerX ;
   randomY= ( rand()% lines)+ centerY  ;
   for(i=1;i<=snake;i++)
   {
      if((randomX==snakeXLocation[i])&&(randomY==snakeYLocation[i])) Create_Apples();
   }
   gotoxy(randomX,randomY); printf("%c",770);
   if(score==1)getch();
} 

The Check_Apples() Method

The Check_Apples() method compares the Snake's location with the apples, if they have collided, the snake to gets a body transplant, it is enlongated, the apple is removed and a new one is placed randomly within the boundaries.

/***************************
 *   check apples          *
****************************/
void CSnake::Check_Apples()
{
	if((snakeXLocation[1]==randomX)&&(snakeYLocation[1]==randomY))
	{
       	       apple++;
	       Remove_Apple();
	       snake+=snake_Enlongment;
	       Create_Apples();
	}
} 

The Display_snake() Method

The Display_snake()) method draws the snake and the enlongment of the snake in a for loop. Display_snake()) also prints out the score and how many apples are left too.

/***************************
 *   display snake         *
****************************/
void CSnake::Display_snake()
{
   for(i=snake;i>=0;i--)
   {
      gotoxy(snakeXLocation[i],snakeYLocation[i]);
      if(i==0)
	  {
              setcolor(color_background);
              printf("%c",177);
      }else setcolor(color_snake);
         if(i==1)           printf("%c",178);
         if((i!=0)&&(i!=1)) printf("%c",219);
   }
   setcolor (color_normal);
   gotoxy(centerX-1,centerY+lines+2);
   printf("level: %2.d",level);
   gotoxy(centerX-1,centerY+lines+2+1);
   printf(" apple(s) :%2.d/%2.d ",apple,(((lines*columns)/30)+6));
   setcolor (color_background);
} 

The keyPressed() Method

The keyPressed() method simply gets the commands issued by the user from the keyboard and sets the direction of the snake. Use the <LEFT>, <RIGHT>, <UP> and <DOWN> keys to steer the snake.

 /***************************
 *   keypressed             *
****************************/
	void CSnake::keyPressed()
{
   if(kbhit())
   {                           //
      c=getch();
      switch(c)
	  {
         case RIGHT :
			 if(direction!=3)
			 {
                       x++ ;
                       direction=1;
                       }else x-- ;
			 break;
	         case LEFT:
			 if(direction!=1)
			 {
                       x-- ;
                       direction=3;
                       }else x++ ;
			 break;
	         case DOWN :
			 if(direction!=2)
			 {
                       y++ ;
                       direction=4;
                       }else y-- ;
			 break;
	         case UP  :
			 if(direction!=4)
			 {
                       y-- ;
                       direction=2;
	                       }else y++ ;
			 break;
	         case SPACE : getch() ; break;
      }
   }
} 

The Main File

Finally the CSnake_main.cpp file is where we create an instance for our class and run our Snake game.

#include "CSnake.h"

int main()
{
  CSnake *snake = new CSnake(1);

  return 0;
}

Thanks for reading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Clark Kent SuperCoder
Sweden Sweden
Member
About me:
I attended programming School and I have a degree in three programming languages.
C/C++, Visual Basic and Java. So i know i can code. And there is a diploma hanging on my wall to prove it.
I am a professional, I've gotten paid to teach coding. I am roughly 20 years old and i have been a teacher's assistant in programming ,
i have held a lecture in Visual basic programming. I have also coached students in C++, Java and Visual basic.

In my spare time i do enjoy developing computer games, and i am developing a rather simple flight simulator game
in the c++ programming language using the openGL graphics libray.
 
I've written about a dozen small simple applications and games.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questiondelete snake? PinmemberTony's Toy29 Dec '10 - 22:04 
Please at least add a line delete snake; in the main() if you really wanna be a good teacher, memory leak is not a good idea.
General[My vote of 1] My vote of 1 Pinmemberjonpreecebsc15 Nov '10 - 6:13 
Fail
General[My vote of 2] My vote of 2! Pinmembervenomation7 Jun '10 - 17:53 
I wont give you a vote of One as you have taken the time to construct this article and its source however I have to agree with someone with your reputation (teacher,programmer...) you really really should have better code.
 
Im a student and that source would make me think "Wow what a noob", the problem is I think you know that this is bad code and put it up for beginner students to understand (as there familiar with poor structure) Poke tongue | ;-P
GeneralSnake, the good old days PinmemberMember 25307607 Jun '10 - 7:11 
I remember playing this in 1980, but the code had bugs and would often hang. I disassembled the code into assembler, and repaired the bugs while shrinking the code base. This was on a Heath H-89 using both CP/M and HDOS. I recently found the source code disk (HDOS format). It was a fun project.
GeneralVery poor use of C++ [modified] PinmemberAescleal6 Jun '10 - 0:48 
I've been thinking about rating this for a couple of days and can't, with any degree of conscience, give it any higher rating.
 
it looks like a poor C application (overuse of globals, loads of functions not taking any parameters that operate on those globals) carved out and bundled into a class.
 
Without looking at any other code, just look at main(). The first questions anyone experienced would ask are:
 
- Why use new when a simple local object would work just as well?
 
- Where's the exception handling?
 
- I know there's not of resources to handle, but why be so careless to leak the one you're actually using?
 
And that's in a function with one line...
 
Ash

modified on Sunday, June 6, 2010 7:11 AM

GeneralRe: Very poor use of C++ PinmemberZhang, Ethan25 Aug '10 - 21:57 
GeneralBug fixed, crash due to uninitialized variable fixed PinmemberTopCoder235 Jun '10 - 20:19 
Smile | :)
GeneralThanks PinmemberDr.Donny5 Jun '10 - 4:58 
This was personally very helpful to me, seeing your approach.
 
Thanks for sharing your code knowing full well that there are shameless trolls about.
 
You still took the risk. For that I am grateful.
GeneralPlease! PinmemberTim Festgeld5 Jun '10 - 3:53 
Do not be to harsh!
GeneralMy vote of 1 PinmemberDave Cross4 Jun '10 - 0:13 
Very poor code standard

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 6 Jun 2010
Article Copyright 2010 by Clark Kent SuperCoder
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid