<?php

/**
 * 本程序由 GPT 生成, 由 copilot 辅助修改完成, 仅供参考
 */

// 定义抽取的牌数量
define('NUM_CARDS', rand(6,8));

// 生成一副扑克牌
$cards = [];
$suits = ['♥', '♠', '♦', '♣'];
$faces = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];

foreach ($suits as $suit) {
    foreach ($faces as $face) {
        $cards[] = $suit . $face;
    }
}

while(true) {

    // 随机抽取指定数量的牌
    $selectedCards = array_rand(array_flip($cards), NUM_CARDS);

    // 输出抽取的牌
    $cardIndexMap = [];
    foreach ($selectedCards as $index => $card) {
        $cardIndexMap[chr(65 + $index)] = $card;
        echo chr(65 + $index) . ': ' . $card . PHP_EOL;
    }

    while(true) {

        // 用户输入牌的序号
        echo '请输入两组牌的序号，以空格分隔：';
        $userInput = trim(fgets(STDIN));

        // 将用户输入分割为两组牌
        $inputCards = explode(' ', $userInput);

        // 检查输入的牌是否合法
        if (count($inputCards) !== 2) {
            echo '输入的牌数量不正确，请重新输入。' . PHP_EOL;
            continue;
        }

        // 计算两组牌的值
        $group1Value = 0;
        $group2Value = 0;

        // 将 $inputCards[0] 和 $inputCards[1] 转为数组
        $inputCards[0] = str_split($inputCards[0]);
        $inputCards[1] = str_split($inputCards[1]);

        foreach ($inputCards[0] as $cardIndex) {
            $group1Value += getValue($cardIndexMap[$cardIndex]);
        }

        foreach ($inputCards[1] as $cardIndex) {
            $group2Value += getValue($cardIndexMap[$cardIndex]);
        }

        // 判断两组牌的值是否相等
        if ($group1Value === $group2Value) {
            echo '两组牌相等' . PHP_EOL;
            break;
        } else {
            echo '两组牌不相等' . PHP_EOL;
        }
    }
}

// 获取牌的值(该部分由于GPT存在问题,由我手动修改)
function getValue($card)
{
    // 通过正则表达式提取出里面的数字和字母
    preg_match('/[0-9]+|[A-Z]+/', $card, $matches);
    $face = $matches[0];
    $list = array('A','2','3','4','5','6','7','8','9','10','J','Q','K');
    return array_search($face, $list) + 1;
}
