首页 > 编程语言 > C语言实现洗牌与发牌游戏
2020
12-29

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');
 }
}

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

编程技巧