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;
Suitcase Suit.Spades:
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;

person.Hand.Add (card);
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;
using System.Threading;

// 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;

//Hand.Add(card); // Background
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 ()
{
Console.Write ("Loading");
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;
using System.Threading;

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)
{
Thread.Sleep (milliseconds);
}

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

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

Blackjack Game class

using system;
using System.Threading;

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): ");
            opt = Console.ReadLine();
        }

        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.AddWinCount ();
_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.");
_dealer.AddWinCount ();
_player.ChipsOnHand - = _player.ChipsOnBet;
}
otherwise if (_dealer.IsBusted &&! _player.IsBusted)
{
Console.WriteLine ($ "{_ player.Name} won.");
_player.AddWinCount ();
_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.AddWinCount ();
_player.ChipsOnHand + = _player.ChipsOnBet;
}
otherwise if (_player.GetHandValue () <_dealer.GetHandValue ())
{
Console.WriteLine ($ "{_ dealer.Name} won.");
_dealer.AddWinCount ();
_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;
Suitcase Suit.Spades:
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;

person.Hand.Add (card);
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;
using System.Threading;

// 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;

//Hand.Add(card); // Background
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 ()
{
Console.Write ("Loading");
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;
using System.Threading;

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)
{
Thread.Sleep (milliseconds);
}

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

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

Blackjack Game class

using system;
using System.Threading;

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): ");
            opt = Console.ReadLine();
        }

        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.AddWinCount ();
_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.");
_dealer.AddWinCount ();
_player.ChipsOnHand - = _player.ChipsOnBet;
}
otherwise if (_dealer.IsBusted &&! _player.IsBusted)
{
Console.WriteLine ($ "{_ player.Name} won.");
_player.AddWinCount ();
_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.AddWinCount ();
_player.ChipsOnHand + = _player.ChipsOnBet;
}
otherwise if (_player.GetHandValue () <_dealer.GetHandValue ())
{
Console.WriteLine ($ "{_ dealer.Name} won.");
_dealer.AddWinCount ();
_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
        menu()
    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)
            menu()
        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
def ask_for_bet ():
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:
add_bet = round (decimal (add_bet), 2)
if (add_bet> m.bank):
sleepy_print (" n  t! *** You do not have enough money to afford this bet! Try it again ***!")
ask_for_bet ()
elif (add_bet < 5):
            sleepy_print("nt!*** Bet is too low. Must meet the minimum ***!")
            ask_for_bet()
        else:
            m.bet += add_bet
            m.bank -= add_bet
    except:
        error_msg()
        ask_for_bet()

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 ()

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

# Options menu
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
Menu()
elif input_var == & # 39; X & # 39 ;:
sleepy_print (& # 39; sExiting ...  n & # 39;)
sys.exit ()
otherwise:
error_msg ()
Menu()

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
ask_for_bet ()
initial_deal ()
display_hands_before_flip ()
player_hit_stand ()
dealer_hit_stand ()
display_hands_after_flip ()

#Octomes
Who wins()
update_total ()

Menu()

`` `

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") {
card.addClass ("red");
}

// 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") {
card.addClass ("red");
}

if (_holeCard) {
card.addClass ("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;
Padding: 10px;
}

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

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

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

Fieldset {
Top edge: 30px;
Limit: 1px fixed # 999;
Boundary radius: 8px;
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;
Padding: 10px;
Width: 70px;
Height: 100px;
Font size: 26px;
Background color: black;
Border: fixed 1px black;
Color white;
Boundary radius: 10px;
}

.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 {
Padding: 0;
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
    return total


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 ;:
Return to


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:
            return email, password


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


def login(cur, 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:
print ("Login failed!")
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
    
  
  
    
    

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;
using System.Threading;

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 ();
Thread.Sleep (1500);

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

// Show the dealer's hand
dealerComputer.ShowUpCard (true);
Thread.Sleep (1500);
// 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): ");
            opt = Console.ReadLine();
        }

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

                // 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.");
                    Thread.Sleep(1500);
                    // Show player's hand
                    currentPlayer.ShowUpCard();
                    Thread.Sleep(1500);
                    Console.WriteLine($"{currentPlayer.Name}'s turn is over.");
                    Thread.Sleep(1500);
                    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);
Thread.Sleep (1500);
Console.WriteLine ($ "{currentPlayer.Name}'s turn.");
Thread.Sleep (1500);
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.");
Thread.Sleep (1500);
Console.WriteLine ($ "{currentPlayer.Name}'s turn.");
Thread.Sleep (1500);
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 ();
_dealer.AddWinCount ();
_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.AddWinCount ();
_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.");
_dealer.AddWinCount ();
}
else if (_dealer.IsBusted &&! _player.IsBusted)
{
Console.WriteLine ($ "{_ player.Name} won.");
_player.AddWinCount ();
_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.AddWinCount ();
_player.ChipsOnHand = _player.ChipsOnHand + _player.ChipsOnBet;
}
else if (_player.GetHandValue () <_dealer.GetHandValue ())
{
Console.WriteLine ($ "{_ dealer.Name} won.");
_dealer.AddWinCount ();
_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 add (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

python – Easier version of the BlackJack game – first oop

I've been learning Python for a few weeks. Last time I started object-oriented programming, and I feel like I'm having a hard time writing relationships between methods and attributes of different objects.

I tried to write a simpler version of the BlackJack card game with the hit or stand option only.

Could you look at my code and possibly give me advice on what to change or improve?

Thank you for taking the time.

import randomly

SUITS = ['Heart','Diamond','Club','Pike']
NUMBERS = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
Money = 200
MIN_BET = 2

Class card:
& # 39; & # 39; & # 39;
Single card class
Use it in a loop to create a full French card game
Print-Return & # 39; suit figure & # 39;
& # 39; & # 39; & # 39;

def __init __ (self, suit, figure):
Self-suit = suit
self.figure = figure

if self.figure == "A":
self.value = 11
elif self.figure in ['J','Q','K']:
self.value = 10
otherwise:
self.value = int (self.figure)

def __str __ (self):
return f & # 39; {self.figure} from {self.suit} & # 39;

def __repr __ (self):
return f & # 39; {self.figure} from {self.suit} & # 39;


Class Deck:

def __init __ (self):
self.deck = [Card(suit, figure) for suit in SUITS for figure in FIGURES]

    def shuffle (self):
Random mix (self-deck)

def draw (self):
return self.deck.pop (0)

def restart (self):
self.deck = [Card(suit, figure) for suit in SUITS for figure in FIGURES]

Class hand:
def __init __ (self):
self.cards = []
        self.value = 0
self.aces = 0

def add_card (self, card):
self.cards.append (card)
self.check_aces ()

def check_value (self):
& # 39; & # 39; & # 39;
Change self-esteem
Returns no value
& # 39; & # 39; & # 39;
ace = self.aces
self.value = 0

for i in range (len (self.cards)):
self.value + = self.cards[i].Value

while self.value> 21 and ass> 0:
Self-value - = 10
Ace - = 1

if self-worth> 21:
self.isBusted = True

return self.value

def check_aces (self):
& # 39; & # 39; & # 39;
Check if & # 39; A & # 39; is in the hand
& # 39; & # 39; & # 39;
self.aces = 0

for i in range (len (self.cards)):
if self-cards[i].figure == & # 39; A & # 39 ;:
self.aces + = 1

# I know I should have a new class trader inherit this function by hand
def dealer_ai (itself, d):
self.check_value ()
while self-value <17:
self.add_card (d.draw ())
self.check_value ()
print (f & # 39; dealer cards: {self.cards} & # 39;

def restart (self):
self.cards = []
        self.value = 0
self.aces = 0

Class Bank:

def __init __ (self, money, min_bet):
Self-money = money
self.min_bet = min_bet
self.play = Right
self.pool = 0

self.check_money ()
print (yourself)


def __str __ (self):
return f & # 39; You have {self.money} $ & # 39;

def check_money (self):
if self. money < self.min_bet:
            self.play = False
        else:
            self.play = True

    def bet(self):
        print(f'You have {self.money}$.')

        while True:
            try:
                bet = int(input('Tell me your bet (should be lower or equal then your money)'))
            except:
                continue
            else:
                break

        if bet>selbst.geld:
self.bet ()

otherwise:
self.pool = 2 * bet
self.money - = bet
print (for your new balance: {self.money} $ & # 39;)

def deposite (self, depo):
self.money + = depo

def player_win (self):
self.deposite (self.pool)
print (You won: {self.pool} $  nyour new balance is {self.money}. & # 39;
self.pool = 0

def player_lose (self):
print (fSorry! You lose {self.pool / 2}.  nYour new balance is {self.money} & # 39;
self.pool = 0


def play_choice ():
choice = & # 39; & # 39;
while true:
Choice = Enter (Do you want to play? J or N: & # 39;)
if choice.lower () == "y":
hand back
elif choice.lower () == & nb; n & # 39 ;:
return incorrectly
otherwise:
play_choice ()

def main ():

print ("Welcome to the blackjack game! There are only two options - Hit or Stand")
print ("If you do not know any rules - google for blackjack")

## Create objects
Deck = Deck ()
player_hand = hand ()
dealer_hand = hand ()
Bank = Bank (MONEY, MIN_BET)

Winner = true
is_playing = play_choice ()
## 1 round -> drag, hit / stand -> dealer -> check if you win
at is_playing:


while true:
deck.restart ()
player_hand.restart ()
dealer_hand.restart ()
deck.shuffle ()
bank.bet ()

# Lets draw 4 cards - 2 for you, 2 for the dealer
player_hand.add_card (deck.draw ())
player_hand.add_card (deck.draw ())
dealer_hand.add_card (deck.draw ())
dealer_hand.add_card (deck.draw ())
player_hand.check_value ()
print (f & 39;  n  nyour cards: {player_hand.cards} with the value {player_hand.value})
print (f & # 39; dealer first card: {dealer_hand.cards.)[0]} & # 39;)
Choice = input (& # 39;  n  nWhat is your choice? - "h" for hit / "s" for stand)
while choice.lower () == & # 39; h & # 39 ;:
player_hand.add_card (deck.draw ())
player_hand.check_value ()
print (f & 39;  n  nyour cards: {player_hand.cards} with the value {player_hand.value})
if player_hand.value> = 21:
break
Choice = input (& # 39;  n  nWhat is your choice? - "h" for hit / "s" for stand)

###
## Check the player value
if player_hand.value == 21:
Winner = true
break
elif player_hand.value> 21:
Winner = False
break

dealer_hand.dealer_ai (deck)


if dealer_hand.value> 21:
Winner = true
break
elif dealer_hand.value == 21:
Winner = False
break

elif player_hand.value> dealer_hand.value:
Winner = true
break
otherwise:
Winner = False
break

if winner:
bank.player_win ()
otherwise:
bank.player_lose ()


is_playing = play_choice ()

if __name__ == "__main__":
Main()