Проблема основного сценария игры в блэкджек (классы уже сделаны)
Для моего классного проекта я должен сделать игру в блэкджек, которая функционирует должным образом. Это упрощенная версия игры (без ставок, удвоения, разделения и т. Д.). Мы должны использовать разные классы для функций Deck, Hand и Card, что я и сделал. Главная проблема, с которой я сталкиваюсь, заключается в том, как собрать все это в единую программу, чтобы она могла работать. Вот мои занятия
class Card(object):
'''A simple playing card. A Card is characterized by two
components:
rank: an integer value in the range 2-14, inclusive (Two-Ace)
suit: a character in 'cdhs' for clubs, diamonds, hearts, and
spades.'''
#------------------------------------------------------------
SUITS = 'cdhs'
SUIT_NAMES = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
RANKS = range(2,15)
RANK_NAMES = ['Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine', 'Ten',
'Jack', 'Queen', 'King', 'Ace']
RANK_VALUES = [99, 99, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
#------------------------------------------------------------
def __init__(self, rank, suit):
'''Constructor
pre: rank in range(1,14) and suit in 'cdhs'
post: self has the given rank and suit'''
self.rank_num = rank
self.suit_char = suit
#------------------------------------------------------------
def getSuit(self):
'''Card suit
post: Returns the suit of self as a single character'''
return self.suit_char
#------------------------------------------------------------
def getRank(self):
'''Card rank
post: Returns the rank of self as an int'''
return self.rank_num
#------------------------------------------------------------
def getCardValue(self):
value = self.RANK_VALUES[self.rank_num]
return value
#------------------------------------------------------------
def suitName(self):
'''Card suit name
post: Returns one of ('clubs', 'diamonds', 'hearts',
'spades') corrresponding to self's suit.'''
index = self.SUITS.index(self.suit_char)
return self.SUIT_NAMES[index]
#------------------------------------------------------------
def rankName(self):
'''Card rank name
post: Returns one of ('ace', 'two', 'three', ..., 'king')
corresponding to self's rank.'''
index = self.RANKS.index(self.rank_num)
return self.RANK_NAMES[index]
#------------------------------------------------------------
def __str__(self):
'''String representation
post: Returns string representing self, e.g. 'Ace of Spades' '''
return self.rankName() + ' of ' + self.suitName()
#------------------------------------------------------------
from random import randrange
from Card import Card
from Hand import Hand
class Deck(object):
def __init__(self):
'''This creates the deck of cards, un-shuffled.'''
cards = []
for suit in Card.SUITS:
for rank in Card.RANKS:
cards.append(Card(rank,suit))
self.cards = cards
def size(self):
'''How many cards are left.'''
return len(self.cards)
def deal(self):
'''Deals a single card.
Pre: self.size() > 0
Post: Returns the next card in self, and removes it from self.'''
return self.cards.pop()
def shuffle(self):
'''This shuffles the deck so that the cards are in random order.'''
n = self.size()
cards = self.cards
for i,card in enumerate(cards):
pos = randrange(i,n)
cards[i] = cards[pos]
cards[pos] = card
def takeAHit(self, whatHand):
aCard = self.deal()
whatHand.addCard(aCard)
def __str__(self):
if self.size() == 52:
return 'The Deck is Full'
elif self.size() > 0:
return 'The Deck has been Used'
else:
return 'The Deck is Empty'
from Card import Card
class Hand(object):
"""A labeled collection of cards that can be sorted"""
#------------------------------------------------------------
def __init__(self, label=""):
"""Create an empty collection with the given label."""
self.label = label
self.cards = []
#------------------------------------------------------------
def add(self, card):
""" Add card to the hand """
self.cards.append(card)
#------------------------------------------------------------
def totalHand(self):
totalHand = 0
aceAmount = 0
for c in self.cards:
if c.getRank() == 14:
aceAmount += 1
totalHand +=c.getCardValue()
while aceAmount > 0:
if totalHand > 21:
aceAmount -= 1
totalHand -= 10
else:
break
return totalHand
def __str__(self):
if self.cards == []:
return "".join([(self.label), "doesn't have any cards."])
tempStringList = [ self. label, "'s Cards, "]
for c in self.cards:
tempStringList.append(str(c))
tempStringList.append(" , ")
tempStringList.pop()
tempStringList.append(" . ")
return "".join(tempStringList)
Теперь по основной функции, по которой мне нужна помощь, мой профессор лишь немного помог мне с работой.
from Deck import Deck
from Card import Card
from Hand import Hand
def rules(playerTotal, dealerTotal):
if playerTotal > 21:
print "You busted!"
if dealerTotal == 21:
print 'To make it worse, dealer has 21.'
elif dealerTotal > 21:
print "The Dealer has busted. You win!"
elif playerTotal == 21:
print " You got 21! So you win!"
if dealerTotal == 21:
print "The Dealer also got 21. Tough Break."
elif dealerTotal == 21:
print "The Dealer got 21! Tough Break, you lose!"
else:
if playerTotal > dealerTotal:
print "You beat the Dealer! You got lucky punk."
if playerTotal == dealerTotal:
print "It is a push, no one wins!"
else:
print "Dealer wins! Better luck next time loser."
Так что я знаю, что должен использовать функцию totalHand из Hand, чтобы определить значения для playerTotal и dealerTotal, но каждый раз, когда я что-то пробую, я получаю эту ошибку. Player1 = raw_input("Как вас зовут?") Dealer = "Дилер" twoCards = Hand(Player1) print twoCards.totalHand()
который печатает "нет" и это все..
Если кто-то может помочь мне, я был бы признателен, я сожалею о своем главном выборе на данный момент..
1 ответ
В произвольном порядке:
Ваш тасование предвзято. Просто используйте Python random.shuffle(), это правильно и быстро.
totalHand неверно (никогда не добавляет не-тузы к значению) и слишком сложно, потому что вы решили использовать 11 в качестве значения туза, и не сообщает, является ли сумма жесткой или мягкой (что необходимо для правильной игры). Измените значение тузов на 1 и упростите:
*
def totalHand(self):
aceFound, isSoft = false, false
total = 0
for c in self.cards:
total += c.getCardValue()
if c.getCardValue() == 1:
aceFound = true
if aceFound and total < 12:
total += 10
isSoft = true
return total, isSoft
Вы не можете основывать свои результаты только на итогах карты. Вы должны разыграть руку в правильном порядке:
- Если у дилера естественно, игра окончена. Игроки с естественным толчком, все остальные проигрывают.
- Каждый игрок по очереди разыгрывает свою руку. Натуралы оплачиваются и удаляются, бюсты проигрывают и удаляются.
- Дилер играет его руку. Если он перебор, все остальные игроки выигрывают, в противном случае игроки выигрывают / проигрывают в зависимости от общего количества