Become a C + + master to improve maintainability

Source: Internet
Author: User

Ideas

The current poker project can be further improved by taking out only the various statements and definitions related to poker separately, putting them in separate files, and taking out only those related to the player and putting them in separate files, while the main function only uses these definitions or declarations, and becomes three files: poker.c, Player.c,main.c. What good would that do? One is to view or modify poker related features, we just need to open poker.c. Now because the program is small, can not feel the advantages of separate, but when writing a program to deal with hundreds of dozens of of structures, if not separate, face a tens of thousands of lines of code in the main file, I believe that ordinary people will be dizzy. Second, when others want to write a poker game, found that our poker.c has been the operation of a deck of cards to achieve the function, so they just copy the poker.c files to their own projects with OK. By dispersing into multiple files, we improve the maintainability and reusability of the code.

Let's look at what's in the code:

    The
    • card structure, which represents a card, must be placed in the POKER.C.
    • defines a number of cards for a macro card_count is only relevant to poker and placed in poker.c.
    • defines an enumeration of poker suits, like macro card_count, in POKER.C. The
    • comparison function, which is only related to poker, is placed in the poker.c.
    • compares the function type definition, and then goes to the comparison function and puts it in the poker.c. The
    • constructs a deck of function initonepack and puts it into poker.c.
    • Shuffle function Shuffle, only the card structure, put into the poker.c. The
    • sort function, in which only the order of poker is arranged, is placed in the poker.c.
    • The function that gets the name of the card, only the poker, put in the poker.c.
    • structure player, which is definitely placed in the player.c. The
    • holds the array pokers of the original deck and puts it in the poker.c.
    • the card function, the player and card two structure, placed in the MAIN.C can,
    • is from the human mind, is a person licensing, so put it in player.c also no problem. This casual, but my personal words feel put in the player.c file is better, so I put in player.c. The
    • function declaration follows the function definition.

Is it possible to include these two files in main.c and then compile the results? Here's a question: C files can also be included, because the essence of include is to copy the contents of the include file to the location of the include line. But the include will generate a lot of errors and the compilation will not succeed. Most of these errors are described as repeating definitions of type or marker. How these errors are caused, and later, say how to solve the problem first. The workaround is simple: Exclude Poker.c and PLAYER.C from compilation, that is, poker.c and PLAYER.C are no longer compiled. Their contents are inserted into the MAIN.C to form a complete main.c, at which time poker.c and player.c do not need to be compiled. If compiled, there is a duplicate definition, which is explained in the following section, "the compilation process is detailed" (expect). So to remove the two files from the project, but can not delete the actual file Oh, just remove the reference to them from the project, if the actual file is deleted, include is not found file.

Delete a reference to a file, as in Qtcreator, do not check the check button:

Now three files are like this:

Poker.c
#include <stdio.h>//Number of decks#define Card_count//define the color of pokerenumsuit{heart, Spade, Diamond, Club, Joker1, joker2};//define Pokertypedef structcard{intValue//cards in pips starting from 1    enumSuit Suit;//Color}card;//Define the type of comparison functiontypedef int(*compare) (card*, card*);//array where the original deck of cards residesCard Pokers[card_count];//Construction of a deck of cardsvoidInitonepack () {intI=0;//Top 52 sheets     for(; i<card_count-2; i++) {pokers[i].value=i/4+1; Pokers[i].suit = i%4; }///The two remaining: King and Xiao Wang    //joker1pokers[i].value=i/4+1; Pokers[i].suit=joker1;//joker2pokers[i+1].value=i/4+2; pokers[i+1].suit=joker2;}//Shuffle, parameter is the original deck of cards, returned after washing the cardscard** Shuffle (Constcard* pokers) {intI//Split cards returns the memory space of the card arraycard** retpokers =malloc(card_count*sizeof(card*));//In order not to change the original deck of cards, build another array, save the hands of the original hands (note that each item is not a card, but the hands of the hand)card** pokers2 =malloc(card_count*sizeof(card*)); for(i=0; i<card_count;i++) {Pokers2[i] = &pokers[i]; }//seed under random seeds. The seed takes the current time,    //So ensure that the sequence of random numbers produced is different each time the program is runSrand (Time (NULL));//Get the random serial number, take the item that the serial number refers to from the pokers2, and add it to the retpokers in turn.      for(i=0; i<card_count;i++) {unsigned intindex = rand ()%card_count;if(Pokers2[index]! = NULL)            {Retpokers[i] = Pokers2[index];        Pokers2[index]=null; }Else{i--; }    } Free(POKERS2);//Return to the array after washing    returnRetpokers;}//Sort function//cards are the cards to be sorted, each of which is a hands-on hand//cardscount is the number of cards//compare_func is a comparison functionvoidSort (card** cards,intCardscount,compare Compare_func) {intI for(i=0; i<cardscount-1; i++) {intJ for(j=0; j<cardscount-i-1; j + +) {if(Compare_func (cards[j],cards[j+1])){intTMP=CARDS[J]; cards[j]=cards[j+1]; cards[j+1]=tmp; }        }    }}//Comparison function, first compare the points and then compare the suitsintCompare1 (card* a,card* b) {if(A->value > B->value) {return 1; }Else if(A->value < B->value) {return 0; }Else{if(A->suit > B->suit)return 1;Else            return 0; }}//Comparison function, first compare the points and then compare the suitsintCompare2 (card* a,card* b) {if(A->value > B->value) {return 0; }Else if(A->value < B->value) {return 1; }Else{if(A->suit > B->suit)return 0;Else            return 1; }}//Get the name of the card//Returns the name string of the card, which is required after the caller has finished using free (). Char* Getcardname (Constcard* card) {//Store suit name    Charsuitstr[ -]={0};//0== ' + '    Switch(Card->suit) { CaseHeart:strcpy(Suitstr,"Red Peach"); Break; CaseSpadestrcpy(Suitstr,"Spades"); Break; CaseDiamondstrcpy(Suitstr,"Block"); Break; CaseClubstrcpy(Suitstr,"Plum Blossom"); Break; }//Store the number of dot names    Charvaluestr[ -];Switch(Card->value) { Case 1:strcpy(Valuestr,"A"); Break; Case  One:strcpy(Valuestr,"J"); Break; Case  A:strcpy(Valuestr,"Q"); Break; Case  -:strcpy(Valuestr,"K"); Break; Case  -:strcpy(Valuestr,"Xiao Wang"); Break; Case  the:strcpy(Valuestr,"King"); Break;default:sprintf(Valuestr,"%d", Card->value); Break; }//Dynamic allocation of sufficient space    Char* ret =malloc( -);//combine two names into a ret    sprintf(Ret,"%s%s", SUITSTR,VALUESTR);returnRET;}
PLAYER.C:
//define Playerstypedef structplayer{Charname[ -];//Player's nameCard * * CARDS;//Player-divided cards. Each item is a pointer to an item in the original deck array, which saves space    intCardscount;//number of cards to be divided by the player}player;// Licensing//players is a player array//playercount is the number of players//shuffledcards is a deck of cards after washing.voidDispatchcards (player** players,intPlayercount,Constcard** shuffledcards) {//Calculate the capacity of each player's hand, if the cards are different in each player's hand,    //A maximum of one, plus 1 is to ensure that the array allocated enough space to accommodate the cards.     intNumbercards = card_count/playercount+1;//Allocate space for each player's array of cards    intI for(i=0; i<playercount;i++) {card* cards =malloc(numbercards*sizeof(card*));    Players[i]->cards = cards; }//Turn to each player in turns     for(i=0; i<card_count;i++) {//Take current playerPlayer *curplayer = Players[i%playercount];//Licensing to playersCurplayer->cards[curplayer->cardscount] = shuffledcards[i];//Player hands increase in actual number of cardscurplayer->cardscount++; }}
MAIN.C:
#include <stdio.h>#include <stdlib.h>#include <time.h>#include "poker.c"#include "player.c"//function declarations//char* getcardname (const card*);//card** Shuffle (const card*);//void dispatchcards (player**, int, const card**);//void Sort (card**,int,compare);//int compare1 (card*, card*);//int Compare2 (card*, card*);//void initonepack ();//array where the original deck of cards residesCard Pokers[card_count];//Entry functionintMainvoid){//Initialize a deck of cardsInitonepack ();//Shuffle, shuffledpokers save after washing the cardscard** shuffledpokers = Shuffle (pokers);//Build three playersPlayer Player1;strcpy(Player1.name,"The Old king next door.");    Player1.cards=null; Player1.cardscount=0; Player Player2;strcpy(Player2.name,"Xiao Ming");    Player2.cards=null; Player2.cardscount=0; Player Player3;strcpy(Player3.name,"Tanaka Turtle Sun");    Player3.cards=null; Player3.cardscount=0;//Put three into an array in order to pass in the card functionplayer* players[]={&player1,&player2,&player3};// LicensingDispatchcards (Players,sizeof(players)/sizeof(player*), shuffledpokers);//The card after washing is run out and released     Free(shuffledpokers);intI//Print out the cards in each player's hand     for(i=0;i<sizeof(players)/sizeof(player*); i++) {//Print the player's name first        printf("%s\n", players[i]->name);//need to sort cards in the hands of playersSort (players[i]->cards,players[i]->cardscount,compare1);//Print all cards in the player's hands        intJ for(j=0; j<players[i]->cardscount;j++) {Char* Name = Getcardname (Players[i]->cards[j]);printf('%s ', name); Free(name); }//Each player needs to change the line one time        printf("\ n"); }//Release an array of players ' hand cards     for(i=0;i<sizeof(players)/sizeof(player*); i++) { Free(players[i]->cards); }return 0;}

Previous: Become a C + + master of the actual combat project

Become a C + + master to improve maintainability

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.