打印我在键入 yes 后使用的牌以再次玩

  • 本文关键字:yes 打印 python python-2.7
  • 更新时间 :
  • 英文 :


我希望这个游戏用前一手剩下的牌开始每手牌。 相反,它从一个完整的、新洗牌的套牌开始。 我怎样才能修复它以继续?我根据您的建议更新了代码,但它没有显示我的表演卡,非常感谢

import random, sys
suits = ('Clubs', 'Spades', 'Hearts', 'Diamonds')
pip = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
pipValues = {'Ace':11, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10}

class Card:

    def __init__(self, suit, pip):
        self.suit = suit
        self.pip = pip
        self.value = pipValues.get(pip)
    def __str__(self):
        thisCard = ""
        thisCard += str(self.pip)
        thisCard += str(self.suit)
        return (thisCard)
    def __repr__(self):
        thisCard = ""
        thisCard += str(self.pip)
        thisCard += str(self.suit)
        return (thisCard)


class Player:
    def __init__(self):
        self.hand = []
        self.handTotal = 0
    def __str__(self):
        printHand = ""
        for i in self.hand:
            printHand += str(i) + " "
        return (printHand)
    def __repr__(self):
        printHand = ""
        for i in self.hand:
            printHand += str(i) + " "
        return (printHand)

class Deck:

    def __init__(self):
        self.cardList = []
        #for each suit take every card
        for i in range(len(suits)):
            for j in range(len(pip)):
                self.cardList.append(Card(suits[i], pip[j]))

    def shuffle(self):
        random. shuffle (self.cardList)
    def dealOne(self, player):
        (player.hand).append(self.cardList[0])
        player.handTotal += self.cardList[0].value
        del self.cardList[0]
        print self.cardList
        return self.cardList

    def __str__(self):
        printString = ""
        for i in range(len(self.cardList)):
            if i % 13 == 0:
                printString += "n t"
                printString += str(self.cardList[i]) + " "
            else:
                printString += str(self.cardList[i]) + " "
        printString += "n"

        return printString

def showHands(player, opponent):
    print ('Dealer shows ' + str(opponent.hand[0]) + ' faceup')
    print ('You show ' + str(player.hand[0]) +str(player.hand[0] ))

def playerTurn(deck, player, other):
    #First, check scores to see if either player has a blackjack:
    if player.handTotal == 21 or other.handTotal == 21:
        if other.handTotal == 21:
            print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
            print ("Dealer has " + str(other) + "for a total of 21")
            print ("Dealer has a Blackjack! Dealer wins!")
            print ("Thanks for playing. Come back again soon! ")
            message()
        else:
            print ("You hold " + str(player) + "for a total of 21")
            print ("You have a Blackjack! You win!")
            print ("Thanks for playing. Come back again soon! ")
            message()   
    hitOrStand = 0
    aces = False
    #IF TWO ACES
    if player.hand[0].pip == "A" and player.hand[1].pip == "A":
        player.hand[0].pipValue = 1
    if player.handTotal == 21:
            print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
            print ("Blackjack! You win!")
            print ("Thanks for playing. Come back soon!")
            print()
            message()
    while hitOrStand != 2:
        #check for aces
        for i in player.hand:
            if i.pip == "A" and i.value == 11:
                aces = True
        print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
        print()
        hitOrStand = input('Do you hit or stand? Enter "1" for hit and "2" for stand: ')
        while hitOrStand != 1 and hitOrStand != 2:
            try:
                hitOrStand = int(hitOrStand)
                break
            except ValueError:
                print ("Enter a valid integer n")
            hitOrStand = input('Do you hit hit or stand? Enter "1" for hit and "2" for stand: ')
        print()
        if hitOrStand == 1:
            print('Card dealt:  ' + str(deck.cardList[0]))
            print()
            deck.dealOne(player)
            #check if an ace was drawn
            for i in player.hand:
                if i.pip == "A" and i.value == 11:
                    aces = True
        if player.handTotal == 21:
            print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
            print ("Blackjack!! You Win!")
            print()
            print ("Thanks for playing. Come back soon!")
            message()
        if player.handTotal > 21:
            #check for aces
            if aces:
                print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("Over 21. Value of ace changed to 1")
                #chanlge value of ace and hand
                player.handTotal = player.handTotal - 10
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        i.value = 1
                #check for other standard aces
                aces = False
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        aces = True
            else:
                print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("You Bust! Dealer Wins!")
                #exit, since you're a loser
                print ("Thanks for Playing! Come Back Soon!")
                print()
                raise SystemExit
        if hitOrStand == 2:
            print ('You stand at: ' + str(player.handTotal))
            print()
    print ("Now Dealer's Turn")
    print ()
def message():
        again = raw_input("Do you want to play again? (Y/N) : ")
        if(again == "Y" or again == "y"):
            main()
        else:
            print "nn-------Thank you for playing!--------nn"
            exit()
def opponentTurn(deck, player, other):
    if other.handTotal == 21:
        raise SystemExit
    aces = False
    hitOrStand = 0
    #IF TWO ACES
    if player.hand[0].pip == "A" and player.hand[1].pip == "A":
        player.hand[0].pipValue = 1
    while hitOrStand != 2:
        #check for aces
        for i in player.hand:
            if i.pip == "A" and i.value == 11:
                aces = True

        print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
        print()
        #if blackjack
        if player.handTotal == 21:
            print ("Dealer has a BlackJack! Dealer Wins!")
            break
        if player.handTotal <21 and other.handTotal == 21:
            print ("Dealer's hand is " + str(player.handTotal) + ". You have a Blackjack! Congratulations! You win! ")
            break
        if player.handTotal < other.handTotal:
            hitOrStand = 1
        if player.handTotal >= other.handTotal:
            hitOrStand = 2
        if hitOrStand == 1:
            print("Dealer hits. " + 'Card dealt:  ' + str(deck.cardList[0]))
            deck.dealOne(player)
            #check if an ace was drawn
            for i in player.hand:
                if i.pip == "A" and i.value == 11:
                    aces = True
        if player.handTotal > 21:
            #check for aces
            if aces:
                print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("Over 21. Value of ace changed to 1")
                #chanlge value of ace and hand
                player.handTotal = player.handTotal - 10
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        i.value = 1
                #check for other standard aces
                aces = False
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        aces = True
            else:
                print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("Dealer Busts! You Win!")
                message()

        if hitOrStand == 2:
            print ("Dealer stands at " + str(player.handTotal))
            print ("Your score is " + str(other.handTotal))
            print ("Dealer Wins!")
            message()
#who won
def main():
    cardDeck = Deck()
    print ('Initial Deck: ')
    print(cardDeck)
    cardDeck.shuffle()
    print ('Shuffled Deck: ')
    print(cardDeck)
    keep_playing = True
    while keep_playing:
        player = Player()
        opponent = Player()
        #give each player 2 cards, alternating
        cardDeck.dealOne(player)
        cardDeck.dealOne(opponent)
        cardDeck.dealOne(player)
        cardDeck.dealOne(opponent)
        print ('Deck after giving 2 cards each')
        print (cardDeck)
        #show 1 faceup card for each player
        showHands(player,opponent)
        #start playing
        playerTurn(cardDeck,player, opponent)
        opponentTurn(cardDeck, opponent, player)
        again = raw_input("Do you want to play again? (Y/N) : ")
        keep_playing = again in "Yy"
    # Reach here after dropping out of the while loop
    print "nn-------Thank you for playing!--------nn"
main()

是的,您可以从前一个游戏中断的地方继续一个游戏。 当前的问题是你递归调用 main。 这从头开始,洗牌一整副牌,等等。

相反,你会想要一个这样的主程序:

def main():
    cardDeck = Deck()
    print ('Initial Deck: ')
    print(cardDeck)
    cardDeck.shuffle()
    print ('Shuffled Deck: ')
    print(cardDeck)
    keep_playing = True
    while keep_playing:
        player = Player()
        opponent = Player()
        #give each player 2 cards, alternating
        cardDeck.dealOne(player)
        cardDeck.dealOne(opponent)
        cardDeck.dealOne(player)
        cardDeck.dealOne(opponent)
        print ('Deck after giving 2 cards each')
        print (cardDeck)
        #show 1 faceup card for each player
        showHands(player,opponent)
        #start playing
        playerTurn(cardDeck,player, opponent)
        opponentTurn(cardDeck, opponent, player)
        again = raw_input("Do you want to play again? (Y/N) : ")
        keep_playing = again in "Yy"
    # Reach here after dropping out of the while loop
    print "nn-------Thank you for playing!--------nn"

这摆脱了你的消息函数和对main的递归调用。

有关完整的解决方案,请参阅 repl.it:

有很多问题,这里有一些总体主题:

如果你不得不重复自己,你就做错了:

aces = False
#IF TWO ACES
if player.hand[0].pip == "A" and player.hand[1].pip == "A":
    player.hand[0].pipValue = 1

#check for aces
    for i in player.hand:
        if i.pip == "A" and i.value == 11:
            aces = True

#check if an ace was drawn
        for i in player.hand:
            if i.pip == "A" and i.value == 11:
                aces = True

#check for aces
if aces:
    print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
    print ("Over 21. Value of ace changed to 1")
    #chanlge value of ace and hand
    player.handTotal = player.handTotal - 10
    for i in player.hand:
        if i.pip == "A" and i.value == 11:
            i.value = 1
    #check for other standard aces
    aces = False
    for i in player.hand:
        if i.pip == "A" and i.value == 11:
            aces = True

每个都被使用了两次...我取而代之的是让我的玩家决定它自己的价值:

@property  
def handTotal(self):
  while sum(card.value for card in self.hand) > 21 and 
        any(card.pip == 'Ace' and card.value == 11 for card in self.hand):
    for card in self.hand:
      if card.pip == 'Ace' and card.value == 11:
        card.value = 1
        break
  return sum(card.value for card in self.hand)

@property装饰器强制它在每次有人请求 handTotal 时重新计算。

<小时 />

告诉主教练你想继续玩

您需要以某种方式将值一直return回 main。因为您已经有一些全局状态变量,所以我添加了playing = True,然后:

def message():
    global playing
    again = input("Do you want to play again? (Y/N) : ")
    if again.lower() == "n":
        print("nn-------Thank you for playing!--------nn")
        playing = False
    return True # Tells `turn()` the game is over

最新更新