1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| import random from time import sleep
class Card(object): def __init__(self, point, suit): self.suit = suit if point == "11": self.point = "J" elif point == "12": self.point = "Q" elif point == "13": self.point = "K" elif point == "1": self.point = "A" else: self.point = point
def __str__(self): return self.suit + self.point
class Game(object): def __init__(self): self.deck = [Card(str(point), suit) for point in range(1, 14) for suit in "♠♥♣♦"] self.playerDeck = [] self.computerDeck = []
def shuffle(self): random.shuffle(self.deck) random.shuffle(self.deck)
def playerDraw(self): self.shuffle() self.playerDeck.append(self.deck.pop()) for card in self.playerDeck: print(card, end=" ") print("玩家:目前共{0}點".format(pointSum(self.playerDeck)))
def computerDraw(self): self.shuffle() self.computerDeck.append(self.deck.pop()) for card in self.computerDeck: print(card, end=" ") print("電腦:目前共{0}點".format(pointSum(self.computerDeck)))
def pointSum(Deck): total1 = 0 total2 = 0 for card in Deck: if card.point == "A": total1 += 1 total2 += 11 elif card.point == "J" or card.point == "Q" or card.point == "K": total1 += 10 total2 += 10 else: total1 += int(card.point) total2 += int(card.point) if total2 > 21 > total1: total2 = total1 return total2
def drawACard(t): try: if input(t).upper() == "Y": return True else: return False except TypeError: return False
def isOver(deck): if pointSum(deck) > 21: return True else: return False
def main(): while drawACard("開始新的遊戲?(y/n)"): player, computer = True, True g = Game() g.playerDraw() g.computerDraw() while drawACard("繼續抽牌?(y/n)"): g.playerDraw() if isOver(g.playerDeck): print("電腦獲勝 玩家失敗") player = False break
while pointSum(g.computerDeck) < pointSum(g.playerDeck) and player: sleep(1) g.computerDraw() if isOver(g.computerDeck): print("電腦失敗 玩家獲勝") computer = False break if player and computer: print("電腦獲勝 玩家失敗")
if __name__ == '__main__': main()
|