Question

Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...

Python Blackjack Game

Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if the player gets 21 points.

Output should look like this:

Enter number of players: 2

Player 1: 7S 5D - 12 points
Player 2: 4H JC - 14 points
Dealer: 10D

Player 1, do you want to hit? [y / n]: y
Player 1: 7S 5D 8H - 20 points
Player 1, do you want to hit? [y / n]: n

Player 2, do you want to hit? [y / n]: y
Player 2: 4H JC 9S - 23 points

Dealer: 10D 9C - 19 points

Player 1 wins
Player 2 loses

Code so far: (I am stuck mostly on __str__ function for Player, Please edit it a little, as when I put it in a list it returns a module rather than just a list with a string in it. You'll see the error in the main statment in Print([a,b])

Please Write code in Python only
import random

class Card (object):
RANKS = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)

SUITS = ('S', 'D', 'H', 'C')

def __init__ (self, rank = 12, suit = 'S'):
    if (rank in Card.RANKS):
      self.rank = rank
    else:
      self.rank = 12

    if (suit in Card.SUITS):
      self.suit = suit
    else:
      self.suit = 'S'

def __str__ (self):
    if self.rank == 1:
      rank = 'A'
    elif self.rank == 13:
      rank = 'K'
    elif self.rank == 12:
      rank = 'Q'
    elif self.rank == 11:
      rank = 'J'
    else:
      rank = self.rank
    return str(rank) + self.suit

def __eq__ (self, other):
    return (self.rank == other.rank)

def __ne__ (self, other):
    return (self.rank != other.rank)

def __lt__ (self, other):
    return (self.rank < other.rank)

def __le__ (self, other):
    return (self.rank <= other.rank)

def __gt__ (self, other):
    return (self.rank > other.rank)

def __ge__ (self, other):
    return (self.rank >= other.rank)


class Deck (object):
def __init__ (self):
    self.deck = []
    for suit in Card.SUITS:
      for rank in Card.RANKS:
        card = Card (rank, suit)
        self.deck.append(card)

def shuffle (self):
    random.shuffle (self.deck)

def deal (self):
    if len(self.deck) == 0:
      return None
    else:
      return self.deck.pop(0)

class Player (object):
# cards is a list of card objects
def __init__ (self, cards):
    self.cards = cards

def hit (self, card):
    self.cards.append(card)

def getPoints (self):
    count = 0
    for card in self.cards:
      if card.rank > 9:
        count += 10
      elif card.rank == 1:
        count += 11
      else:
        count += card.rank

    # deduct 10 if Ace is there and needed as 1
    for card in self.cards:
      if count <= 21:
        break
      elif card.rank == 1:
        count = count - 10
  
    return count

# does the player have 21 points or not
def hasBlackjack (self):
    return len (self.cards) == 2 and self.getPoints() == 21

# complete the code so that the cards and points are printed
def __str__ (self):
    b = []
    for i in self.cards:
        b.append(str(i))
    return b



# Dealer class inherits from the Player class
class Dealer (Player):
def __init__ (self, cards):
    Player.__init__ (self, cards)
    self.show_one_card = True

# over-ride the hit() function in the parent class
# add cards while points < 17, then allow all to be shown
def hit (self, deck):
    self.show_one_card = False
    while self.getPoints() < 17:
      self.cards.append (deck.deal())

# return just one card if not hit yet by over-riding the str function
def __str__ (self):
    if self.show_one_card:
      return str(self.cards[0])
    else:
      return Player.__str__(self)

class Blackjack (object):
def __init__ (self, numPlayers = 1):
    self.deck = Deck()
    self.deck.shuffle()

    self.numPlayers = numPlayers
    self.Players = []
    print(self.Players)
    print(self.deck.deal(), self.deck.deal())
    print(Player([self.deck.deal(), self.deck.deal()]))

    # create the number of players specified
    # each player gets two cards
    for i in range (self.numPlayers):
        self.Players.append(self.deck.deal())
  
    print(self.Players)

    # create the dealer
    # dealer gets two cards
    self.dealer = Dealer ([self.deck.deal(), self.deck.deal()])
    print(self.dealer)

def play (self):
    # Print the cards that each player has
    for i in range (self.numPlayers):
        print ("Player " + str(i + 1) + ': ' + self.Players[i])

    # Print the cards that the dealer has
    print ('Dealer: ' + str(self.dealer))

    # Each player hits until he says no
    playerPoints = []
    for i in range (self.numPlayers):
      while True:
        choice = input ('do you want to hit? [y / n]: ')
        if choice in ('y', 'Y'):
          (self.Players[i]).hit (self.deck.deal())
          points = (self.Players[i]).getPoints()
          print ('Player ' + str(i + 1) + ': ' + self.Players[i])
          if points >= 21:
            break
        else:
          break
      playerPoints.append ((self.Players[i]).getPoints())

    # Dealer's turn to hit
    self.dealer.hit (self.deck)
    print(playerPoints)
    dealerPoints = self.dealer.getPoints()
    print ('Dealer: ' + self.dealer + ' - ' + str(dealerPoints))

    # determine the outcome; you will have to re-write the code
    # it was written for just one player having playerPoints
    # do not output result for dealer
    if dealerPoints > 21:
      print ('Dealer loses')
    elif dealerPoints > playerPoints:
      print ('Dealer wins')
    elif (dealerPoints < playerPoints and playerPoints <= 21):
      print ('Player wins')
    elif dealerPoints == playerPoints:
      if self.player.hasBlackjack() and not self.dealer.hasBlackjack():
        print ('Player wins')
      elif not self.player.hasBlackjack() and self.dealer.hasBlackjack():
        print ('Dealer wins')
      else:
        print ('There is a tie')

    a = Card()
    b = Card(11, 'D')
    c = [a,b]
    print("c,", c)
    Player('QS', 'JD')
    print(Player([a, b]))
    print(Dealer([a, b]))
    numPlayers = eval (input ('Enter number of players: '))
    while (numPlayers < 1 or numPlayers > 6):
      numPlayers = eval (input ('Enter number of players: '))
    game = Blackjack (numPlayers)
    game.play()

main()

Homework Answers

Answer #1

********************************************************************

Code for BLackJack game

*********************************************************************

SUITS = ['C', 'S', 'H', 'D']
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
MAX_PLAYERS_GAME = 5
MAX_BAL = 500
cbalance = 0


class Card(object):
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank

if rank == 'A':
self.point = 11
elif rank in ['K', 'Q', 'J']:
self.point = 10
else:
self.point = int(rank)

self.hidden = False

def __str__(self):
if self.hidden:
return '[X]'
else:
return '[' + self.suit + ' ' + self.rank + ']'

def hide_card(self):
self.hidden = True

def reveal_card(self):
self.hidden = False

def is_ace(self):
return self.rank == 'A'


class Deck(object):
def __init__(self):
self.cards = [Card(suit, rank) for suit in SUITS for rank in RANKS]
self.shuffle()

def __str__(self):
cards_in_deck = ''
for card in self.cards:
cards_in_deck = cards_in_deck + str(card) + ' '
return cards_in_deck

def shuffle(self):
random.shuffle(self.cards)

def deal_card(self):
card = self.cards.pop(0)
return card


class Hand(object):
def __init__(self):
self.hand = []

def add_card(self, card):
self.hand.append(card)
return self.hand

def get_value(self):
aces = 0
value = 0
for card in self.hand:
if card.is_ace():
aces += 1
value += card.point
while (value > 21) and aces:
value -= 10
aces -= 1
return value


class Dealer(Hand):
def __init__(self, name, deck):
Hand.__init__(self)
self.name = name
self.deck = deck
self.isBust = False

def show_hand(self):
for card in self.hand:
print card,
print

def hit(self):
print "Hit"
self.add_card(self.deck.deal_card())
return self.hand

def stand(self):
print "%s gets the %d. Done." % (self.name, self.get_value())

def check_bust(self):
if self.get_value() > 21:
self.isBust = True
print "%s gets" % self.name
else:
self.stand()


class Player(Dealer):
def __init__(self, name, deck, bet):
Dealer.__init__(self, name, deck)
self.bet = bet
self.isBust = False
self.isSurrender = False
self.isSplit = False
self.split = []


def play(player, deck):
print player.name + ':',
player.show_hand()
if player.name == 'Deal':
while player.get_value() < 17:
player.hit()
player.show_hand()
player.check_bust()
else:
global chip_balance
if chip_balance > player.bet and not player.isSplit:
if player.hand[0].point == player.hand[1].point:
choice = input_func("Hitout, Stand, DoubleDown, Split (h/s/d/p/u) ", str.lower,
range_=('h', 's', 'd', 'p', 'u'))
else:
choice = input_func("Hitout, Stand, DoubleDown or Surrender? (h/s/d/u) ", str.lower,
range_=('h', 's', 'd', 'u'))
else:
choice = input_func("Hitout, Stand or Surrender? (h/s/u) ", str.lower, range_=('h', 's', 'u'))
while choice == 'h':
player.hit()
player.show_hand()
if player.get_value() > 21:
player.isBust = True
print "%s gets" % player.name
break
choice = input_func("Hit or Stand? (h/s) ", str.lower, range_=('h', 's'))

if choice == 's':
player.stand()

if choice == 'd':
chip_balance -= player.bet
player.bet *= 2
print "New balance = %d" % chip_balance
player.hit()
player.show_hand()
player.check_bust()

if choice == 'u':
player.isSurrender = True
chip_balance += (player.bet - player.bet / 2)
print "New balance = %d" % chip_balance

if choice == 'p':
chip_balance -= player.bet
print "New balance of player = %d" % chip_balance
player.split.append(Player(' Split_1', deck, player.bet))
player.split.append(Player(' Split_2', deck, player.bet))
for p in player.split:
p.add_card(player.hand.pop(0))
p.add_card(deck.deal_card())
p.isSplit = True
play(p, deck)


def input_func(prompt, type_=None, min_=None, max_=None, range_=None):
value = ''
while True:
value = raw_input(prompt)
if type_ is not None:
try:
value = type_(value)
except ValueError:
print "Sorry I don't understand."
continue
if min_ is not None and value < min_:
print "Sorry your input can not be less than %d!" % min_
elif max_ is not None and value > max_:
print "Sorry your input can not be more than %d!" % max_
elif range_ is not None and value not in range_:
print "select from", range_
else:
break
return value


def report(player, dealer):
global chip_balance
if player.isSurrender:
tag = 'surrender'
elif player.isBust:
tag = 'lose'
elif len(player.hand) == 2 and player.get_value() == 21 and not player.isSplit:
tag = 'blackjack'
chip_balance += player.bet * 3
elif dealer.isBust or (player.get_value() > dealer.get_value()):
tag = 'win'
chip_balance += player.bet * 2
elif player.get_value() == dealer.get_value():
tag = 'push'
chip_balance += player.bet
else:
tag = 'lose'
print "%s: %-*s Balance = %d" % (player.name, 10, tag, chip_balance)


def game():
players = []
global chip_balance
deck = Deck()

player_num = input_func("enter the number of players: (1-5) ", int, 1, MAX_PLAYERS)

print " start game..\n"

for i in range(player_num):
if chip_balance > 0:
player_name = 'Player_' + str(i + 1)
print "%s:" % player_name
player_bet = input_func("Please bet", int, 1, chip_balance)
chip_balance -= player_bet
print "New balance after update is %d." % chip_balance
player = Player(player_name, deck, player_bet)
players.append(player)
else:
print "\n number of player is %d. There's no balance to support more players." % (len(players))
break

dealer = Dealer('Dealer', deck)

for i in range(2):
for player in (players + [dealer]):
player.add_card(deck.deal_card())

dealer.hand[1].hide_card()
print "\nDealer:"
dealer.show_hand()
print
dealer.hand[1].reveal_card()

for player in (players + [dealer]):
play(player, deck)
print

print "Final result\n"

for player in players:
if not player.split:
report(player, dealer)
else:
print "%s: split" % player.name
for p in player.split:
report(p, dealer)

print "\nFinal balance is %d.\n" % chip_balance


if __name__ == '__main__':

chip_balance = input_func("\nWelcome to BlackJack! enter the chip balance: (1-500) ", int, 1, MAX_BALANCE)
while True:
game()
if chip_balance < 1:
print " don't have enough balance to proceed. Game over."
break
proceed = input_func("Do you want to continue? (yes/no) ", str.lower, range_=('y', 'n'))
if proceed == 'n':
print "\nThank you for playing! See you next time."
break

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will look like: Enter number of players: 2 Player 1: 7S 5D - 12 points Player 2: 4H JC - 14 points Dealer: 10D Player 1, do you want to hit? [y / n]: y Player 1: 7S 5D 8H - 20 points Player 1, do you want to hit? [y / n]: n Player 2, do you want to hit? [y / n]: y...
I need some tests for this python class. some tests for some of the functions in...
I need some tests for this python class. some tests for some of the functions in this class like. def __init__ def __eq__ def __lt__ def __hash__ I am using Pycharm and useing Pytest to write some tests but have no idea how to write one --------------------------------------------------------------------------------------------------- class Movie: def __set_title_internal(self, title: str): if title.strip() == "" or type(title) is not str: self.__title = None else: self.__title = title.strip() def __set_release_year_internal(self, release_year: int): if release_year >= 1900 and type(release_year) is...
"""linkedQueue.py implements LinkedQueue""" class Node(object): def __init__(self, e, nextNode): self.item, self.next = (e, nextNode) def __str__(self):...
"""linkedQueue.py implements LinkedQueue""" class Node(object): def __init__(self, e, nextNode): self.item, self.next = (e, nextNode) def __str__(self): return str(self.item)    class LinkedQueue(object): def __init__(self): #O(1) self._front, self._rear =(None, None) self._size = 0    def enqueue(self, e): # add e to the rear of the queue. newTail = Node(e, None) if self.isEmpty(): self._front = newTail else: self._rear.next = newTail self._rear = newTail self._size += 1 def front(self): # raise exception if it is empty, otherwise return front element if self.isEmpty(): raise Exception("call...
Your group is required to develop a simple Android BlackJack card game. Part B (35 Marks)...
Your group is required to develop a simple Android BlackJack card game. Part B – Group Submission (Do it on android studio) i need the full working code in android studio The program shall fulfil the following requirements: 1) There are total of 4 main features : User authentication/login, game setting, playing game and view history. User Login 2) Allow the player to register new user account or login using the existing account to play the game. Each user account...
In java create a dice game called sequences also known as straight shooter. Each player in...
In java create a dice game called sequences also known as straight shooter. Each player in turn rolls SIX dice and scores points for any sequence of CONSECUTIVE numbers thrown beginning with 1. In the event of two or more of the same number being rolled only one counts. However, a throw that contains three 1's cancels out player's score and they mst start from 0. A total of scores is kept and the first player to reach 100 points,...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a room class Room(object): # the constructor def __init__(self,name,image): # rooms have a name, exits (e.g., south), exit locations (e.g., to the south is room n), # items (e.g., table), item descriptions (for each item), and grabbables (things that can # be taken and put into the inventory) self.name = name self.image = image self.exits = {} self.items = {} self.grabbables = [] # getters...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT