演算法 -- 紙牌遊戲_小貓釣魚
阿新 • • 發佈:2018-12-12
星期天小哼和小哈約在一起玩桌遊,他們正在玩一個非常古怪的撲克遊戲——“小貓釣魚”。遊戲的規則是這樣的:將一副撲克牌平均分成兩份,每人拿一份。小哼先拿出手中的第一張撲克牌放在桌上,然後小哈也拿出手中的第一張撲克牌,並放在小哼剛打出的撲克牌的上面,就像這樣兩人交替出牌。出牌時,如果某人打出的牌與桌上某張牌的牌面相同,即可將兩張相同的牌及其中間所夾的牌全部取走,並依次放到自己手中牌的末尾。當任意一人手中的牌全部出完時,遊戲結束,對手獲勝。(用兩個佇列和一個棧完成)
程式碼如下:
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <stdlib.h> /* * 遊戲規則是這樣的,將一副撲克牌平均分成兩份,每人拿一份。小哼先拿出手中的第一張撲克牌放桌上,然後小哈也拿出手中的第一張撲克牌 並放在小哼剛打出的撲克牌的上面,就像這樣兩個人交替出牌。出牌時,如果某人打出的牌與桌上某張牌的牌面相同,即可將兩張相同的牌 及中間的牌全部拿走,並依次放到自己手中的牌的末尾。當任意一個人手上的牌全部打完時,另一個人獲勝 * 郭文峰 * 2018/9/29 */ struct queue { int data[1000]; int head; int tail; }; struct stack { int data[10]; int top; }; int main(void) { struct queue q1, q2; struct stack s; int i = 0; int t = 0; int book[10]; //初始化佇列 q1.head = 1; q1.tail = 1; q2.head = 1; q2.tail = 1; //初始化棧 s.top = 0; for (i = 0; i < 10; i++) { book[i] = 0; } //依次向佇列插入6個數 //給小哼6張牌 for (i = 1; i <= 6; i++) { scanf("%d", &q1.data[q1.tail]); q1.tail++; } //依次向佇列插入6個數 //給小哈6張牌 for (i = 1; i <= 6; i++) { scanf("%d", &q2.data[q2.tail]); q2.tail++; } //當佇列不為空的時候執行迴圈 while (q1.head < q1.tail && q2.head < q2.tail) { t = q1.data[q1.head];//小哼出一張牌 //判斷小哼打出的牌是否能贏 if (book[t] == 0)//表明桌上沒有牌面為t 的牌 { q1.head++; s.top++; s.data[s.top] = t; book[t] = 1; } else { q1.head++; q1.data[q1.tail] = t; q1.tail++; while (s.data[s.top] != t) { book[s.data[s.top]] = 0; q1.data[q1.tail] = s.data[s.top]; q1.tail++; s.top--; } } t = q2.data[q2.head];//小哈出一張牌 //判斷小哈打出的牌是否能贏 if (book[t] == 0)//表明桌上沒有牌面為t 的牌 { q2.head++; s.top++; s.data[s.top] = t; book[t] = 1; } else { q2.head++; q2.data[q2.tail] = t; q2.tail++; while (s.data[s.top] != t) { book[s.data[s.top]] = 0; q2.data[q2.tail] = s.data[s.top]; q2.tail++; s.top--; } } } if (q2.head == q2.tail) { printf("小哼WIN\n"); printf("小哼手上還剩的牌為:"); for (i = q1.head; i <= q1.tail - 1; i++) { printf(" %d", q1.data[i]); } if (s.top > 0) { printf("\n桌上的牌是:"); for (i = 1; i <= s.top; i++) { printf(" %d", s.data[i]); } } else { printf("桌上沒有牌了!\n"); } } else { printf("小哈WIN\n"); printf("小哈手上還剩的牌為:"); for (i = q2.head; i <= q2.tail - 1; i++) { printf(" %d", q2.data[i]); } if (s.top > 0) { printf("\n桌上的牌是:"); for (i = 1; i <= s.top; i++) { printf(" %d", s.data[i]); } } else { printf("桌上沒有牌了!\n"); } } system("pause"); return 0; }