|
1 | 1 | 'use strict' |
2 | 2 |
|
3 | 3 | exports.parseDeck = parseDeck |
| 4 | +exports.encodeDeck = encodeDeck |
4 | 5 |
|
5 | 6 | const b64 = require('base64-js') |
6 | 7 |
|
7 | 8 | const CURRENT_VERSION = 2 |
8 | 9 | const ENCODE_PREFIX = "ADC" |
9 | 10 |
|
| 11 | + |
| 12 | +function encodeDeck(deck) { |
| 13 | + if (!deck || !deck.heroes || !deck.cards) throw "invalid deck" |
| 14 | + |
| 15 | + const heroes = deck.heroes.sort((a, b) => a.id - b.id) |
| 16 | + const cards = deck.cards.sort((a, b) => a.id - b.id) |
| 17 | + |
| 18 | + const encoder = cardEncoder() |
| 19 | + encoder.writeVar(heroes.length, 3) |
| 20 | + heroes.forEach(it => encoder.writeCard(it.id, it.turn)) |
| 21 | + encoder.resetPreviousId() |
| 22 | + cards.forEach(it => encoder.writeCard(it.id, it.count)) |
| 23 | + |
| 24 | + const versionAndHeroes = CURRENT_VERSION << 4 | extractNBitsWithCarry(heroes.length, 3) |
| 25 | + const checksum = computeChecksum(encoder.getBytes()) |
| 26 | + const name = (deck.name || "").substr(0, 63) |
| 27 | + |
| 28 | + const header = [versionAndHeroes, checksum, name.length] |
| 29 | + const nameArray = Array.apply(null, { length: name.length }).map((_, i) => name.charCodeAt(i)) |
| 30 | + |
| 31 | + const encodedDeck = b64.fromByteArray(header.concat(encoder.getBytes(), nameArray)) |
| 32 | + const sanitizedDeckCode = ENCODE_PREFIX + encodedDeck.replace(/\//g, "-").replace(/=/g, "_") |
| 33 | + |
| 34 | + return sanitizedDeckCode |
| 35 | +} |
| 36 | + |
| 37 | +function cardEncoder() { |
| 38 | + const bytes = [] |
| 39 | + var previousId = 0 |
| 40 | + |
| 41 | + function writeVar(value, bitsToSkip) { |
| 42 | + if (value < (1 << bitsToSkip)) return |
| 43 | + value = value >>> bitsToSkip |
| 44 | + while (value > 0) { |
| 45 | + bytes.push(extractNBitsWithCarry(value, 7)) |
| 46 | + value = value >>> 7 |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + function writeCard(id, n) { |
| 51 | + const nPart = n <= 3 ? n - 1 : 3 |
| 52 | + |
| 53 | + const delta = id - previousId |
| 54 | + previousId = id |
| 55 | + const idPart = extractNBitsWithCarry(delta, 5) |
| 56 | + |
| 57 | + bytes.push((nPart << 6) | idPart) |
| 58 | + writeVar(delta, 5) |
| 59 | + if (n > 3) writeVar(n, 0) |
| 60 | + } |
| 61 | + |
| 62 | + return { |
| 63 | + writeVar, |
| 64 | + writeCard, |
| 65 | + resetPreviousId: () => previousId = 0, |
| 66 | + getBytes: () => bytes |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +function extractNBitsWithCarry(value, bits) { |
| 71 | + const bitLimit = 1 << bits |
| 72 | + if (value < bitLimit) return value |
| 73 | + return bitLimit | (value & (bitLimit - 1)) |
| 74 | +} |
| 75 | + |
| 76 | + |
| 77 | + |
10 | 78 | function parseDeck(deckCode) { |
11 | 79 | if (!deckCode.startsWith(ENCODE_PREFIX)) throw "invalid deck code prefix" |
12 | 80 | const b64Str = deckCode.substr(ENCODE_PREFIX.length) |
|
0 commit comments