C語言實現(xiàn)隨機發(fā)撲克牌
本文實例為大家分享了C語言實現(xiàn)隨機發(fā)撲克牌的具體代碼,供大家參考,具體內(nèi)容如下
算法如下:
1、將1-10作為方塊、2-20作為梅花,3-30作為紅桃,4-40作為黑桃,JQK以及大小王分別排序共54張存放在一維數(shù)組中。
3、3個人用一個二維數(shù)組來存放三人的牌。
2、主要分為打散(亂序),分配,顯示三個操作
打散即洗牌:通過rand以及srand函數(shù)來獲得,為了避免相同的序列,使用標準時間來作為序列種子。
void shuffle(int *cards, int lenth) { int temp, i, index; time_t t; srand((unsigned int)(&t)); for (i = 0; i < lenth - 1; i++) //保證每一次交換都是和剩下的數(shù)進行交換 { index = rand() % (lenth - i) + i; if (index != i) { temp = cards[i]; cards[i] = cards[index]; cards[index] = temp; } } }
分配:將亂序的卡組分別依次排入一個二維數(shù)組中
void deal(int(*everycards)[18], int* cards) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 18; j++) { everycards[i][j] = cards[i * 18 + j]; } } }
顯示:數(shù)字卡用迭代的方法顯示,而JQK則用switch方法實現(xiàn)
void display(int(*everycards)[18], char *name1, char *name2, char *name3) { int i, j; //方塊、梅花、紅桃、黑桃 putchar('\n'); printf("分配卡牌如下:\n"); for (i = 0; i < 3; i++) { switch (i) { case 0: printf("%s手上的牌是: ", name1); break; case 1: printf("%s手上的牌是: ", name2); break; case 2: printf("%s手上的牌是: ", name3); break; } for (j = 0; j < 18; j++) { if (everycards[i][j] >= 1 && everycards[i][j] <= 10) { printf("方%d ", everycards[i][j]); } else if (everycards[i][j] >= 11 && everycards[i][j] <= 20) { printf("梅%d ", everycards[i][j] - 10); } else if (everycards[i][j] >= 21 && everycards[i][j] <= 30) { printf("紅%d ", everycards[i][j] - 20); } else if (everycards[i][j] >= 31 && everycards[i][j] <= 40) { printf("黑%d ", everycards[i][j] - 30); } else { switch (everycards[i][j]) { case 41: printf("方J "); break; case 42: printf("方Q "); break; case 43: printf("方K "); break; case 44: printf("梅J "); break; case 45: printf("梅Q "); break; case 46: printf("梅K "); break; case 47: printf("紅J "); break; case 48: printf("紅Q "); break; case 49: printf("紅K "); break; case 50: printf("黑J "); break; case 51: printf("黑Q "); break; case 52: printf("黑K "); break; case 53: printf("小王 "); break; case 54: printf("大王 "); break; } } } putchar('\n'); putchar('\n'); } }
具體實現(xiàn)如下
主函數(shù)下方所示(由于是vs2019所以scanf用的是微軟自帶的scanf_s):
int main(void) { char name1[MAX], name2[MAX], name3[MAX]; int cards[54], everycards[3][18], lenth, i; char YorN; //初始化撲克牌 for (int count1 = 0; count1 < 54; count1++) { cards[count1] = count1 + 1; } lenth = sizeof(cards) / sizeof(cards[0]); printf("請輸入1號玩家的名字:"); scanf_s("%s", name1, MAX); int b1 = getchar(); printf("請輸入2號玩家的名字:"); scanf_s("%s", name2, MAX); int b2 = getchar(); printf("請輸入3號玩家的名字:"); scanf_s("%s", name3, MAX); int b3 = getchar(); putchar('\n'); printf("方塊 = 方,梅花 = 梅,紅桃 = 紅, 黑桃 = 黑\n"); //先做一次洗牌 shuffle(cards, lenth); deal(everycards, cards); display(everycards, name1, name2, name3); //尋問是否進行再次洗牌 while (1) { printf("\n請選擇是否重新洗牌(Y/N):"); scanf_s("%c", &YorN); int b4 = getchar(); // if (YorN == 'Y') { shuffle(cards, lenth); deal(everycards, cards); display(everycards, name1, name2, name3); } else if (YorN == 'N') { break; } } return 0; }
學生黨,初學習編程,第一次發(fā)博客,望各位大佬指正錯誤和不足。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。