Tuesday, December 13, 2016

Game - Score Management using C.


Following C program demonstrate how to maintain score in a Game. Score of respective arrow key press event will be increased by one on every arrow key press event.

#include <stdio.h>
#include <windows.h>

COORD c = {0, 0};
void setxy (int x, int y)
{
 c.X = x; c.Y = y; // Set X and Y coordinates
 SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}

int main() 
int i, j, x=25, y=10, ch1, ch2;
int  score_x1=5, score_y1=4, up=1, down=1, right=1, left=1; 
printf("Press UP, DOWN, RIGHT, LEFT Arrow Key..\n");
  printf("Press X to exit game... \n"); 
setxy(5,3); //Top border line...
for(i=0; i<44; i++)
printf("%c", 196);
setxy(5,5);//Bottom border line...
for(i=0; i<44; i++)
printf("%c", 196);
//Verticle lines
setxy(5,4);
printf("| Left:0   | Right:0   | Up:0   | Down:0   |");
ch1 = getch(); 
ch2 = 0;

 //When accepting arrow key, function must be called twice; first call  returns 0/0xE0; second call returns actual key code
if (ch1 == 0xE0) 
{
   setxy(x,y);
   while(ch2 != 'X')
   {
ch2 = getch();
switch(ch2) 
case 72: //Up
setxy(x,--y);
printf("%c",2);
setxy(score_x1+28,score_y1);
printf("%d",up++);
break; 
case 80: //Down
     setxy(x,++y);
     printf("%c",2);
     setxy(score_x1+39,score_y1);
     printf("%d",down++);
     break; 
case 75: //Left
     setxy(--x,y);
     printf("%c",2);
     setxy(score_x1+7,score_y1);
     printf("%d",left++);
     break; 
case 77: //Right
     setxy(++x,y);
     printf("%c",2);
     setxy(score_x1+19,score_y1);
     printf("%d",right++); break; 
default: break; 
}
  }
 } 
return 0; 
}

//Design and developed by cprogrampracticals.blogspot.in

Fig.: Game Score Management



No comments:

Post a Comment