TypeScript implements poker data suit, value acquisition and generation


1. TypeScript code that implements the function of obtaining suits and values ​​​​in poker data

type CardData = number;

const LOGIC_MASK_COLOR = 0xF0; // 花色掩码
const LOGIC_MASK_VALUE = 0x0F; // 数值掩码

// 获取数值
function GetCardValue(cardData: CardData): number {
  return cardData & LOGIC_MASK_VALUE;
}

// 获取花色
function GetCardColor(cardData: CardData): number {
  return (cardData & LOGIC_MASK_COLOR) >> 4;
}


In this implementation, we use type CardData = number to define the type of poker data as number, which represents one byte of data.


Then, we defined the constants `LOGIC_MASK_COLOR` and `LOGIC_MASK_VALUE` to represent the pattern mask and the value mask respectively.
The `GetCardValue` function obtains the numerical value of the playing card through bitwise AND operation, that is, retaining the value of the numerical mask part.
The `GetCardColor` function obtains the suit of the playing card through bitwise AND operation, that is, retains the value of the suit mask part, and shifts the result to the right by 4 bits to obtain the numerical value of the suit.
Please note that this assumes that the input `cardData` parameter is a byte representing playing card data, and that the suit and numerical information have been processed according to the mask.

2. TypeScript code that implements the function of converting suits and numerical values ​​into poker data

type CardData = number;

const LOGIC_MASK_COLOR = 0xF0; // 花色掩码
const LOGIC_MASK_VALUE = 0x0F; // 数值掩码

// 根据花色和数值生成扑克数据
function GenerateCardData(color: number, value: number): CardData {
  const cardColor = (color << 4) & LOGIC_MASK_COLOR;
  const cardValue = value & LOGIC_MASK_VALUE;
  return cardColor | cardValue;
}


In this implementation, we still use type CardData = number to define the type of poker data as number, which represents one byte of data. Then, we defined the constants LOGIC_MASK_COLOR and LOGIC_MASK_VALUE to represent the suit mask and the value mask respectively.


GenerateCardDataThe function accepts suit and value as parameters, and generates corresponding poker data based on mask and shift operations.


Specifically, `cardColor` is obtained by shifting the suit left by 4 bits and performing a bitwise AND operation with the suit mask to ensure that the suit information is in the correct location.

cardValueObtained by performing a bitwise AND operation with a numeric mask to ensure that the numeric information is in the correct location.


Finally, cardColor and cardValue are combined using a bitwise OR operation to generate the final poker data.


Usage example:

const color = 1;   // 花色
const value = 2;   // 数值
const cardData = GenerateCardData(color, value);
console.log(cardData);   // 输出生成的扑克数据

Please note that this assumes that the suit and numerical parameters are legal and within the legal range.


Guess you like

Origin blog.csdn.net/lizhong2008/article/details/134993926