Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Thursday, 24 May 2012

How To Make SNAKE Game In c/c++


How To Make SNAKE Game In c/c++
hello friends today i will show you how to make a snake game in c.
i thinks game code is too long, so just copy past it....
enjoy coding in c....!!!!
Here is the required informations:


// Header Files

#include
#include

// Macros
#define LEFT 1
#define RIGHT 2
#define UP 3
#define DOWN 4

//Game Data

int score; //Keeps the count of game score
int gamedelay;//Lower the game delay faster is the game speed.

struct Snake_Data {

int length;
int head_x; // Stores Head X Coordinate
int head_y; // Stores Head Y Coordinate
int head_dir; // Stores Head Direction
int tail_x; // Stores Tail X Coordinat
int tail_y; // Stores Tail Y Coordinat
int tail_dir; // Stores Tail Direction
int bend_x [1000]; //Stores X Bend Coordinate Declare it big enough to accomodate maximum bends
int bend_y [1000];
int bend_dir [1000]; // Stores Bend direction when tail reaches that X Coordinate
} Snake; // Declares a variable of the structure

// User - Defined functions -

int randomvalue (int starting, int ending) // Return a random int value between end and starting parameters

{
static int previous = 0;
int answer;
if (previous <0) previous = 0;
int difference = starting - ending;
time_t t;
srand((unsigned) time(&t));
for (int i = 0; i
answer = (rand () % difference);
previous++;
return answer;
}

void gamephysics ()
{
static int foodcount = 0;//Keep Count of food
int futurex, futurey, futurepixel;
int i;
char scorestring [100];
if (foodcount < 500) //Adds a food if no food is present and upto maximum 500 food
{
int valid = 0;
int foodx;
int foody;
while (!valid)
{
foodx = randomvalue (15,1003);
foody = randomvalue (15,695);
if (getpixel (foodx,foody)!= 15)
{
putpixel (foodx,foody,2);
foodcount++;
valid = 1;
}

}
}

//Boundary Collision Check -

if (Snake.head_x <= 10 || Snake.head_x >= 1008 || Snake.head_y <= 10 || Snake.head_y >= 700)
{
outtextxy (499,345, "Game Over");
delay (3000);
exit (1);
}

//Get future value of head in int variable futurex and futurey and calculate the logic

futurex = Snake.head_x;
futurey = Snake.head_y;
if (Snake.head_dir == LEFT)
{
futurex --;
}
if (Snake.head_dir == RIGHT)
{
futurex ++;
}
if (Snake.head_dir == UP)
{
futurey --;
}
if (Snake.head_dir == DOWN)
{
futurey ++;
}
futurepixel = getpixel(futurex,futurey);

if (futurepixel == 2)//Food Eaten
{
foodcount --; //Reduce count
score++; //Increase Score
setcolor (0);//Rewrite Score
setfillstyle (0,0);
bar (11,701,1007, 735);
setcolor (4);
sprintf (scorestring, "Score : %d", score);
outtextxy (20,710, scorestring);
//Increase the size of snake by 100 pixel you can put as much as you want
if (Snake.tail_dir == UP)
{
for (i = 0; i<101;i++) putpixel (Snake.tail_x,Snake.tail_y+i,15);
Snake.tail_y +=100;
}
if (Snake.tail_dir == DOWN)
{
for (i = 0; i<101;i++) putpixel (Snake.tail_x,Snake.tail_y-i,15);
Snake.tail_y -=100;
}
if (Snake.tail_dir == LEFT)
{
for (i = 0; i<101;i++)
putpixel (Snake.tail_x+i,Snake.tail_y,15);
Snake.tail_x +=100;
printf ("LEFT");
}
if (Snake.tail_dir == RIGHT)
{
for (i = 0; i<101;i++)
putpixel (Snake.tail_x-i,Snake.tail_y,15);
Snake.tail_x -=100;
printf ("RIGHT");
}

}
if (futurepixel == 15)
{
outtextxy (499,345, "Game Over");
delay (3000);
exit (1);
}

}



void userinput () //Process User Input and maps it into game
{
static int i = 0;
if ( i > 1000) i = 0; // Makes the bend array a circular queue
static int j = 0;
if ( j > 1000) j = 0;
char input;
if (kbhit ())
{
input = getch ();
//Change Respective Return value to our MACRO Direction Code Value
if (input == 80) input = DOWN;

if (input == 72) input = UP;

if (input == 75) input = LEFT;

if (input == 77) input = RIGHT;




//Change head direction based on logic

if (input == LEFT && Snake.head_dir != RIGHT && Snake.head_dir != LEFT)
{
Snake.head_dir = LEFT;
Snake.bend_x [i] = Snake.head_x;
Snake.bend_y [i] = Snake.head_y;
Snake.bend_dir [i] = LEFT;
i++;
}
if (input == RIGHT && Snake.head_dir != LEFT && Snake.head_dir != RIGHT)
{
Snake.head_dir = RIGHT;
Snake.bend_x [i] = Snake.head_x;
Snake.bend_y [i] = Snake.head_y;
Snake.bend_dir [i] = RIGHT;
i++;
}
if (input == UP && Snake.head_dir != DOWN && Snake.head_dir != UP)
{
Snake.head_dir = UP;
Snake.bend_x [i] = Snake.head_x;
Snake.bend_y [i] = Snake.head_y;
Snake.bend_dir [i] = UP;
i++;
}
if (input == DOWN && Snake.head_dir != UP && Snake.head_dir != DOWN)
{
Snake.head_dir = DOWN;
Snake.bend_x [i] = Snake.head_x;
Snake.bend_y [i] = Snake.head_y;
Snake.bend_dir [i] = DOWN;
i++;
}


}

//Code to change the y direction at respective time
if (Snake.tail_x == Snake.bend_x [j] && Snake.tail_y == Snake.bend_y [j])
{
Snake.tail_dir = Snake.bend_dir [j];
j++;
}

}

void movesnake ()
{
//Move the Head
if (Snake.head_dir == LEFT)
{
Snake.head_x --;
}
if (Snake.head_dir == RIGHT)
{
Snake.head_x ++;
}
if (Snake.head_dir == UP)
{
Snake.head_y --;
}
if (Snake.head_dir == DOWN)
{
Snake.head_y ++;
}
putpixel (Snake.head_x, Snake.head_y,15);

//Move the Tail
putpixel (Snake.tail_x, Snake.tail_y,0);
if (Snake.tail_dir == LEFT)
{
Snake.tail_x --;
}
if (Snake.tail_dir == RIGHT)
{
Snake.tail_x ++;
}
if (Snake.tail_dir == UP)
{
Snake.tail_y --;
}
if (Snake.tail_dir == DOWN)
{
Snake.tail_y ++;
}


}


void gameengine ()//Soul of our game.
{
while (1)
{
movesnake ();
userinput ();
gamephysics ();
delay (5);
}

}

void initscreen ( ) //Draws Intial Screen.
{
int i;
char scorestring [100];
//Draw Boundary
setcolor (4);
line (10,10,10,700);
line (1008,10,1008,700);
line (10,700,1008,700);
line (10,10,1008,10);
//Write Score on scree
sprintf (scorestring, "Score : %d", score);
outtextxy (20,710, scorestring);
//Draw Intial Snake Body
for (int i = Snake.length; i>0;i--) //This part should be redesigned for change of code of intial values
{
putpixel (Snake.head_x-i,Snake.head_y,15);
}
}

void initgamedata ( ) //Snakes starting coordinate if you modify any one make sure also modify dependent values
{
int i;
Snake.length = 100;
Snake.head_x = 200;
Snake.head_y = 200;
Snake.head_dir = RIGHT;
Snake.tail_x = Snake.head_x- Snake.length;
Snake.tail_y = Snake.head_y;
Snake.tail_dir = Snake.head_dir;
for (int i = 0; i <1000;i++) // There is no bend initally
{
Snake.bend_x[i] = 0;
Snake.bend_dir[i] = 0;
}
score = 0;
gamedelay = 1000; // Should be change according to game speed need.

}

// Main Function

int main ()

{
initwindow(1018, 736,"Snake 1.0"); // Create the Snake Window with value is optimize for mode 1024 * 768
initgamedata ();
initscreen ();
gameengine ();
return 0;
}


Thanks.

Monday, 14 May 2012

What is C ? Learn about C

Learn about C In easiest way/ 

C For Beginners

C is a programming language invented in the early 1970s by Dennis Ritchie as a language for writing operating systems.
Here is a short overview and history of C.
The purpose of C is to precisely define a series of operations that a computer can perform to accomplish a task. Most of these operations involve manipulating numbers and text, but anything that the computer can physically do can be programmed in C.
Computers have no intelligence- they have to be told exactly what to do and this is defined by the programming language you use. Once programmed they can repeat the steps as many times as you wish at very high speed. Modern PCs are so fast they can count to a billion in a second or two.

What can a C program do?

Typical programming tasks includes putting data into a database or pulling it out, displaying high speed graphics in a game or video, controlling electronic devices attached to the PC or even playing music and/or sound effects. You can even write software to generate music or help you compose.

Is C the best programming language?

Some computer languages were written for a specific purpose. Java was originally devised to control toasters, C for programming Operating Systems,Pascal to teach good programming techniques but C was intended to be more like a high level assembly language which could be used to port applications to different computer systems.
There are some tasks that can be done in C but not very easily, for example designing GUIscreens for applications. Other languages like Visual Basic, Delphi and more recently C# have GUI design elements built in to them and so are better suited for this type of task. Also somescripting languages that provide extra programmability to applications like MS Word and even Photoshop tend to be done in variants of Basic, not C.
You can find out more about the other computer languages and how they stack up against C.

Which computers have C?

This is better stated as which computers don't have C! The answer- almost none, after 30 years of use it is everywhere. It is particularly useful im embedded systems with limited amounts of RAM and ROM. There are C compilers for just about every type of operating system. Find out more about Operating Systems.

How do I get started with C?

First you need a C compiler. There are many commercial and free ones available. The list below has instructions for downloading and installing the compilers. Both are completely free and include anIDE to make life easier for you to edit, compile anddebug your applications. The instructions also show you how to enter and compile your first C application.

How do I begin writing C applications?

C code is written using a text editor. This can be notepad or an IDE like those supplied with the three compilers listed above. You write a computer program as a series of instructions (called statements) in a notation that looks a little like mathematical formulas.
 int c=0;
 float b= c*3.4+10; 
This is saved out in a text file and then compiled and linked to generate machine code which you then can run. Every application you use on a computer will have been written and compiled like this, and many of them will be wriiten in C. Read more about compilers and how they work. You can't usually get hold of the original source code unless it was open source.

Is there plenty of C Open Source?

Because it is so widespread, much open source software has been written in C. Unlike commercial applications, where the source code is owned by a business and never made available, open source code can be viewed and used by anyone. It's an excellent way to learn coding techniques. You can see many examples in the C Code Library

Could I get a programming job?

Certainly. There are many C jobs out there and an immense body of code exists that will need updating, maintaining and occasionally rewriting. The top three most popular programming languages according to the quarterly Tiobe.com survey, are Java, C and C++.
You could write your own games but you'll need to be artistic or have an artist friend. You'll also need music and sound effects. Find out more about game development. Games like Quake 2 and 3 were written in C and the code is available free online for you to study and learn from it.
Perhaps a professional 9-5 career would suit you better- read about a professional career or perhaps consider entering the world of software engineering writing software to control nuclear reactors, aircraft, space rockets or for other safety critical areas.

What Tools and Utilities are there?

Well if you can't find what you want, you could always write it. That is how most of the tools around came into existence. We've listed some tools and utilities but keep checking back.

So what now?

First you have to learn to program in C. Read the tutorials and join the forums and ask questions. But most of all have fun!

Learn About Pascal - The Programming Language In Easy Way

Definition: Pascal is a programming language invented in the early 1970s by Professor Nicklaus Wirth to teach good programming practices to students. It was not a commercial success until the mid 80s when Borland launched a low cost quality Pascal development system called Turbo Pascal. This was followed up by a Windows Development system calledDelphi which is also Pascal based.
Delphi lost significant market share to C++, Java and C# for several years and this trend was accelerated recently when Borland announced that it would sell all of it's desktop development tools.

Learn About Object Oriented Programming

what is ??Object Oriented Programming 
Definition: Object Oriented Programming (OOP) is a method of developing software that models the real world using objects. For example a driving simulation might have road objects, vehicle objects and possibly human objects.
An object is a self contained item of data that can only be accessed or changed in a controlled way. This prevents side effects- a common problem in procedural (non object ) code where data is globally accessible. Objects can receive or send messages to other objects by calling their methods.
Objects can be defined in terms of existing objects- this is known as inheritance. For an indepth look at OOP, see the article on Object Oriented Programming.

Glossary:

A B C D E F G H

Learn About Compilers and Interpreters

What's the difference?


Before the Java and C# programming languages appeared, computer programs were onlycompiled or interpreted. Languages like Assembly Language, C, C++, Fortran, Pascal were almost always compiled into machine code. Languages like Basic,VbScript and JavaScript were usually interpreted.
So what is the difference between a compiled program and an Interpreted one?

Compiling

To write a program takes these steps:
  1. Edit the Program
  2. Compile the program into Machine code files.
  3. Link the Machine code files into a runnable program (also known as an exe).
  4. Debug or Run the Program
With some languages like Turbo Pascal and Delphi steps 2 and 3 are combined.
Machine code files are self-contained modules of machine code that require linking together to build the final program. The reason for having separate machine code files is efficiency; compilers only have to recompile source code that have changed. The machine code files from the unchanged modules are reused. This is known as Making the application. If you wish to recompile and rebuild all source code then that is known as a Build.
Linking is a technically complicated process where all the function calls between different modules are hooked together, memory locations are allocated for variables and all the code is laid out in memory, then written to disk as a complete program. This is often a slower step than compiling as all the machine code files must be read into memory and linked together.

Interpreting

The steps to run a program via an interpreter are
  1. Edit the Program
  2. Debug or Run the Program
This is a far faster process and it helps novice programmers edit and test their code quicker than using a compiler. The disadvantage is that interpreted programs run much slower than compiled programs. As much as 5-10 times slower as every line of code has to be re-read, then re-processed.

Enter Java and C#

Both of these languages are semi-compiled. They generate an intermediate code that is optimized for interpretation. This intermediate language is independant of the underlying hardware and this makes it easier to port programs written in either to other processors, so long as an interpreter has been written for that hardware.
Java when compiled produces bytecode that is interpreted at runtime by a Java Virtual Machine(JVM). Many JVMs use a Just-In-Time compiler that converts bytecode to native machine code and then runs that code to increases the interpretation speed. In effect the Java source code is compiled in a two-stage process.
C# is compiled into Common Intermediate Language (CIL, which was previously known as Microsoft Intermediate Language MSIL. This is run by the Common Language Runtime (CLR), part of the .NET framework an environment that provides support services such as garbage collection and Just-In-Time compilation.
Both Java and C# employ speedup techniques so the effective speed is almost as fast as a pure compiled language. If the application spends a lot of time doing input and output like reading disk files or running database queries then the speed difference is barely noticeable.

What Does this Mean to me?

Unless you have a very specific need for speed and must increase the frame rate by a couple of frames per second, you can forget about speed. Any of C, C++ or C# will provide sufficient speed for games, compilers, and operating systems.