Easy Card Games to Code in C

This article is for anyone who is interested in game programming. I volition take you through the basics of game programming. Here we are specifically focusing on the classic DOS games. I cover and give examples for: Determining Initial requirements, Developing an Interface, analyzing different elements of the game design in the program that we're going to brand, and developing logic for Gameplay.

  • Download source code - 44.three KB

Game Programming

Earlier we really bound into game programming, we need to know something called event driven programming. Event driven programming refers to that style of programming wherein the user of the application is free to choose from several options rather than be confined to a predetermined sequence of interactions with the plan. Game programming is one common case of issue driven programming. A game is a airtight, i.due east., complete and self sufficient formal system that represents a subset of reality. A game is a perfect combination of actions-reactions or event-responses where every response is based on the most-recently occurred event.

Elements of Game Programming

In general, a computer game has five elements:

  • Graphics
  • Sound
  • Interface
  • Gameplay
  • Story

Graphics

Graphics consists of any images that are displayed and whatsoever effects that are performed on them. This includes 3D objects, textures, 2D tiles, 2d full screen shots, Full Motion Video (FMV) and annihilation else that the player will see.

Sound

Sound consists of whatever music or sound effects that are played during the game. This includes starting music, CD music, MIDI or Mod tracks, Foley furnishings (environment sounds), and audio effects.

Interface

Sound consists of any music or sound furnishings that are played during the game. This includes starting music, CD music, MIDI or MOD tracks, Foley effects (surroundings sounds), and audio effects.

Gameplay

It encompasses how fun the game is, how immense it is, and the length of playability.

Story

The game's story includes any background before the game starts, all information the player gains during the game or when they win and any information they larn about character in the game. A story is an element of a game. The difference between a story and a game is that a story represents the facts in an immutable (i.e., stock-still) sequence, while a game represents a branching tree of sequences and allows the player to create his own story by making selection at each branch point.

Though graphics plays an of import part in game programming, in this article we're not going to emphasize upon graphics and sound element of a game. We shall be concentrating at elementary game programming through text based interfaces.

Game Design Sequence

Since game design requires ane to explore one's artistic abilities, it cannot be formulated in a step past pace process. Notwithstanding, at that place are certain technical steps that i needs to follow in i manner or another.
These are:

  1. Determining Initial requirements.
  2. Develop Interface.
  3. Develop Interface.
  4. Develop Logic for Scoring points.

We will look at each of these in item.

Interface is another very of import aspect of game programming. The interface is the mode of communication between the figurer and the role player. Like any human language, it is the funnel through which the programmer must squeeze the avalanche of thoughts, ideas and feelings that he/she seeks to share with the beau histrion. Interface will dictate what can or cannot be done. Interface is composed of input and output. While developing interface, the developer should develop the static brandish screens and dynamic display screen. Static brandish is the screen which remains unaffected by the player'south actions i.eastward., the input past the player. The dynamic display, on the other mitt, is the screen which is governed by the player's deportment i.e., the input by the player.

Examples of some static display screens are:

Game selection screens

What options are available to the thespian on the game startup? This describes what options are on the menu, how and where it appears on what screen, how the player gets there, and how he gets out.

Game start screen

What does the screen looks like at the beginning of the game, what are the startup parameters, where are the characters, etc? What messages, if whatever are on screen, and where? Intro music? Etc.

Since the dynamic screen vary as per the input given by the player, their descriptions are too many to be listed here. Some examples:

Message Screens

While developing interfaces, you besides need to piece of work on screens in response to legal deportment of the player, by intimating that he/she is on the right track. Also, you demand to piece of work on the screens required to warn the role player in instance he/she commits an illegal move or action.

End of game bulletin

These screens include messages and responses to questions like: What happens when the player loses? What happens when the player wins? What happens when the player get the high score? Where does the thespian go when the game is over? How does he start a new game?

This stride involves developing a proper logic for gameplay. This requires the game-developer to answer many questions in the class of program-lawmaking. These questions include: How is game played? What are the controls? What is the Game Goal? How is the player going to reach the game goal? etc. In other words, we must say that since game represents an outcome-driven state of affairs, the game-programmer i.e., you must specify or programme everything that includes:

  1. Determining Initial requirements

    While writing a game plan, afterwards selecting the goal-of-game, one needs to determine its initial requirements. For instance, to write a game plan for guessing a number, you demand to decide about a mode to generate the number, number of players involved, number of chances allowed to the role player, a scoring methodology etc. Here nosotros are non aiming at making you a professional game programmer, rather nosotros are concentrating more at giving you an idea of writing simple or elementary game programs.

    Full general Description of Game: The general description of a game involves the general overview of the game, how it works, what happens on each level, etc. Information technology describes all parts of the game from the player's perspective:

    • What he'south supposed to know earlier he starts playing.
    • What he sees.
    • What he does.
    • His intended reaction to what he sees and does.
  2. Develop Interface
  3. Develop Logic of Gameplay
    • responses to the user/player's action.
    • responses to system events.
    • rules of the game.
    • if information technology's a two player game (if the figurer is a player), and then the computer'south moves and actions.
  4. Develop Logic for Keeping Scores

    Developing logic for the scoring purposes is a subset of developing logic for the game play. For this, you lot must first decide the scoring policy that you're going to follow in your game. Yous're going to decide the maximum number of chances immune, the scoring mechanism, whether information technology is tied to time or not, etc. During this stage, the milestone events are worked out and appropriately scoring (positively or negatively) is carried out.

    Milestone Events in a Game

    Every one time in a while, the player needs to be rewarded (or penalized) somehow for reaching that signal in the game. Each of these places where something special happens is chosen a Milestone Consequence. There are a judge to let the player know he's on the right (or wrong) track, and volition encourage (or discourage) him to keep going.

Now that nosotros take discussed these different phases in game-development, let us not develop a simple tic-tac-toe game.

General Description of the game:

  1. It'due south a two player game so the program takes the proper name of two players and assign O and X to the players.
  2. Players enter their move plow past plow, into the box they cull.
  3. Program needs to assure that no box is overwritten.
  4. If the thespian tries to enter his/her move into the box that'southward already taken by the other thespian the the gamble passes over to the other player.
  5. Programme needs to run till a histrion wins, want to quit the game or until there are no moves left.
  6. After a player wins, program displays the message and will inquire the player if he/she wants to play again.

Now let u.s. clarify different elements of the game pattern in the plan that nosotros're going to make.

It's a two player game, and then we need ii variables to shop their names and run a loop to ask for the player to enter their move turn by turn. So nosotros demand another variable to store the turn to see which role player is to enter the motility. Here are the variables:

          char          name[2][30];          int          gamble;        

We need a function to handle the navigation to the boxes when the role player presses arrow keys and striking the Enter button to enter his movement in the box. We need some other variable to rail the current box the histrion is on at the movement. An array to store the values entered past the player. So here are the variables:

          int          box;          char          a[3][3];          int          navigate(char            a[3][3],            int            box,            int            player,            int            fundamental);        

Here in this part, char a[3][iii] is the array that holds the moves. box is the box the histrion was on, and fundamental is the key pressed.

Another variable is required to count the number of turns. There are nine boxes in full however the number of turns maybe more than nine considering if the player tries to enter his motility into a box that's already taken, and so the take a chance passes over to the other player.

          int          turns;        

We need a function to put the move into the box chosen by the player and we need to make sure that nosotros don't overwrite the value in a box:

          void          putintobox(char          a[iii][3],          char          ch,          int          box);

Here a[three][3] is used to stand for the boxes, ch is the character 'O' or 'X', and box is the box into which the value is to be entered. Now how would we know what character to put into the box? Well, this function is called by the navigate function mentioned above. So if the navigate function is called like this: box = navigate(a[3][3],three,0,ENTER);, then information technology means that player1(hither player1-0, player2 is represented by 2) needs to enter into box iii. The putintobox role checks if the box is taken and enter the value in to the array that represents the boxes (a[iii][3]), and calls another function showbox(char ch, int box) to show the graphic symbol on screen in the specified box.

checkforwin checks if the thespian has won the game or not and boxesleft will check if all boxes are filled. We would demand another variable to check if the player wants to quit the game so – int quit;.

In lodge to interact with the user, many messages are displayed. Also the player is told if he won the game or if information technology'due south a draw. The program will also enquire if the role player wants to play once more. So in our programme, the messages would be:

The logic of this program is to run a while loop that runs till a actor wins, or all the boxes are filled upwardly but no one won the game or if the user wants to quit. Now while the loop is running, the variable chance that tracks whose adventure is it to enter the move is updated. A function volition check what was the key what pressed by the user (user can enter but upward, downward, left, correct or enter key) and moves the cursor to the specified box and enter the character assigned to the role player into the array and displays that on the screen. Information technology also makes sure that no box is overwritten. Information technology the user tries to overwrite the box, risk is passed on to the other histrion as a penalty to the role player who entered the wrong movement. At the stop of the program, the user is asked if he/she wants to play the game again.

  1. Initial requirements
  2. Developing Interface
    • Ask the name of the players.
    • Brandish whose chance is it to enter the motility.
    • Brandish if a player wins or if information technology's a draw.
    • Display a bulletin when the histrion wants to quit.
    • Display a message asking if the player wants to play again.
  3. Developing logic for Gameplay

Here is the list of functions nosotros would demand:

  • void showframe(int posx, int posy) - This function will bear witness the frame of the Tic Tac Toe on the specified position.
  • void showbox(int ch, int box) - This function will show a specified character into the specified box.
  • void putintobox(char a[three][3], char ch, int box) - This function is used to write the character into the array and will call showbox(ch,box).
  • void gotobox(int box) - This function will accept the cursor into the specified box.
  • int navigate(char a[iii][3], int box, int actor, int key) - This function volition be used to track the box number the user is at while he is pressing the arrows keys on the keyboard. This will also get the box number in which the user wants to enter the character assigned to him/her.
  • int checkforwin(char a[3][3]) - Checks if the thespian wins.
  • int boxesleft(char a[three][3]) - To bank check how many boxes are left.

Details of the part: void showframe(int posx, int posy)

          void          showframe(int          posx,          int          posy) {          int          hour=196, vr=179;           int          crossbr=197;              int          x=posx, y=posy;          int          i,j;    gotoxy(35,4); cprintf("          TIC TAC TOE");   gotoxy(35,five);          for(i=0;i<          11;i++) cprintf("          %c",223);          for(i=0;i<          2;i++)   {          for(j=1;j<=11;j++)      {       gotoxy(x,y);       printf("          %c",hr);       x++;p;    ten++;      }     ten=posx; y+=2;   }   ten=posx+3; y=posy-1;          for(i=0;i<          two;i++)   {          for(j=ane;j<=five;j++)    {       gotoxy(ten,y);       printf("          %c",vr);       y++;    }    10+=4;y=posy-1;   }     x=posx+3; y=posy;     gotoxy(ten,y);   printf("          %c",crossbr);     x=posx+7; y=posy;         gotoxy(x,y);   printf("          %c",crossbr);    x=posx+3; y=posy+2;                       gotoxy(ten,y);   printf("          %c",crossbr);    x=posx+7; y=posy+ii;            gotoxy(x,y);   printf("          %c",crossbr);  }

void showbox(char ch, int box)

          void          showbox(char          ch,          int          box) {          switch(box)    {          case          1          :	gotoxy(_x+1,_y-ane); printf("          %c",ch);          break;           case          2          :	gotoxy(_x+5,_y-one); printf("          %c",ch);          pause;           example          3          :	gotoxy(_x+9,_y-1); printf("          %c",ch);          break;           case          4          :	gotoxy(_x+1,_y+1); printf("          %c",ch);          break;           case          5          :	gotoxy(_x+v,_y+1); printf("          %c",ch);          intermission;           case          6          :	gotoxy(_x+9,_y+i); printf("          %c",ch);          break;           case          vii          :	gotoxy(_x+1,_y+3); printf("          %c",ch);          pause;           case          8          :	gotoxy(_x+5,_y+3); printf("          %c",ch);          interruption;           case          ix          :	gotoxy(_x+9,_y+3); printf("          %c",ch);          break;    } }

void putintobox(char a[three][three], char ch, int box)

          void          putintobox(char          arr[3][3],          char          ch,          int          box) {          switch(box)   {          case          ane          :          if(arr[0][0] !=          '          X'          && arr[0][0]!=          '          O')                 { arr[0][0] = ch; 		          showbox(ch,1); 		        }          interruption;          case          2          :          if(arr[0][1] !=          '          X'          && arr[0][1]!=          '          O') 		        { arr[0][1] = ch; 		          showbox(ch,ii); 		        }          interruption;          example          3          :          if(arr[0][2] !=          '          X'          && arr[0][2]!=          '          O')                 { arr[0][2] = ch; 		          showbox(ch,3); 		        }          break;          case          4          :          if(arr[1][0] !=          '          X'          && arr[1][0]!=          '          O') 		       { arr[one][0] = ch; 		         showbox(ch,4); 		       }          break;          instance          5          :          if(arr[1][1] !=          '          X'          && arr[1][1]!=          '          O') 		        { arr[one][1] = ch; 		         showbox(ch,5); 		        }          pause;          case          6          :          if(arr[1][2] !=          '          X'          && arr[one][2]!=          '          O') 		        { arr[1][2] = ch;                   showbox(ch,half-dozen); 		        }          pause;          case          7          :          if(arr[2][0] !=          '          X'          && arr[two][0]!=          '          O')      		    { arr[2][0] = ch; 		          showbox(ch,7); 		        }          break;          case          eight          :          if(arr[two][i] !=          '          10'          && arr[ii][1]!=          '          O') 		        { arr[2][1] = ch; 		          showbox(ch,8); 		        }          intermission;          case          9          :          if(arr[2][two] !=          '          X'          && arr[2][2]!=          '          O') 		        { arr[ii][two] = ch; 		          showbox(ch,9); 		        }          break;    }}

void gotobox(int box)

          void          gotobox(int          box) {          switch(box)   {          case          i          : gotoxy(_x+one,_y-1);          suspension;          example          two          : gotoxy(_x+5,_y-1);          break;          case          3          : gotoxy(_x+ix,_y-1);          break;          example          4          : gotoxy(_x+1,_y+1);          break;          case          5          : gotoxy(_x+5,_y+1);          break;           instance          6          : gotoxy(_x+ix,_y+1);          break;           case          7          : gotoxy(_x+1,_y+three);          pause;           case          8          : gotoxy(_x+5,_y+iii);          suspension;           case          9          : gotoxy(_x+9,_y+3);          break;    } }

int navigate(char a[3][3], int box, int player, int key)

          int          navigate(char          arr[three][iii],          int          box,          int          actor,          int          key) {          switch(primal)    {          case          UPARROW    :          if( (box!=one) || (box!=2) || (box!=3) ) 		               { box-=3;          if(box<          ane) box =          one; gotobox(box); }          suspension;          case          DOWNARROW  :          if( (box!=7) || (box!=8) || (box!=9) ) 		               { box+=three;          if(box>          9) box =          9; gotobox(box); }          break;          case          LEFTARROW  :          if( (box!=ane) || (box!=4) || (box!=7) ) 		               { box--;          if(box<          one) box =          1; gotobox(box); }          break;          case          RIGHTARROW :          if( (box!=iii) || (box!=half-dozen) || (box!=9) ) 		               { box++;          if(box>          9) box =          9; gotobox(box); }          intermission;          case          ENTER      :          if(role player ==          0) 			            putintobox(arr,'          O',box);          else          if(histrion ==          one) 			            putintobox(arr,'          Ten',box);          break;     }          return          box; }

int checkforwin(char a[3][iii])

          int          checkforwin(char          arr[three][3]) {          int          w=0;               if((arr[0][0] == arr[0][i]) && (arr[0][1] == arr[0][ii])) w =          i;          else          if((arr[ane][0] == arr[i][1]) && (arr[1][1] == arr[ane][2])) westward =          1;          else          if((arr[2][0] == arr[ii][1]) && (arr[2][1] == arr[ii][2])) w =          ane;              else          if((arr[0][0] == arr[1][0]) && (arr[1][0] == arr[2][0])) w =          1;          else          if((arr[0][1] == arr[1][i]) && (arr[1][i] == arr[2][i])) w =          one;          else          if((arr[0][2] == arr[1][2]) && (arr[1][2] == arr[2][ii])) west =          1;              else          if((arr[0][0] == arr[i][1]) && (arr[1][1] == arr[ii][2])) west =          1;          else          if((arr[0][2] == arr[ane][ane]) && (arr[1][1] == arr[2][0])) w =          one;          render          w; }

int boxesleft(char a[3][three])

          int          boxesleft(char          a[3][3]) {          int          i,j,boxesleft=nine;          for(i=0;i<          three;i++)     {          for(j=0;j<          three;j++)       {          if((a[i][j] ==          '          10') ||(a[i][j] ==          '          O'))           boxesleft--;       }     }          return          boxesleft; }

Now we have all the functions in place, we movement on to the third step that talks near Presentation.

We have actually taken intendance of presentation in some of the to a higher place written functions, haven't we?

The ASCII grapheme used in this program to display the vertical line is 179 and for horizontal line is 196. For a cross - 197. Check this website for more than information about extended ASCII characters http://www.asciitable.com/.

You tin can even printout your ASCII table with a C program. Here is an case:

          #include                      <            stdio.h            >                    int          main() {     FILE *fh;          int          ch;           fh = fopen("          ascii.txt","          r");          for(i=0;i<          256;i++)      fprint(fh,"          \due north%d - %c",i,i);       fclose(fh);          return          0; }

At present we will talk almost Exception Handling. Hither in this program, we have kept it simple and so nix much to worry near here, however, we do have the name from the user. The array nosotros use to store the name is of size 30. What if the user enters a string that is more than 30 in length? This would result in a buffer overflow. This may crash your program correct abroad or produce unexpected results. To avoid this either we can write a function that would go a string from the stdin ane by one and stops if Enter is pressed or if string is more than 30 OR we can utilise the inbuilt function known as fgets.

Finally, putting it all together:

          #include                      <            stdio.h            >                    #include                      <            conio.h            >                    int          chief() {            showframe(12,25);     printf("          \nPlayer one, enter your name:"); fgets(name[0],          30, stdin);     printf("          \nPlayer 2, enter your name:"); fgets(proper noun[one],          30, stdin);       printf("          \n%s, you take 0",proper noun[0]);     printf("          \due north%s, you take X",name[1]); getch();       clrscr();          practice          {          while(!enter)        {          if(khbit())           ch = getch();          switch(ch)            {          case          UPARROW : box = navigate(a[3][3], box, player, UPARROW);              .              .              .            }        }          if(quit)          break;               win = checkforwin(a);           }while(!win)          if(win)     { .       .     }          else          if(quit)     {    .          .     }          return          0; }

View the consummate source code and executable to take a look at how the program works.

Hither are some screenshots of the working executable for Tic Tac Toe:

Image 1

Image 2

Image 3

This commodity was not a complete fully fledged commodity for game programming but I hope that you gain something out of information technology. If yous have any questions, delight experience free to e-mail me at shine_hack@yahoo.com

Source code for this programme can be obtained at: http://techstuff.x10.mx/articles/.

Happy programming!

Shine Jacob (Enot): shine_hack@yahoo.com

smithmher1991.blogspot.com

Source: https://www.codeproject.com/Articles/447332/Game-Programming-in-C-For-Beginners

0 Response to "Easy Card Games to Code in C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel