## preface

• The cover image is from Baidu picture, thank you 🙏.
• Poker – bull fighting game I believe many people have played it, do not know it does not matter, to give you a simple introduction of the rules:
1. Take a deck of playing cards and remove the Kings and queens, keeping only the remaining cards`2 - A``4`Plant a different color`52 `Zhang;
2. Everyone draws from the same deck`5`One card, the score for different cards is shown in the table below;

• Score calculation:
1. Find the sum that can be`10`divisible`5`In the card`3`Zhang;
2. If you can identify something like this`3`Card deck, surplus`2`The sum of the cards is less than or equal to`10`, the score is`2`The sum of the remaining cards, otherwise the sum minus`10`(a variety of`3`The sum of a deck of cards`10`Multiples of, need to let the remainder`2`A card scores the most points).
3. If you can’t identify something like this`3 `For a deck of cards, the score is`0`;
4. For example,`score(J, Q, K, 5, 8) = 3, score(2, Q, K, 5, 3) = 10, score(A, 2, 3, 4, A) = 0, score(5, 6, 10, 9, 3) = 3`.
• If the scores are different, the one with the highest score wins;
• If the scores are the same, they are compared according to the highest number of points in a player’s hand on the scoresheet (`K > Q > J > 10 ...`);
• If the score and the highest count are the same, then spades (`S`) > Heart (`H`“> < span style =” max-width: 100%;`C`) > rhombus (`D`) compares the highest count suit. namely`"H9S7CAC2D7"`(the hearts`9`, spades`7`, the plum blossom`A`, the plum blossom`2`And the diamond`7`) beat`"D9D5C6S5DA"`.
• The end of the article has the entire game source code.

### Began to comb

• Through the last part, the rules of the game are clear, the next step is to comb through the whole process, what do we need to do?
1. Gets all the values in the given string;
2. Calculate whether there is`3`A deck of cards can be`10`Divisible, and record the remainder`2`Zhang’s score;
3. If the score is the same, how to find the highest number and the corresponding suit;
4. Judge the score, the highest number of points, suits in turn, and get the winner.

#### Gets all the values in the given string

• First of all, because of the existence of the corresponding points`J, Q, K, A`Four letters, so the idea is to define a key-value conversion object that can convert the string corresponding to the score point to the corresponding numeric score point.
``/ / the string into the corresponding numerical const score = {' A ': 1,' 2 ', 2, '3', 3, '4', 4, '5' : 5, '6', 6, '7', 7, '8', 8, '9' : 9, '10' : 10, 'J' : 10, 'Q': 10, 'K': 10, };Copy the code``
• Iterates through the string of cards in the given player’s hand to get the corresponding`5`Card score; (This was missed in the initial consideration`10`This number, all the string lengths follow`10`To calculate, there is a problem).Assume that all given test cases are correct.
1. Traversal determines if the second following the current index exists and does not correspond to a suit;
2. If it is not the suit, the last two digits are chosen to represent the score point, and converted to the corresponding value, and the index moves`3`A;
3. If it is a suit, the last digit is chosen to indicate the score point, and converted to the corresponding value, and the index moves`2`A;
``Const filterString = STR => {const len = str.length; const list = []; for(let i = 0; i < len;) { let NumberValue, flag; if(str[i + 2] && ! Typelist. includes(STR [I + 2])) {typelist. includes(STR [I + 2])) {typelist. includes(STR [I + 2]); flag = false; } else { NumberValue = score[str[i+1]]; flag = true; } list.push(NumberValue); flag ? i += 2 : i += 3; } return listCopy the code``

#### Calculate whether there is`3`A deck of cards can be`10`Divisible, and record the remainder`2`Zhang’s score

• In the previous step, we got an array of points, so now we have to calculate the score.
• At first I wanted to enumerate all the components`3`A and`2`Array, and then the sum of each judgment; I thought it was very complicated and wasted a lot of space; And then the colleague said summation and then minus ergodic`2`Wouldn’t that be the sum of two?Sometimes too stubborn forward solution, you can also consider reverse solution.
• Since we only need to consider the largest score, we don’t need to record the same score, so I use`Set`Data structure, there is the same value filter, do not need to write a filter judgment.
``Const getMaxScore = list => {const result = new Set([0]); const len = list.length; const sum = list.reduce((pre, next) => pre + next, 0); for(let i = 0; i < len - 1; i ++) { for(let j = i + 1; j < len; Const twoSum = list[I] + list[j]; const twoSum = list[I] + list[j]; const threeSum = sum - twoSum; if(threeSum % 10 === 0) { result.add(twoSum > 10 ? twoSum - 10 : twoSum); // If the total is not more than 10, the score is the sum of the 2 remaining cards, otherwise the sum is minus 10}}} return math.max (... result); }Copy the code``

#### If the score is the same, how to find out the highest number and the corresponding suit

• Through the previous step, we can already calculate the score of the player, then if the score is the same, how to get the corresponding maximum score point and the corresponding suit?
##### Methods a
• First, we define an array of points and arrays of different suit types;
``/ / score points const typeList = [' A ', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J' and 'Q', 'K']. // const typeList = ['S', 'H', 'C', 'D'];Copy the code``
• Then, we traverse the score point group from back to front. When there is a corresponding score point in the player’s hand string, we get the index subscript of the corresponding score point string, and then get the previous value of the index.
##### Method 2
• inGets all the values in the given stringWhen we obtain the corresponding score point, we convert the score point into an object`key`(define`scoreKey`), corresponding to`value`Defines a suit weight object for suit weights`typeScore`), and put five objects into an array based on the object’s`key``value`After sorting, take the first array, which is the maximum value of the corresponding player’s hand and the corresponding suit.
``Const scoreKey = object. assign(score, {'J': 11, 'Q': 12, 'K': 13,}) const typeScore = {'S': 4, // Spades 'H': 3, // hearts 'C': 2, // clubs 'D': 1 // diamonds}; /** * @Description: String * @param {String} * @return {[Object, Array]} */ const filterString = STR => {const len = str.length; const strObjList = []; const list = []; for(let i = 0; i < len;) {// Sort array object keys, fractional values, trailing digits let key, NumberValue, flag; if(str[i + 2] && ! Typelist. includes(STR [I + 2])) {typelist. includes(STR [I + 2])) {typelist. includes(STR [I + 2])) {typelist. includes(STR [I + 2]); NumberValue = score[str.slice(i+1, i + 3)]; flag = false; } else { key = scoreKey[str[i+1]]; NumberValue = score[str[i+1]]; flag = true; } strobjlist.push ({typeScore[STR [I]] // weight of typeScore[STR [I]] // weight of typeScore}); list.push(NumberValue); flag ? i += 2 : i += 3; } strobjlist.sort ((a, b) => {if(a.key > b.key) {return -1; } else if(a.cookie === b.cookie) {return a.cookie - b.cookie > 0? 1:1; } return 1; }) const strMaxObj = strObjList[0]; return [strMaxObj, list]; }Copy the code``

#### Judge the score, the highest number of points, suits in turn, and get the winner

• The required data has been obtained from the previous steps, and this part is easy, just call the written methods sequentially.
``Const getWinPlayer = (player1, player2) => {const [player1_strMaxObj, player1_list] = filterString(player1); const [player2_strMaxObj, player2_list] = filterString(player2); const player1_score = getMaxScore(player1_list); const player2_score = getMaxScore(player2_list); If (player1_score > player2_score) {return 'Leon'; } else if(player1_score < player2_score) {return 'Judy' else {player1_strmaxobj.key > player2_strMaxObj.key) { return 'Leon'; } else if (player1_strmaxobj.key < player2_strmaxobj.key) {return 'Judy'} else {// Max same // compare suit if(player1_strMaxObj.value > player2_strMaxObj.value) { return 'Leon'; } else if (player1_strMaxObj.value < player2_strMaxObj.value) { return 'Judy' } } } }Copy the code``

### other

• I thought it was over here, until I got the test data, and I realized it wasn’t.
• The data are`3400 +` The test dataAnd it’s not the desired data structure, so what do you do? When you see two sets of data on a single line separated by a semicolon, it’s time to show your regular expression skills. use`VS Code`The editor opens the file,`Mac`use`command + f`Open search (`Windows`use`ctrl + f`), select Re.
``/[A-Z0-9]{10,}; [A-Z0-9]{10,}/Copy the code``
• Note:`VS Code`The slashes left and right of the regular need to be removed.

• Write a look, huh?? There is no match, I hurriedly check the re written, found no problem ah. I looked at the unmatched data again, and… , is actually problematic data, that I manually delete? Of course not. Hundreds? I’m going to modify the re directly and convert it to usable data first. Converted data
``/[A-Z0-9]{1,}; [A-Z0-9]{1,}/Copy the code``
• `OK`, the data is usable, then change the test, since there is abnormal data that filter out.
``Const filterData = data => {const filter = data. Filter (item => {const regexp = /([a-z0-9]{10,}; [A-Z0-9]{10,})/g; return regexp.test(item); }); return filter; } const getFinallyWinner = () => {const newData = filterData(testData); let leonCount = 0, judyCount = 0; newData.map(item => { const players = item.split('; ') const win = getWinPlayer(players[0], players[1]); win === 'Leon' ? leonCount ++ : judyCount ++; }) return \${leonCount} times, \${judyCount} times; } document.getElementById('winner').innerHTML = getFinallyWinner();Copy the code``

### expand

1. If the filter does not satisfy the length of`10`After the data, there are abnormal data, how to verify the correctness of the data?
• A repository of relevant checksum regulars`test.js`There is in the file, you can think about it, write it and compare it. Found after changing the re`15`One piece of data is satisfied`/([A-Z0-9]{10,}; [A-Z0-9]{10,})/g`But it’s not valid data.
2. Now this is for two people to play, and the data is dead data, can we change to custom number (`2 ~ 10`People)?
3. Other questions or suggestions are welcome to leave comments.
4. `GitHub`Warehouse source, welcome`Fock`,`Star`.

### Past wonderful

• Basic specifications for front-end development
• Build from 0 Vite + Vue3 + element-plus + VUE-Router + ESLint + husky + Lint-staged
• “Front-end advanced” JavaScript handwriting methods/use tips self-check
• An introduction to JavaScript design patterns and creative patterns
• Public account open small program best solution (Vue)
• Axios you probably don’t know how to use