C语言实现纸牌游戏(小猫钓鱼)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C语言实现纸牌游戏(小猫钓鱼)

齐123   2020-10-11 我要评论

C语言使用队列和栈实现纸牌游戏–小猫钓鱼,供大家参考,具体内容如下

C语言:

//纸牌游戏--小猫钓鱼--队列 栈--(所谓的拉火车) 
#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
*/

该程序使用队列来实现玩家的手中的牌(玩家的牌只能前面出牌,赢得牌依次放后面),用栈实现桌子上的牌(出牌放在末端,赢牌也是从末端拿走)。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们