C Programming Code Examples
C > Games and Graphics Code Examples
Egg Game in C
/* Egg Game in C */
#include"dos.h"
#include"graphics.h"
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<dos.h>
#include<stdlib.h>
#include<iostream.h>
union REGS i,o;
main()
{
int initmouse();
int restrictmouseptr(int,int,int,int);
int getmousepos(int *,int *,int *);
int showmouseptr();
int gd=DETECT,gm,maxx,maxy,x,y,button;
initgraph(&gd,&gm,"");
int count=0;
maxx=getmaxx();
maxy=getmaxy();
setbkcolor(1);
setviewport(0,0,maxx,maxy,1);
gotoxy(26,1);
if(initmouse()==0)
{
closegraph();
restorecrtmode();
//to go back to normal graphics mode or deleting viewport.
printf("
mouse driver not loaded");
exit(1);
}
restrictmouseptr(0,getmaxy()-20,maxx,getmaxy()-15);
int a=30;int b=0;
setcolor(0);
setfillstyle(1,15);
int score=0;
count=20;
int s=5;
int level=0;
char name[40];
gotoxy(5,2);
cout<<"PLEASE ENTER YOUR SWEET NAME::-";
gets(name);
gotoxy(5,2);
cout<<"
";
while(!kbhit())
{
getmousepos(&button,&x,&y);
setcolor(15);
setfillstyle(1,15);
fillellipse(a,b,10,15);
if((b>getmaxy()-20)&&(b<=getmaxy()-15))
// For checking the egg position.
{
if(a>=(x-20)&&(a<=(x+60)))
{
score+=10;
gotoxy(320,2);
textcolor(13);
cout<<"your score: "<<score;
}
}
if(b>getmaxy()+40)
{
b=0;
a=random(getmaxx());
gotoxy(10,2);
cout<<"eggs left: "<<count;
count--;
if(count==-1)
{
gotoxy(32,10);
cout<<"LEVEL COMPLETED.";
level++;
if(level==4)
{
goto varun;
}
count=10;
s++;
getch();
gotoxy(32,10);
cout<<" ";
}
}
setcolor(10);
line(x,getmaxy(),x+40,getmaxy());
line(x,getmaxy(),x-20,getmaxy()-20);
line(x+40,getmaxy(),x+60,getmaxy()-20);
line(x-20,getmaxy()-20,x+60,getmaxy()-20);
delay(10);
setcolor(0);
line(x,getmaxy(),x+40,getmaxy());
line(x,getmaxy(),x-20,getmaxy()-20);
line(x+40,getmaxy(),x+60,getmaxy()-20);
line(x-20,getmaxy()-20,x+60,getmaxy()-20);
setfillstyle(1,0);
fillellipse(a,b,10,15);
b+=s;
}
varun:
gotoxy(30,12);
cout<<"EXCELLENT WORK "<<name;
gotoxy(33,15);
cout<<"GAME OVER. ";
gotoxy(32,18);
cout<<"YOUR SCORE:"<<score;
gotoxy(58,24);
cout<<"COMPOSED BY:";
gotoxy(55,25);
cout<<"VARUN KUMAR SONKER";
gotoxy(30,10);
cout<<"GREATEST SCORE::"<< 540;
getch();
getch();
}
initmouse()
{
i.x.ax=0;//for initialising mouse.
int86(0x33,&i,&o);
return(o.x.ax);
}
showmouseptr()
{
i.x.ax=1; // for displaying mouse pointer.
int86(0x33,&i,&o);
}
restrictmouseptr(int x1,int y1,int x2,int y2)
{
i.x.ax=7; //to define the upper left boundry of mouse.
i.x.cx=x1;
i.x.dx=x2;
int86(0x33,&i,&o);
i.x.ax=8; //to define the bottom right boundry of mouse.
i.x.cx=y1;
i.x.dx=y2;
int86(0x33,&i,&o);
}
getmousepos(int *button,int *x, int *y)
{
i.x.ax=3; //to move mouse.
int86(0x33,&i,&o);
*button=o.x.bx;
*x=o.x.cx;
*y=o.x.dx;
}
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.
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:
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.
Use the textcolor function to define what color you want to use for text. You can use this function to vary the text colors of your output. Colors must be written in all caps, or expressed as a numeral.
setbkcolor() function is used to set the background color in graphics mode. The default background color is black and default drawing color as we know is white. setbkcolor() function takes only one argument it would be either the name of color defined in graphics.h header file or number associated with those colors. If we write setbkcolor(yellow) it changes the background color in Green.
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.
Get string from stdin. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str. A terminating null character is automatically appended after the characters copied to str. Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).
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.
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.
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.
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.
The gotoxy() function places the cursor at the desired location on the screen. This means it is possible to change the cursor location on the screen using the gotoxy() function. It is basically used to print text wherever the cursor is moved.
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,
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.
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.
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.
#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:
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.
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.
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.
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).
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 goto statement in C programming language provides an unconditional jump from the 'goto' to a labeled statement in the same function. The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program control to a predefined label. The goto statment can be used to repeat some part of the code for a particular condition. It can also be used to break the multiple loops which can't be done by using a single break statement.
setviewport() establishes a new viewport for graphics output. The viewport corners are given in absolute screen coordinates by (left,top) and (right,bottom). The current position (CP) is moved to (0,0) in the new window. The parameter clip determines whether drawings are clipped (truncated) at the current viewport boundaries. If clip is nonzero, all drawings will be clipped to the current viewport. setviewport function is used to restrict drawing to a particular portion on the screen.
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.
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 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 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.
C program Read two strings and Concatenate them, without using library functions. Display the 'Concatenated String'. Take two strings as input and store them in the arrays string1 and
C Program accepts array and swap elements using pointers. C program to accept an array of 10 elements and swap 3rd element with 4th element using pointers and display the
This C Program to calculates the volume and surface area of cone. This program is used to find the the volume and surface area of cone. Surface_Area = Pi * r * (r + sqrt(r2 + h2)) and
Declare variable to be guess. Declare variable to store guessed date. Declare variable to test for invalid input. Display the intro and directions. Get the users guess and store it.