编译一个代码,实现给三个玩家随机发牌,打印发牌结果并打印剩余的三张牌。
编写前构思思路
<1>创建数组存储花色和牌数 二维数组
<2>随机发牌,使用rand函数
<3>打印发牌的结果
代码分装
主函数:( PEOPLE (玩家数:3) ALL_POKER(总牌数:54)T 10(用T表示10)
ROW (牌堆数组的行数:5) COLUMN (牌堆数组的列数:13)
(全局变量)
//牌
int visited[ROW][COLUMN] = { 0 };
//用户
char players[PEOPLE][17][1024] = { 0 };
#define _CRT_SECURE_NO_WARNINGS 1
#define PEOPLE 3
#define ALL_POKER 54
#define T 10
#define ROW 5
#define COLUMN 13
//牌
int visited[ROW][COLUMN] = { 0 };
//用户
char players[PEOPLE][17][1024] = { 0 };
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
int main() {
void givePoker(char(*pokers)[COLUMN]);
void printfPlayerCards();
void showRemainpokers(char(*pokers)[COLUMN]);
char pokers[ROW][COLUMN] =
{
{'A','2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'},
{'A','2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'},
{'A','2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'},
{'A','2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'},
{'W','w'}
};
givePoker(pokers);
printfPlayerCards();
printf("底牌有:\n");
showRemainpokers(pokers);
return 0;
}
//发牌
void givePoker(char(*pokers)[COLUMN]){
void getColor(int color, int* P_pointNum, char* playersCards);
//播种
srand((unsigned int)time(NULL));
//发牌
for (int i = 0; i < 51; ) {
int color = rand() % ROW;
int pointNum = rand() % COLUMN;
char playersCards[1024] = { 0 };
//获取花色
getColor(color, &pointNum, playersCards);
//判断是否已经发过
if (visited[color][pointNum] == 0) {
char num[2] = { *(*(pokers + color) + pointNum),'\0' };
//将花色和点数拼接到一起
strcat(playersCards, num);
//将牌发给用户
strcpy(players[i / 17][i % 17], playersCards);
visited[color][pointNum] = 1;//表示牌已经随机
i++;
}
}
}
//获取花色
void getColor(int color, int* P_pointNum, char* playersCards) {
switch (color)
{
case 0:
strcpy(playersCards, "梅花");
break;
case 1:
strcpy(playersCards, "方块");
break;
case 2:
strcpy(playersCards, "红桃");
break;
case 3:
strcpy(playersCards, "黑桃");
break;
case 4:
//解决随机大小王的问题
*P_pointNum = (*P_pointNum) % 2;//?
strcpy(playersCards, "");
break;
}
}
//打印发牌
void printfPlayerCards() {
for (int i = 0; i < PEOPLE; i++) {
printf("players:%d\n",i+1);
for (int j = 0; j < 17; j++) {
printf("%-8s",*(players+i)+j);
}
printf("\n");
}
}
//显示剩余牌
void showRemainpokers(char(*pokers)[COLUMN]) {
void getColor(int color, int* P_pointNum, char* playersCards);
int remain = 1;
//遍历visited数组,将剩余没有发出去的牌进行存储并打印
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
if (remain > 3) {
return;//循环结束
}
if (*(*(visited + i) + j) == 0) {
char remainCards[1024] = { 0 };
int pointNum = j;
getColor(i, &pointNum, remainCards);
char num[2] = { *(*(pokers+i) + pointNum),'\0'};
//将花色和点数拼接组成剩余牌
strcat(remainCards, num);
printf("%-8s",remainCards);
remain++;
}
}
}
}