-
Notifications
You must be signed in to change notification settings - Fork 0
/
blackjack.ts
86 lines (72 loc) · 2 KB
/
blackjack.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { Hand } from "./Hand";
import { Deck } from "./Deck";
import { PlayingCard } from "./PlayingCard";
interface BlackjackHandProps {
hit(deck: Deck): void;
getTotalHand(): number[];
getTotalHandString(): string;
}
export class BlackjackHand extends Hand implements BlackjackHandProps {
readonly name: string = "Player";
totalHand: number[] = [0, 0];
numericalHand: number[][] = [[], []];
//Factory Method
static create(): BlackjackHand {
return new BlackjackHand();
}
getTotalHand(): number[] {
return this.totalHand;
}
getTotalHandString(): string {
const hand = this.getTotalHand();
return `${hand[0]}${
hand[1] && hand[1] <= 21 && hand[0] !== hand[1] ? ` or ${hand[1]}` : ``
}`;
}
hit(deck: Deck): void {
const card = deck.draw();
if (card === undefined) throw new Error("No cards in the deck to draw.");
this.addCard(card);
switch (card.rank) {
case "Ace":
this.totalHand[1] += 11;
if (this.totalHand[1] > 21 && this.totalHand[0] + 11 <= 21) {
this.totalHand[0] += 11;
} else {
this.totalHand[0] += 1;
}
break;
case "King":
case "Queen":
case "Jack":
this.totalHand = this.totalHand.map((value) => value + 10);
break;
default:
const convertedInt = Number.parseInt(card.rank);
this.totalHand = this.totalHand.map((value) => value + convertedInt);
break;
}
console.log(this.name + " hit " + card.rank)
this.notifyObservers();
}
}
export class DealerHand extends BlackjackHand {
static instance: DealerHand;
private constructor(){
super();
}
static create(): DealerHand {
if(!DealerHand.instance){
DealerHand.instance = new DealerHand();
}
return DealerHand.instance;
}
name: string = "Dealer";
hidingCard: boolean = true;
getHand(): PlayingCard[] {
return this.hidingCard ? this.cards.slice(1) : this.cards;
}
showHand(): void {
this.hidingCard = false;
}
}