欢迎来到代码驿站!

C代码

当前位置:首页 > 软件编程 > C代码

C语言实现洗牌与发牌游戏

时间:2021-03-05 12:42:50|栏目:C代码|点击:

本文实例为大家分享了C语言实现洗牌与发牌游戏的具体代码,供大家参考,具体内容如下

普通版

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define SUITS 4
#define FACES 13
#define CARDS 52

void shuffle(int wDeck[][FACES]);
void send(int wDeck[][FACES], const char* wSuit[], const char* wFace[]);

void main()
{
 int deck[SUITS][FACES]={0};
 const char* suit[SUITS]={"Heart","Diamond","Club","Spade"};
 const char* face[FACES]={"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"};
 
 srand(time(NULL));
 shuffle(deck);
 send(deck, suit, face);
}

void shuffle(int wDeck[][FACES])
{
 int row,column,card;

 for(card=1;card<=CARDS;card++)
 {
 row = rand() % SUITS;
 column = rand() % FACES;
 while(wDeck[row][column] != 0)
 {
 row = rand() % SUITS;
 column = rand() % FACES;
 }
 wDeck[row][column] = card;
 }
}

void send(int wDeck[][FACES], const char* wSuit[], const char* wFace[])
{
 int card,row,column;
 for(card=1;card<=CARDS;card++)
 {
 for(row=0;row<SUITS;row++)
 {
 for(column=0;column<FACES;column++)
 {
 if(wDeck[row][column] == card)
 {
  printf("%5s of %-8s%c",wFace[column],wSuit[row], card % 2 ==0 ? '\n' : '\t');
 }
 }
 }
 }
}

高性能版

//先按顺序填满52个格子,再产生随机格子相互交换

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define CARDS 52
#define FACES 13

struct card
{
 const char* face;
 const char* suit;
};
typedef struct card Card;

void shuffle(Card *const wDeck);
void send(const Card *const wDeck);//指针常量与数据常量均不可以改变,都用const限定,*前是限定指针,*后是限定数据

void main()
{
 const char* wSuit[]={"Heart","Diamond","Club","Spade"};//指针数组是一个数组
 const char* wFace[]={"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"};
 int i;
 Card deck[CARDS];
 for(i=0;i<CARDS;i++)
 {
 deck[i].suit = wSuit[i / FACES];
 deck[i].face = wFace[i % FACES];
 }
 
 srand(time(NULL));
 shuffle(deck);
 send(deck);
}

void shuffle(Card *const wDeck)
{
 int i,j;
 Card temp;
 for(i=0;i<CARDS;i++)
 {
 j = rand() % CARDS;
 temp = wDeck[i];
 wDeck[i] = wDeck[j];
 wDeck[j] = temp;
 }
}

void send(const Card *const wDeck)
{
 int i;
 for(i=0;i<CARDS;i++)
 {
 printf("%5s of %-8s%c",wDeck[i].face,wDeck[i].suit, (i+1) % 4 == 0 ? '\n' : '\t');
 }
}

上一篇:浅谈C++基类的析构函数为虚函数

栏    目:C代码

下一篇:C语言 数据类型详细介绍

本文标题:C语言实现洗牌与发牌游戏

本文地址:http://www.codeinn.net/misctech/74770.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有