-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathProgram.cs
645 lines (622 loc) · 16.3 KB
/
Program.cs
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
Exception? exception = null;
List<Card> deck;
List<Card> discardPile;
List<PlayerHand> playerHands;
List<Card> dealerHand;
int playerMoney = 100;
const int minimumBet = 2;
const int maximumBet = 500;
int previousBet = 10;
int bet;
int activeHand;
State state = State.IntroScreen;
bool discardShuffledIntoDeck = false;
try
{
Initialize();
DefaultBet();
activeHand = 0;
while (!(state is State.PlaceBet && playerMoney < minimumBet))
{
Render();
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.Enter:
switch (state)
{
case State.IntroScreen:
state = State.PlaceBet;
break;
case State.PlaceBet:
playerMoney -= bet;
previousBet = bet;
InitializeRound();
if (ScoreCards(playerHands[activeHand].Cards) is 21)
{
playerMoney += (playerHands[activeHand].Bet / 2) * 3;
playerHands[activeHand].Bet = 0;
playerHands[activeHand].Resolved = true;
state = State.ConfirmDealtBlackjack;
break;
}
state = State.ChooseMove;
break;
case State.ConfirmSplit:
if (ScoreCards(playerHands[activeHand].Cards) is 21)
{
playerMoney += (playerHands[activeHand].Bet / 2) * 3;
playerHands[activeHand].Bet = 0;
playerHands[activeHand].Resolved = true;
state = State.ConfirmDealtBlackjack;
break;
}
state = State.ChooseMove;
break;
case State.ConfirmDealtBlackjack
or State.ConfirmBust
or State.ConfirmDoubleDownDraw:
ProgressStateAfterHandCompletion();
break;
case State.ConfirmDraw
or State.ConfirmLoss
or State.ConfirmDealerCardFlip
or State.ConfirmDealerDraw
or State.ConfirmWin:
ProgressStateAfterDealerAction();
break;
}
break;
case ConsoleKey.DownArrow:
if (state is State.PlaceBet)
{
bet = Math.Max(minimumBet, bet - 2);
}
break;
case ConsoleKey.UpArrow:
if (state is State.PlaceBet)
{
bet = Math.Min(Math.Min(maximumBet, playerMoney), bet + 2);
if (bet % 2 is 1)
{
bet--;
}
}
break;
case ConsoleKey.D1 or ConsoleKey.NumPad1: // stay
if (state is State.ChooseMove)
{
ProgressStateAfterHandCompletion();
}
break;
case ConsoleKey.D2 or ConsoleKey.NumPad2: // hit
if (state is State.ChooseMove)
{
playerHands[activeHand].Cards.Add(deck[^1]);
deck.RemoveAt(deck.Count - 1);
if (ScoreCards(playerHands[activeHand].Cards) > 21)
{
playerHands[activeHand].Resolved = true;
playerHands[activeHand].Bet = 0;
state = State.ConfirmBust;
}
}
break;
case ConsoleKey.D3 or ConsoleKey.NumPad3: // double down
if (state is State.ChooseMove && playerMoney > playerHands[activeHand].Bet)
{
playerMoney -= playerHands[activeHand].Bet;
playerHands[activeHand].Bet *= 2;
playerHands[activeHand].DoubledDown = true;
playerHands[activeHand].Cards.Add(DrawCard());
if (ScoreCards(playerHands[activeHand].Cards) > 21)
{
playerHands[activeHand].Resolved = true;
playerHands[activeHand].Bet = 0;
state = State.ConfirmBust;
}
else
{
state = State.ConfirmDoubleDownDraw;
}
}
break;
case ConsoleKey.D4 or ConsoleKey.NumPad4: // split
if (state is State.ChooseMove && CanSplit())
{
playerMoney -= playerHands[activeHand].Bet;
playerHands.Add(new());
playerHands[^1].Bet = playerHands[activeHand].Bet;
playerHands[^1].Cards.Add(playerHands[activeHand].Cards[^1]);
playerHands[activeHand].Cards.RemoveAt(playerHands[activeHand].Cards.Count - 1);
playerHands[activeHand].Cards.Add(deck[^1]);
deck.RemoveAt(deck.Count - 1);
playerHands[^1].Cards.Add(deck[^1]);
deck.RemoveAt(deck.Count - 1);
state = State.ConfirmSplit;
}
break;
case ConsoleKey.Escape:
return;
}
}
state = State.OutOfMoney;
Render();
GetEnterOrEscape:
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.Enter: return;
case ConsoleKey.Escape: return;
default: goto GetEnterOrEscape;
}
}
catch (Exception e)
{
exception = e;
throw;
}
finally
{
Console.CursorVisible = true;
Console.Clear();
Console.WriteLine(exception?.ToString() ?? "Blackjack was closed.");
}
void Render()
{
Console.CursorVisible = false;
Console.Clear();
Console.WriteLine();
Console.WriteLine(" Blackjack");
Console.WriteLine();
if (state is State.IntroScreen)
{
Console.WriteLine(" This is the Blackjack card game. It is played with a standard 52");
Console.WriteLine(" count playing card deck. The goal is to get closer to 21 than the");
Console.WriteLine(" dealer without busting (going over 21). At the start of each round");
Console.WriteLine(" you will place a bet, then the dealer will deal you two cards and");
Console.WriteLine(" himself two cards (one face up and one face down). Then you will");
Console.WriteLine(" choose your move: stay, hit, double down, or split (up to 3 times)");
Console.WriteLine(" until your turn is complete. Then the dealer will reveal his face");
Console.WriteLine(" down card and draw cards as needed in attempts to be closer to 21");
Console.WriteLine(" as you.");
Console.WriteLine();
Console.WriteLine(" Bets must be in multiples of $2, because if you are dealt a");
Console.WriteLine(" blackjack you will get payed out 3:2.");
Console.WriteLine();
Console.WriteLine(" The dealer must draw until he has a hand score of at least 17.");
Console.WriteLine();
Console.WriteLine(" Suits: H (Hearts), C (Clubs), D (Diamonds), S (Spades).");
Console.WriteLine();
Console.WriteLine(" Card Values: Ace (1 or 11), Jack (10), Queen (10), King(10),");
Console.WriteLine(" and all other cards use their number value (eg. 3H -> 3).");
Console.WriteLine();
Console.WriteLine(" If you double down you are dealt one additional card on the hand");
Console.WriteLine(" and then that hand is locked in.");
Console.WriteLine();
Console.WriteLine(" Press [escape] to close the game at any time.");
Console.WriteLine();
Console.WriteLine(" Press [enter] to continue...");
return;
}
Console.WriteLine($" Cards In Dealer Deck: {deck.Count}");
Console.WriteLine($" Cards In Discard Pile: {discardPile.Count}");
Console.WriteLine($" Your Money: ${playerMoney}");
if (state is not State.IntroScreen &&
state is not State.PlaceBet &&
state is not State.OutOfMoney)
{
Console.WriteLine();
Console.WriteLine($" Dealer Hand{(dealerHand.Any(c => !c.FaceUp) ? "" : ($" ({ScoreCards(dealerHand)})"))}:");
for (int i = 0; i < Card.RenderHeight; i++)
{
Console.Write(" ");
for (int j = 0; j < dealerHand.Count; j++)
{
string s = dealerHand[j].Render()[i];
Console.Write(j < dealerHand.Count - 1 ? s[..5] : s);
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine($" Your Hand{(playerHands.Count > 1 ? "s" : "")}:");
for (int hand = 0; hand < playerHands.Count; hand++)
{
for (int i = 0; i < Card.RenderHeight; i++)
{
if (hand == activeHand)
{
Console.Write(i == Card.RenderHeight / 2 ? " > " : " ");
}
else
{
Console.Write(" ");
}
for (int j = 0; j < playerHands[hand].Cards.Count; j++)
{
string s = playerHands[hand].Cards[j].Render()[i];
Console.Write(j < playerHands[hand].Cards.Count - 1 ? s[..5] : s);
}
Console.WriteLine();
}
Console.WriteLine($" Hand Score: {ScoreCards(playerHands[hand].Cards)}");
Console.WriteLine($" Hand Bet: {(playerHands[hand].Bet > 0 ? $"${playerHands[hand].Bet}" : "---")}");
}
}
Console.WriteLine();
if (discardShuffledIntoDeck)
{
Console.WriteLine(" The dealer shuffled the discard pile into the deck.");
Console.WriteLine();
discardShuffledIntoDeck = false;
}
switch (state)
{
case State.PlaceBet:
Console.WriteLine(" Place your bet...");
Console.WriteLine(" Use [up] or [down] arrows to increase or decrease bet.");
Console.WriteLine(" Use [enter] to place your bet.");
Console.WriteLine($" Bet (${minimumBet}-${maximumBet}): ${bet}");
break;
case State.ConfirmDealtBlackjack:
Console.WriteLine(" You were dealt a blackjack (21). You win this hand!");
Console.WriteLine(" Your bet was payed out.");
Console.WriteLine(" Press [enter] to continue...");
break;
case State.ChooseMove:
Console.WriteLine(" Choose your move...");
Console.WriteLine(" [1] Stay");
Console.WriteLine(" [2] Hit");
if (playerMoney > playerHands[activeHand].Bet)
{
Console.WriteLine(" [3] Double Down");
}
if (CanSplit())
{
Console.WriteLine(" [4] Split");
}
break;
case State.ConfirmBust:
Console.WriteLine($" Bust! Your hand ({ScoreCards(playerHands[activeHand].Cards)}) is greater than 21.");
Console.WriteLine(" You lose this bet.");
Console.WriteLine(" Press [enter] to continue...");
break;
case State.ConfirmSplit:
Console.WriteLine(" You split your hand and the dealer dealt you an additional");
Console.WriteLine(" card to each split.");
Console.WriteLine(" Press [enter] to continue...");
break;
case State.ConfirmDealerDraw:
Console.WriteLine(" The dealer drew a card to his hand.");
Console.WriteLine(" Press [enter] to continue...");
break;
case State.ConfirmDealerCardFlip:
Console.WriteLine(" The dealer flipped over his second card.");
Console.WriteLine(" Press [enter] to continue...");
break;
case State.ConfirmLoss:
Console.WriteLine($" Lost! The dealer ({ScoreCards(dealerHand)}) beat your hand ({ScoreCards(playerHands[activeHand].Cards)}).");
Console.WriteLine(" Press [enter] to continue...");
break;
case State.ConfirmDraw:
Console.WriteLine($" Draw! This hand was equal to the dealer's hand ({ScoreCards(dealerHand)}).");
Console.WriteLine($" Your bet was returned to you.");
Console.WriteLine(" Press [enter] to continue...");
break;
case State.ConfirmWin:
Console.WriteLine($" Win! The dealer {(ScoreCards(dealerHand) > 21 ? "busted" : "stands")} ({ScoreCards(dealerHand)}).");
Console.WriteLine($" Your bet was payed out.");
Console.WriteLine(" Press [enter] to continue...");
break;
case State.OutOfMoney:
Console.WriteLine($" You ran out of money. Better luck next time.");
Console.WriteLine(" Press [enter] to close the game...");
break;
case State.ConfirmDoubleDownDraw:
Console.WriteLine($" You doubled down and the dealer dealt you one more");
Console.WriteLine($" card on your hand.");
Console.WriteLine(" Press [enter] to close the game...");
break;
default:
throw new NotImplementedException();
}
}
bool CanSplit() =>
playerMoney >= playerHands[activeHand].Bet &&
playerHands[activeHand].Cards.Count is 2 &&
playerHands[activeHand].Cards[0].Value == playerHands[activeHand].Cards[1].Value &&
playerHands.Count < 4;
int ScoreCards(List<Card> cards)
{
int score = 0;
int numberOfAces = 0;
foreach (Card card in cards)
{
if (card.Value is Value.King or Value.Queen or Value.Jack)
{
score += 10;
}
else if (card.Value is not Value.Ace)
{
score += (int)card.Value;
}
else
{
numberOfAces++;
}
}
if (numberOfAces is 0)
{
return score;
}
int scoreWithAn11 = score + 11 + (numberOfAces - 1);
if (scoreWithAn11 <= 21)
{
return scoreWithAn11;
}
else
{
return score + numberOfAces;
}
}
void Initialize()
{
discardPile = new();
playerHands = new();
dealerHand = new();
deck = new();
foreach (Suit suit in Enum.GetValues<Suit>())
{
foreach (Value value in Enum.GetValues<Value>())
{
deck.Add(new()
{
Suit = suit,
Value = value,
FaceUp = true,
});
}
}
Shuffle(deck);
}
void InitializeRound()
{
playerHands = new();
playerHands.Add(new());
playerHands[0].Bet = bet;
playerHands[0].Cards.Add(DrawCard());
playerHands[0].Cards.Add(DrawCard());
dealerHand = new();
dealerHand.Add(DrawCard());
dealerHand.Add(DrawCard());
dealerHand[^1].FaceUp = false;
}
bool UnresolvedHands()
{
bool unresolvedHands = false;
foreach (PlayerHand hand in playerHands)
{
if (!hand.Resolved)
{
unresolvedHands = true;
break;
}
}
return unresolvedHands;
}
void ProgressStateAfterHandCompletion()
{
if (!UnresolvedHands())
{
discardPile.AddRange(dealerHand);
foreach (PlayerHand hand in playerHands)
{
discardPile.AddRange(hand.Cards);
}
activeHand = 0;
DefaultBet();
state = State.PlaceBet;
return;
}
do
{
activeHand++;
} while (activeHand < playerHands.Count - 1 && ScoreCards(playerHands[activeHand].Cards) > 21);
if (activeHand < playerHands.Count)
{
if (ScoreCards(playerHands[activeHand].Cards) is 21)
{
playerMoney += (playerHands[activeHand].Bet / 2) * 3;
playerHands[activeHand].Bet = 0;
playerHands[activeHand].Resolved = true;
state = State.ConfirmDealtBlackjack;
return;
}
state = State.ChooseMove;
}
else
{
activeHand = 0;
dealerHand[^1].FaceUp = true;
state = State.ConfirmDealerCardFlip;
}
}
void ProgressStateAfterDealerAction()
{
if (!UnresolvedHands())
{
discardPile.AddRange(dealerHand);
foreach (PlayerHand hand in playerHands)
{
discardPile.AddRange(hand.Cards);
}
activeHand = 0;
DefaultBet();
state = State.PlaceBet;
return;
}
if (playerHands.Any(hand => !hand.Resolved) && ScoreCards(dealerHand) < 17)
{
dealerHand.Add(DrawCard());
state = State.ConfirmDealerDraw;
return;
}
for (int i = 0; i < playerHands.Count; i++)
{
if (!playerHands[i].Resolved)
{
if (ScoreCards(dealerHand) > 21 || ScoreCards(dealerHand) < ScoreCards(playerHands[i].Cards))
{
activeHand = i;
playerMoney += playerHands[activeHand].Bet * 2;
playerHands[activeHand].Resolved = true;
state = State.ConfirmWin;
return;
}
else if (ScoreCards(playerHands[i].Cards) < ScoreCards(dealerHand))
{
activeHand = i;
playerHands[activeHand].Bet = 0;
playerHands[activeHand].Resolved = true;
state = State.ConfirmLoss;
return;
}
else if (ScoreCards(playerHands[i].Cards) == ScoreCards(dealerHand))
{
activeHand = i;
playerMoney += playerHands[activeHand].Bet;
playerHands[activeHand].Bet = 0;
playerHands[activeHand].Resolved = true;
state = State.ConfirmDraw;
return;
}
}
}
}
void DefaultBet()
{
bet = Math.Min(playerMoney, previousBet);
if (bet % 2 is 1)
{
bet--;
}
}
void Shuffle(List<Card> cards)
{
for (int i = 0; i < cards.Count; i++)
{
int swap = Random.Shared.Next(cards.Count);
(cards[i], cards[swap]) = (cards[swap], cards[i]);
}
}
void ShuffleDiscardIntoDeck()
{
deck.AddRange(discardPile);
discardPile.Clear();
Shuffle(deck);
discardShuffledIntoDeck = true;
}
Card DrawCard()
{
if (deck.Count <= 0)
{
ShuffleDiscardIntoDeck();
}
Card card = deck[^1];
deck.RemoveAt(deck.Count - 1);
return card;
}
class Card
{
public Suit Suit;
public Value Value;
public bool FaceUp = true;
public const int RenderHeight = 7;
public string[] Render()
{
if (!FaceUp)
{
return
[
$"┌───────┐",
$"│███████│",
$"│███████│",
$"│███████│",
$"│███████│",
$"│███████│",
$"└───────┘",
];
}
char suit = Suit.ToString()[0];
string value = Value switch
{
Value.Ace => "A",
Value.Ten => "10",
Value.Jack => "J",
Value.Queen => "Q",
Value.King => "K",
_ => ((int)Value).ToString(CultureInfo.InvariantCulture),
};
string card = $"{value}{suit}";
string a = card.Length < 3 ? $"{card} " : card;
string b = card.Length < 3 ? $" {card}" : card;
return
[
$"┌───────┐",
$"│{a} │",
$"│ │",
$"│ │",
$"│ │",
$"│ {b}│",
$"└───────┘",
];
}
}
class PlayerHand
{
public List<Card> Cards = new();
public int Bet;
public bool Resolved = false;
public bool DoubledDown = false;
}
enum Suit
{
Hearts,
Clubs,
Spades,
Diamonds,
}
enum Value
{
Ace = 01,
Two = 02,
Three = 03,
Four = 04,
Five = 05,
Six = 06,
Seven = 07,
Eight = 08,
Nine = 09,
Ten = 10,
Jack = 11,
Queen = 12,
King = 13,
}
enum State
{
IntroScreen,
PlaceBet,
ConfirmDealtBlackjack,
ChooseMove,
ConfirmBust,
ConfirmSplit,
ConfirmDoubleDownDraw,
ConfirmDealerDraw,
ConfirmDealerCardFlip,
ConfirmLoss,
ConfirmDraw,
ConfirmWin,
OutOfMoney,
}