#include<stdio.h>
#include<stdbool.h>
int num_suit[4]; //花色
int num_rank[13]; //点数
void read_cards(void) {
//初始化
for (int i = 0; i < 4; i++) num_suit[i] = 0;
for (int i = 0; i < 13; i++) num_rank[i] = 0;
bool in_hand[4][13] = { false }; //手上已有的牌
int cnt_read = 0; //已读的牌数
//读取
while (cnt_read < 5) {
bool bad_card = false; //读取未成功的牌
printf("Enter a card (rank&suit): ");
char c = getchar();
int rank = 0;
switch (c){
case '0': exit(0); //退出程序
case '2': rank = 0; break;
case '3': rank = 1; break;
case '4': rank = 2; break;
case '5': rank = 3; break;
case '6': rank = 4; break;
case '7': rank = 5; break;
case '8': rank = 6; break;
case '9': rank = 7; break;
case 'T': case 't': rank = 8; break;
case 'J': case 'j': rank = 9; break;
case 'Q': case 'q': rank = 10; break;
case 'K': case 'k': rank = 11; break;
case 'A': case 'a': rank = 12; break;
default: bad_card = true; break;
}
c = getchar();
int suit = 0;
switch (c) {
case 'S': case 's': suit = 0; break;
case 'H': case 'h': suit = 1; break;
case 'C': case 'c': suit = 2; break;
case 'D': case 'd': suit = 3; break;
default: bad_card = true; break;
}
//处理剩余字符
while (c = getchar() != '\n') {
if (c != ' ' && c != '\t') {
bad_card = true;
}
}
//rank suit
if (bad_card) {
printf("Bad card; ignored.\n");
}
else if (in_hand[suit][rank]) {
printf("Duplicate card; ignored.\n");
}
else {
cnt_read++;
in_hand[suit][rank] = true;
num_suit[suit]++;
num_rank[rank]++;
}
}
}
bool flush, straight, four, three;
int pairs;
void analyze_hand(void) {
//初始化
flush = false;
straight = false;
four = false;
three = false;
pairs = 0;
//判断同花
for (int i = 0; i < 4; i++) {
if (num_suit[i] == 5) {
flush = true;
}
}
//判断顺子
int len = 0;
for (int i = 0; i < 13; i++) {
if (!num_rank[i]) {
if (len < 5) len = 0;
continue;
}
len++;
}
if (len == 5) straight = true;
//对数,三张,四张
for (int i = 0; i < 13; i++) {
if (num_rank[i] == 2) {
pairs++;
}else if (num_rank[i] == 3) {
three = true;
}else if (num_rank[i] == 4) {
four = true;
}
}
}
void print_result(void) {
if (flush && straight) {
printf("Straight flush\n");
}
else if (four) {
printf("Four\n");
}
else if (three && pairs == 1) {
printf("Full house\n");
}
else if (flush) {
printf("Flush\n");
}
else if (straight) {
printf("Straight\n");
}
else if (three) {
printf("Three\n");
}
else if (pairs == 2) {
printf("Two pairs\n");
}
else if (pairs == 1) {
printf("Pairs\n");
}
else {
printf("High cards\n");
}
putchar('\n');
}
int main(void) {
while (1) {
read_cards(); //读取手牌
analyze_hand(); //分析手牌
print_result(); //打印结果
}
return 0;
}
【C语言】11_实现德州扑克
于 2024-05-10 21:29:23 首次发布