Skip to content

Instantly share code, notes, and snippets.

@errorseven
Last active November 17, 2018 08:20
Show Gist options
  • Save errorseven/fc103016987689d1125a430840a2ceb2 to your computer and use it in GitHub Desktop.
Save errorseven/fc103016987689d1125a430840a2ceb2 to your computer and use it in GitHub Desktop.
BlackJack Class & Game - Class Handles: Scoring, creating decks, players, dealer hands, money, tracking bets
class BlackJack {
static _ := "".base.base := blackJack
__New(deckNumber, player) {
this.deck := this.BuildDeck(deckNumber)
this.cards := {"A": "Ace", "Q": "Queen", "K": "King"
, "J": "Jack", "T": 10}
this.suits := {"♥": "Hearts", "♣": "Clubs", "♦": "Diamonds"
, "♠": "Spades"}
this.dealer["hand"] := []
this.player["money"] := 100
this.player["hand"] := []
this.player.bet := 0
this.cardsDealt := 0
this.newDeal()
}
backCard[] {
get {
back :=
(Ltrim
"┌─────────┐
│°°°° │
│° °°°°°│
│°°° ° °°│
│° °° │
│°°°° °° │
│ °° │
│°° °°│
└─────────┘"
)
return back
}
}
faceCard[] {
get {
face :=
(Ltrim
"┌─────────┐
│{2:} │
│{1:} │
│ │
│ {2:} │
│ │
│ {2:}│
│ {1:}│
└─────────┘"
)
return face
}
}
BuildDeck(x:=1, deck:="23456789TJQKA") {
suits := []
loop % x * 4 {
suit := A_Index == 1 ? "♥"
: A_index == 2 ? "♦"
: A_index == 3 ? "♠"
: "♣"
for e, value in StrSplit(deck) {
newDeck .= value
suits.push(suit)
}
}
newDeck := StrSplit(newDeck)
deck := []
loop % newDeck.length() {
deck.push({"Face": newDeck[A_Index], "Suit": suits[A_Index]})
}
return this.Shuffle(deck)
}
Shuffle(arr) {
i := arr.MaxIndex() + 1
while(i > 1, i -= 1) {
Random, rnd, 1, % i
tmp := arr[rnd]
arr[rnd] := arr[i]
arr[i] := tmp
}
return arr
}
newDeal() {
this.player.bet := 0
this.cardsDealt := this.player.hand.count() + this.dealer.hand.count()
if (this.player.hand.count()) {
loop % this.player.hand.count() {
this.deck.insertAt(1, this.player.hand.pop())
}
loop % this.dealer.hand.count() {
this.deck.insertAt(1, this.dealer.hand.pop())
}
}
if (this.cardsDealt >= this.deck.count() - 10)
this.deck := this.Shuffle(this.deck)
loop % 2 {
this.player.hand.push(this.deck.pop())
this.dealer.hand.push(this.deck.pop())
}
}
printHand(hand) {
for e, v in (hand)
x .= (this.cards.hasKey(v["face"]) ? this.cards[v["face"]] " "
: v["face"] " ") . "of " this.suits[(v["suit"])] " & "
return trim(x, " & ")
}
HandEvaluator(hand, r:=0) {
For e, v in hand
r += (v["face"] == "A" ? 0 : instr("TJQK", v["face"])
? 10 : v["face"])
For e, v in hand
r += (v["face"] == "A" ? ((r + 11) > 21 ? 1 : 11) : 0)
return r
}
}
#Include %A_ScriptDir%\blackJack.ahk
title =
(
██████╗ ██╗ █████╗ ██████╗██╗ ██╗ ██╗ █████╗ ██████╗██╗ ██╗
██╔══██╗██║ ██╔══██╗██╔════╝██║ ██╔╝ ██║██╔══██╗██╔════╝██║ ██╔╝
██████╔╝██║ ███████║██║ █████╔╝ ██║███████║██║ █████╔╝
██╔══██╗██║ ██╔══██║██║ ██╔═██╗ ██ ██║██╔══██║██║ ██╔═██╗
██████╔╝███████╗██║ ██║╚██████╗██║ ██╗╚█████╔╝██║ ██║╚██████╗██║ ██╗
╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚════╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝
)
DllCall("AllocConsole")
hConsole:=DllCall("GetConsoleWindow","UPtr")
Stdout:=FileOpen(DllCall("GetStdHandle", "int", -11, "ptr"), "h `n")
Stdin:=FileOpen(DllCall("GetStdHandle", "int", -10, "ptr"), "h `n")
e:=SetConsoleOutputCP(65001)
game := new BlackJack(1, 1)
loop {
if (game.player.bet > 0) {
q := updateGameScreen(game)
gameLogic(Q, game)
} else {
if (game.player.money == 0)
reload
while (game.player.bet == 0) {
RunWait %comspec% /c "cls"
Q := print(Format("{}`n`nYour Money: ${}`n`n"
. "How much would you like to bet? "
, title, game.player.money))
if (isInt(Q) and Q > 0 and Q <= game.player.money)
game.player.bet += Q, game.player.money -= Q
else if (Q == "exit" or Q == "quit")
exitApp
}
}
}
gameLogic(x, game) {
if (x == "exit" or x == "quit")
exitApp
else if (x == "hit") {
game.player.hand.push(game.deck.pop())
if (isBust(game))
game.newDeal()
}
else if (x == "double" && game.player.money >= game.player.bet) {
game.player.hand.push(game.deck.pop())
game.player.money -= game.player.bet
game.player.bet *= 2
return isBust(game) ? game.newDeal() : finishHand(game)
}
else if (x == "stand")
finishHand(game)
}
isBust(game) {
if (game.HandEvaluator(game.player.hand) > 21) {
updateGameScreen(game,"", 1)
print("`n`nYou busted this hand...", 1)
sleep 5000
return 1
}
return 0
}
finishHand(game) {
z := game.HandEvaluator(game.player.hand)
updateGameScreen(game, game.dealer.hand)
sleep 2000
while ((y := game.HandEvaluator(game.dealer.hand)) < 17) {
game.dealer.hand.push(game.deck.pop())
updateGameScreen(game, game.dealer.hand)
sleep 2000
}
if (y == z && z <= 21) { ; push
game.player.money += game.player.bet
print("`n`nPush! You get your money back!", 1)
sleep 5000
game.newDeal()
}
else if (y > 21 or z > y) { ; Win
game.player.money += game.player.bet * 2
print("`n`nYou win!", 1)
sleep 5000
game.newDeal()
}
else { ; lose
print("`n`nYou lose this hand...", 1)
sleep 5000
game.newDeal()
}
}
isInt(n) {
if n is Integer
return 1
return 0
}
updateGameScreen(game, dealer="", query=0) {
RunWait %comspec% /c "cls"
if (dealer == "") {
dealer := [], dealer.push(game.dealer.hand.1)
Q := print(Format("{}{}{}{}{}{}{}"
, "Dealers Hand: " game.printHand(dealer) "`n"
,stackCards(game.dealer.hand, [game.faceCard, game.backCard], 1)
,"Players Hand: " game.printHand(game.player.hand) "`n"
,stackCards(game.player.hand, [game.faceCard, game.backCard])
, "`t[Hit] [Double] [Stand] [Quit]`n"
, "`tMoney:`t" game.player.money "`t`tBet:`t" game.player.bet "`n"
, "Your Play? "), query)
} else {
Q := print(Format("{}{}{}{}{}{}{}"
, "Dealers Hand: " game.printHand(dealer) "`n"
,stackCards(game.dealer.hand, [game.faceCard, game.backCard])
,"Players Hand: " game.printHand(game.player.hand) "`n"
,stackCards(game.player.hand, [game.faceCard, game.backCard])
, "`t[Hit] [Double] [Stand] [Quit]`n"
, "`tMoney:`t" game.player.money "`t`tBet:`t" game.player.bet "`n"
, "Your Play? "), 1)
}
return q
}
Print(string="", skip=0){
global Stdout
global Stdin
if (!StrLen(string))
return 1
e:=DllCall("WriteConsole" . ((A_IsUnicode) ? "W" : "A")
, "UPtr", Stdout.__Handle
, "Str", string
, "UInt", strlen(string)
, "UInt*", Written
, "uint", 0)
if (!e) or (ErrorLevel)
return 0 ;Failure
Stdout.Read(0)
if (skip)
return 0
query := RTrim(stdin.ReadLine(), "`n")
return query
}
SetConsoleOutputCP(codepage) {
e:=DllCall("SetConsoleOutputCP","UInt",codepage)
if (!e) or (ErrorLevel)
return 0 ;Failure
return 1
}
stackCards(hand, cards, d:=0) {
c := StrSplit(cards[1], "`n"), b := StrSplit(cards[2], "`n")
if (d) {
for e, v in c {
results .= "`t" Format(v, hand[1].suit, hand[1].face)
. "`t" b[e] "`n"
}
return results "`n`n"
}
else {
for e, v in c {
loop % hand.count() {
results .= "`t" Format(v, hand[A_Index].suit
, hand[A_index].face)
}
results .= "`n"
}
return results "`n`n"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment