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 > Games and Graphics Code Examples

Oil Spill Game in C.

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
/* Oil Spill Game in C */ #include<graphics.h> #include<stdio.h> #include<stdlib.h> #include<time.h> #include<dos.h> #define L 75 #define R 77 /* variable initialisations */ union REGS i,o; int ch1,ch2; int mx,my,vx=270,vy; int temp,retval; char s[20],s1[20]; char ch; int gd=DETECT,gm; int x,y=400,r,c=7,score=0,lifes=4,flag=0,dlyfactor=0; /* main function */ main() { initialise(); firstscreen(); displaylifes(); displayscore(); welcome(); while(1) { condition1(); display_drop(); is_keyhit(); check_catchdrop(); check_looselife(); } nosound(); } /* sub functions */ initialise() { initgraph(&gd,&gm,""); mx=getmaxx();my=getmaxy(); setcolor(4); x=mx/2; image(x,y,c); vy=20; } firstscreen() { button3d(100,0,430,5); button3d(100,0,5,450); button3d(100,450,430,5); button3d(525,0,5,455); setfillstyle(1,7); bar(270,5,275,10); bar(320,5,325,10); bar(370,5,375,10); setfillstyle(1,8); bar(267,10,278,15); bar(317,10,328,15); bar(367,10,378,15); button3d(280,448,80,9); setcolor(4); outtextxy(290,450,"OIL SPIL"); } welcome() { setfillstyle(1,0); bar(200,250,450,350); clk_but3d(200,250,250,100); settextstyle(0,0,2); setcolor(4); outtextxy(240,280," WELCOME"); outtextxy(215,310, " TO OILSPIL"); getch(); setfillstyle(1,0); bar(200,250,453,353); return; } is_keyhit() { if(kbhit()) { i.h.ah=0; int86(22,&i,&o); if(o.h.ah==1) { nosound();closegraph();exit(0); } if(o.h.ah==75) { sound(1800);image(x,y,0);x=x-10;image(x,y,c);nosound(); } if(o.h.ah==77) { sound(1800);image(x,y,0);x=x+10;image(x,y,c);nosound(); } if(o.h.ah==80) { dlyfactor+=250; } if(o.h.ah==72) { dlyfactor-=250; } } } image(int x,int y,int c) { int b; setcolor(c); rectangle(x-10,y+6,x+10,y+20); setcolor(0); line(x-9,y+6,x+9,y+6); setfillstyle(1,c); bar(x-9,y+6,x+9,y+19); setfillstyle(1,0); bar(x-6,y+6,x+6,y+19); setcolor(c); for(b=1;b<=6;b++) line(x-10+b,y+19+b,x+10-b,y+19+b); setfillstyle(1,c); bar(x-1,y+19+b,x+1,y+25+b); fillellipse(x,y+25+b+3,8,3); } object(int x,int y,int c) { setcolor(c); setfillstyle(1,c); fillellipse(x,y+5,4,8); } condition1() { if(flag==1||vy>410) { vy = 20; temp = random(3); if(temp==0) vx=270; else if(temp==1) vx=320; else if(temp==2) vx =370; flag=0; } } check_looselife() { if(lifes==0) { setfillstyle(1,0); bar(200,250,450,350); clk_but3d(200,250,250,100); settextstyle(0,0,2); setcolor(1); outtextxy(240,290,"GAME OVER"); getch(); closegraph(); play_again(); exit(0); } } display_drop() { object(vx,vy,8); delay(3000+dlyfactor); object(vx,vy,0); vy+=10; } check_catchdrop() { if((x-5<=vx)&&(vx<=x+5)&&vy==410) displayscore(); else if(vy>410) displaylifes(); nosound(); } displaylifes() { settextstyle(0,0,1); clk_but3d(0,440,90,13); setcolor(7); outtextxy(5,445,s1); lifes = lifes -1; sprintf(s1,"LIFES = %d", lifes); setcolor(4); outtextxy(5,445,s1); flag=0; } displayscore() { settextstyle(0,0,1); clk_but3d(540,440,90,13); setcolor(7); outtextxy(545,445,s); score=score+1; sprintf(s,"SCORE = %d",score); setcolor(4); outtextxy(545,445,s); flag=1; vy=20; } button3d(int x,int y,int l,int w) { setcolor(LIGHTGRAY); setfillstyle(1,LIGHTGRAY); bar(x,y,x+l,y+w); setcolor(WHITE); line(x,y,x+l,y); line(x,y,x,y+w); setcolor(DARKGRAY); line(x+l+1,y,x+l+1,y+w+1); line(x,y+w+1,x+l+1,y+w+1); } clk_but3d(int x,int y,int l,int w) { setcolor(LIGHTGRAY); setfillstyle(1,LIGHTGRAY); bar(x,y,x+l,y+w); setcolor(DARKGRAY); line(x,y,x+l,y); line(x,y,x,y+w); setcolor(WHITE); line(x+l+1,y,x+l+1,y+w+1); line(x,y+w+1,x+l+1,y+w+1); } letter(int x,int y,int l,int w) { char s[1]; int ch=3; setcolor(RED); sprintf(s,"%c",ch); outtextxy(x + l/4 + 2,y + w/5, s); } restore_defaults() { y=400;c=7;score=0;lifes=4;flag=0;dlyfactor=0; } play_again() { printf("To Play again Press 'y'"); if(getch()=='y') { restore_defaults(); main(); } else }

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

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.

Ellipse is used to draw an ellipse (x,y) are coordinates of center of the ellipse, startangle is the starting angle, end angle is the ending angle, and fifth and sixth parameters specifies the X and Y radius of the ellipse. To draw a complete ellipse strangles and end angle should be 0 and 360 respectively. Making a circle and an ellipse in C can be done easily. How to do is, first initialize a graph with two parameters and a path to the "bgi" folder in your system.

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.

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.

An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.

The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.

Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers,

Delay function is used to suspend execution of a program for a particular time. delay() function requires a parameter which should be a number, defining the milliseconds for the delay. To use delay function in your program you should include the "dos.h" header file which is not a part of standard C library. Here unsigned int is the number of milliseconds (remember 1 second = 1000 milliseconds).

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.

In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.

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.

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.

The kbhit is basically the Keyboard Hit. Function kbhit in C is used to determine if a key has been pressed or not. 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.

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.

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.

line() is a library function of graphics.c in c programming language which is used to draw a line from two coordinates. line() function 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 nosound() function in C language is used to stop the sound played by sound() function. nosound() function is simply silent the system. Sound function produces the sound of a specified frequency and nosound function turn off the PC speaker.

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.

The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program. The exit() function is the standard library function of the C, which is defined in the stdlib.h header file. So, we can say it is the function that forcefully terminates the current program and transfers the control to the operating system to exit the program. The exit(0) function determines the program terminates without any error message, and then the exit(1) function determines the program forcefully terminates the execution process.

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 (x_radius, y_radius) as x and y radius of ellipse. Where, (x, y) is center of the ellipse. (x_radius, y_radius) are x and y radius of ellipse.

bar() function is a C graphics function that is used to draw graphics in the C programming language. The graphics.h header contains functions that work for drawing graphics. The bar() function is also defined in the header file. The bar() function is used to draw a bar ( of bar graph) which is a 2-dimensional figure. It is filled rectangular figure. The function takes four arguments that are the coordinates of (X, Y) coordinates of the top-left corner of the bar {left and top } and (X, Y) coordinates of the bottom-right corner of the bar {right and bottom}.

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.

A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose. To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows:

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, try to use some random values in loop, vary delay and enjoy.

In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed.

#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. Here are the two types of file that can be included using #include:

Write formatted data to string. Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str. The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version). A terminating null character is automatically appended after the content. After the format parameter, the function expects at least as many additional arguments as needed for format.

Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language: Simple assignment operator. Assigns values from right side operands to left side operand. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.

C programming code to Identical to scanf() except that data is from buf. The number of variables assigned. A value of zero means that no fields were assigned. EOF indicates

Program code enter Month number between 1-12 and print number of days in month using If Else. Input month number from user. Store it in a variable say month and for each month

C Language program code to find first & last digit. Input a number from user & store it in some variable say num. Find last digit using modulo division by 10 lastDigit = num % 10.