python 图形界面“诈金花”游戏,更新了!附完整代码

news/2024/11/7 18:23:03/

旧版本的代码请见上一篇博文: 

python 从一道作业题到制作一个图形界面的“诈金花”游戏_Hann Yang的博客-CSDN博客Player1: ('♥Q', '♣2', '♣8') - 单张Player2: ('♦10', '♥7', '♠6') - 单张Player3: ('♣4', '♠4', '♦2') - 对子Player4: ('♠5', '♠9', '♥6') - 单张Player5: ('♠7', '♠3', '♣5') - 单张【Player3 win!】--> ('♣4', '♠4', '♦2') 对子(16.94%)https://blog.csdn.net/boysoft2002/article/details/128146513本文尝试在旧版本的基础上,“升级”以下几个部分:

一、图形的旋转,模拟四个玩家两两面对围坐在牌桌上

旋转方法 rotate(angle) 本文只用到转动角度这一个参数,角度正值表示逆时针转动;负值表示顺时针转动。

method rotate in module PIL.Image:

rotate(angle, resample=0, expand=0, center=None, translate=None, fillcolor=None) method of PIL.Image.Image instance
    Returns a rotated copy of this image.  This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre.
    :param angle: In degrees counter clockwise.
    :param resample: An optional resampling filter.  This can be one of :py:data: `PIL.Image.NEAREST`  (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC`
       (cubic spline interpolation in a 4x4 environment).
       If omitted, or if the image has mode "1" or "P", it is set to :py:data: `PIL.Image.NEAREST`. See :ref:`concept-filters`.
    :param expand: Optional expansion flag.  If true, expands the output image to make it large enough to hold the entire rotated image.
       If false or omitted, make the output image the same size as the input image.  Note that the expand flag assumes rotation around the center and no translation.
    :param center: Optional center of rotation (a 2-tuple).  Origin is the upper left corner.  Default is the center of the image.
    :param translate: An optional post-rotate translation (a 2-tuple).
    :param fillcolor: An optional color for area outside the rotated image.
    :returns: An :py:class:`~PIL.Image.Image` object.

如不是正方形图片,转动角度不是180度的话,就会被截掉一部分。效果如下: 

演示代码:

import tkinter as tk
from PIL import Image,ImageTkdef load(i=0):img = Image.open("pokers.png").resize((375,150))box = img.rotate(90*i)res = ImageTk.PhotoImage(image=box)img.close()return resif __name__ == '__main__':root = tk.Tk()root.geometry('800x480')root.title('图片旋转')cv = tk.Canvas(root, width=1600, height=800, bg='darkgreen')cv.pack()png = [None]*4coord = ((i,j) for j in (120,345) for i in (200,600))for i,xy in enumerate(coord):png[i] = load(i)cv.create_image(xy, image=png[i])cv.create_text(xy[0],xy[1]+95, text=f'逆时针转动{i*90}度',fill='white')root.mainloop()

为保存全图在转动之前,设置一个正方形框 box = img.crop((0,0,375,375)).rotate(-90*i),顺时针转动的效果如下:

演示代码:

import tkinter as tk
from PIL import Image,ImageTkdef load(i=0):img = Image.open("pokers.png").resize((375,150))box = img.crop((0,0,375,375)).rotate(-90*i)res = ImageTk.PhotoImage(image=box)img.close()return resif __name__ == '__main__':root = tk.Tk()root.geometry('800x800')root.title('图片旋转')cv = tk.Canvas(root, width=1600, height=800, bg='darkgreen')cv.pack()png = []coord = ((i,j) for j in (200,600) for i in (200,600))for i,xy in enumerate(coord):png.append(load(i))cv.create_image(xy, image=png[i])root.mainloop()

然后再用crop()方法来截取出黑色背景除外的部分,就是所需的转动四个方向上的图像;最后把这些图片再次分割成一张张小纸牌,存入一个三维列表备用。 

二、增加筹码变量,使得比大小游戏有累积输赢过程

在玩家文本框后各添加一个筹码文本框,动态显示每一局的输赢情况;各玩家的筹码值存放于全局变量Money列表中,主要代码如下:

    ALL, ONE = 1000, 200 #筹码初始值、单次输赢值Money = [ALL]*4 #设置各方筹码初始值......cv.create_text(tx,ty, text=f'Player{x+1}', fill='white') #玩家1-4显示文本框txt.append(cv.create_text(tx+60,ty, fill='gold',text=Money[x])) #筹码显示框......Money[idx] += ONE*4 #每次赢ONE*3,多加自己的一份for i in range(4):Money[i] -= ONE #多加的在此扣减cv.itemconfig(txt[i], text=str(Money[i])) #修改各方的筹码值cv.update()

三、界面增加下拉式菜单,菜单项调用的绑定函数

显示效果见题图左上角,主要代码如下:

    btnCmd = '发牌',dealCards,'开牌',playCards,'洗牌',ShuffleMenu = tk.Menu(root)menu = tk.Menu(Menu, tearoff = False)for t,cmd in zip(btnCmd[::2],btnCmd[1::2]):menu.add_radiobutton(label = t, command = cmd)menu.add_separator() #菜单分割线menu.add_command(label = "退出", command = ExitApp)Menu.add_cascade(label="菜单",menu = menu)root.config(menu = Menu)

四、导入信息框库,增加提示信息框的使用

使用了2种信息框类型:提示showinfo()和确认选择askokcancel()

tkinter.messagebox库共有8种信息框类型,其使用方法基本相同,只是显示的图标有区别:

Help on module tkinter.messagebox in tkinter:

NAME
    tkinter.messagebox

FUNCTIONS
    askokcancel(title=None, message=None, **options)
        Ask if operation should proceed; return true if the answer is ok
    
    askquestion(title=None, message=None, **options)
        Ask a question
    
    askretrycancel(title=None, message=None, **options)
        Ask if operation should be retried; return true if the answer is yes
    
    askyesno(title=None, message=None, **options)
        Ask a question; return true if the answer is yes
    
    askyesnocancel(title=None, message=None, **options)
        Ask a question; return true if the answer is yes, None if cancelled.
    
    showerror(title=None, message=None, **options)
        Show an error message
    
    showinfo(title=None, message=None, **options)
        Show an info message
    
    showwarning(title=None, message=None, **options)
        Show a warning message

DATA
    ABORT = 'abort'
    ABORTRETRYIGNORE = 'abortretryignore'
    CANCEL = 'cancel'
    ERROR = 'error'
    IGNORE = 'ignore'
    INFO = 'info'
    NO = 'no'
    OK = 'ok'
    OKCANCEL = 'okcancel'
    QUESTION = 'question'
    RETRY = 'retry'
    RETRYCANCEL = 'retrycancel'
    WARNING = 'warning'
    YES = 'yes'
    YESNO = 'yesno'
    YESNOCANCEL = 'yesnocancel'

:发牌、开牌、洗牌按钮可否点击,由两个全局变量控制,当不能使用时弹出提示信息框。但更好方式通常是设置按钮的state状态,在 tk.DISABLED 和 tk.NORMAL 之间切换,用以下代码:

if btn[0]['state'] == tk.DISABLED:btn[0]['state'] = tk.NORMAL
else:btn[0]['state'] = tk.DISABLED  #使得按钮灰化,无法被按下#或者在初始按钮时使用:
tk.Button(root,text="点不了",command=test,width=10,state=tk.DISABLED)

“诈金花”完整源代码

import tkinter as tk
import tkinter.messagebox as msg
from PIL import Image,ImageTk
from time import sleep
from random import shuffle as DealCards
#代码中所有print()语句行测试用都可删除
def loadCards():PngList = []infile = Image.open("pokers.png") for k in range(4):box = 0,0,1500,1500 #设置正方形区域存放图片旋转后的状态box = infile.crop(box).rotate(90*k) #图片逆时间旋转90度的整数倍if   k==0: rng = (0,0,1500,600)elif k==1: rng = (0,0,600,1500)elif k==2: rng = (0,900,1500,1500)elif k==3: rng = (900,0,1500,1500)box = box.crop(rng) #截取掉旋转产生的黑色背景images = []for j in range(4): #分割所有纸牌的图像存入三维列表image = []for i in range(15):if k%2:rng = (j*150,i*100,j*150+150,i*100+100)else:rng = (i*100,j*150,i*100+100,j*150+150)img = ImageTk.PhotoImage(image=box.crop(rng))image.append(img)images.append(image)PngList.append(images)'''调整并统一各方向上的纸牌图像顺序'''PngList[0],PngList[2] = PngList[2],PngList[0]for i in range(4):for j in range(2):PngList[j][i]=PngList[j][i][::-1]for i in range(0,4,3):PngList[i]=PngList[i][::-1]infile.close()return PngListdef initCards():global PP = [f+v for f in F for v in V]DealCards(P)print('洗牌结果:\n',P)def clearCards():global cvcv.itemconfig(txt1, text="")cv.itemconfig(txt2, text="")if len(Pokers):for j in range(3):for i in range(4):cv.itemconfig(cards[i][j], image=Cards[i][0][0])cv.update()sleep(0.3)def dealCards():global cv,isReady1,isReady2if not isReady1:showInfo('不要重复发牌,发牌结束后请开牌!')returnclearCards()isReady1 = Falsefor j in range(3):for i in range(4):cv.itemconfig(cards[i][j], image=Cards[i][1][0])cv.update()sleep(0.2)if len(P)<12: initCards()isReady2 = Falsedef playCards():global cv,isReady1,isReady2,P,Pokersif isReady1:showInfo('还没发牌,请发牌或者洗牌!')elif isReady2:showInfo('发牌还未结束,请勿开牌!')else:P = Result(P)isReady1,isReady2 = True,Truefor i,pok in enumerate(Pokers):for j,p in enumerate(pok):x,y = F.index(p[0]), V.index(p[1])cv.itemconfig(cards[i][j], image=Cards[i][x][y+2])cv.update()for i in range(4):cv.itemconfig(txt[i], text=str(Money[i])) #修改各方的筹码值cv.update()if min(Money)<=0: #统计输赢成绩zero = [f'Player{i}' for i,j in enumerate(Money,1) if j<=0]winner = [f'Player{i}({j})' for i,j in enumerate(Money,1) if j>ALL]info = '、'.join(zero)+'已输光筹码,点击确定重新开始!\n\n'info += f'本轮胜者(筹码多于初始值):'+'、'.join(winner)sleep(1)msg.showinfo(title = '提示',message=info)for i in range(4):Money[i] = ALL #重置各方筹码初始值cv.itemconfig(txt[i], text=str(Money[i])) cv.update()clearCards()initCards()isReady1,isReady2 = True,Falsedef Scores(pokers):f,p = [],[]for poker in pokers:f.append(F.index(poker[0])+1)p.append(V.index(poker[1])+2)t = sorted(p)intSame = len(set(t))isFlush = int(len(set(f))==1)isStraight = t[0]+1==t[1]==t[2]-1if intSame==1:return 500_0000+t[0] #豹子elif intSame==2: #对子一样大比较剩下的单张return (100+t[1])*10000+(t[2] if t[0]==t[1] else t[0])else: #顺金(同花顺)顺子 else #单张或金花Straight = 200_0000*(1+isFlush)+t[2]Flush = ((300*isFlush+t[2])*100+t[1])*100+t[0] return Straight if isStraight else Flushdef Result(P):global cv,PokersPokers,Winner = [],[]for i in range(0,3*4,3):Pokers.append(P[i:i+3])for i,p in enumerate(Pokers,1):win = Scores(p)idx = win//100_0000print(f"Player{i}: {*p,} - {W[idx]}".replace('T','10'))Winner.append(win)win = max(Winner) #没有判断“一样大”,如是则谁在前谁为大idx = Winner.index(win)big = win//10000win = big//100per = X[win] if win else Y[big-5]pok = W[win] if win else '单'+V[big-2]text1 = f"【Player{idx+1} win!】"text2 = f"{pok}{*Pokers[idx],} {per}%\n".replace('T','10')print(text1,'--> ',text2)cv.itemconfig(txt1, text=text1)cv.itemconfig(txt2, text=text2)Money[idx] += ONE*4 #每次赢ONE*3,多加自己的一份for i in range(4): Money[i] -= ONE #多加的在此扣减return P[3*4:] #去掉一局已发的牌def Shuffle():global isReady1if isReady1:clearCards()initCards()showInfo('已重新洗牌,请发牌!')else:showInfo('还没开牌呢,请勿洗牌!')def showInfo(info):msg.showinfo(title='提示',message=info)def ExitApp():if msg.askokcancel(title='确认',message='确定要退出吗?'):root.destroy()  #关闭窗口退出程序if __name__ == '__main__':W = "单张","对子","顺子","金花","顺金","豹子" #牌型X = 74.38, 16.94, 3.26, 4.96, 0.22, 0.24  #各牌型出现概率Y = 0.54, 1.36, 2.44, 3.8, 5.43, 7.33, 9.5, 11.95, 14.66, 17.38 #单张概率V = *(str(i) for i in range(2,10)),*'TJQKA' #T代表10F = '♠', '♥', '♣', '♦'ALL, ONE = 1000, 200 #筹码初始值、单次输赢值Money = [ALL]*4 #设置各方筹码初始值'''Written by HannYang@CSDN, 2022.12.03'''root = tk.Tk()root.title('诈金花')root.geometry('1024x768')root.resizable(0,0) #禁止窗体改变大小cv = tk.Canvas(root, width=1024, height=680, bg='darkgreen')cv.pack()Pokers = []initCards()Cards = loadCards()isReady1,isReady2 = True,True #发牌、开牌的准备标记cards = [[None]*3 for _ in range(4)]'''设置发牌区域'''x1, x2, x3, dx = 400, 180, 830, 105y1, y2, y3 = 100, 550, 220 #调整坐标,使左右两家的牌横向显示imgxy = [[(x1,y1),(x1+dx,y1),(x1+2*dx,y1)],[(x3,y3),(x3,y3+dx),(x3,y3+2*dx)],[(x1,y2),(x1+dx,y2),(x1+2*dx,y2)],[(x2,y3),(x2,y3+dx),(x2,y3+2*dx)]]btn,txt = [],[]for x,lst in enumerate(imgxy):for y,coord in enumerate(lst):cards[x][y] = cv.create_image(coord, image=Cards[x][0][0])x1,y1,x2,y2 = coord[0]-50,coord[1]-50,coord[0]+50,coord[1]+50if x%2:cv.create_rectangle(x1-25,y1,x2+25,y2) #纸牌外框else:cv.create_rectangle(x1,y1-25,x2,y2+25)if x%2:tx,ty = coord[0]-25,coord[1]+65 #玩家、筹码的显示坐标else:tx,ty = coord[0]-130,coord[1]+90cv.create_text(tx,ty, text=f'Player{x+1}', fill='white') #玩家1-4显示文本框txt.append(cv.create_text(tx+60,ty, fill='gold',text=Money[x])) #筹码显示框'''设置显示每次开牌的胜者、牌型和出现概率的文本框'''txt1 = cv.create_text(510,300, fill='tomato', font=("宋体", 24))txt2 = cv.create_text(510,360, fill='yellow', font=("宋体", 12))'''设置命令按钮和菜单'''btnCmd = '发牌',dealCards,'开牌',playCards,'洗牌',Shufflefor i in range(3):btn.append(tk.Button(root,text=btnCmd[i*2],command=btnCmd[i*2+1],width=10))btn[i].place(y=710, x=350+i*110)Menu = tk.Menu(root)menu = tk.Menu(Menu, tearoff = False)for t,cmd in zip(btnCmd[::2],btnCmd[1::2]):menu.add_radiobutton(label = t, command = cmd)menu.add_separator() #菜单分割线menu.add_command(label = "退出", command = ExitApp)Menu.add_cascade(label="菜单",menu = menu)root.config(menu = Menu)''''''root.mainloop()

运行结果:


http://www.ppmy.cn/news/2113.html

相关文章

多数之和问题

文章目录多数求和问题1两数之和(无序)题解2两数之和(有序)题解3两数之和(二叉搜索树)题解4 三数之和题解5四数之和题解多数求和问题 针对给一组用例,和一个目标数target,求用例中多数相加等于target的所有数,且不能重复问题,一般有两种解法: 集合(不要求排序)双指针(要求排序…

springboot基于Java的电影院售票与管理系统毕业设计源码011449

电影院售票与管理系统的设计与实现 摘 要 信息化社会内需要与之针对性的信息获取途径&#xff0c;但是途径的扩展基本上为人们所努力的方向&#xff0c;由于站在的角度存在偏差&#xff0c;人们经常能够获得不同类型信息&#xff0c;这也是技术最为难以攻克的课题。针对电影院售…

JVM—双亲委派

文章目录什么是双亲委派&#xff1f;为什么要有双亲委派原理&#xff1f;破坏双亲委派的例子————————————————————————————————什么是双亲委派&#xff1f; ​ 就是我们写的java源文件到最终运行&#xff0c;必须要经过编译和类加载这两个阶段…

Springboot企业资源管理信息系统kvonv计算机毕业设计-课程设计-期末作业-毕设程序代做

Springboot企业资源管理信息系统kvonv计算机毕业设计-课程设计-期末作业-毕设程序代做 【免费赠送源码】Springboot企业资源管理信息系统kvonv计算机毕业设计-课程设计-期末作业-毕设程序代做本源码技术栈&#xff1a; 项目架构&#xff1a;B/S架构 开发语言&#xff1a;Java…

TCP--三次握手和四次挥手

原文网址&#xff1a;TCP--三次握手和四次挥手_IT利刃出鞘的博客-CSDN博客 简介 本文介绍TCP的三次握手和四次挥手。即&#xff1a;TCP建立连接和断开连接的过程。 三次握手 流程图 主机 A为客户端&#xff0c;主机B为服务端。 第一次握手 A 发送同步报文段&#xff08;SYN…

一篇文章让你搞懂各种压缩,gzip压缩,nginx的gzip压缩,Minification压缩

前言 同学们可能听过这些压缩&#xff0c;但是可能不是了解&#xff0c;这篇文章让你弄清他们 webpack的gzip压缩和nginx的gzip压缩有什么区别&#xff1f;怎样开启gzip压缩&#xff1f;Minfication压缩又是什么鬼&#xff1f;怎样使项目优化的更好&#xff1f;本篇文章讲的是…

TypeScript算法题实战——二叉搜索树篇

二叉搜索树&#xff0c;也叫二叉查找树、二叉排序树&#xff0c;是具有下列性质的二叉树&#xff1a; 若它的左子树不空&#xff0c;则左子树上所有结点的值均小于它的根结点的值&#xff1b; 若它的右子树不空&#xff0c;则右子树上所有结点的值均大于它的根结点的值。 注意…

C++校园导游程序及通信线路设计

C校园导游程序及通信线路设计 一、设计内容&#xff1a; 设计校园平面图&#xff0c;所含景点不少于10个。以图中顶点表示校内各景点&#xff0c;存放景点名称、代号、简介等信息&#xff1b;以边表示路径&#xff0c;存放路径长度等相关信息。 (1) 显示校园平面图&#xff08…