使用C语言实现纸牌游戏

发布时间:2020-10-28 19:34:40 作者:Leah
来源:亿速云 阅读:165

使用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
*/

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

看完上述内容,你们掌握使用C语言实现纸牌游戏的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. js+canvas实现纸牌游戏
  2. C语言中如何实现纸牌24点小游戏

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c语言

上一篇:使用js+h5 canvas实现图片验证码功能

下一篇:springboot如何配置嵌入式servlet容器

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》