C语言使用队列和栈实现纸牌游戏–小猫钓鱼,供大家参考,具体内容如下
C语言:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
//纸牌游戏--小猫钓鱼--队列 栈--(所谓的拉火车)
#include <stdio.h>
struct queue //队列
{
int data[1000];
int head;
int tail;
};
struct stack //栈
{
int data[10];
int top;
};
int main(void)
{
struct queue q1, q2; //小哼 q1 和小哈 q2 的队列
struct stack s; //栈
int book[10]; //记录,判断是否第二次出现
int i, t;
q1.head = 1, q1.tail = 1; //初始化队列
q2.head = 1, q2.tail = 1;
s.top = 0; //初始化栈
for(i = 1;i <= 9;i++) //初始化出现次数为 0
book[i] = 0;
for(i = 1; i <= 6; i++) { //这里给定一个人 6 张牌
scanf("%d", &q1.data[q1.tail]);
q1.tail++;
}
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){ //当桌上无此牌时
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) { //把桌子上赢的牌收回去, 此处没有收最后一根牌 t
book[s.data[s.top]] = 0; //取消标记
q1.data[q1.tail] = s.data[s.top]; //依次放在队尾
q1.tail++;
s.top--; //栈中少了一张牌,所以- 1
}
//收回桌上的 t 牌
book[t] = 0;
q1.data[q1.tail] = t;
q1.tail++;
s.top--;
}
if(q1.head == q1.tail ) //如果小哼牌打完了,游戏结束
break;
//轮到小哈出牌了,和小哼一样判断
t = q2.data[q2.head];
if(book[t] == 0) {
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--;
}
book[t] = 0;
q2.data[q2.tail] = t;
q2.tail++;
s.top--;
}
}
if(q2.head == q2.tail ) {
printf("小哼 win \n");
printf("小哼当前手中的牌是 ");
for(i = q1.head;i < q1.tail;i++)
printf(" %d",q1.data[i]);
if(s.top) { //如果桌子上有牌的话
printf("\n桌子的牌是");
for(i = 1;i <= s.top;i++)
printf(" %d",s.data[i]);
printf("\n");
}
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) { //如果桌子上有牌的话
printf("\n桌子的牌是");
for(i = 1;i <= s.top;i++)
printf(" %d",s.data[i]);
printf("\n");
} else
printf("\n桌子上已经没有牌了");
}
return 0;
}
/*Code Running Results
1 2 3 4 5 6
3 2 1 5 2 6
小哈 win
小哈当前手中的牌是 5 6 2 3 1 3 2 5 2
桌子的牌是 4 6 1
*/
|
该程序使用队列来实现玩家的手中的牌(玩家的牌只能前面出牌,赢得牌依次放后面),用栈实现桌子上的牌(出牌放在末端,赢牌也是从末端拿走)。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_45772965/article/details/108986543








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。