So i am making the card game called War, the rules are the following:
- Player 1 and player 2 each queues of cards called q1 and q2. Both
queues are not empty. The players also have empty battle stacks s1
and s2. - Each player removes a card from the front of their queue and puts it
on the top of their stack - If the cards have equal face values, a war happens.
- Each player moves 3 additional cards from their queue to their stack
and check the face value of their top cards again. This may happen
several times. Go to 3 again. - If the cards do not have equal values, the battle has ended and a
can be determined.
the function i have to write is called start_battle.c and the logic i have came up with is the following, the queue_front, queue_empty and stack_top functions are already written. So my pseudocode is the following:
function start_battle(q1, q2, s1, s2, logfile)
warc=0
move front card of q1 to the top of s1
move front card of q2 to the top of s2
while (top cards of s1 and s2 have equal value
and both q1 and q2 are not empty)
for i=1 to 3
if q1 is not empty
move front card of q1 to the top of s1
endif
done
for i=1 to 3
if q2 is not empty
move front card of q2 to the top of s2
endif
done
done
return warc
My code is the following:
#include "libcardlist.h"
int start_battle(queue *q1, queue *q2, stack *s1, stack *s2, FILE *logfile){
int warc =0;
int i;
stack_push(s1, queue_front(q1));
stack_push(s2, queue_front(q2));
card c1 = stack_top(s1);
card c2 = stack_top(s2);
while (c1.face==c2.face&& queue_empty(q1)==0 && queue_empty(q2)==0) {
warc++;
for (i=0; i<3; i++) {
if(queue_empty(q1)==0){
stack_push(s1, queue_front(q1));
}
}
for (i=0; i<3; i++) {
if (queue_empty(q2)==0){
stack_push(s2, queue_front(q2));
}
}
}
return warc;
}
oh and
typedef struct {
int face; /* 2-14 */
char suit; /* C H S D */
} card;
When i test it, my code is stuck in the while loop, can someone help me fix it?
I added the
queue_pop()where appropriate in your algorithm. Once you copy the card from a queue to a stack (via push) you need to remove it from your pile. In reality this should be part of the main-play of the game, not the intro (its the same, but you’ll figure that out eventually), and you’ll need to move both stacks of cards to the appropriate queue once a winner of a specific round is declared.Anyway, get your pops in there.