用python写一个麻将游戏
时间: 2024-05-17 20:16:44 浏览: 201
使用Python写一个小游戏
好的,这是一个麻将游戏的代码示例,使用Python语言编写:
```python
import random
# 麻将牌总数
MAHJONG_COUNT = 144
# 麻将牌的种类
MAHJONG_KINDS = ["万", "条", "饼", "风", "箭"]
# 麻将牌的数字
MAHJONG_NUMS = ["一", "二", "三", "四", "五", "六", "七", "八", "九"]
# 风牌的种类
MAHJONG_FENG_KINDS = ["东", "南", "西", "北"]
# 箭牌的种类
MAHJONG_JIAN_KINDS = ["中", "发", "白"]
# 玩家初始手牌数量
INIT_HAND_COUNT = 13
# 麻将牌的类
class Mahjong:
def __init__(self, kind, num):
self.kind = kind
self.num = num
def __str__(self):
return self.num + self.kind
# 麻将牌堆的类
class MahjongHeap:
def __init__(self):
self.heap = []
self.init_heap()
self.shuffle()
# 初始化麻将牌堆
def init_heap(self):
for kind in MAHJONG_KINDS:
if kind == "风":
for feng in MAHJONG_FENG_KINDS:
for i in range(4):
self.heap.append(Mahjong(feng, ""))
elif kind == "箭":
for jian in MAHJONG_JIAN_KINDS:
for i in range(4):
self.heap.append(Mahjong(jian, ""))
else:
for num in MAHJONG_NUMS:
for i in range(4):
self.heap.append(Mahjong(kind, num))
# 洗牌
def shuffle(self):
random.shuffle(self.heap)
# 摸牌
def draw(self):
if len(self.heap) > 0:
return self.heap.pop()
else:
return None
# 玩家类
class Player:
def __init__(self, name):
self.name = name
self.hand = []
# 摸牌
def draw(self, mahjong):
self.hand.append(mahjong)
# 打牌
def discard(self, index):
if index >= 0 and index < len(self.hand):
return self.hand.pop(index)
else:
return None
# 显示手牌
def show_hand(self):
print(self.name + "的手牌:")
for i, mahjong in enumerate(self.hand):
print(str(i+1) + ": " + str(mahjong))
# 游戏类
class Game:
def __init__(self):
self.players = []
self.mahjong_heap = MahjongHeap()
# 添加玩家
def add_player(self, player):
self.players.append(player)
# 开始游戏
def start(self):
# 发牌
for i in range(INIT_HAND_COUNT):
for player in self.players:
player.draw(self.mahjong_heap.draw())
# 显示玩家手牌
for player in self.players:
player.show_hand()
# 主循环
while True:
for player in self.players:
# 玩家摸牌
mahjong = self.mahjong_heap.draw()
player.draw(mahjong)
print(player.name + "摸了一张牌:" + str(mahjong))
# 显示玩家手牌
player.show_hand()
# 玩家打牌
while True:
index = input(player.name + "打哪张牌?")
if index.isdigit():
index = int(index) - 1
mahjong = player.discard(index)
if mahjong is not None:
print(player.name + "打出了:" + str(mahjong))
break
else:
print("无效的牌号!")
else:
print("无效的输入!")
# 判断是否有人胡牌、和牌、杠牌、碰牌等等
# 判断是否有人胡牌
# 判断是否有人和牌
# 判断是否有人杠牌
# 判断是否有人碰牌
# 判断是否流局
# 结束游戏
def end(self):
pass
# 测试代码
if __name__ == "__main__":
game = Game()
game.add_player(Player("张三"))
game.add_player(Player("李四"))
game.add_player(Player("王五"))
game.start()
game.end()
```
阅读全文