## Beginner – Simplified Blackjack in Python

I just started learning python a few weeks ago, and like so many others here, I'm looking for feedback on my simplified blackjack game. I would like to know if the code could have been more elegant / shorter and how.

PS – In my code, aces count for the time being only as 1.

``````class Bank():

def __init__(self,bet,balance):
self.bet = bet
self.balance = balance

def transaction_win(self):
self.balance+=self.bet*2
return self.balance

def transaction_loss(self):
self.balance-=self.bet
return self.balance

def introduction():
print('*'*40)
print('nWelcome to Blackjack!')
print('This is a simplified version of the actual game')
print('Each card club is represented by its initial i.e. (H)earts,(S)pade,(D)iamond and (C)lub')
print('Player can only Hit or Stay. Double down, insurance, card splits are not a feature of the game')
print('Rest of the rules remain the same. Good luck and have fun!n')
print('*'*40)
print('nn')
balance = int(input('What is the maximum total balance you can bet?'))
bet = int(input('What amount would you like to bet?'))
return balance,bet

class Deck():

def __init__(self,card_no):
self.card_no = card_no

def card_display(self):
if self.card_no in range(1,14):
card_house = 'H'
elif self.card_no in range(14,27):
card_house = 'S'
elif self.card_no in range(27,40):
card_house = 'D'
else:
card_house = 'C'
temp = self.card_no%13
if temp==0:
temp = 13
return str(temp)+card_house

def card_score(self):
temp = self.card_no%13
if temp in range(1,11):
card_score = 1
elif temp in range(11,13):
card_score =  10
else:
card_score = 10
return card_score

def start_game(player_hand,dealer_hand):
cards = list(range(1,53))
shuffle(cards)
print('Card deck shuffled!')
print('Dealing cardsnn')
player_card = (cards.pop(),cards.pop())
dealer_card = (cards.pop(),cards.pop())
player_score = ()
dealer_score = ()

for (i,j) in zip(player_card,dealer_card):
temp1 = Deck(i)
temp2 = Deck(j)
player_hand.append(temp1.card_display())
player_score.append(temp1.card_score())
dealer_hand.append(temp2.card_display())
dealer_score.append(temp2.card_score())

return player_hand,dealer_hand,cards,player_score,dealer_score

def hand_score(player_score,dealer_score):
return sum(player_score),sum(dealer_score)

def display_hand(player_hand,dealer_hand,choice):

if choice == 1:
print('Dealer hand:',end=' ')
for i in dealer_hand(:-1):
print(i,end=' ')
print('*')
else:
print('Dealer hand: '+' '.join(dealer_hand))
print('n'*5)
print('Player hand: '+' '.join(player_hand))

def player_choice():
while True:
try:
choice = int(input('Do you want to Hit(1) or Stay(2)?'))
except:
print('Error! Not a numeral input or invalid numeral input. Please try again')
else:
if choice not in (1,2):
print('Invalid numeral input. Please try again')
continue
else:
return choice
break

def win_check(player_total,dealer_total,bet,balance,choice):
temp = Bank(bet,balance)
if player_total == 21:
print('Congrats! You won!')
balance = temp.transaction_win()
return True,balance
elif dealer_total == 21 and choice == 2:
print('Sorry, you lost your bet')
balance = temp.transaction_loss()
return True,balance
elif player_total>21:
print('Bust! Sorry, you lost your bet')
balance = temp.transaction_loss()
return True,balance
elif dealer_total<21 and dealer_total>player_total and choice == 2:
print('Sorry, you lost your bet')
balance = temp.transaction_loss()
return True,balance
elif dealer_total>21 and choice == 2:
print('Congrats! You won!')
balance = temp.transaction_win()
return True,balance
else:
return False,balance

def play_again(balance):
wish = input('Do you wish to play again? (Y)es or (N)o?')
bet = 0
if 'y' in wish.lower():
print('Available balance: {}'.format(balance))
while True:
try:
bet = int(input('how much would you like to bet?'))
except:
print('please give a numeric input')
else:
if balance-bet<0:
print('Please do not bet more than available balance. Try again')
continue
else:
break
elif 'n' in wish.lower():
print('Thanks for playing. Your final balance is {}'.format(balance))
else:
clear_output()
print('Give proper input please')
play_again(balance)

from random import shuffle
from IPython.display import clear_output

balance,bet = introduction()

while balance>0 and play_answer == True:

choice = 1
winner_check = False
player_hand,dealer_hand,cards,player_score,dealer_score = start_game((),())
player_total,dealer_total = hand_score(player_score,dealer_score)
display_hand(player_hand,dealer_hand,choice)
choice = player_choice()
while (choice == 1 or choice == 2) and winner_check == False:

card_drawn = cards.pop()
temp = Deck(card_drawn)
if choice == 1:
player_total+=temp.card_score()
player_hand.append(temp.card_display())
player_score.append(temp.card_score())
else:
dealer_total+=temp.card_score()
dealer_hand.append(temp.card_display())
dealer_score.append(temp.card_score())

clear_output()
display_hand(player_hand,dealer_hand,choice)
winner_check,balance = win_check(player_total,dealer_total,bet,balance,choice)
if winner_check==True:
break
elif winner_check == False and choice == 1:
choice = player_choice()
else:
pass

if balance == 0:
print('You are too poor to bet more. Better luck next time.')
break
else:
pass

del winner_check,player_hand,dealer_hand,cards,player_score,dealer_score,player_total,dealer_total,temp
``````

## Object-oriented – Console-based BlackJack in C # – Follow-Up

I did some code refactoring of my console-based BlackJack in C #. Finally found a better solution to solve ace problems (double aces should have the value 22 and the third ace the value 1).

I still find it difficult to share the UI and program logic, though I created a static screen class for it. Second, I still can not figure out what purpose or what need hand teaching has, as suggested by some. Estimate some code reviews for design patterns or other code revisions of this version of my BlackJack.

Left

card class

``````using system;
using System.Collections.Generic;

public listing
{
Diamonds, clubs, hearts, spades
}

public listing
{
Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Jack, Queen, King
}

public map
{
public Suit Suit {received; }
public face face {get; }
public string FaceName {get; }

// set value is for Ace, since Ace can be 1 or 11.
public int Value {get; to adjust; }

public char symbol {get; }

public ConsoleColor CardColor {get; to adjust; }

/// Initialize value and suit icon
public card (suit suit, face face)
{
Suit = suit;
Face = face;

Switch (suit)
{
case Suit.Clubs:
Symbol = & # 39; ♣ & # 39 ;;
CardColor = ConsoleColor.White;
break;
Symbol = & # 39; ♠ & # 39 ;;
CardColor = ConsoleColor.White;
break;
case Suit.Diamonds:
Symbol = & # 39; ♦ & # 39 ;;
CardColor = ConsoleColor.Red;
break;
Case Suit.Hearts:
Symbol = & # 39; ♥ & # 39 ;;
CardColor = ConsoleColor.Red;
break;
}

Switch (face)
{
case Face.Ten:
Value = 10;
FaceName = "10";
break;
Case Face.Jack:
Value = 10;
FaceName = "J";
break;
Case Face.Queen:
Value = 10;
FaceName = "Q";
break;
Case Face.King:
Value = 10;
FaceName = "K";
break;
Case Face.Ace:
Value = 11;
FaceName = "A";
break;
Default:
Value = (int) face + 1;
FaceName = Value.ToString ();
break;
}
}

public void PrintCardColor ()
{
Utility.WriteLineInColor (\$ "{this.Symbol} {this.FaceName}", this.CardColor);
}

public void PrintCard (Card _card)
{
Console.Write (\$ "Drawn card is");
Utility.WriteLineInColor (\$ "{_ card.Symbol} {_ card.FaceName}", _card.CardColor);
}
}
``````

deck class

``````using system;
using System.Collections.Generic;
using System.Linq;

public deck
{
// Field
private list Deck;

public deck ()
{
/// Build a deck with 52 cards.
Deck = new list(52);
InitializeColdDeck ();
Mix();
Screen.PrintShufflingDeck ();
}

private void InitializeColdDeck ()
{
var suitAsList = Enum.GetValues ​​(type of (suit))(). ToArray ();

// Alternative way is down at LINQ. Functional programming.
// This way, more precise and less error-prone.
deck = suitAsList
Select number (
suit => Enumerable.Range (0, 12),
(Color, rank) => new card ((color) color, (face) rank))
.List();

// Alternative method is below with 2 for loops:
// This way seems more readable but prone to error.
// for (int j = 0; j <4; j ++)
// for (int i = 0; i < 13; i++)
//         deck.Add(new Card((Suit)j, (Face)i));
}

// Pick top card and remove it from the deck.
// Return: The top card of the deck
public Card DrawCard(Player person, bool test = false)
{
Card card;
if (test)
{
card = new Card(Suit.Clubs, Face.Ace);
}
else
{
card = deck[0];
}

if (person.GetHandValue() + card.Value == 21 && person.Hand.Count == 1)
// Check natural black jack immediately after received first 2 cards.
person.IsNaturalBlackJack = true;
else if (person.GetHandValue() + card.Value > 21 && card.Face == Face.Ace)
// person's hand count is not used here, as the first two cards can be double aces.
// only the first aces are counted as 11, while the following aces are 1
// if the manual value is greater than 21
card.Value = 1;

deck.Remove (card);
Return card;
}

/// Randomize the order of the cards in the deck using the Fisher-Yates-Shuffle algorithm.
private void shuffle ()
{
Random rng = new Random ();

int n = deck.Count;

// Each loop finds a random card to insert into a new card list object.
during (n> 1)
{
n--;
int k = rng.Next (n + 1);
Card card = deck[k];
deck[k] = Deck[n];
deck[n] = Card;
}
}

public void ShowRemainingDeckCount ()
{
Console.WriteLine (" nRest cards in deck:" + GetRemainingDeckCount ());
}

public int GetRemainingDeckCount ()
{
Return Deck.Count;
}
}
``````

player class

``````using system;
using System.Collections.Generic;

// This player class is designed specifically for the BlackJack game
// Some player properties only apply to BlackJack games
public player
{
public string Name {get; to adjust; }
public list Get a hand; to adjust; }

public bool IsNaturalBlackJack {get; to adjust; }

public bool IsBusted {get; to adjust; } = false;

public int TotalWins {get; to adjust; } = 0;
public static int TotalWinsCounter {get; private set; } = 0;

public int ChipsOnHand {get; to adjust; } = 500;

public int ChipsOnBet {get; to adjust; }

public bool turn {get; to adjust; } = true;

public player (string name = "dealer")
{
this.Name = name;
Hand = new list(5);
}
public int GetHandValue ()
{
int value = 0;
foreach (map card in hand)
Value + = card.Value;

Return value;
}

public void ShowHandValue ()
{
Console.WriteLine (\$ "{this.Name}'s hand value is: {this.GetHandValue ()} ({this.Hand.Count} cards)");
}

public void ShowUpCards (bool isDealer = false)
{
Console.WriteLine (\$ " n {this.Name} has:");
if (isDealer)
{
Utility.WriteLineInColor (\$ "{this.Hand[0].Symbol} {this.Hand[0].FaceName}, this.Hand[0].CardColor);

Utility.WriteLineInColor ("", ConsoleColor.Magenta);

The hand value of Console.WriteLine (\$ "{this.Name} is: {this.Hand[0].Value}");
}
otherwise
{
foreach (var card in this.Hand)
card.PrintCardColor ();

ShowHandValue ();
}
}

public void AddWinCount ()
{
this.TotalWins = ++ TotalWinsCounter;
}

public void hit (Deckdeck)
{
Console.Write (\$ "{this.Name} hits.");
Utility.Sleep ();

// Take a card from the stack and take it on the player's hand.
// card card = new card (Suit.Hearts, Face.Ace); //deck.DrawCard ();
Card card = deck.DrawCard (this);
// If an ace is in the hand, change the entire value of the ace to 1.
// if (this.GetHandValue () + card.Value> 21 && card.Face == Face.Ace)
// card.Value = 1;

card.PrintCardColor (); // UI
Utility.Sleep ();
}

public void ()
{
Console.WriteLine (\$ "{this.Name} stands."); // UI
Utility.Sleep ();

this.ShowUpCards (); // UI
Utility.Sleep ();

this.Turn = false;
}

public bool CanPlayerStand (bool isPlayerBusted)
{
// Player can stand unconditionally
if (! this.Name.Equals ("Dealer"))
return true;
else if (isPlayerBusted) // so that the dealer stops automatically when the player goes bankrupt
return true;

return it incorrectly;
}

public void ResetPlayerHand ()
{
this.Hand = new list(5);
this.IsNaturalBlackJack = false;
this.IsBusted = false;
}
}
``````

Screen class

``````using system;

public static class screen
{
public static void SplashScreen ()
{
Utility.printDotAnimation (20);
Console.Clear ();
Console.Title = "Steve C # Console-based Blackjack Game (Version 2)";
Console.Write ("Steve C # console-based BlackJack game");
Utility.WriteInColor ("♠", ConsoleColor.White);
Utility.WriteInColor ("♥", ConsoleColor.Red);
Utility.WriteInColor ("♣", ConsoleColor.White);
Utility.WriteInColor ("♦", ConsoleColor.Red);
}

public static void PromptPlayerName ()
{
Console.Write (" n  nEnter the name of the player:");
}
public static void PrintShufflingDeck ()
{
Console.Write ("mixing cold deck");
Utility.printDotAnimation ();
}
}
``````

use class

``````using system;

Class utility
{

public static void WriteLineInColor (string text, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine (text);
Console.ResetColor ();
}

public static void WriteInColor (string text, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.Write (text);
Console.ResetColor ();
}

Public static hibernation (int miliseconds = 1500)
{
}

public static void printDotAnimation (int timer = 10)
{
for (var x = 0; x <timer; x ++)
{
Console.Write (".");
}
Console.WriteLine ();
}

public static void Line ()
{
Console.WriteLine (" n ------------------------------------------- ------- ");
}
}
``````

Blackjack Game class

``````using system;

public class BlackJackGame
{
private deck deck;
public void Play ()
{
bool continuePlay = true;
Screen.SplashScreen ();
Screen.PromptPlayerName ();

var player = new player (Console.ReadLine ());

var dealerComputer = new player ();

Deck = new deck ();

while (continuePlay)
{
// Initialize the screen and reset the specific property of the player and dealer
// for the new round.
Console.Clear ();
player.ResetPlayerHand ();
dealerComputer.ResetPlayerHand ();

// Create a new deck if the remaining cards are less than 20
if (deck.GetRemainingDeckCount () <20)
Deck = new deck ();

deck.ShowRemainingDeckCount ();

// Show player bankroll
Console.WriteLine (\$ "{player.Name} Chips Balance: {player.ChipsOnHand}");

if (player.ChipsOnHand <= 10)
{
Utility.WriteLineInColor ("Not enough chips in your account.", ConsoleColor.Red);
Utility.WriteLineInColor ("Please reload your chips from the counter to continue playing.  N", ConsoleColor.Red);

continuePlay = false;
break;
}

// wager received from the player
Console.Write ("Enter Chips:");
player.ChipsOnBet = Convert.ToInt16 (Console.ReadLine ());
// For the sake of brevity, here is no input validation.

// Deal the first two cards to the player (background)
deck.DrawCard (player);
deck.DrawCard (player);

// Show the player's hand (UI)
player.ShowUpCards ();
Utility.Sleep ();

Utility.Line ();

// Distribute the first two cards to the dealer (background)
deck.DrawCard (dealerComputer);
deck.DrawCard (dealerComputer);

// Show dealer's hand (UI)
dealerComputer.ShowUpCards (true);
Utility.Sleep ();

Utility.Line ();

// Check Natural Black Jack
if (CheckNaturalBlackJack (player, dealerComputer) == false)
{
// If both do not have natural blackjack,
// Then it's the player's turn to continue.
// After the player's turn, it's the dealer's turn.
TakeAction (player);
TakeAction (dealerComputer, player.IsBusted);

AnnounceWinnerForTheRound (Player, DealerComputer);
}

Console.WriteLine ("This round is over.");

Console.Write (" nReport? J or N?");

continuePlay = Console.ReadLine (). ToUpper () == "Y"? true wrong;
// For brevity, no input validation
}

PrintEndGame (Player, DealerComputer);
}

private void TakeAction (player currentPlayer, bool isPlayerBusted = false)
{
string opt = "";
currentPlayer.Turn = true;

Console.WriteLine (\$ " n {currentPlayer.Name}'s turn.");

while (currentPlayer.Turn)
{
if (currentPlayer.Name.Equals ("Dealer"))
{
Utility.Sleep (2000); // pretend thinking time.
// Mini A.I for dealers.
if (isPlayerBusted) // If a player goes bankrupt, the dealer can fight for victory
// break; // The dealer still has to reveal the hole card even though the player is broke
opt = "S";
otherwise
opt = currentPlayer.GetHandValue () <= 16 ? "H" : "S";
}
else
{
// Prompt player to enter Hit or Stand.
Console.Write("Hit (H) or Stand (S): ");
}

switch (opt.ToUpper())
{
case "H":
currentPlayer.Hit(deck);
currentPlayer.ShowHandValue();

break;
case "S":
//if (currentPlayer.CanPlayerStand(isPlayerBusted))
currentPlayer.Stand();

break;
default:
Console.WriteLine("Invalid command.");
break;
}

CheckPlayerCard(currentPlayer);
}

Console.WriteLine(\$"{currentPlayer.Name}'s turn is over.");
Utility.Line();
Utility.Sleep();
}

private void CheckPlayerCard(Player _currentPlayer)
{
// If current player is busted, turn is over.
if (_currentPlayer.GetHandValue() > 21)
{
Utility.WriteLineInColor ("Bust!", ConsoleColor.Red);
Utility.Sleep ();

_currentPlayer.IsBusted = true;
_currentPlayer.Turn = false;
}
// If the current player's total card is 5, the round is over.
otherwise if (_currentPlayer.Hand.Count == 5)
{
Console.WriteLine (\$ "{_ currentPlayer.Name} already has 5 cards in hand.");
Utility.Sleep ();

_currentPlayer.Turn = false;
}
}

private bool CheckNaturalBlackJack (player, player)
{
Console.WriteLine ();
if (_dealer.IsNaturalBlackJack && _player.IsNaturalBlackJack)
{
Console.WriteLine ("Players and dealers have natural BlackJack. Tie Game!");
_dealer.ShowUpCards ();
return true;
}
otherwise if (_dealer.IsNaturalBlackJack &&! _player.IsNaturalBlackJack)
{
Console.WriteLine (\$ "{_ dealer.Name} got natural BlackJack, {_Dealer.Name} won!");
_dealer.ShowUpCards ();
_player.ChipsOnHand - = (int) Math.Floor (_player.ChipsOnBet * 1.5);
return true;
}
otherwise if (! _dealer.IsNaturalBlackJack && _player.IsNaturalBlackJack)
{
Console.WriteLine (\$ "{_player.Name} got natural BlackJack, {_Player.Name} won!");
_player.ChipsOnHand + = (int) Math.Floor (_player.ChipsOnBet * 1.5);
return true;
}

// waxblock
return it incorrectly;
}

private void AnnounceWinnerForTheRound (player _player, player _dealer)
{
Console.WriteLine ();
if (! _dealer.IsBusted && _player.IsBusted)
{
Console.WriteLine (\$ "{_ dealer.Name} won.");
_player.ChipsOnHand - = _player.ChipsOnBet;
}
otherwise if (_dealer.IsBusted &&! _player.IsBusted)
{
Console.WriteLine (\$ "{_ player.Name} won.");
_player.ChipsOnHand + = _player.ChipsOnBet;
}
otherwise if (_dealer.IsBusted && _player.IsBusted)
{
Console.WriteLine ("Bind Game");
}
otherwise if (! _dealer.IsBusted &&! _player.IsBusted)
if (_player.GetHandValue ()> _dealer.GetHandValue ())
{
Console.WriteLine (\$ "{_ player.Name} won.");
_player.ChipsOnHand + = _player.ChipsOnBet;
}
otherwise if (_player.GetHandValue () <_dealer.GetHandValue ())
{
Console.WriteLine (\$ "{_ dealer.Name} won.");
_player.ChipsOnHand - = _player.ChipsOnBet;
}

otherwise if (_player.GetHandValue () == _dealer.GetHandValue ())
Console.WriteLine ("Bind Game");

}

private void PrintEndGame (Player Player, Player DealerComputer)
{
Console.WriteLine (\$ "{player.Name} won {player.TotalWins} times.");
Console.WriteLine (\$ "{dealerComputer.Name} won {dealerComputer.TotalWins} times.");
Console.WriteLine ("game over, thank you for playing.");
}
}
``````

## Object-oriented – Console-based BlackJack in C #

I did some code refactoring of my console-based BlackJack in C #. Finally found a better solution to solve ace problems (double aces should have the value 22 and the third ace the value 1).

I still find it difficult to share the UI and program logic, though I created a static screen class for it. Second, I still can not figure out what purpose or what need hand teaching has, as suggested by some. Estimate some code reviews or other code redesigns for this version of my BlackJack.

card class

``````using system;
using System.Collections.Generic;

public listing
{
Diamonds, clubs, hearts, spades
}

public listing
{
Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Jack, Queen, King
}

public map
{
public Suit Suit {received; }
public face face {get; }
public string FaceName {get; }

// set value is for Ace, since Ace can be 1 or 11.
public int Value {get; to adjust; }

public char symbol {get; }

public ConsoleColor CardColor {get; to adjust; }

/// Initialize value and suit icon
public card (suit suit, face face)
{
Suit = suit;
Face = face;

Switch (suit)
{
case Suit.Clubs:
Symbol = & # 39; ♣ & # 39 ;;
CardColor = ConsoleColor.White;
break;
Symbol = & # 39; ♠ & # 39 ;;
CardColor = ConsoleColor.White;
break;
case Suit.Diamonds:
Symbol = & # 39; ♦ & # 39 ;;
CardColor = ConsoleColor.Red;
break;
Case Suit.Hearts:
Symbol = & # 39; ♥ & # 39 ;;
CardColor = ConsoleColor.Red;
break;
}

Switch (face)
{
case Face.Ten:
Value = 10;
FaceName = "10";
break;
Case Face.Jack:
Value = 10;
FaceName = "J";
break;
Case Face.Queen:
Value = 10;
FaceName = "Q";
break;
Case Face.King:
Value = 10;
FaceName = "K";
break;
Case Face.Ace:
Value = 11;
FaceName = "A";
break;
Default:
Value = (int) face + 1;
FaceName = Value.ToString ();
break;
}
}

public void PrintCardColor ()
{
Utility.WriteLineInColor (\$ "{this.Symbol} {this.FaceName}", this.CardColor);
}

public void PrintCard (Card _card)
{
Console.Write (\$ "Drawn card is");
Utility.WriteLineInColor (\$ "{_ card.Symbol} {_ card.FaceName}", _card.CardColor);
}
}
``````

deck class

``````using system;
using System.Collections.Generic;
using System.Linq;

public deck
{
// Field
private list Deck;

public deck ()
{
/// Build a deck with 52 cards.
Deck = new list(52);
InitializeColdDeck ();
Mix();
Screen.PrintShufflingDeck ();
}

private void InitializeColdDeck ()
{
var suitAsList = Enum.GetValues ​​(type of (suit))(). ToArray ();

// Alternative way is down at LINQ. Functional programming.
// This way, more precise and less error-prone.
deck = suitAsList
Select number (
suit => Enumerable.Range (0, 12),
(Color, rank) => new card ((color) color, (face) rank))
.List();

// Alternative method is below with 2 for loops:
// This way seems more readable but prone to error.
// for (int j = 0; j <4; j ++)
// for (int i = 0; i < 13; i++)
//         deck.Add(new Card((Suit)j, (Face)i));
}

// Pick top card and remove it from the deck.
// Return: The top card of the deck
public Card DrawCard(Player person, bool test = false)
{
Card card;
if (test)
{
card = new Card(Suit.Clubs, Face.Ace);
}
else
{
card = deck[0];
}

if (person.GetHandValue() + card.Value == 21 && person.Hand.Count == 1)
// Check natural black jack immediately after received first 2 cards.
person.IsNaturalBlackJack = true;
else if (person.GetHandValue() + card.Value > 21 && card.Face == Face.Ace)
// person's hand count is not used here, as the first two cards can be double aces.
// only the first aces are counted as 11, while the following aces are 1
// if the manual value is greater than 21
card.Value = 1;

deck.Remove (card);
Return card;
}

/// Randomize the order of the cards in the deck using the Fisher-Yates-Shuffle algorithm.
private void shuffle ()
{
Random rng = new Random ();

int n = deck.Count;

// Each loop finds a random card to insert into a new card list object.
during (n> 1)
{
n--;
int k = rng.Next (n + 1);
Card card = deck[k];
deck[k] = Deck[n];
deck[n] = Card;
}
}

public void ShowRemainingDeckCount ()
{
Console.WriteLine (" nRest cards in deck:" + GetRemainingDeckCount ());
}

public int GetRemainingDeckCount ()
{
Return Deck.Count;
}
}
``````

player class

``````using system;
using System.Collections.Generic;

// This player class is designed specifically for the BlackJack game
// Some player properties only apply to BlackJack games
public player
{
public string Name {get; to adjust; }
public list Get a hand; to adjust; }

public bool IsNaturalBlackJack {get; to adjust; }

public bool IsBusted {get; to adjust; } = false;

public int TotalWins {get; to adjust; } = 0;
public static int TotalWinsCounter {get; private set; } = 0;

public int ChipsOnHand {get; to adjust; } = 500;

public int ChipsOnBet {get; to adjust; }

public bool turn {get; to adjust; } = true;

public player (string name = "dealer")
{
this.Name = name;
Hand = new list(5);
}
public int GetHandValue ()
{
int value = 0;
foreach (map card in hand)
Value + = card.Value;

Return value;
}

public void ShowHandValue ()
{
Console.WriteLine (\$ "{this.Name}'s hand value is: {this.GetHandValue ()} ({this.Hand.Count} cards)");
}

public void ShowUpCards (bool isDealer = false)
{
Console.WriteLine (\$ " n {this.Name} has:");
if (isDealer)
{
Utility.WriteLineInColor (\$ "{this.Hand[0].Symbol} {this.Hand[0].FaceName}, this.Hand[0].CardColor);

Utility.WriteLineInColor ("", ConsoleColor.Magenta);

The hand value of Console.WriteLine (\$ "{this.Name} is: {this.Hand[0].Value}");
}
otherwise
{
foreach (var card in this.Hand)
card.PrintCardColor ();

ShowHandValue ();
}
}

public void AddWinCount ()
{
this.TotalWins = ++ TotalWinsCounter;
}

public void hit (Deckdeck)
{
Console.Write (\$ "{this.Name} hits.");
Utility.Sleep ();

// Take a card from the stack and take it on the player's hand.
// card card = new card (Suit.Hearts, Face.Ace); //deck.DrawCard ();
Card card = deck.DrawCard (this);
// If an ace is in the hand, change the entire value of the ace to 1.
// if (this.GetHandValue () + card.Value> 21 && card.Face == Face.Ace)
// card.Value = 1;

card.PrintCardColor (); // UI
Utility.Sleep ();
}

public void ()
{
Console.WriteLine (\$ "{this.Name} stands."); // UI
Utility.Sleep ();

this.ShowUpCards (); // UI
Utility.Sleep ();

this.Turn = false;
}

public bool CanPlayerStand (bool isPlayerBusted)
{
// Player can stand unconditionally
if (! this.Name.Equals ("Dealer"))
return true;
else if (isPlayerBusted) // so that the dealer stops automatically when the player goes bankrupt
return true;

return it incorrectly;
}

public void ResetPlayerHand ()
{
this.Hand = new list(5);
this.IsNaturalBlackJack = false;
this.IsBusted = false;
}
}
``````

Screen class

``````using system;

public static class screen
{
public static void SplashScreen ()
{
Utility.printDotAnimation (20);
Console.Clear ();
Console.Title = "Steve C # Console-based Blackjack Game (Version 2)";
Console.Write ("Steve C # console-based BlackJack game");
Utility.WriteInColor ("♠", ConsoleColor.White);
Utility.WriteInColor ("♥", ConsoleColor.Red);
Utility.WriteInColor ("♣", ConsoleColor.White);
Utility.WriteInColor ("♦", ConsoleColor.Red);
}

public static void PromptPlayerName ()
{
Console.Write (" n  nEnter the name of the player:");
}
public static void PrintShufflingDeck ()
{
Console.Write ("mixing cold deck");
Utility.printDotAnimation ();
}
}
``````

use class

``````using system;

Class utility
{

public static void WriteLineInColor (string text, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine (text);
Console.ResetColor ();
}

public static void WriteInColor (string text, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.Write (text);
Console.ResetColor ();
}

Public static hibernation (int miliseconds = 1500)
{
}

public static void printDotAnimation (int timer = 10)
{
for (var x = 0; x <timer; x ++)
{
Console.Write (".");
}
Console.WriteLine ();
}

public static void Line ()
{
Console.WriteLine (" n ------------------------------------------- ------- ");
}
}
``````

Blackjack Game class

``````using system;

public class BlackJackGame
{
private deck deck;
public void Play ()
{
bool continuePlay = true;
Screen.SplashScreen ();
Screen.PromptPlayerName ();

var player = new player (Console.ReadLine ());

var dealerComputer = new player ();

Deck = new deck ();

while (continuePlay)
{
// Initialize the screen and reset the specific property of the player and dealer
// for the new round.
Console.Clear ();
player.ResetPlayerHand ();
dealerComputer.ResetPlayerHand ();

// Create a new deck if the remaining cards are less than 20
if (deck.GetRemainingDeckCount () <20)
Deck = new deck ();

deck.ShowRemainingDeckCount ();

// Show player bankroll
Console.WriteLine (\$ "{player.Name} Chips Balance: {player.ChipsOnHand}");

if (player.ChipsOnHand <= 10)
{
Utility.WriteLineInColor ("Not enough chips in your account.", ConsoleColor.Red);
Utility.WriteLineInColor ("Please reload your chips from the counter to continue playing.  N", ConsoleColor.Red);

continuePlay = false;
break;
}

// wager received from the player
Console.Write ("Enter Chips:");
player.ChipsOnBet = Convert.ToInt16 (Console.ReadLine ());
// For the sake of brevity, here is no input validation.

// Deal the first two cards to the player (background)
deck.DrawCard (player);
deck.DrawCard (player);

// Show the player's hand (UI)
player.ShowUpCards ();
Utility.Sleep ();

Utility.Line ();

// Distribute the first two cards to the dealer (background)
deck.DrawCard (dealerComputer);
deck.DrawCard (dealerComputer);

// Show dealer's hand (UI)
dealerComputer.ShowUpCards (true);
Utility.Sleep ();

Utility.Line ();

// Check Natural Black Jack
if (CheckNaturalBlackJack (player, dealerComputer) == false)
{
// If both do not have natural blackjack,
// Then it's the player's turn to continue.
// After the player's turn, it's the dealer's turn.
TakeAction (player);
TakeAction (dealerComputer, player.IsBusted);

AnnounceWinnerForTheRound (Player, DealerComputer);
}

Console.WriteLine ("This round is over.");

Console.Write (" nReport? J or N?");

continuePlay = Console.ReadLine (). ToUpper () == "Y"? true wrong;
// For brevity, no input validation
}

PrintEndGame (Player, DealerComputer);
}

private void TakeAction (player currentPlayer, bool isPlayerBusted = false)
{
string opt = "";
currentPlayer.Turn = true;

Console.WriteLine (\$ " n {currentPlayer.Name}'s turn.");

while (currentPlayer.Turn)
{
if (currentPlayer.Name.Equals ("Dealer"))
{
Utility.Sleep (2000); // pretend thinking time.
// Mini A.I for dealers.
if (isPlayerBusted) // If a player goes bankrupt, the dealer can fight for victory
// break; // The dealer still has to reveal the hole card even though the player is broke
opt = "S";
otherwise
opt = currentPlayer.GetHandValue () <= 16 ? "H" : "S";
}
else
{
// Prompt player to enter Hit or Stand.
Console.Write("Hit (H) or Stand (S): ");
}

switch (opt.ToUpper())
{
case "H":
currentPlayer.Hit(deck);
currentPlayer.ShowHandValue();

break;
case "S":
//if (currentPlayer.CanPlayerStand(isPlayerBusted))
currentPlayer.Stand();

break;
default:
Console.WriteLine("Invalid command.");
break;
}

CheckPlayerCard(currentPlayer);
}

Console.WriteLine(\$"{currentPlayer.Name}'s turn is over.");
Utility.Line();
Utility.Sleep();
}

private void CheckPlayerCard(Player _currentPlayer)
{
// If current player is busted, turn is over.
if (_currentPlayer.GetHandValue() > 21)
{
Utility.WriteLineInColor ("Bust!", ConsoleColor.Red);
Utility.Sleep ();

_currentPlayer.IsBusted = true;
_currentPlayer.Turn = false;
}
// If the current player's total card is 5, the round is over.
otherwise if (_currentPlayer.Hand.Count == 5)
{
Console.WriteLine (\$ "{_ currentPlayer.Name} already has 5 cards in hand.");
Utility.Sleep ();

_currentPlayer.Turn = false;
}
}

private bool CheckNaturalBlackJack (player, player)
{
Console.WriteLine ();
if (_dealer.IsNaturalBlackJack && _player.IsNaturalBlackJack)
{
Console.WriteLine ("Players and dealers have natural BlackJack. Tie Game!");
_dealer.ShowUpCards ();
return true;
}
otherwise if (_dealer.IsNaturalBlackJack &&! _player.IsNaturalBlackJack)
{
Console.WriteLine (\$ "{_ dealer.Name} got natural BlackJack, {_Dealer.Name} won!");
_dealer.ShowUpCards ();
_player.ChipsOnHand - = (int) Math.Floor (_player.ChipsOnBet * 1.5);
return true;
}
otherwise if (! _dealer.IsNaturalBlackJack && _player.IsNaturalBlackJack)
{
Console.WriteLine (\$ "{_player.Name} got natural BlackJack, {_Player.Name} won!");
_player.ChipsOnHand + = (int) Math.Floor (_player.ChipsOnBet * 1.5);
return true;
}

// waxblock
return it incorrectly;
}

private void AnnounceWinnerForTheRound (player _player, player _dealer)
{
Console.WriteLine ();
if (! _dealer.IsBusted && _player.IsBusted)
{
Console.WriteLine (\$ "{_ dealer.Name} won.");
_player.ChipsOnHand - = _player.ChipsOnBet;
}
otherwise if (_dealer.IsBusted &&! _player.IsBusted)
{
Console.WriteLine (\$ "{_ player.Name} won.");
_player.ChipsOnHand + = _player.ChipsOnBet;
}
otherwise if (_dealer.IsBusted && _player.IsBusted)
{
Console.WriteLine ("Bind Game");
}
otherwise if (! _dealer.IsBusted &&! _player.IsBusted)
if (_player.GetHandValue ()> _dealer.GetHandValue ())
{
Console.WriteLine (\$ "{_ player.Name} won.");
_player.ChipsOnHand + = _player.ChipsOnBet;
}
otherwise if (_player.GetHandValue () <_dealer.GetHandValue ())
{
Console.WriteLine (\$ "{_ dealer.Name} won.");
_player.ChipsOnHand - = _player.ChipsOnBet;
}

otherwise if (_player.GetHandValue () == _dealer.GetHandValue ())
Console.WriteLine ("Bind Game");

}

private void PrintEndGame (Player Player, Player DealerComputer)
{
Console.WriteLine (\$ "{player.Name} won {player.TotalWins} times.");
Console.WriteLine (\$ "{dealerComputer.Name} won {dealerComputer.TotalWins} times.");
Console.WriteLine ("game over, thank you for playing.");
}
}
``````

Sample output of the program

## 1 Cent Casino – www.1Centcasino.com – Gambling & Casino

1xBet Casino is licensed and regulated by Curacao eGaming. 1xBet offers casino games in all categories. 1xBet sportsbook includes over 1,000 events daily. You can bet on a variety of popular sports: football, tennis, basketball, volleyball, ice hockey, golf, boxing, handball, American football, hockey, baseball, table tennis, biathlon, Australian football and bandy. We also offer bets on cricket, snooker, formula 1, cycling, ski jumping, curling, floorball, inline hockey and water polo. With 1xBet you can bet daily on more than 1,000 sporting events.

Live bets are available 24 hours a day. Most sports offer more than 30 markets for each event, including corner bets, yellow cards, free kicks, etc.

PAYMENT / REPAYMENT
1xBet supports various payment methods over 160 options to choose from.

cryptocurrency

E-Wallets

bank cards

And many more.

Winnings are paid according to the same method used for the deposit.

PROMOTIONS

1xBet offers 100% up to € 130 for new players.

One-time free bet every year on your birthday.

With Advancebet you can also bet without credit.

Various freebets and casino free spins.

Profitable rewards with the loyalty program of the1xbet.

Unique promotions at top football matches.

1xBet is accessible on mobile devices and works on Android, iOS and Windows devices, allowing gamers to easily spin mobile slots on the go.

Enter PROMO CODE:

TOPGOLDBONUS

https://1xbet.com

,

## Game – Blackjack CLI in Python 3

This is a simple CLI blackjack game in Python3. I've seen others already published here, trying to implement some of their solutions and logic where I understand it. My game is a bit different because I have a "probability mode". This shows the probabilities of bust or blackjack if the user makes another hit. It also displays the chances of the dealer's hidden card revealing a blackjack (no chance for the dealer to crash, as you can not just give up 2 cards).

There are three classes to store variables that I want to access throughout the program. This avoids having to pass arguments on constantly. In my opinion, this leads to an easy-to-understand code, but I am not very experienced, so I do not know if this is good practice. Or should I use more classes … or expand on them and not have so many functions in the global space?

I also wonder about my use of try exceptions in the ask_for_bet () function. Is this the right use? Should I use it elsewhere?

Thank you in advance for your eyes!

``````import randomly
import time
from decimal import decimal
Import sys

Class money:
def __init __ (self, bank, bet):
self._bank = bank
self._bet = bet

# Getter / Setter for player's bank
@Property
def bank (self):
Return round (decimal number (self._bank), 2)

@ Bank setter
Def Bank (amount, amount):
self._bank = amount

# Getter / Setter for the bet
@Property
def Bet (self):
Return round (decimal number (own concrete), 2)

@ bet.Setter
def Bet (amount, amount):
self._bet = amount

m = money (100, 0)

Class Prob_mode:
def __init __ (self, value):
self._value = value

# Getter / Setter for the probability mode
@Property
def value (self):
return self._value

@value.Setter
def value (self, boolean):
self._value = boolean

p = Prob_mode (False)

Class Cards:
def __init __ (self, dealer_total, player_total):
self._deck = []
self._player_hand = []
self._dealer_hand = []
self._dealer_total = dealer_total
self._player_total = player_total

# Getter / Setter for dealer_total
@Property
def dealer_total (self):
return self._dealer_total

@ dealer_total.setter
def dealer_total (amount, amount):
self._dealer_total = Amount

# Getter / Setter for player_total
@Property
def player_total (self):
return self._player_total

@player_total.setter
def player_total (amount, amount):
self._player_total = Amount

c = maps (0, 0)

#### Card handling functions ####
def draw_card ():
popped_card = c.deck.pop (random.randint (0, len (c.deck) - 1))
Return popped_card

def initial_deal ():
for _ in the range (0, 2):
c.player_hand.append (draw_card ())
c.dealer_hand.append (draw_card ())
hand_value (c.dealer_hand, & # 39; dealer & # 39;
hand_value (c.player_hand, & # 39; player & # 39;)

def cardify_full_hand (hand):
cardified_hand = []
for i in the range (0, (len (hand)))):
card = f "| {hand[i]} | "
cardified_hand.append (card)
return & # 39; & # 39; .join (cardified_hand)

def cardify_dealer_initial ():
card1 = f "| {c.dealer_hand[0]} | "
card2 = "| ≈ |"
cardified_hand = [card1, card2]
return & # 39; & # 39; .join (cardified_hand)

def hand_value (hand, who = none):
sum_of_hand = 0
ace_count = hand.count (& # 39; A & # 39;
face_count = hand.count (& # 39; K & # 39;) + hand.count (& # 39; Q & # 39;) + hand.count (& # 39; J & # 39;)
for the card in hand:
if (type (map) == int):
sum_of_hand + = map
sum_of_hand + = 10 * face_count
if (ace_count> 0):
if (sum_of_hand> = 11):
sum_of_hand + = ace_count
otherwise:
sum_of_hand + = (11 + ace_count - 1)
if who == "dealer":
c.dealer_total = sum_of_hand
elif who == "Player":
c.player_total = sum_of_hand
otherwise:
return sum_of_hand

#### Display functions ####
def line ():
sleepy_print (& # 39; ------------------------------------------- & # 39)

def sleepy_print (string):
Time sleep (.5)
Pressure (string)
Time sleep (.5)

def error_msg ():
sleepy_print (" n  t! *** Invalid choice, try again ***!  n")

def update_total ():
sleepy_print (f " nNow you have \$ {m.bank}  n")
# Bankruptcy test
if (m.bank < 5):
input("ntYou don't have enough money. Hit ENTER to restart gamen")
m.bank = 100
else:
player_choice = input('ENTER for new game or "M" to go back to menun').upper()
if (player_choice == ""):
start_game()
elif (player_choice == 'M'):
time.sleep(.5)
else:
error_msg()
update_total()

def display_hands_before_flip():
line()
dealer_display = f"nDealer hand = {cardify_dealer_initial()}"
player_display = f"nPlayer hand = {cardify_full_hand(c.player_hand)}"
if p.value:
dealer_display += f" --------probability--> {blackjack_prob_msg (hand_value ([cdealer_hand[cdealer_hand[cdealer_hand[cdealer_hand[0]]))} "
player_display + = f "-------- probability -> {blackjack_prob_msg (c.player_total)} {bust_prob_msg (c.player_total)}"
print (dealer_display + & # 39; n)
print (f "* The bet is \$ {m.bet} *")
print (player_display + & # 39; n & # 39;
Line()

def display_hands_after_flip ():
Line()
print (" nDealer draw ...")
Time sleep (.5)
print (f " nhandlerhand = {cardify_full_hand (c.dealer_hand)}")
print (f "Sum = {c.dealer_total}  n")
print (f "player hand = {cardify_full_hand (c.player_hand)}")
print (f "Sum = {c.player_total}  n")

#### Probability functions ####
def_deck_list_to_nums ():
deck_of_all_nums = []
for card in c.deck:
if ((card == K K)) | (card == Q Q)) | (card == J J))):
deck_of_all_nums.append (10)
elif (map == & # 39; A & # 39;):
deck_of_all_nums.append (1)
otherwise:
deck_of_all_nums.append (card)
return deck_of_all_nums

def bust_prob_msg (hand_total):
danger_card_count = 0
if hand_total> = 12:
for i in deck_list_to_nums ():
if ((hand_total + i)> 21):
danger_card_count + = 1
Percent = decimal (danger_card_count / len (c.deck)) * 100
Return f "Failure =% {round (percent, 2)}"

def blackjack_prob_msg (hand_total):
a_count = c.deck.count (& # 39; A & # 39;
bj_card_count = 0
if (hand_total == 10):
bj_card_count = a_count
elif (hand_total> = 11):
for i in deck_list_to_nums ():
if ((hand_total + i) == 21):
bj_card_count + = 1
Percent = decimal number (bj_card_count / len (c.deck)) * 100
Return f "Blackjack =% {round (percent, 2)}"

#### Results ####
def player_win ():
if (c.player_total == 21):
Blackjack ()
otherwise:
if (c.dealer_total> 21):
print (" t  t dealer BUSTED ...  n")
m.bank + = m.bet * 2
sleepy_print ("++ you win! ++  n")

def Blackjack ():
Time sleep (.5)
print ("\$ \$ \$ \$ \$ \$ \$ \$ \$ \$")
Time sleep (.05)
print ("\$ \$ BLACKJACK \$ \$")
Time sleep (.05)
print ("\$ 1.5x \$ \$")
Time sleep (.05)
print ("\$ Win! \$")
Time sleep (.05)
print ("\$ \$ \$")
Time sleep (.05)
print ("\$ \$")
Time sleep (.05)
print ("\$")
m.bank + = (m.bet * decimal (2,5))

def dealer_win ():
sleepy_print ("--Dealer won -  n")

def tie (both_bust = false):
if both_bust:
print ((" t You and the dealer both have ... ...)"
elif (c.player_total == 21):
print ((" t You and the dealer both have Blackjack ...  n"))
sleepy_print ("~~ It's a tie ~~  n")
m.bank + = m.bet

#### Main Gameplay and Run features
print (f " nMax bet = \$ {m.bank}")
add_bet = input ("Press ENTER to set the minimum amount (\$ 5.00) or enter a higher amount: \$").
if (add_bet == ""):
m.bank = m.bank - 5
m.bet = 5
return
To attempt:
sleepy_print (" n  t! *** You do not have enough money to afford this bet! Try it again ***!")
elif (add_bet < 5):
sleepy_print("nt!*** Bet is too low. Must meet the minimum ***!")
else:
except:
error_msg()

def player_hit_stand():
# If blackjack
if (c.player_total == 21):
input("You have 21! Hit ENTER to see what the dealer has...")
return
player_choice = input('Do you want to hit ("H") or stand ("S")?nEnter response: ').upper()
if (player_choice == 'H'):
c.player_hand.append(draw_card())
hand_value(c.player_hand, 'player')
# If bust
if (c.player_total > 21):
display_hands_before_flip ()
input ("You BUSTED! Press ENTER to see what the dealer has ...")
return
# If still in the game (total player <21)
otherwise:
Time sleep (.5)
display_hands_before_flip ()
player_hit_stand ()
elif (player_choice == & # 39; S & # 39;):
return
otherwise:
error_msg ()
player_hit_stand ()

def dealer_hit_stand ():
# Dealer hits up to 17 or higher
while (c.dealer_total < 17):
c.dealer_hand.append(draw_card())
hand_value(c.dealer_hand, 'dealer')

def who_wins():
difference = c.player_total - c.dealer_total
# Bust outcomes
if ((c.player_total > 21) | (c.dealer_total> 21)):
if ((c.player_total> 21) & (c.dealer_total> 21)):
Tie (both_bust = True)
elif (c.player_total> 21):
dealer_win ()
otherwise:
player_win ()
# All other results
elif (difference == 0):
Tie ()
elif (difference> 0):
player_win ()
otherwise:
dealer_win ()

# Switch probability
if p.value:
prob_indicator = & # 39; a & # 39;
otherwise:
prob_indicator = & # 39; off & # 39;

print (f & # 39;  n  n  t Enter "P" to toggle the probability mode (currently: {prob_indicator}) & # 39;)
print (& # 39; t type "X" to finish the game & # 39;)
print (& # 39;  n  t  t - Press ENTER to issue a new hand - & # 39;)
input_var = input (). upper ()
if input_var == "":
Start game ()
elif input_var == & # 39; P & # 39 ;:
Time sleep (.5)
p.value = not p.value
elif input_var == & # 39; X & # 39 ;:
sleepy_print (& # 39; sExiting ...  n & # 39;)
sys.exit ()
otherwise:
error_msg ()

def start_game ():
# Empty hands, zero bet and new deck at the beginning of each hand
c.dealer_hand = []
c.player_hand = []
m.bet = 0
c.deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'] * 4

sleepy_print (& # 39;  n  n ******************** New Hand *************************** # 39)

# Play action
initial_deal ()
display_hands_before_flip ()
player_hit_stand ()
dealer_hit_stand ()
display_hands_after_flip ()

#Octomes
Who wins()
update_total ()

$$`` `$$
``````

## BlackJack in JavaScript – Code Review Stack Exchange

``````// variable / object declaration and initialization - start
const isDebug = false;
// const DELAY = 2000;
var gameOver = wrong;
const deck = {
Cards: []
}

var tempCard;
const player = {
Cards: [],
HandValue: 0,
isWinner: wrong,
canHit: true,
hasAce: wrong
}

const dealer = {
Cards: [],
HandValue: 0,
isWinner: wrong,
canHit: true,
hasAce: wrong
}

var result = document.getElementById ("gameResult");

const cardSuit = ["hearts", "diams", "clubs", "spades"];
const cardFace = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

\$ ("checkmark Dealer"). hide ();
\$ ("checkmarkPlayer"). hide ();
\$ ("# handValueDealer"). hide ();
// variable / object declaration and initialization - end

// var x = document.getElementById ("myAudio");

// function playAudio () {
// x.play ();
//}

if (! isDebug) {
document.getElementById ("btnDevelopment"). style.display = "none";
document.getElementById ("deck"). style.display = "none";
document.getElementById ("oneDeck"). style.display = "none";
document.getElementById ("playerCards"). style.display = "none";
document.getElementById ("dealerCards"). style.display = "none";
//document.getElementById("result").style.display = "none";
} else {
document.getElementById ("btnDevelopment"). style.display = "block";
document.getElementById ("deck"). style.display = "block";
document.getElementById ("oneDeck"). style.display = "block";
document.getElementById ("playerCards"). style.display = "block";
document.getElementById ("dealerCards"). style.display = "block";
//document.getElementById("result").style.display = "block";
}

const showGameButtons = (cardDealt) => {
if (cardDealt) {
\$ ("# btnDeal"). hide ();
\$ ("# btnHit"). show ();
\$ ("# btnStand"). show ();

//document.getElementById("btnDeal").disabled = true;
//document.getElementById("btnHit").disabled = false;
//document.getElementById("btnStand").disabled = false;
} else {
\$ ("# btnDeal"). show ();
\$ ("# btnHit"). hide ();
\$ ("# btnStand"). hide ();

//document.getElementById("btnDeal").disabled = false;
//document.getElementById("btnHit").disabled = true;
//document.getElementById("btnStand").disabled = true;
}

if (player.isWinner === true) {
document.getElementById ("containerDealer"). classList.remove ("winner");
document.getElementById ("containerPlayer"). classList.add ("winner");

\$ ("# handValueDealer"). show ();
\$ ("checkmarkPlayer"). show ();
\$ ("checkmark Dealer"). hide ();
} else if (dealer.isWinner === true) {
document.getElementById ("containerPlayer"). classList.remove ("winner");
document.getElementById ("containerDealer"). classList.add ("winner");

\$ ("# handValueDealer"). show ();
\$ ("checkmarkPlayer"). hide ();
\$ ("checkmark Dealer"). show ();
} else {

}
}
showGameButtons (false);

// In JavaScript, functions are objects.
// You can work with functions as if they were objects.
Feature card (suit, face) {
this.suit = suit;
this.face = face;

Switch (face) {
Case "A":
this.faceValue = 11;
break;
Case "J":
Case "Q":
Case "K":
this.faceValue = 10;
break;
Default:
this.faceValue = parseInt (face);
break;
}
};

const createDeck = () => {
deck.cards = [];
deck.cards.length = 0;
cardSuit.forEach (function (suit) {
cardFace.forEach (function (face) {
deck.cards.push (new card (suit, face));
});
});
}

const shuffleDeck = () => {
// Fisher-Yates shuffle algorithm
leave temp, i, rnd;
for (i = 0; i < deck.cards.length; i++) {
rnd = Math.floor(Math.random() * deck.cards.length);
temp = deck.cards[i];
deck.cards[i] = deck.cards[rnd];
deck.cards[rnd] = temp;
}
}

const newDeck = () => {
createDeck ();
shuffleDeck ();
document.getElementById ("oneDeck"). innerHTML = "";

player.cards = [];
player.handValue = 0;

dealer.cards = [];
dealer.handValue = 0;

var myNode = document.getElementById ("cardContainerPlayer");
var fc = myNode.firstChild.firstChild;

while (fc) {
myNode.removeChild (fc);
fc = myNode.firstChild;
}

var myNodeDealer = document.getElementById ("cardContainerDealer");
var fcDealer = myNodeDealer.firstChild.firstChild;

while (fcDealer) {
myNodeDealer.removeChild (fcDealer);
fcDealer = myNodeDealer.firstChild;
}

document.getElementById ("playerCards"). innerHTML = "";
document.getElementById ("dealerCards"). innerHTML = "";

document.getElementById ("oneDeck"). innerHTML = JSON.stringify (deck);
}

const burnOneCard = () => {
// Remove the upper deck for burning
deck.cards.splice (0, 1);
}

const showDeck = () => {
document.getElementById ("oneDeck"). innerHTML = JSON.stringify (deck);
}

const dealOneCardToPlayer = (x, isHit) => {
// return new promise (function (resolution) {
// setTimeout (function () {
// Take a card from the top deck to assign it to the tempcard.
tempCard = deck.cards.splice (0, 1);

//console.log(tempCard[0].Face);
//console.log(tempCard[0].faceValue);

player.cards.push (TempCard);

//console.log(player.handValue);

if (tempCard[0].face === "A") {
player.hasAce = true;
}

player.handValue = countHandValue (TempCard[0], Player, isHit);
document.getElementById ("handValuePlayer"). innerHTML = player.handValue;

// if (player.cards.length === 5) {
// player.canHit = false;
//}

// Conditional (ternary) operator
player.canHit = player.cards.length === 5? False right

if (player.canHit) {
\$ ("# btnHit"). show ();
} else {
\$ ("# btnHit"). hide ();
}

//player.cards.push(new card ("Pik", "A"));
//player.cards.push(new card ("Pik", "10"));
document.getElementById ("playerCards"). innerHTML = JSON.stringify (player);

makeCardPlayer (TempCard)[0]);
// to solve ();
//     }, DELAY);
//});

}

const dealOneCardToDealer = (holeCard, isHit) => {
// return new promise (function (resolution) {
// setTimeout (function () {
// Take a card from the top deck to assign it to the tempcard.
tempCard = deck.cards.splice (0, 1);

//console.log(tempCard[0].Face);
//console.log(dealer.handValue);

if (tempCard[0].face === "A") {
dealer.hasAce = true;
}

dealer.handValue = countHandValue (TempCard)[0]Dealer, isHit);
document.getElementById ("handValueDealer"). innerHTML = dealer.handValue;

Dealer.cards.push (TempCard);

//dealer.handValue = countHandValue (TempCard[0]);

// Conditional (ternary) operator
dealer.canHit = dealer.cards.length === 5? False right

if (dealer.canHit) {
\$ ("# btnHit"). show ();
} else {
\$ ("# btnHit"). hide ();
}

document.getElementById ("dealerCards"). innerHTML = JSON.stringify (dealer);

makeCard Dealer (TempCard)[0]holecard);
// to solve ();
//     }, DELAY);
//});
}

const countAllHandValue = (cardsOnHand) => {
//console.log(hasAceInHand(cardsOnHand));
be sum = 0;
for (let keys cardsOnHand on)
Let arr = cardsOnHand[key];
for (let i = 0; i < arr.length; i++) {
let obj = arr[i];
for (let prop in obj) {
if (prop === "faceValue") {
sum = sum + obj[prop];
}
}
}
}
return sum;
}

const countHandValue = (onecard, person, isHit) => {
if (isHit) {
// Only an Ace can be covered for this solution. More than one ace will be a mistake.
if (person.handValue> 10 && person.hasAce === true) {
person.cards.forEach (card => {
Console.log (card[0]);
if (card[0].face === & # 39; A & # 39;) card[0].faceValue = 1;
Return the card[0];
});
person.handValue = countAllHandValue (person.cards);
// Loop through the whole ace and transform the whole value of the ace from 11 to 1
// recalculate all cards.
} else {
person.handValue = person.handValue + onecard.faceValue;
}
} else {
person.handValue = person.handValue + onecard.faceValue;
}

//console.log(person.handValue);
//console.log(onecard);

return person.handValue;
}

const showHandValue = () => {
document.getElementById ("playerCardsHandValue"). innerHTML = player.handValue;
document.getElementById ("dealerCardsHandValue"). innerHTML = dealer.handValue;
}

const getDeckCardCount = () => {
document.getElementById ("deckCardCount"). innerHTML = deck.cards.length;
}

const checkGameOver = () => {
if (gameOver) {
\$ (". holeCard>: nth-child (1)"). show ();
\$ (". holeCard>: nth-child (2)"). show ();

\$ ("holeCard"). removeClass ("holeCard");
\$ ("# handValueDealer"). show ();

showGameButtons (false);
}
}

const checkEndGame1 = () => {
gameOver = true;
if (player.handValue === 21 && dealer.handValue! == 21) {
result.innerHTML = "BlackJack! player won.";
player.isWinner = true;
} else if (player.handValue! == 21 && dealer.handValue === 21) {
result.innerHTML = "BlackJack! Dealer Won.";
dealer.isWinner = true;
} else if (player.handValue === 21 && dealer.handValue === 21) {
result.innerHTML = "Push";
} else {
gameOver = false;
}
}

const checkEndGame2 = () => {
if (player.cards.length <= 5 && player.handValue > 21) {
result.innerHTML = "Bust! Merchant won.";
dealer.isWinner = true;
gameOver = true;
}
}

const checkEndGame3 = () => {

if (player.cards.length <= 5 && dealer.cards.length <= 5) {
// check the bust
if (player.handValue <= 21 && dealer.handValue > 21) {
result.innerHTML = "Bust! Player won.";
player.isWinner = true;
} else if (player.handValue === 21 && dealer.handValue! == 21) {
result.innerHTML = "BlackJack! player won.";
player.isWinner = true;
} else if (player.handValue! == 21 && dealer.handValue === 21) {
result.innerHTML = "BlackJack! Dealer Won.";
dealer.isWinner = true;

} else if (player.handValue === dealer.handValue) {
result.innerHTML = "Push";
} else if (player.handValue> dealer.handValue) {
result.innerHTML = "Player won.";
player.isWinner = true;
} else if (player.handValue.) < dealer.handValue) {
result.innerHTML = "Dealer won.";
dealer.isWinner = true;
} else {
result.innerHTML = "Error";
}
} else {
result.innerHTML = "Error";
}
gameOver = true;
}

// This function use JQuery lib
function makeCardPlayer(_card) {
// .card is created in the template card css class
var card = \$(".card.templatePlayer").clone();

card.removeClass("templatePlayer");

// .cardFace is created in the template card css class
// It will search for this css class and add the content aka innerHTML
card.find(".playerCardFace").html(_card.face);

// .suit is created in the template card css class
// It will search for this css class and add the content aka innerHTML
card.find(".playerCardSuit").html("&" + _card.suit + ";");
// ♠ -> ♠, & clubs; -> ♣ & hearts; -> ♥, & Diams; -> ♦
// more characters, https://www.w3schools.com/charsets/ref_utf_symbols.asp

// Hearts and diamonds are red. Otherwise standard color is black.
if (_card.suit === "Hearts" || _card.suit === "Diams") {
}

// Option: replace previous card with new card (always show one card)
\$ ("# cardContainerPlayer"). append (card);
}

// This function uses JQuery lib
Function makeCardDealer (_card, _holeCard) {
// .card is created in the CSS class for template cards
var card = \$ ("card.templateDealer"). clone ();

card.removeClass ("templateDealer");

// .cardFace is created in the CSS class for template cards
// It searches for this CSS class and calls its content innerHTML
card.find ("dealerCardFace"). html (_card.face);

// .suit is created in the CSS class for template cards
// It searches for this CSS class and calls its content innerHTML
card.find ("dealerCardSuit"). html ("&" + _card.suit + ";");
// & spades; -> ♠, & clubs; -> ♣ & hearts; -> ♥, & Diams; -> ♦
// more characters, https://www.w3schools.com/charsets/ref_utf_symbols.asp

// Hearts and diamonds are red. Otherwise standard color is black.
if (_card.suit === "Hearts" || _card.suit === "Diams") {
}

if (_holeCard) {
}

// Option: replace previous card with new card (always show one card)
\$ ("#cardContainerDealer"). append (card);

\$ (". holeCard>: nth-child (1)"). hide ();
\$ (". holeCard>: nth-child (2)"). hide ();

}

const deal = () => {
newDeck ();

// Option: burn the first card before a card is dealt
// to the first player
burnOneCard;

// dealOneCardToPlayer ()
// .then (dealOneCardToDealer)
// .then (dealOneCardToPlayer)
// .then (dealOneCardToDealer (true));

dealOneCardToPlayer ("", false);
dealOneCardToDealer (false, false);
dealOneCardToPlayer ("", false);

// true for hole card
dealOneCardToDealer (true, false);

showGameButtons (true);
checkEndGame1 ();
checkGameOver ();
}

const hit = () => {
dealOneCardToPlayer ("", true);
checkEndGame2 ();
checkGameOver ();
}

const stand = () => {
// Recalculate dealer's dealer value
//dealer.handValue = countAllHandValue (dealer.cards);

// Simple AI to automate the dealer's decision to hit or stand
if (dealer.handValue> = 17) {
checkEndGame3 ();
} else {
// Hit until the dealer's hand value is more than 16
while (dealer.handValue <17) {
dealOneCardToDealer (false, true);
checkEndGame3 ();
}
}
checkGameOver ();
}``````
``````Body{
Font size: 2em;
}

h3, h5 {
Align text: center;
}

h5 {
Top edge: -40px;
}

/ * Purpose of troubleshooting * /
div #oneDeck {
Edge: 1px solid green;
Margin: 10px;
}

/ * Purpose of troubleshooting * /
div # playerCards {
Edge: 1px continuous blue;
Margin: 10px;
}

/ * Purpose of troubleshooting * /
div # dealerCards {
Border: 1px continuous red;
Margin: 10px;
}

#mainContainer {
Max width: 600px;
Margin: 0 car;
}

Fieldset {
Top edge: 30px;
Limit: 1px fixed # 999;
Box Shadow: 0 0 10px # 999;
}

Legend {
Background: #fff;
}

#cardContainerPlayer {
Display: Flex;
Flex Wrap: Wrap;
}

Card {
Display: Inline block;
align vertically: above; / * float: left; * /
Align text: center;
Margin: 5px;
Width: 70px;
Height: 100px;
Font size: 26px;
Background color: black;
Border: fixed 1px black;
Color white;
}

.holeCard {
/ * Visibility: hidden; * /
Border: fixed 1px black;
Background: repeating linear gradient (45 degrees, # 606dbc, # 606dbc 10px, # 465298 10px, # 465298 20px);
}

red
Background color: red;
Border: stuck 1px # 8C001A;
}

.templatePlayer, .templateDealer {
Display: none;
}

#btnGame {
Margin: 10px;
}

Winner
Border: tight 5px # 7ac142;
}

.btnGame {
Background color: dodgerblue; / * Green * /
Border: none;
Color white;
Upholstery: 15px 32px;
/ * Edge radius: 10px; * /
Align text: center;
Text decoration: none;
Display: Inline block;
Font size: 16px;
Cursor: pointer;
-webkit transition time: 0.4 s; / * Safari * /
Transitional period: 0.4 s;
Box Shadow: 0 8px 16px 0 rgba (0,0,0,0,2), 0 6px 20px 0 rgba (0,0,0,0,19);
}

#btnHit {
Right edge: 20px;
}

.flex-container {
Margin: 0;
Display: Flex;
Reason for justification: space;
Max width: 100%;
Overflow: car;
/ * Border: 1px solid red * /
}``````
``````

Simple javascript blackjack game
developed by Steve Ngai

Remaining maps in the deck:

Dealer (Hand Value: )

Player (value of the hand: )

Game result

``````

## python – Blackjack game with database

This is the latest version of my blackjack game, and I've made a pretty big update. Now you can create an account that is stored in the MySQL database and you can bet money that is also stored in the database.

``````from random import shuffle
import os
import cymysql
from passport import passport
Import sys

def shuffled_shoe ():
Shoe ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'A', 'J', 'Q', 'K']* 4
Shuffle (Shoe)
back shoe

def deal_card (shoe, person, number):
for _ in the range (number):
person.append (shoe.pop ())

def deal_hand (shoe, player, dealer):
deal_card (Shoe, Player, 2)
deal_card (shoe, dealer, 2)

Def Score (person):
non_aces = [c for c in person if c != 'A']
Aces = [c for c in person if c == 'A']
total = 0
for card in non_time:
if card in & # 39; JQK & # 39 ;:
total + = 10
otherwise:
total + = int (map)
for the map in Assen:
if totally <= 10:
total += 11
else:
total += 1

def display_info(still_playing, player, dealer, money, money_bet, player_stands):
os.system('cls' if os.name == 'nt' else 'clear')
print(f"Money: \${money}")
print(f"Money bet: \${money_bet}")
print("Your cards:   [{}] ({})".format("][".join(player), score(player)))
if player_stands:
print("Dealer cards: [{}] ({})".format("][".join(dealer), score(dealer)))
else:
print("Dealer cards: [{}][?]".format(dealer[0]))
first_hand = len(dealer) == 2
if score(player) == 21:
print("Blackjack! You won")
still_playing = False
money += money_bet * 2
elif first_hand and score(dealer) == 21:
print("Dealer got a blackjack. You lost!")
still_playing = False
elif score(player) > 21
print ("Busted, you lost!")
still_playing = Wrong
if player stands:
if score (dealer)> 21:
print ("The dealer is broken, you won")
Money + = Money_Bet * 2
Elif Score (Player)> Score (Vendor):
print ("You beat the dealer! You won!")
Money + = Money_Bet * 2
Elif Score (Player) < score(dealer):
print("Dealer has beaten you. You lost!")
else:
print("Push. Nobody wins or losses.")
money += money_bet
still_playing = False
return still_playing, money

def hit_or_stand():
while True:
print("What do you choose?")
print("[1] Hit")
print("[2] Stand")
ans = input("> ")
if ans in in & # 39; 12 & # 39 ;:

def bet ():
print ("How much money do you want to spend?")
money = int (input (">"))
return money

def player_play (shoe, player, dealer, money, money_bet, player_plays, player_stands):
while not player stalls:
if hit_or_stand () == & # 39; 2 & # 39 ;:
player_stands = Right
player_plays = Wrong
elif not player stands:
deal_card (shoe, player, 1)
display_info (True, Player, Dealer, Money, Money Concrete, Player Stands)
if score (player)> = 21:
player_plays = Wrong
break
return player_plays, player_stands

def dealer_play (shoe, dealer, DEALER_MINIMUM_SCORE):
during the score (dealer) <= DEALER_MINIMUM_SCORE:
deal_card(shoe, dealer, 1)
return False

def play_again(cur, money):
while True:
print("nDo you want to play again?")
print("[1] Yes")
print("[2] No")
ans = input("> ")
if ans == & # 39; 1 & # 39 ;:
hand back
elif ans == & # 39; 2 & # 39 ;:
cur.execute ("UPDATE" user "SET" money "=% s", (money))
cur.close ()
return incorrectly

def get_user_info ():
while true:
E-Mail = Input ("E-Mail-Address (up to 255 characters.):")
password = getpass ("Password (up to 255 characters.):")
if len (email) <255 and len (password) < 255:

def register(cur, email, password):
cur.execute("INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)", (email, password))

cur.execute("SELECT * FROM `users` WHERE `Email`=%s AND `Password`=%s LIMIT 1", (email, password))
return bool(cur.fetchall())

def check_account(cur, email):
cur.execute("SELECT * FROM `users` WHERE `Email`=%s LIMIT 1", (email,))
return bool(cur.fetchone())

def start():
print("Do you want to start playing? (Y)es/(N)o")
ans = input("> ").lower()
if ans == & # 39; y & # 39 ;:
hand back
elif ans == & nb; n & # 39 ;:
return incorrectly

def main ():
conn = cymysql.connect (
host = & # 39; 127.0.0.1 & # 39 ;,
user = & # 39 ;, root & # 39 ;,
passwd = & # 39 ;,
db = & # 39; blackjack & # 39;
)
with conn:
cur = conn.cursor ()
email, password = get_user_info ()
checked = check_account (current, e-mail)
if marked:
logged in = login (cur, email, password)
when logged in:
print ("You have successfully registered!")
otherwise:
sys.exit ()
otherwise:
register (cur, email, password)
print ("You have successfully registered and received \$ 1000!")
cur.execute ("SELECT" money "FROM" user "WHERE" email "=% s") (email,)
money = cur.fetchone ()
Cash = money[0]
keeps_playing = start ()
at keep_playing:
shoe = shuffled_shoe ()
Player = []
Dealer = []
still_playing = Right
player_plays = Right
player_stands = False
money_bet = bet ()
cash - = money_bet
deal_hand (shoe, player, dealer)
still_playing, cash = display_info (still_playing, player, dealer, cash, money, player's stalls)
while breastfeeding:
during player_plays:
player_plays, player_stands = player_play (shoe, player, dealer, cash, money_bet, player_plays, player_stands)
still_playing = dealer_play (shoe, dealer, 17)
still_playing, cash = display_info (still_playing, player, dealer, cash, money, player's stalls)
keeps_playing = play_again (cur, cash)

If __name__ == & # 39; __ main __ & # 39 ;:
Main()
``````

## Game – JavaScript BlackJack prototype

Create BlackJack in JavaScript and decide to get started right away to try things out first. Now I'm at the point where I want to think about how best to organize this and maybe start with empty boards.

Specific areas:

• What's the best way to update the UI?
• Incorporation of dealer's hand in the hand class to reduce repeatability
• The nested IFs may be reduced
• Inclusion of the split

I was not worried about the betting / payouts / chip counts for this prototype, but of course that is added.

Code:

``````

Early prototype of BlackJack

.flex line {
Display: Flex;
Flex-Flow: line break;
Justification content: spaces;
}

const suits = [
{
digit: 'H',
word: 'hearts'
},
{
digit: 'C',
word: 'clubs'
},
{
digit: 'D',
word: 'diamonds'
},
{
digit: 'S',
}
]
const cardsWithoutSuits = [
{
numeric: 11,
word: 'ace',
digit: 'A'
},
{
numeric: 2,
word: 'two',
},
{
numeric: 3,
word: 'three',
},
{
numeric: 4,
word: 'four',
},
{
numeric: 5,
word: 'five',
},
{
numeric: 6,
word: 'six',
},
{
numeric: 7,
word: 'seven',
},
{
numeric: 8,
word: 'eight',
},
{
numeric: 9,
word: 'nine',
},
{
numeric: 10,
word: 'ten',
},
{
numeric: 10,
word: 'jack',
digit: 'J'
},
{
numeric: 10,
word: 'queen',
digit: 'Q'
},
{
numeric: 10,
word: 'king',
digit: 'K'
}
]

class Hand{
constructor(bet){
// assigning the bet value
this.bet = bet;
// default values, no cards dealt yet
this.cards = [];
this.value = 0;
this.blackjack = false;
this.soft = false;
this.bust = false;
this.winner = false;
this.aceQuantity = 0;
this.canHit = false;
this.canStay = false;
this.canSplit = false;
this.canDouble = false;
this.finished = false;
this.textResult = '';
this.payout = 0;
};
evaluate(){
this.aceQuantity = this.cards.filter(x => x.word === 'ace').length;
this.value = this.cards.filter(x => x.word !== 'ace').reduce((total, x) => +total + x.numeric, 0);
this.soft = false;
for (var i = 0; i < this.aceQuantity; i++) {
if (this.value + 11 > 21) this.value += 1;
else {
this.value +=11;
if (this.value !== 21) this.soft = true;
}
}

if (this.cards.length === 2) {
this.canDouble = true;
this.canSplit = this.cards[0].word === this.cards[1].word;
} else {
this.canSplit = false;
this.canDouble = false;
}

if (this.value > 21){
this.bust = true;
this.finished = true;
this.canHit = false;
this.canStay = false;
}

if(this.value === 21){
this.finished = true;
this.canHit = false;
if (this.cards.length === 2) {
this.blackjack = true;
}
}

if (this.bust) {
this.textResult = `Busted!`;
this.payout = 0;
} else if (this.blackjack) {
this.textResult = `BlackJack!`;
} else if (game.dealerFinished) {
if (this.finished) {
if (game.dealerValue > 21) {
this.textResult = `Winner!`;
} else if (this.value > game.dealerValue) {
this.textResult = `Winner!`;
} else if (this.value === game.dealerValue) {
this.textResult = `Push`;
} else if (this.value < game.dealerValue) {
this.textResult = `Loser`;
}
}
} else {
this.textResult = `Standing on \${this.value}`;
}
}
}

function createDeck(decks = 1){
let deck = [];
for (let i = 0; i < decks; i++) {
suits.forEach( x => {
cardsWithoutSuits.forEach( y => {
deck.push({
numeric: y.numeric,
word: y.word,
suit: x.word,
phrase: `\${y.word} of \${x.word}`,
abbr: `\${y.hasOwnProperty('digit') ? y.digit : y.numeric}\${x.digit}`
})
})
})
}
return deck;
}

function shuffle(array){
let array2 = [];
while (array.length){
let index = Math.floor(Math.random() * array.length);
let card = array.splice(index, 1);
array2.push(card[0]);
}
return array2;
}

let game = {
state: 'start',
deck: [],
dealerCards: [],
dealerFinished: false,
dealerValue: 0,
hands: [],
shuffle: function(){
this.deck = shuffle(createDeck(4));
},
deal: function(){
this.hands.forEach(x => {
x.cards.push(this.deck.shift());
x.evaluate();
});
this.dealerCards.push(this.deck.shift());
this.hands.forEach(x => {
x.cards.push(this.deck.shift());
x.evaluate();
});
this.dealerCards.push(this.deck.shift());
},
tempCreateTestHands: function(){
this.hands.push(new Hand(5));
this.hands.push(new Hand(10));
this.hands.push(new Hand(25));
},
dealCard: function(hand){
if (hand === -1) {
this.dealerCards.push(this.deck.shift());
updateUI();
} else {
this.hands[hand].cards.push(this.deck.shift());
this.hands[hand].evaluate();
}
},
tempStart: function(){
game.dealerFinished = false;
game.hands = [];
game.dealerCards = [];
if (game.deck.length < 30) game.shuffle();
game.tempCreateTestHands();
game.deal();
updateUI();
},
let aceQuantity = this.dealerCards.filter(x => x.word === 'ace').length;
let value = this.dealerCards.filter(x => x.word !== 'ace').reduce((total, x) => +total + x.numeric, 0);
for (var i = 0; i < aceQuantity; i++) {
if (value + 11 > 21) value += 1;
else {
value +=11;
}
}
this.dealerValue = value;
if (value < 17) {
this.dealCard(-1);
} else {
this.dealerFinished = true;
game.hands.forEach(x => x.evaluate());
updateUI();
}
}

}

game.tempStart();

function updateUI(){
const playersUI = [document.getElementById('hand1'), document.getElementById('hand2'), document.getElementById('hand3')];
const dealer = document.getElementById('dealer');

const handsRemaining = game.hands.filter(x => !x.finished).length;
if (handsRemaining) dealer.innerHTML = `<h2>Dealer</2><p>Card Hidden</p><p>\${game.dealerCards[1].phrase}</p><p>Showing \${game.dealerCards[1].numeric}</p>`;
else dealer.innerHTML = `<h2>Dealer</2>` + game.dealerCards.map(x => `<p>\${x.phrase}</p>`).join('') + `<p>Total: \${game.dealerValue}</p>`;

if (!handsRemaining && !game.dealerFinished) {
}

for (var i = 0; i < game.hands.length; i++) {
let buttons = '';
if (game.hands[i].finished){
buttons += `<div>`;
if (game.hands[i].busted) buttons +=`BUSTED`;
else {
buttons += game.hands[i].textResult;
}

buttons += `</div>`
} else {

buttons += `<div>
<button class='hit' onclick="buttonHandler(\${i}, 'hit')">HIT</button>
<button class='stay' onclick="buttonHandler(\${i}, 'stay')">STAY</button>
`;
if (game.hands[i].canDouble) buttons +=`<button class='double' onclick="buttonHandler(\${i}, 'double')">DOUBLE</button>`;
if (game.hands[i].canSplit) buttons +=`<button class='split' onclick="buttonHandler(\${i}, 'split')">SPLIT</button>`;
buttons += `</div>`;
}
playersUI[i].innerHTML = `<h2>Hand \${i + 1}</2>` + game.hands[i].cards.map(x => `<p>\${x.phrase}</p>`).join('') + `<p>Total: \${game.hands[i].soft ? 'Soft' : ''} \${game.hands[i].value}</p>\${buttons}`;
}
}

function buttonHandler(playerHand, action){
switch (action) {
case 'stay':
game.hands[playerHand].finished = true;
break;
case 'hit':
game.dealCard(playerHand);
break;
case 'double':
game.dealCard(playerHand);
game.hands[playerHand].finished = true;
game.hands[playerHand].bet = game.hands[playerHand].bet * 2;
break;
case 'split':
console.log(`split function not setup yet...`);
break;
default:
console.log(`error, cannot find \${action} in the switch statement.`);
}

updateUI();
}

document.getElementById("deal").onclick = function() {
game.tempStart();
}

``````

## My BlackJack game in the C # console

What do you think about my BlackJack game in terms of object-oriented programming?

My code is at https://github.com/ngaisteve1/BlackJack

``````with system;

public class BlackJackGame
{
private static cover card deck;
public void play ()
{
bool continuePlay = true;

Console.Title = "Steve BlackJack Game (Version 2)";
Console.Write ("Steve BlackJack Game");
Utility.MakeColor2 ("♠", ConsoleColor.White);
Utility.MakeColor2 ("♥", ConsoleColor.Red);
Utility.MakeColor2 ("♣", ConsoleColor.White);
Utility.MakeColor2 ("♦", ConsoleColor.Red);

deck = new deckCard ();
Console.Write (" n  nEnter the name of the player:");

// Create a player
var player = new player (Console.ReadLine ());

// Create dealer
var dealerComputer = new player ();

while (continue)
{
// initialize screen and certain properties of the player - start
Console.Clear ();
player.IsNaturalBlackJack = false;
player.IsBusted = false;
dealerComputer.IsNaturalBlackJack = false;
dealerComputer.IsBusted = false;
// initialize screen and certain properties of the player - end

if (deck.GetRemainingDeckCount () <20)
{
// Get a new mixed deck.
deck.Initialize ();
Console.WriteLine ("Low number of cards left, new cold deck created.");
}

deck.ShowRemainingDeckCount ();

// Show player bankroll
Console.WriteLine (\$ "{player.Name} Chips Balance: {player.ChipsOnHand}");

// Retrieve bets from the player
Console.Write ("Enter the amount of the chip bet:");
player.ChipsOnBet = Convert.ToInt16 (Console.ReadLine ());

// Distribute the first two cards to the player
deck.DealHand (player);

// Show the player's hand
player.ShowUpCard ();

// Distribute the first two cards to the dealer
deck.DealHand (dealerComputer);

// Show the dealer's hand
dealerComputer.ShowUpCard (true);
// Check the natural black socket
if (! checkNaturalBlack (Player, DealerComputer))
{
// If both do not have natural black sockets
// then it's the player's turn to continue.
PlayerAction (player);

Console.WriteLine (" n --------------------------------------- --- ");

PlayerAction (DealerComputer);

Console.WriteLine (" n --------------------------------------- --- ");

// announce the winner.
AnnounceWinner (player, dealer computer);
}

Console.WriteLine ("This round is over.");

Console.Write (" nRepeat? J or N?");

continuePlay = Console.ReadLine () == "Y"? true wrong;
// for the sake of brevity, no input validation
}

Console.WriteLine (\$ "{player.Name} won {player.TotalWins} times.");
Console.WriteLine (\$ "{dealerComputer.Name} won {dealerComputer.TotalWins} times.");
Console.WriteLine ("game over, thank you for playing.");

}

private static empty PlayerAction (Player currentPlayer)
{
// put on the player's turn

bool playerTurnContinue = true;

String opt = "";

while (playerTurnContinue)
{
Console.Write (\$ " n {currentPlayer.Name}'s turn.");

if (currentPlayer.Name.Equals ("Dealer"))
{
Thread.Sleep (2000); // before thinking
// Mini A.I for dealers.
opt = currentPlayer.GetHandValue () < 16 ? "H" : "S";
}
else
{
// Prompt player to enter Hit or Stand.
Console.Write("Hit (H) or Stand (S): ");
}

switch (opt.ToUpper())
{
case "H":
Console.Write(\$"{currentPlayer.Name} hits. ");
// Take a card from the deck and put into player's Hand.

// Check if there is any Ace in the Hand. If yes, change all the Ace's value to 1.
if (currentPlayer.GetHandValue() > 21 && currentPlayer.CheckAceInHand ())
currentPlayer.Hand = currentPlayer.ChangeAceValueInHand ();

currentPlayer.ShowHandValue ();

break;
Cases":
if (currentPlayer.GetHandValue ()) < 16)
Console.WriteLine(\$"{currentPlayer.Name} is not allowed to stands when hand value is less than 16.");
else
{
Console.WriteLine(\$"{currentPlayer.Name} stands.");
// Show player's hand
currentPlayer.ShowUpCard();
Console.WriteLine(\$"{currentPlayer.Name}'s turn is over.");
playerTurnContinue = false;
}

break;
default:
Console.WriteLine("Invalid command.");
break;
}

// If current player is busted, turn is over.
if (currentPlayer.GetHandValue() > 21)
{
Utility.MakeColor ("Busted!", ConsoleColor.Red);
Console.WriteLine (\$ "{currentPlayer.Name}'s turn.");
currentPlayer.IsBusted = true;
playerTurnContinue = false;
}
// If the current player's total card is 5, the turn is over.
else if (currentPlayer.Hand.Count == 5)
{
Console.WriteLine (\$ "{currentPlayer.Name} already has 5 cards in your hand.");
Console.WriteLine (\$ "{currentPlayer.Name}'s turn.");
playerTurnContinue = false;
}

}
}

private static bool checkNaturalBlack (player _player, player _dealer)
{
Console.WriteLine ();
if (_dealer.IsNaturalBlackJack && _player.IsNaturalBlackJack)
{
Console.WriteLine ("Players and Dealers Have Natural BlackJack Tie Ties!");
_dealer.ShowUpCard ();

return true;
}
else if (_dealer.IsNaturalBlackJack &&! _player.IsNaturalBlackJack)
{
Console.WriteLine (\$ "{_ dealer.Name} has won natural BlackJack. {_Dealer.Name}!);
_dealer.ShowUpCard ();
_player.ChipsOnHand = _player.ChipsOnHand - (int) Math.Floor (_player.ChipsOnBet * 1.5);
return true;
}
else if (! _dealer.IsNaturalBlackJack && _player.IsNaturalBlackJack)
{
Console.WriteLine (\$ "{_ player.Name} has won natural BlackJack. {_Player.Name}!);
_player.ChipsOnHand = _player.ChipsOnHand + (int) Math.Floor (_player.ChipsOnBet * 1.5);
return true;
}

// protection block
return it incorrectly;
}

private static void AnnounceWinner (player _player, player _dealer)
{
Console.WriteLine ();
if (! _dealer.IsBusted && _player.IsBusted)
{
Console.WriteLine (\$ "{_ dealer.Name} won.");
}
else if (_dealer.IsBusted &&! _player.IsBusted)
{
Console.WriteLine (\$ "{_ player.Name} won.");
_player.ChipsOnHand = _player.ChipsOnHand + _player.ChipsOnBet;
}
else if (_dealer.IsBusted && _player.IsBusted)
Console.WriteLine ("tie game");
else if (! _dealer.IsBusted &&! _player.IsBusted)
if (_player.GetHandValue ()> _dealer.GetHandValue ())
{
Console.WriteLine (\$ "{_ player.Name} won.");
_player.ChipsOnHand = _player.ChipsOnHand + _player.ChipsOnBet;
}
else if (_player.GetHandValue () <_dealer.GetHandValue ())
{
Console.WriteLine (\$ "{_ dealer.Name} won.");
_player.ChipsOnHand = _player.ChipsOnHand - _player.ChipsOnBet;
}

else if (_player.GetHandValue () == _dealer.GetHandValue ())
Console.WriteLine ("tie game");

}
``````

}

## c # Blackjack game [on hold]

``````                                static void shuffle(this IList List)
{
Random random = new random ();
int n = list.Count;

for (int i = list.Count - 1; i> 1; i--)
{
int rnd = random. Next (i + 1);
T-value = list[rnd];
list[rnd] = List[i];
list[i] = Value;
}
}

static void Main (String[] args)
{
Random rand = new Random ();

list Map = new list(52);

for (int i = 1; i <= 52; i ++)
{
}

card.Shuffle ();

int count = 0;

while (count < 2)
{
int card_suit = rand.Next(1, 5);

if (card >= 2 && card <= 10)
{
Console.Write (card);
}
``````

Error CS0019: Operator & # 39;; = & # 39; can not access operands of List & # 39; & # 39; and & # 39; Int & # 39; be applied