Bootstrap

python扑克游戏_Python-----模拟扑克纸牌游戏

运用类完成一个扑克牌类(无大小王)的小游戏: 用户需要输入用户名,以下为用户可选选项: 1. 洗牌 2. 随机抽取一张 3. 指定抽取一张 4. 从小到大排序 5. 退出

洗牌:每次执行的结果顺序随机。

随机抽取一张:显示结果为:太白金星您随机抽取的牌为:黑桃K

指定抽取一张: 用户输入序号(1~52) 比如输入5,显示结果为:太白金星您抽取的第5张牌为:黑桃A

将此牌从小到大显示出来。A -> 2 -> 3 .......-> K

提供思路: 52张牌可以放置一个容器中。 用户名,以及盛放牌的容器可以封装到对象属性中。

low版 import random class Cards: def init(self,name,allcards): self.name = name self.allcards = allcards

def shuffle_card(self):

print(list(set(self.allcards)))

def take_card(self):

z1 = self.allcards

random.shuffle(z1)

print(f'{self.name}您随机抽取的牌为:{z1[0]}')

def draw(self):

num = int(input('请输入指定的牌顺序:').strip())

print(f'{self.name}您抽取的第{num}张牌为:{self.allcards[num - 1]}')

def sorting(self):

print(self.allcards)

def end(self):

exit()

print('1.洗牌\n2.随机抽取一张\n3.指定抽取一张\n4.从小到大排序\n5.退出\n')

n = input('请输入用户名:').strip() while 1: allcards = [] lis1 = ['红心', '草花', '黑桃', '方片'] for i in lis1: for k in range(1, 14): if k == 1: allcards.append((i, 'A')) elif k == 11: allcards.append((i, 'J')) elif k == 12: allcards.append((i, 'Q')) elif k == 13: allcards.append((i, 'K')) else: allcards.append((i, k)) num = int(input('请输入序号选择:').strip()) s1 = Cards(n,allcards) dic = {1: s1.shuffle_card,2: s1.take_card,3: s1.draw,4: s1.sorting,5: s1.end} dicnum

进阶版 import random class Poker: rank = ['A'] + [str(i) for i in range(2,11)] + list('JQK') color = '黑桃 红心 方片 梅花'.split() def init(self,username): self.username = username self.cards = [(c,r) for c in self.color for r in self.rank]

def shuffle(self):

random.shuffle(self.cards)

return self.cards

def _random(self):

card = random.choice(self.cards)

return f'{self.username}您随机抽取的牌为: {card[0]}{card[1]}'

def appoint(self):

num = input('请输入选项:').strip()

card = self.cards[int(num)-1]

return f'{self.username}您抽取的第{num}张牌为: {card[0]}{card[1]}'

def sort(self):

self.sort_card = [(c,r)for r in self.rank for c in self.color]

return self.sort_card

def exit_out(self):

exit('成功退出程序')

def main(): choice_dict = { 1 : Poker.shuffle, 2 : Poker._random, 3 : Poker.appoint, 4 : Poker.sort, 5 : Poker.exit_out, } while 1: username = input('请输入用户名:').strip() obj = Poker(username) print( ''' 1.洗牌 2.随机抽取一张 3.指定抽取一张 4.从小到大排序 5.退出 ''' ) choice_num = input('请输入选项:').strip() print(choice_dictint(choice_num))

if name == 'main': main()

;