【发布时间】:2023-04-04 01:50:01
【问题描述】:
所以我正在制作一款名为战争的纸牌游戏,规则如下:
- 玩家 1 和玩家 2 分别排列称为 q1 和 q2 的牌。两个都 队列不为空。玩家也有空的战斗栈s1 和 s2。
- 每位玩家从队列前面取出一张牌并将其放入 在他们的堆栈顶部
- 如果牌面值相等,就会发生战争。
- 每位玩家将 3 张额外的牌从他们的队列中移到他们的堆叠中 并再次检查他们的顶牌的面值。这可能会发生 几次。再次转到 3。
- 如果卡牌的值不同,则战斗结束并获得 可以确定。
我必须编写的函数名为 start_battle.c,我想出的逻辑如下,queue_front、queue_empty 和 stack_top 函数已经编写好了。所以我的伪代码如下:
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
我的代码如下:
#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;
}
哦和
typedef struct {
int face; /* 2-14 */
char suit; /* C H S D */
} card;
当我测试它时,我的代码卡在了 while 循环中,有人可以帮我解决它吗?
【问题讨论】:
-
queue_front()真的会从队列中移除卡片吗? -
queue_front() 只是获取队列最前面的数据。
-
那你需要把它拿掉,否则你的卡在两堆里。
-
它们是 2 张不同的牌,有 2 叠,s1 和 s2。
-
另外,您的
while条件似乎无效,因为queue_empty(q1)==0表示q1 is not empty,这始终是正确的,并且c1和c2在循环内永远不会改变。