Catalog
  1. 1. 现有纸牌游戏的规则如下:将一副扑克牌平均分成两份,每人拿一份。小哼先拿出手中的第一张扑克牌放在桌上,然后小哈也拿出手中的第一张扑克牌,并放在小哼刚打出的扑克牌的上面,就像这样两人交替出牌。出牌时,如果某人打出的牌与桌面上某张牌的牌面相同,即可将两张相同的牌及其中间所夹的牌全部取走,并依次放入到自己手中牌的末尾。当任意一个人手中的牌全部出完时,游戏结束,对手获胜。
栈和队列的综合应用——纸牌游戏

现有纸牌游戏的规则如下:将一副扑克牌平均分成两份,每人拿一份。小哼先拿出手中的第一张扑克牌放在桌上,然后小哈也拿出手中的第一张扑克牌,并放在小哼刚打出的扑克牌的上面,就像这样两人交替出牌。出牌时,如果某人打出的牌与桌面上某张牌的牌面相同,即可将两张相同的牌及其中间所夹的牌全部取走,并依次放入到自己手中牌的末尾。当任意一个人手中的牌全部出完时,游戏结束,对手获胜。

#include<iostream>
using namespace std;
struct queue {//将队列的元素封装为一个结构体
int data[1000];
int head;
int tail;
};
struct stack {//将栈的元素封装为一个结构体
int data[10];
int top;
};
int main() {
struct queue 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++)
book[i] = 0;
//小哼手上的6张牌
for (i = 1; i <= 6; i++) {
cin >> q1.data[q1.tail];
q1.tail++;
}
//小哈手上的6张牌
for (i = 1; i <= 6; i++) {
cin >> 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的牌
book[s.data[s.top]] = 0;
q1.data[q1.tail] = s.data[s.top];
q1.tail++; s.top--;
}
if (q1.head == q1.tail) break;
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--;
}
//收回桌上为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++)
cout << 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++)
cout << s.data[i] <<" ";
}
else
printf("\n桌上已经没有牌了");
}


system("pause");
return 0;
}

运行结果:

Author: superzhaoyang
Link: http://yoursite.com/2019/09/16/栈和队列的综合应用——纸牌游戏/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付宝

Comment