Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var sha256 = require('js-sha256').sha256;
  2.  
  3. var Deck = function(get_seed) {
  4.     var used_cards = {};
  5.     var n_used_cards = 0;
  6.  
  7.     var get_bits = function(seed) {
  8.         var arr = sha256.array(seed);
  9.         var ret = [];
  10.         for (const i of arr) {
  11.             var k = 1;
  12.             for (var p = 0; p < 8; ++p) {
  13.                 ret.push(i & k);
  14.                 k *= 2;
  15.             }
  16.         }
  17.         return ret;
  18.     };
  19.  
  20.     var cur_sha = get_bits(get_seed());
  21.     var cur_idx = 0;
  22.  
  23.     var get_bit = function() {
  24.         if (cur_idx === 256) {
  25.             this.cur_sha = get_bits(get_seed());
  26.             this.cur_idx = 0;
  27.         }
  28.         return this.cur_sha[this.cur_idx];
  29.     }
  30.  
  31.     this.get_card = function() {
  32.         var rem = 52 - n_used_cards;
  33.         var cur = get_bit();
  34.         var pow = 2;
  35.         while (pow < rem) {
  36.             cur += get_bit() * pow;
  37.             pow *= 2;
  38.         }
  39.         if (cur >= rem) {
  40.             return this.get_card();
  41.         }
  42.         var idx = 0;
  43.         for (var i = 0; i < 52; ++i) {
  44.             while (idx in used_cards) {
  45.                 ++idx;
  46.             }
  47.             ++idx;
  48.         }
  49.         while (idx in used_cards) {
  50.             ++idx;
  51.         }
  52.         used_cards[idx] = true;
  53.         ++n_used_cards;
  54.         return to_card(idx);
  55.     }
  56.  
  57.     var to_card = function(idx) {
  58.         var num = idx % 13;
  59.         var suit = Math.floor(idx / 4);
  60.         return {
  61.             num: num,
  62.             suit: ['diamonds', 'clubs', 'hearts', 'spades'][suit]
  63.         };
  64.     }
  65. };
  66.  
  67. module.exports = Deck;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement