打印我在键入“是”后使用的卡片,以便再次玩

2024-10-06 08:02:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让这场比赛开始时,每一手牌的剩余从上一手牌。相反,它开始于一个完整的,新洗牌甲板。我怎样才能把它修好继续? 我根据你的建议更新了代码,但是它没有显示我的展示卡,非常感谢

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 "\n\n-------Thank you for playing!--------\n\n"
            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 "\n\n-------Thank you for playing!--------\n\n"
main()

Tags: pipandofselfyouforifplayer
2条回答

有关完整的解决方案,请参见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)

每当有人请求handTotal时,@property修饰符就会强制它重新计算。你知道吗


告诉梅因你想继续玩

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

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

是的,你可以从上一场比赛结束的地方继续一场比赛。当前的问题是递归调用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 "\n\n   -Thank you for playing!    \n\n"

这样就消除了消息函数和对main的递归调用。你知道吗

相关问题 更多 >