Skip to main content
Code Review

Return to Revisions

2 of 3
make title describe what code does instead of goals - refer to help center section "Titling your question" on https://codereview.stackexchange.com/help/how-to-ask; add new line after closing fence so it won't be formatted with code

Object-Oriented Blackjack

This is my first post, and I was actually going to post this on Stackoverflow when I was rather suggested posting the code here, as it may be better suited.

Here is the github repository, if that is allowed here, as it seems easy to receive suggestions.

BlackJack

I am looking for criticism as everything I have learned has been self taught, and mainly in this manner. Self-teach, practice, build, post, refine, move on.

The first bit of code would be the inherited code.

import time, itertools, random
def countyDots():
 for i in range(5):
 line = "." * i
 print(line, end="")
 print("\r", end="")
 time.sleep(0.5)
class Card(object):
 def __init__(self, rank, suit):
 self.rank = rank
 self.suit = suit
 self.valueChart = {
 "2": 2,
 "3": 3,
 "4": 4,
 "5": 5,
 "6": 6,
 "7": 7,
 "8": 8,
 "9": 9,
 "10": 10,
 "J": 10,
 "Q": 10,
 "K": 10,
 "A": 11,
 }
 def getValues(self):
 cardValues = self.valueChart
 returnedValue = 0
 for rank, value in cardValues.items():
 if self.rank == rank:
 returnedValue = value
 return returnedValue 
 
class Player(object):
 def __init__(self):
 self.name = self.defineName()
 #initialize player bank to 200ドル
 self.balance = 200
 print("Beginning Balance: 200ドル.00 USD\n")
 ##initialize player hand
 self.hand = []
 
 #initialize score and currentBet to 0
 self.score = 0
 self.bet = 0
 def placeBet(self):
 
 currentBet = input(f"BALANCE: ${self.balance}\nHow much would you like to bet? (1, 2, 5, 10, 25): ")
 
 def is_number(n):
 try:
 int(n)# Type-casting the string to `float`.
 # If string is not a valid `float`, 
 # it'll raise `ValueError` exception
 except ValueError:
 return False
 return True
 if is_number(currentBet):
 currentBet = int(currentBet)
 if currentBet in (1, 2, 5, 10, 25):
 self.balance -= currentBet
 self.bet = currentBet
 print(f"\nCurrent Bet: {currentBet}\nBALANCE: {self.balance}\n")
 else:
 self.placeBet()
 else:
 self.placeBet()
 
 def defineName(self):
 #Ask for name from user
 newName = input("What is your Name?: ")
 #confirm new name with user
 confirmation = input(f"Your name is {newName}, correct? (Y/N): ")
 
 #convert confirmation to all lowercase and eliminate whitespace
 confirmation = confirmation.lower().strip()
 while confirmation != "y":
 newName = input("Sorry. What is your Name?: ")
 countyDots()
 confirmation = input(f"So you prefer to be called {newName}? (Y/N): ")
 confirmation = confirmation.lower().strip()
 if confirmation == "y":
 return newName
 
 def showHand(self):
 print(f"{self.name}'s HAND")
 for card in self.hand:
 rank = card[0]
 suit = card[1]
 print(f"{rank} of {suit}")
 def getAction(self):
 action = input("Would you like to HIT or STAND?: ")
 action = action.lower().strip()
 return action
 def calculateScore(self):
 self.score = 0
 for card in self.hand:
 rank = card[0]
 suit = card[1]
 card = Card(rank, suit)
 
 value = card.getValues()
 self.score += value
 
 print(f"{self.name}'s SCORE: {self.score}\n")
 return self.score
 def showBalance(self):
 print(f"BALANCE: {self.balance}")
class Dealer(object):
 def __init__(self):
 self.name = "Dealer"
 #initialize a dealer score to 0
 self.score = 0
 #initialize a dealer hand
 self.hand = []
 #initialize a dealer bank of 1,000,000
 self.bank = 1000000
 def showHand(self):
 print(f"{self.name}'s HAND")
 for card in self.hand:
 rank = card[0]
 suit = card[1]
 print(f"{rank} of {suit}")
 
 def calculateScore(self):
 self.score = 0
 for card in self.hand:
 rank = card[0]
 suit = card[1]
 card = Card(rank, suit)
 
 value = card.getValues()
 self.score += value
 
 print(f"{self.name}'s SCORE: {self.score}\n")
 return self.score
 
class Deck(object):
 def __init__(self):
 self.deck = []
 self.ranks = (
 "2",
 "3",
 "4",
 "5",
 "6",
 "7",
 "8",
 "9",
 "10",
 "J",
 "Q",
 "K",
 "A",
 )
 def buildDeck(self):
 suits = ("Spades ♠", "Clubs ♣", "Hearts ♥", "Diamonds ♦")
 cards = list(itertools.product(self.ranks, suits))
 random.shuffle(cards)
 for card in cards:
 self.deck.append(card)
 return self.deck
class Shoe(Deck):
 def __init__(self):
 self.shoe = []
 
 def buildShoe(self):
 for i in range(5):
 newDeck = Deck()
 newDeck.buildDeck()
 for card in newDeck.deck:
 self.shoe.append(card)
 
 def dealCard(self):
 gameDeck = self.shoe
 dealtCard = self.shoe[0]
 self.shoe.pop(0)
 return dealtCard

The Second bit of code is the gameLogic file which executes at the bottom.


class GameLogic(object):
 def __init__(self, player, dealer, shoe):
 self.player = player
 self.dealer = dealer
 self.gameShoe = shoe
 
 def beginGame(self):
 self.dealer.hand = []
 self.player.hand = []
 #initalize the players first bet
 self.player.placeBet()
 #initialize the shoe of cards (5 decks of cards)
 self.gameShoe.buildShoe()
 
 self.player.hand.append(self.gameShoe.dealCard())
 self.dealer.hand.append(self.gameShoe.dealCard())
 self.player.hand.append(self.gameShoe.dealCard())
 self.dealer.hand.append(self.gameShoe.dealCard())
 self.player.showHand()
 self.player.calculateScore()
 countyDots()
 self.dealer.showHand() #These need to be changed so that they reflect one face up card
 self.dealer.calculateScore() #and one face down card
 countyDots()
 self.playerAction(self.player.getAction())
 def keepPlaying(self):
 userResponse = input("\nPRESS ENTER FOR NEXT HAND\nType 'EXIT' to quit game\n")
 userResponse = userResponse.lower().strip()
 if userResponse == "":
 self.beginGame()
 elif userResponse == "exit":
 exit()
 else:
 self.keepPlaying()
 
 def playerAction(self, action):
 
 if action == "hit":
 print("You chose to Hit")
 #player takes on an additional card
 self.player.hand.append(self.gameShoe.dealCard())
 self.player.showHand()
 self.player.calculateScore()
 if self.player.score <= 21:
 newAction = self.player.getAction()
 self.playerAction(newAction)
 elif self.player.score > 21:
 print("BUSTED!!! YOU LOSE")
 #Proceed to 
 self.dealer.showHand()
 #set currentbet to 0
 self.player.bet = 0
 self.keepPlaying()
 #show dealers hand for good faith
 #set player bet to 0
 #set forth with "would you like to play another round"
 #if player total score isnt higher than 21, we ask the same question
 #if the player total score is higher than 21, we end the game immediately and proceed to ask endgame()
 elif action == "stand":
 print("You chose to STAND\n")
 #if action is to stand then we need to proceed forward with the game logic for the dealer.
 self.dealer.showHand()
 self.dealer.calculateScore()
 while self.dealer.score < 16:
 countyDots()
 self.dealer.hand.append(self.gameShoe.dealCard())
 self.dealer.showHand()
 self.dealer.calculateScore()
 
 if self.dealer.score > 21:
 print("The dealer has busted!")
 
 #pay the player the player 2times their bet
 payout = self.player.bet * 2
 self.player.balance += payout
 print(f"{self.player.name} WON {self.player.bet}")
 self.player.showBalance()
 #reset bet to 0 for the next round
 self.player.bet = 0
 self.keepPlaying()
 
 elif self.dealer.score <= 21 and self.dealer.score >= 16:
 
 if self.player.score > self.dealer.score:
 print("The player WINS!")
 #pay the player the player 2times their bet
 payout = self.player.bet * 2
 self.player.balance += payout
 print(f"{self.player.name} WON {self.player.bet}")
 self.player.showBalance()
 #reset bet to 0 for the next round
 self.player.bet = 0
 self.keepPlaying()
 elif self.player.score <= self.dealer.score:
 print("The PLAYER LOSES!")
 print(f"{self.player.name} LOST {self.player.bet}")
 self.player.showBalance()
 #reset bet to 0 for the next round
 self.player.bet = 0
 self.keepPlaying() 
 else:
 print("Some Real Bad shit happened herrrrrr")
 
#initialize a dealer
dealer1 = Dealer()
#initialize a player
player1 = Player()
#initialize a game shoe
gameShoe = Shoe()
#Initialize GamePlay
game = GameLogic(player1, dealer1, gameShoe)
#Begin Game Play
game.beginGame()
lang-py

AltStyle によって変換されたページ (->オリジナル) /