- Tkinter GUI Programming by Example
- David Love
- 274字
- 2021-08-27 18:49:10
The Deck class
The Deck will need to contain 52 unique cards and must be able to shuffle itself. It will also need to be able to deal cards and decrease in size as cards are removed:
class Deck:
def __init__(self):
self.cards = [Card(s, v) for s in ["Spades", "Clubs", "Hearts",
"Diamonds"] for v in ["A", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "J", "Q", "K"]]
def shuffle(self):
if len(self.cards) > 1:
random.shuffle(self.cards)
def deal(self):
if len(self.cards) > 1:
return self.cards.pop(0)
When creating an instance of the Deck, we simply need to have a collection of every possible card. We achieve this using a list comprehension which contains lists of every suit and value. We pass each combination over to the initialization for our Card class to create 52 unique Card instances.
Our Deck will need to be able to be shuffled, so that every game is different. We use the shuffle function in the random library to do this for us. To avoid any potential errors, we will only shuffle a deck which still has two or more cards in it, since shuffling one or zero cards is pointless.
After shuffling, we will need to deal cards too. We utilize the pop function of a list (which is the data structure holding our cards) to return the top card and remove it from the deck so that it cannot be dealt again.
The final utility concept to be created for our game to work is the concept of a Hand. All players have a hand of cards, and each hand is worth a numerical value based on the cards it contains.
- C++面向?qū)ο蟪绦蛟O(shè)計(jì)(第三版)
- Boost程序庫(kù)完全開(kāi)發(fā)指南:深入C++”準(zhǔn)”標(biāo)準(zhǔn)庫(kù)(第5版)
- Visual Studio 2012 Cookbook
- Linux核心技術(shù)從小白到大牛
- .NET 4.0面向?qū)ο缶幊搪劊夯A(chǔ)篇
- Scala Design Patterns
- SSM輕量級(jí)框架應(yīng)用實(shí)戰(zhàn)
- RabbitMQ Cookbook
- Getting Started with Python and Raspberry Pi
- Python 3 數(shù)據(jù)分析與機(jī)器學(xué)習(xí)實(shí)戰(zhàn)
- 工業(yè)機(jī)器人離線編程
- Android移動(dòng)應(yīng)用開(kāi)發(fā)項(xiàng)目教程
- Python預(yù)測(cè)之美:數(shù)據(jù)分析與算法實(shí)戰(zhàn)(雙色)
- Solr權(quán)威指南(下卷)
- Learn C Programming