Files
CardGame/include/Functions.h
2024-06-23 11:14:09 +08:00

52 lines
1.3 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#pragma once
#include <cstdlib>
#include <ctime>
#include "SqList.h"
#include "SqStack.h"
// 发牌
inline void DealCards(int N, SqList<int>*& PA, SqList<int>*& PB)
{
int* CardPile = new int[N]; // 发牌堆
srand((int)time(nullptr)); // 基于当前时间设置随机数种子
for (int i = 0; i < N; i++) CardPile[i] = 2; // 默认情况下每个面值有两张牌
int j = 1, k = 1; // 牌放入顺序表PA,PB中的位置(降低发牌过程中的时间复杂度)
for (int i = 0; i < N * 2; i++)
{
int num = rand() % N; // 获取一个 0~N-1 的随机数
while (true)
{
if (CardPile[num] != 0) // 如果该数对应面值的牌未发完
{
if (i % 2 == 0) // 如果发牌次数(i+1)为奇数则发给PA
{
InsertElem_i(*PA, j++, num + 1);
CardPile[num]--;
}
else // 否则发给PB
{
InsertElem_i(*PB, k++, num + 1);
CardPile[num]--;
}
break;
}
else num = (num + 1) % N; // 若发完则检查下一位数字对应面值的牌
}
}
delete[] CardPile; // 释放发牌堆占用的内存
}
// 寻找栈内元素并返回其位置
inline int FindElem(SqStack<int>& S, int e)
{
int i = S.top; // 从栈顶开始查找
for (; i >= 0; i--)
if (S.base[i] == e) return S.top - i; // 返回距离
return -1;
}
// 判断谁的回合
inline bool IsPlayerA(int i)
{
return i % 2 == 1;
}