❤️Python发牌--面向对象❤️

    科技2024-12-21  17

     

    #用Card类表示一张牌 class Card(): '''一张牌''' types = ['♥', '♠', '♦', '♣'] symbols = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] def __init__(self,types,symbols,face_up=True): self.types=types self.symbols=symbols self.isFace=face_up def __str__(self): if self.isFace: return self.types+self.symbols else: return 'XY' def flip(self): self.face_up=not self.face_up # 用Hand表示一个牌手(玩家) class Hand(): def __init__(self): self.cards=[] def add(self,card): self.cards.append(card) def clear(self): self.cards=[] def give(self,card,other_hand): other_hand.append(card) def __str__(self): if self.cards: rep ='' for c in self.cards: rep+=str(c)+'\t' else: rep='无牌' return rep #Poke类是对一幅牌的抽象,它可以被看做是拥有全部54张的牌手,所以继承了Hand类。 class Poke(Hand): def gen_poke(self):# 生成一副牌 for t in Card.types: for s in Card.symbols: self.add(Card(t,s)) def rand_poke(self):# 洗牌 import random as r r.shuffle(self.cards) def deal(self,hands,per_hand=13):# 将牌发给玩家,每人默认13张牌 for p in range(per_hand): for hand in hands: if self.cards: top_card=self.cards[0] self.cards.remove(top_card) hand.add(top_card) else: print('牌已发完!') def show_poke(players): results = [player.__str__() for player in players] pk = [] for result in results: pk1 = result.rstrip() pk2 = pk1.split('\t') print(pk2) pk.append(pk2) # 接下来要将这种字符串和图片挂钩 image_name = [] # 存放52张牌对应图片的地址 for i in range(len(pk)): for j in pk[i]: str_name = './images/{}.jpg'.format(j) image_name.append(str_name) wj = [image_name[i:i+13] for i in range(len(image_name)) if i%13==0] # 把图片分给四个玩家 return wj if __name__=='__main__': print('准备发牌') # 洗牌,发牌 players=[Hand(),Hand(),Hand(),Hand()] poke1=Poke() poke1.gen_poke() poke1.rand_poke() poke1.deal(players,13) wj = show_poke(players) # 打印牌,首先要从前面的表示方法转换为字符串,然后在转换为对应的图片集 # 图形显示各位玩家的牌 import tkinter as tk from PIL import Image,ImageTk win=tk.Tk() win.title('发牌程序') win.geometry('1024x768') cv=tk.Canvas(win,bg='green',width=1024,height=768) images=[] for i in range(4): for j in range(13): img=Image.open(wj[i][j]) images.insert(i*13+j,ImageTk.PhotoImage(img)) persons=[images[13*i:13*(i+1)]for i in range(4)] for x in range(0, 13): cv.create_image((240 + 40 * x, 80), image=persons[0][x]) cv.create_image((120, 150 + 40 * x), image=persons[1][x]) cv.create_image((240 + 40 * x, 680), image=persons[2][x]) cv.create_image((850, 150 + 40 * x), image=persons[3][x]) cv.pack() win.mainloop()

     素材及名称:

    效果图:

    学习参考部分代码

    Processed: 0.015, SQL: 8