Simple Swapping Card’s game with C Graphics!


Simple Swapping Card’s game with C Graphics!


#include "stdio.h"
#include "graphics.h"
#include "stdlib.h"
#include "math.h"
#include "time.h"

#define BREADTH 30          //Breadth of card
#define HEIGHT 40                       //Height of card

int xco[4]={0,50,200,350},r=75,x,pos,SPEED=14;

void swap(int a,int b,int c,int t)  //Function to rotate cards
{
    int y1,y2;
    cleardevice();
    if(pos==a)                      //Change answer position
        pos=b;
    else if(pos==b)
        pos=a;
    for(x=xco[a];x<=xco[b];x++)     //Rotate on circumference
    {
        cleardevice();
        y1=200+sqrt((r*r)-((x-xco[a]-r)*(x-xco[a]-r)));
        y2=200-sqrt((r*r)-((x-xco[a]-r)*(x-xco[a]-r)));
        rectangle(xco[c],200,xco[c]+BREADTH,200+HEIGHT);
        if(t==1)        //Anti-clockwise rotation
        {
            rectangle(x,y1,x+BREADTH,y1+HEIGHT);
            rectangle(xco[b]+xco[a]-x,y2,xco[b]+xco[a]-x+BREADTH,y2+HEIGHT);
        }
        else                    //Clockwise rotation
        {
            rectangle(x,y2,x+BREADTH,y2+HEIGHT);
            rectangle(xco[b]+xco[a]-x,y1,xco[b]+xco[a]-x+BREADTH,y1+HEIGHT);
        }
        delay(SPEED);           //Delay depending on SPEED
    }
}

void start()                //For starting animation
{
    int i;
    char str[2];
    cleardevice();
    for(i=1;i<=3;i++)               //Draw three cards & number them 1, 2 & 3
    {
        rectangle(xco[i],200,xco[i]+BREADTH,200+HEIGHT);
        sprintf(str,"%c",i+48);
        outtextxy(xco[i]+BREADTH/2,200+HEIGHT+20,str);
    }
    for(i=0;i<10;i++)               //Indicate start card
    {
        setfillstyle(SOLID_FILL,3+i);
        floodfill(xco[pos]+15,200+15,15);
        delay(250);
    }
}
int main()
{
    int gd,gm,a,b,c,t,i;
    randomize();
    detectgraph(&gd,&gm);
    initgraph(&gd,&gm,"c:\\tc\\bgi");
    cleardevice();
    setcolor(15);
    settextstyle(DEFAULT_FONT,HORIZ_DIR,2);
    pos=rand()%3+1;                 //Initialize start card positoon randomly
    start();
    for(i=0;i<30;i++)
        {
                a=rand()%2+1;           //Choose random pair of cards for swap
                b=(a==1)?2:3;           //either (1,2) or (2,3)
                c=(a==1)?3:1;
                t=rand()%2;             //Randomize t:Indicates anticlockwise/clockwise rotation
                swap(a,b,c,t);
                if(SPEED>3)
                      SPEED--;        //Increase speed i.e. decrease delay time
        }
    printf("\n\n\t\tPosition of the Card ? (1, 2 or 3)\n\t\t");
    scanf("%d",&t);
    if(t==pos)          //Check if right/wrong
        printf("\n\n\t\tCorrect!!!");
    else
        printf("\n\n\t\tWrong!!!");
    getch();
    return 1;
}




Explanation :

Global Variables :

We have 4 global integers & an array. These variables are declared as global to avoid frequent passing of values between different functions.
xco[4] : The array describes the positions of the three cards on the screen, It simply holds the starting corner’s x-coordinate. Note that we have made the array of size 4 rather than of 3 to enable us to use the array as 1 based. It means that the 0th element of array i.e.’0′ has no importance.
r : It describes the radius of the circle on the circumference of which the cards are going to rotate. Note that the radius should be the (exact difference between two positions of cards)/2. For e.g in this case r = (200-50)/2 = (350-200)/2. This is to ensure that the animation of rotation is perfectly synced with the positions of cards.
pos : As described earlier, it holds the current position of the indicated card. We will use this to check the correctness of guess made by the player.
SPEED : We will use this integer variable to change the speed of rotation sequentially. Note that as the value of SPEED decreases the actual speed of animation increases. We will limit the minimum value of SPEED to be up to ‘3’ only. (Only superman will be able to guess the card beyond this speed !)

Definitions :

BREADTH & HEIGHT : As commented, these two describe the breadth & height of rectangular card being drawn. It is important that we choose appropriate values of these two depending on the radius of circle of rotation because a wrong choice may result in overlapping of cards during animation. Still don’t stop yourself from playing with these two attributes.

Details of Program :

We first call the randomize() function so that the random number generator gets initialized properly (that’s why we have included the ‘time.h’ file) See this for more help on randomize().
Choosing the first card at the start is also random & that’s why I have used the statement “pos=rand()%3+1”. This initialize the ‘pos’ with random starting card. The +1 is due to the use of 1 based indexing.
When the start function is called the starting animation will be displayed.
Now comes the interesting part, we have used the loop as we want to perform the swappings for 30 times (you may change this number as per your desire).
Note that the variables a,b,c actually indicate the card numbers. We first randomize the card number in ‘a’ (either 0 or 1 only because we will swap either 0&1 or 1&2 at a time, so ‘a’ will always be either 0 or 1). Then we give the appropriate value to ‘b’ depending on card number in ‘a’. ‘c’ will be the remaining third card.
We randomize ‘t’ between 0 or 1. ‘t’ actually describes that whether the rotation should be anti-clockwise or clockwise. (This makes the swapping totally random). Next we call the swap function passing all the arguments.
Next two lines are to increase the speed, work on your own on this.
After completing all the swapping we ask the player for her/his guess & scan it in ‘t’. Then we compare the answer with ‘pos’ & display appropriate message as per the result.

Functions :

start() : void start() is the function which displays the starting animation. First we draw three cards & their numbers. If you are confused with use of sprintf & str here do read this.
Next we colour the card described by ‘pos’. Note that we have to give the coordinates of inside point for floodfill() carefully. The loop is used to fill different colours sequentially one by one.
swap() : This is the core part of our program. Here we rotate thee cards ‘a’ & ‘b’ while just print the third card ‘c’ as it is & we do this all as per the direction provided by ‘t’.
First of all we update the ‘pos’ with new position only when the prev ‘pos’ card is being swapped.
Next part is of animating the circular rotation :
  • What we do here is that we move a counter x-coordinate ‘x’ from left side card’s position till the right side card’s position. During this, at each iteration we calculate two y co-ordinates ‘y1’ & ‘y2’ using the centre-radius formula. Note that sqrt() function returns only positive root which is used to get ‘y1’ while we use the second statement with a ‘-‘ sign to generate the second y-coordinate 7 store it in ‘y2’.
  • Next we draw the card ‘c’ which remains still at its position.
  • Now, if t=1, we draw the left card using lower y-coordinate & right card using upper one. Otherwise we do the exact opposite of this. This simulates the animation of anti-clockwise & clockwise rotation of cards. Note that the cards rotate on the circumference of circle only.
  • One complete rotation occurs when the control comes out of for loop.

What next ?

Done with the above program ? Try the following things to make your program better :
  • Being creative : You can make the cards more realistic with design improvements.
  • More cards ? : Playing with more cards can be more great. Try implementing your brain logic for more than 3 cards.
  • Why only Circle ? : Go beyond the circumference of the circle, you can try to implement square-shaped paths for rotation too!! Remember “your imagination is your limit”.

No comments:

Post a Comment