Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

C++ Programming Code Examples

C++ > Computer Graphics Code Examples

Snake Game

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
/* Snake Game */ #include<iostream.h> #include<conio.h> #include<graphics.h> #include<dos.h> #include<stdlib.h> #include<stdio.h> #include<time.h> #include<string.h> class Snake { int p1,p2,v1,v2,v3,e1,e2,prev,now,n,colr,dsp,cnt,dly,m; int stp,egGen; int xr,yr; void caught(); public: long scr; int strtX,strtY,endX,endY; int pos[100][2]; void show(); void init(); void egg(); void transpose(); void gnrtCond(); void gnrtUnCond(); void check(); void checkEgg(); void move(); void chngDir(); void sndEt(); void sndCgt(); int test(); void score(); Snake(); Snake(Snake*); ~Snake(); }; Snake::Snake() { } Snake::~Snake() { } void Snake::checkEgg() { if((e1 == p1) && (e2 == p2)) {sndEt(); egg(); dly--; score(); n++; } } void Snake::sndEt() {nosound(); sound(2500); delay(2); nosound(); } void Snake::sndCgt() {nosound(); for(int x=1000;x>0;x--) {sound(x); delay(1); } nosound(); } void Snake::score() { char *p; ltoa(scr,p,10); settextstyle(8,0,1); setcolor(0); outtextxy(585,40,p); if(egGen != 1){ scr = scr + dly / 10; } ltoa(scr,p,10); setcolor(10); outtextxy(585,40,p); } void Snake::gnrtCond() {if(n < 367) {if(now == 8 && (prev != 8 && prev != 2)) {pos[0][0] = p1; pos[0][1] = p2 - dsp; prev = now; } if(now == 4 && (prev != 4 && prev != 1)) {pos[0][0] = p1 + dsp; pos[0][1] = p2; prev = now; } if(now == 2 && (prev != 8 && prev != 2)) {pos[0][0] = p1; pos[0][1] = p2 + dsp; prev = now; } if(now == 1 && (prev != 1 && prev != 4)) {pos[0][0] = p1 - dsp; pos[0][1] = p2; prev = now; } } } void Snake::gnrtUnCond() { if( prev == 8 ) {pos[0][0] = p1; pos[0][1] = p2 - dsp; } if( prev == 4 ) {pos[0][0] = p1 + dsp; pos[0][1] = p2; } if( prev == 2 ) {pos[0][0] = p1; pos[0][1] = p2 + dsp; } if( prev == 1 ) {pos[0][0] = p1 - dsp; pos[0][1] = p2; } p1 = pos[0][0]; p2 = pos[0][1]; } void Snake::check() { if(p1 > endX) {p1 = strtX;} else if(p1 < strtX) {p1 = endX;} if(p2 > endY) {p2 = strtY;} else if(p2 < strtY) {p2 = endY;} pos[0][0] = p1; pos[0][1] = p2; for(int i = 1;i < n;i++) { if(p1 == pos[i][0] && p2 == pos[i][1]) {caught(); break; } } } void Snake::show() { int x = getcolor(); if(egGen != 1) { setcolor(getbkcolor()); setfillstyle(1,getbkcolor()); fillellipse(v1,v2,yr,yr); } else egGen = 0; if(egGen == 2) egGen--; setcolor(colr); setfillstyle(1,9); if(now == 8 || now == 2) fillellipse(pos[0][0],pos[0][1],xr,yr); else if(now == 4 || now == 1) fillellipse(pos[0][0],pos[0][1],yr,xr); setcolor(x); } void Snake::transpose() { int i,j,x,y; p1 = pos[0][0]; p2 = pos[0][1]; if(!egGen){ v1 = pos[n-1][0]; v2 = pos[n-1][1]; } else egGen = 0; for(i = n-1;i >= 1;i--) {pos[i][0] = pos[i-1][0]; pos[i][1] = pos[i-1][1]; } } void Snake::move() { int st = 0; do{ if(!kbhit()) {checkEgg(); if(!st) show(); else st = 0; delay(dly/4); transpose(); delay(dly/4); gnrtUnCond(); delay(dly/4); check(); delay(dly/4); } else if(stp){ chngDir(); gnrtCond(); check(); show(); st = 1; } }while(stp); } void Snake::init() {time_t tm; srand(time(&tm)); dsp = 20; n = 5; prev = 4; for(int i = 4;i >= 0;i--) {pos[i][0] = 201 + (n - i - 1) * dsp; pos[i][1] = 301; } strtX = 21; strtY = 21; endX = 481; endY = 361; colr = 14; now = prev; dsp = 20; stp = 111; cnt = -1; scr = 0; dly = 150; xr = 3; yr = 9; egg(); egGen = 1; score(); int x = getcolor(); setlinestyle(0,1,3); setcolor(15); rectangle(strtX-15,strtY-15,endX+15,endY+15); rectangle(endX+25,strtY-15,getmaxx()-15,endY+15); rectangle(strtX-15,endY+25,getmaxx()-15,getmaxy()-5); line(endX+25,strtY+75,getmaxx()-15,strtY+75); line(endX+25,strtY+200,getmaxx()-15,strtY+200); line(endX+25,strtY+275,getmaxx()-15,strtY+275); setlinestyle(0,1,1); settextstyle(8,0,1); setcolor(11); outtextxy(514,40,"SCORE"); setcolor(14); settextstyle(11,0,5); outtextxy(524,110," CONTROLS "); outtextxy(522,135,"p = PAUSE"); outtextxy(522,155,"g = RESUME"); outtextxy(522,175,"e = EXIT"); outtextxy(513,195,"ARROWS"); outtextxy(512,205," -MOVEMENT"); setcolor(14); settextstyle(4,0,9); outtextxy(getmaxx()-500,getmaxy()-110,"SNAKE"); settextstyle(8,0,1); setcolor(x); } void Snake::caught() { stp = 0; sndCgt(); for(int i=0;i<=7;i++) {if(i%2) {setcolor(10); outtextxy(512,250,"GAME OVER"); delay(900); } else {setcolor(0); outtextxy(512,250,"GAME OVER"); delay(500); } } sleep(1); } void Snake::chngDir() {int clr; fillsettingstype *p; char x = getch(); if(x == 72) now = 8; else if(x == 77) now = 4; else if(x == 80) now = 2; else if(x == 75) now = 1; else if(x == 'e') caught(); else if(x == 'p') {//int y = getcolor(); int twnkl = 1; settextstyle(11,0,9); while(1) {if(kbhit()) {int c = getch(); if(c == 'g') {clr = getcolor(); setcolor(0); rectangle(endX+40,endY-10,getmaxx()-35,getmaxy()-160); outtextxy(endX+60,endY-29,"PAUSE"); break; } } else {if(twnkl%2) {clr = getcolor(); setcolor(10); rectangle(endX+40,endY-10,getmaxx()-35,getmaxy()-160); outtextxy(endX+60,endY-29,"PAUSE"); setcolor(clr); delay(1000); } else { clr = getcolor(); setcolor(0); rectangle(endX+40,endY-10,getmaxx()-35,getmaxy()-160); outtextxy(endX+60,endY-29,"PAUSE"); delay(1000); } } twnkl++; } settextstyle(8,0,1); } } Snake::Snake(Snake *p) { *p=NULL; } void Snake::egg() { do {e1 = (rand() % 100) * dsp + strtX; e2 = (rand() % 100) * dsp + strtY; }while(test()); int x = getcolor(); setcolor(7); setfillstyle(1,random(15)+1); fillellipse(e1,e2,xr+2,xr+2); setcolor(x); egGen = 2; } int Snake::test() { for(int i=0;i<n;i++) {if(e1 == pos[i][0] && e2 == pos[i][1]) break; if(v1 == e1 && v2 == e2) break; if((e1 >= endX+1) || (e2 >= endY+1)) break; } if(i != n) return 1; else return 0; } void main() {Snake snk; int gd=DETECT,gm,i,j,k,x,y; clrscr(); initgraph(&gd,&gm,"E:\Turboc3"); snk.init(); snk.move(); closegraph(); restorecrtmode(); }

Initialize random number generator. The pseudo-random number generator is initialized using the argument passed as seed. The C++ <cstdlib> srand() function seeds the pseudo-random number generator used by rand() function. If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand. Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand. If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.

Our system can create various sounds on different frequencies. The sound() is very useful as it can create very nice music with the help of programming and our user can enjoy music during working in out the program. Sound function produces the sound of a specified frequency. Used for adding music to a C++ program.

Generate random number. Returns a pseudo-random integral number in the range between 0 and RAND_MAX. This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand. RAND_MAX is a constant defined in <cstdlib>. The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers. The rand() function generates numbers randomly.

The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fill color. Current fill pattern and fill color is used to fill the area. setfillstyle sets the current fill pattern and fill color. To set a user-defined fill pattern, do not give a pattern of 12 (USER_FILL) to setfillstyle; instead, call setfillpattern.

A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors destroy (or delete) the object. Destructors in C++ are members functions in a class that delete an object. They are called when the class object goes out of scope such as when the function ends, the program ends, a delete variable is called etc. Destructors are different from normal member functions as they don't take any argument and don't return anything. Also, destructors have the same name as their class and their name is preceded by a tilde(~).

Return bit value. Returns whether the bit at position pos is set (i.e., whether it is one). C++ bitset test() function is used to test whether the bit at position p is set or not. The C++ bitset::test function is used to check if the bit at specified position is set or not. It returns true if the bit at specified position is set, else returns false. Unlike the access operator (operator[]), this function performs a range check on pos before retrieveing the bit value, throwing out_of_range if pos is equal or greater than the bitset size.

The kbhit is basically the Keyboard Hit. This function is present at conio.h header file. So for using this, we have to include this header file into our code. The functionality of kbhit() is that, when a key is pressed it returns nonzero value, otherwise returns zero. kbhit() is used to determine if a key has been pressed or not. If a key has been pressed then it returns a non zero value otherwise returns zero.

Draws an ellipse using (x,y) as a center point and xradius and yradius as the horizontal and vertical axes, and fills it with the current fill color and fill pattern. The header file graphics.h contains fillellipse() function which draws and fills an ellipse with center at (x, y) and (xradius, yradius) as x and y radius of ellipse. Where, (x, y) is center of the ellipse. (xradius, yradius) are x and y radius of ellipse.

rectangle() is used to draw a rectangle. Coordinates of left top and right bottom corner are required to draw the rectangle. left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.

restorecrtmode restores the original video mode detected by initgraph. This function can be used in conjunction with setgraphmode to switch back and forth between text and graphics modes. Textmode should not be used for this purpose; use it only when the screen is in text mode, to change to a different text mode. restorecrtmode is implemented in winbgim, but it does not do any work. This is because both the graphics window and the text window are always open during any Windows program, so there is no need to switch back and forth between the two modes.

Settextstyle function is used to change the way in which text appears, using it we can modify the size of text, change direction of text and change the font of text. settextstyle sets the text font, the direction in which text is displayed, and the size of the characters. A call to settextstyle affects all text output by outtext and outtextxy.

delay() function is used to hold the program's execution for given number of milliseconds, it is declared in dos.h header file. There can be many instances when we need to create a delay in our programs. C++ provides us with an easy way to do so. We can use a delay() function for this purpose in our code. We can run the code after a specific time in C++ using delay() function.

setlinestyle() is a function which is used to draw the line of different- different styles. Turbo C compiler provides five line styles that are solid, dotted, center, dashed and user defined. These all five line styles are already enumerated in graphics.h header file as given below: setlinestyle() function contains three parameters type, pattern and thickness. First parameter contains the type of line like solid, dashed or dotted etc. Second parameter is applicable only when type of line is user defined. Third parameter specifies the thickness of the line it takes values 1 (line thickness of one pixel (normal)) or 3 (line thickness of three pixels (thick).

The header file graphics.h contains line() function which is used to draw a line from a point(x1, y1) to point(x2, y2) i.e. (x1, y1) and (x2, y2) are end points of the line. The function line() draws a line on the graphics screen between two specified points. So this function requires four parameters namely x1, y1, x2, and y2 to represent two points. This function draws a line from (x1, y1) coordinates to (x2, y2) coordinates on the graphics screen.

Get current time. Get the current calendar time as a value of type time_t. The function returns this value, and if the argument is not a null pointer, it also sets this value to the object pointed by timer. The value returned generally represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp). Although libraries may use a different representation of time: Portable programs should not use the value returned by this function directly, but always rely on calls to other elements of the standard library to translate them to portable types (such as localtime, gmtime or difftime).

The header file graphics.h contains closegraph() function which closes the graphics mode, deallocates all memory allocated by graphics system and restores the screen to the mode it was in before you called initgraph. closegraph() function is used to re-enter in the text mode and exit from the graphics mode. If you want to use both text mode and graphics mode in the program then you have to use both initgraph() and closegraph() function in the program. This function deallocates all memory allocated by graphics system and restores the screen to that mode in which it was presented before you called the initgraph() function.

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C++ language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant. (2D) array in C++ programming is also known as matrix. A matrix can be represented as a table of rows and columns. In C/C++, we can define multi dimensional arrays in simple words as array of arrays. Data in multi dimensional arrays are stored in tabular form (in row major order).

The header file graphics.h contains getmaxx() function which returns the maximum X coordinate for current graphics mode and driver. getmaxx() returns the maximum (screen-relative) x value for the current graphics driver and mode. For example, on a CGA in 320*200 mode, getmaxx returns 319. getmaxx is invaluable for centering, determining the boundaries of a region onscreen, and so on.

It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.

Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.

setcolor() function is used to set the foreground color in graphics mode. After resetting the foreground color you will get the text or any other shape which you want to draw in that color. setcolor sets the current drawing color to color, which can range from 0 to getmaxcolor. The current drawing color is the value to which pixels are set when lines, and so on are drawn. The drawing colors shown below are available for the CGA and EGA, respectively.

C programming language provides sleep() function in order to wait for a current thread for a specified time. slepp() function will sleep given thread specified time for the current executable. Of course, the CPU and other processes will run without a problem. The sleep() function shall cause the calling thread to be suspended from execution until either the number of realtime seconds specified by the argument seconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested due to the scheduling of other activity by the system. The sleep() function shall cause the calling thread to be suspended from execution until either the number of realtime seconds specified by the argument seconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested

To create a program in Graphics Mode, the first step would be to include the header file graphics.h. This file is required for Graphics programming. After this, the graphics have to be initialized. C Language supports 16 Bit's MS-DOS environment. Initializing the Graphics mode is to call various functions, one such is called initgraph. initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver), and putting the system into graphics mode. To start the graphics system, first call the initgraph function. initgraph loads the graphics driver and puts the system into graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to autodetect the attached video adapter at run time and pick the corresponding driver. If you tell initgraph to autodetect, it calls detectgraph to select a graphics driver and mode. initgraph also resets all graphics settings to their defaults (current position, palette, color, viewport, and so on)

The nosound() function in C language is used to stop the sound played by sound() function. The nosound() function is simply silent the system. The sound() and nosound() functions are very useful as they can create very nice music with the help of programming and our user can enjoy music during working in out the program.

The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program. The getch() function does not accept any parameter from the user. It returns the ASCII value of the key pressed by the user as an input.

The header file graphics.h contains getmaxy() function which returns the maximum Y coordinate for current graphics mode and driver. getmaxy returns the maximum (screen-relative) y value for the current graphics driver and mode. For example, on a CGA in 320*200 mode, getmaxy returns 199. getmaxy is invaluable for centering, determining the boundaries of a region onscreen, and so on.

outtextxy displays a text string in the viewport at the given position (x, y), using the current justification settings and the current font, direction, and size. To maintain code compatibility when using several fonts, use textwidth and textheight to determine the dimensions of the string. If a string is printed with the default font using outtext or outtextxy, any part of the string that extends outside the current viewport is truncated. outtextxy is for use in graphics mode; it will not work in text mode.

In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

Program to find the connected components of the "Undirected Graph". This can be done using depth first search algorithm. Fills stack with vertices (in increasing order of finishing