目前是模拟是两个人对战的。使用栈和队列模拟。
#define kCardSize 52
typedef struct stack{
int data[kCardSize];
int top;
}*StackP;
typedef struct stack Stack;
typedef struct queue{
int data[kCardSize];
int header,tail;
}*QueueP;
typedef struct queue Queue;
void initCard(void);
void insertQueue(QueueP aQueue,StackP aStack);
void deleteQueue(QueueP aQueue,StackP aStack,int t,int mark[]);
int isEmpty(QueueP aQueue);
#include "CardGame.h"
void initData(QueueP aQueue){
aQueue->header = 0;
aQueue->tail = 0;
for (int i = 0; i < kCardSize; ++i) {
aQueue->data[i] = 0;
}
srand((unsigned int)time(NULL));
for (int i = 0; i < kCardSize/2; ++i) {
aQueue->data[i] = rand()%12+1;
aQueue->tail++;
printf("%d ",aQueue->data[i]);
}
}
void initCard(void)
{
QueueP queue1 = (QueueP)malloc(sizeof(Queue));
QueueP queue2 = (QueueP)malloc(sizeof(Queue));
initData(queue1);
printf("\n");
initData(queue2);
StackP stack = (StackP)malloc(sizeof(Stack));
for (int i = 0; i < kCardSize; ++i) {
stack->data[i] = 0;
}
stack->top = 0;
int mark[kCardSize/2] = {0};
for (;!isEmpty(queue1)&&!isEmpty(queue2);) {
int t = queue1->data[queue1->header];
if (mark[t] == 0) {
mark[t] = 1;
insertQueue(queue1, stack);
}
else{
deleteQueue(queue1,stack,t,mark);
}
t = queue2->data[queue2->header];
if (mark[t] == 0) {
mark[t] = 1;
insertQueue(queue2, stack);
}
else{
deleteQueue(queue2,stack,t,mark);
}
}
if (isEmpty(queue1)) {
printf("\nwin-1\n");
}
else if (isEmpty(queue1)){
printf("\nwin-2\n");
}
else if (isEmpty(queue1)&&isEmpty(queue1))
{
printf("win-1-2\n");
}
if (queue1) {
free(queue1);
queue1 = NULL;
}
if (queue2) {
free(queue2);
queue2 = NULL;
}
if (stack) {
free(stack);
stack = NULL;
}
}
void insertQueue(QueueP aQueue,StackP aStack){
aStack->data[aStack->top] = aQueue->data[aQueue->header];
aQueue->data[aQueue->header] = 0;
aQueue->header++;
if (aQueue->header >= kCardSize) {
aQueue->header = aQueue->header%kCardSize;
}
aStack->top++;
}
void deleteQueue(QueueP aQueue,StackP aStack,int t,int mark[]){
aQueue->data[aQueue->tail] = t;
aQueue->tail++;
aStack->top--;
if (aQueue->tail >= kCardSize) {
aQueue->tail = aQueue->tail%kCardSize;
}
while ((aStack->top >= 0)&&(t != aStack->data[aStack->top])) {
mark[aStack->data[aStack->top]] = 0;
aQueue->data[aQueue->tail] = aStack->data[aStack->top];
aStack->data[aStack->top] = 0;
aStack->top--;
aQueue->tail++;
if (aQueue->tail >= kCardSize) {
aQueue->tail = aQueue->tail%kCardSize;
}
}
if ((aStack->top >= 0)&&(t == aStack->data[aStack->top])) {
mark[aStack->data[aStack->top]] = 0;
aQueue->data[aQueue->tail] = aStack->data[aStack->top];
aStack->data[aStack->top] = 0;
}
aQueue->data[aQueue->header] = 0;
aQueue->header++;
if (aQueue->header >= kCardSize) {
aQueue->header = aQueue->header%kCardSize;
}
if (aStack->top < 0) {
aStack->top = 0;
}
}
int isEmpty(QueueP aQueue){
for (int i = 0;i < kCardSize; ++i) {
if (aQueue->data[i]) {
return 0;
}
}
return 1;
}