给我用Python写一个斗地主的游戏代码
时间: 2024-04-25 11:14:40 浏览: 177
python实现斗地主游戏
好的,以下是一个简单的斗地主游戏代码,希望能帮到你:
```python
import random
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f"{self.suit}{self.rank}"
class Deck:
suits = ["♠", "♥", "♣", "♦"]
ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
def __init__(self):
self.cards = [Card(suit, rank) for suit in self.suits for rank in self.ranks]
def shuffle(self):
random.shuffle(self.cards)
def deal(self):
return self.cards.pop()
class Player:
def __init__(self, name):
self.name = name
self.cards = []
def add_card(self, card):
self.cards.append(card)
def remove_card(self, card):
self.cards.remove(card)
def sort_cards(self):
self.cards.sort(key=lambda card: (Deck.suits.index(card.suit), Deck.ranks.index(card.rank)))
def show_cards(self):
print(f"{self.name}的牌:", end=" ")
for card in self.cards:
print(card, end=" ")
print("\n")
def main():
deck = Deck()
deck.shuffle()
player1 = Player("玩家1")
player2 = Player("玩家2")
player3 = Player("玩家3")
for i in range(17):
player1.add_card(deck.deal())
player2.add_card(deck.deal())
player3.add_card(deck.deal())
landlord_cards = []
for i in range(3):
landlord_cards.append(deck.deal())
print("地主牌:", end=" ")
for card in landlord_cards:
print(card, end=" ")
print("\n")
player1.sort_cards()
player2.sort_cards()
player3.sort_cards()
player1.show_cards()
player2.show_cards()
player3.show_cards()
if __name__ == "__main__":
main()
```
这个代码实现了一个简单的斗地主游戏,包括牌的初始化、洗牌、发牌、排序等操作。你可以基于此代码继续完善斗地主游戏的其他玩法和逻辑。
阅读全文