python 图形界面“诈金花”游戏,更新了!附完整代码_python把52张扑克图片转为界面

(1)Python所有方向的学习路线(新版)

这是我花了几天的时间去把Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

最近我才对这些路线做了一下新的更新,知识体系更全面了。

在这里插入图片描述

(2)Python学习视频

包含了Python入门、爬虫、数据分析和web开发的学习视频,总共100多个,虽然没有那么全面,但是对于入门来说是没问题的,学完这些之后,你可以按照我上面的学习路线去网上找其他的知识资源进行进阶。

在这里插入图片描述

(3)100多个练手项目

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了,只是里面的项目比较多,水平也是参差不齐,大家可以挑自己能做的项目去练练。

在这里插入图片描述

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

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

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,ImageTk

def load(i=0):
    img = Image.open("pokers.png").resize((375,150))
    box = img.rotate(90*i)
    res = ImageTk.PhotoImage(image=box)
    img.close()
    return res

if __name__ == '__main__':
    root = tk.Tk()
    root.geometry('800x480')
    root.title('图片旋转')
    cv = tk.Canvas(root, width=1600, height=800, bg='darkgreen')
    cv.pack()

    png = [None]*4
    coord = ((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,ImageTk

def 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 res

if __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,'洗牌',Shuffle
    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)
四、导入信息框库,增加提示信息框的使用

使用了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()语句行测试用都可删除
#Written by Hann@CSDN,2022.12.06
#https://hannyang.blog.csdn.net/
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 PngList
 
def initCards():
    global P
    P = [f+v for f in F for v in V]
    DealCards(P)
    print('洗牌结果:\n',P)

def clearCards():
    global cv
    cv.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,isReady2
    if not isReady1:
        showInfo('不要重复发牌,发牌结束后请开牌!')
        return
    clearCards()
    isReady1 = False
    for 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 = False
 
def playCards():
    global cv,isReady1,isReady2,P,Pokers
    if isReady1:
        showInfo('还没发牌,请发牌或者洗牌!')
    elif isReady2:
        showInfo('发牌还未结束,请勿开牌!')
    else:
        P = Result(P)
        isReady1,isReady2 = True,True
        for 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])) #修改各方的筹码值


### 最后

不知道你们用的什么环境,我一般都是用的Python3.6环境和pycharm解释器,没有软件,或者没有资料,没人解答问题,都可以免费领取(包括今天的代码),过几天我还会做个视频教程出来,有需要也可以领取~  

给大家准备的学习资料包括但不限于:  

Python 环境、pycharm编辑器/永久激活/翻译插件  

python 零基础视频教程  

Python 界面开发实战教程  

Python 爬虫实战教程  

Python 数据分析实战教程  

python 游戏开发实战教程  

Python 电子书100本  

Python 学习路线规划

![](https://img-blog.csdnimg.cn/d29631674929476f9c3b30f7ff58dff0.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ZlaTM0Nzc5NTc5MA==,size_16,color_FFFFFF,t_70)




**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

0f7ff58dff0.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ZlaTM0Nzc5NTc5MA==,size_16,color_FFFFFF,t_70)




**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

  • 18
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值