Yatzy.ts 2.25 KB
Newer Older
1
import { isConsecutives, sumOfSelectedValue, toDiceMap } from './dice-utils';
2
3

type D6 = 1 | 2 | 3 | 4 | 5 | 6;
Lucas BRETTES's avatar
Lucas BRETTES committed
4
export default class Yatzy {
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

  private readonly dice: number[];

  constructor(d1: D6, d2: D6, d3: D6, d4: D6, d5: D6) {
    this.dice = [d1, d2, d3, d4, d5];
  }

  chance(): number {
    return this.dice.reduce((previous, next) => previous + next);
  }

  yatzy(): number {
    return (new Set(this.dice).size === 1) ? 50 : 0;
  }

  ones(): number {
21
    return sumOfSelectedValue(this.dice, 1);
22
23
24
  }

  twos(): number {
25
    return sumOfSelectedValue(this.dice, 2);
26
27
28
  }

  threes(): number {
29
    return sumOfSelectedValue(this.dice, 3);
Lucas BRETTES's avatar
Lucas BRETTES committed
30
31
32
  }

  fours(): number {
33
    return sumOfSelectedValue(this.dice, 4);
Lucas BRETTES's avatar
Lucas BRETTES committed
34
35
36
  }

  fives(): number {
37
    return sumOfSelectedValue(this.dice, 5);
Lucas BRETTES's avatar
Lucas BRETTES committed
38
39
40
  }

  sixes(): number {
41
    return sumOfSelectedValue(this.dice, 6);
42
43
44
  }

  onePair(): number {
45
    const diceMap = toDiceMap(this.dice);
46
47
48
49
50
51
    const keyPairs = Object.entries(diceMap).filter(([key, value]) => value >= 2).map(([key, value]) => +key);

    return keyPairs.length > 0 ? Math.max(...keyPairs) * 2 : 0;
  }

  twoPair(): number {
52
    const diceMap = toDiceMap(this.dice);
53
54
    const keyPairs = Object.entries(diceMap).filter(([key, value]) => value >= 2).map(([key, value]) => +key);

55
    return keyPairs.length === 2 ? keyPairs.reduce((firstPair, secondPair) => (firstPair*2) + (secondPair*2)) : 0;
56
57
58
  }

  threeOfAKind(): number {
59
    const diceMap = toDiceMap(this.dice);
60
61
62
63
64
    const threeOfAKindDice = Object.keys(diceMap).find(k => diceMap[k] >= 3);
    return threeOfAKindDice ? +threeOfAKindDice * 3 : 0;
  }

  fourOfAKind(): number {
65
    const diceMap = toDiceMap(this.dice);
66
67
68
69
70
    const fourOfAKindDice = Object.keys(diceMap).find(k => diceMap[k] >= 4);
    return fourOfAKindDice ? +fourOfAKindDice * 4 : 0;
  }

  smallStraight(): number {
71
    return isConsecutives(this.dice) && Math.min(...this.dice) === 1 ? 15 : 0;
72
73
74
  }

  largeStraight(): number {
75
    return isConsecutives(this.dice) && Math.max(...this.dice) === 6 ? 20 : 0;
76
77
78
  }

  fullHouse(): number {
79
    const diceMap = toDiceMap(this.dice);
80
81
    return Object.keys(diceMap).length === 2 && Object.values(diceMap).some(d => d === 2 || d === 3) 
      ? Object.keys(diceMap).reduce((sum, key) => sum += (+key * diceMap[key]), 0) : 0;
82
  }
Lucas BRETTES's avatar
Lucas BRETTES committed
83
}