菜鸟学Python之写抽奖Demo

记得以前上大学时学C++的期末大作业, 也是写了个MFC的36选6的抽奖程序自娱自乐, 这次看着支付宝里的收益周周乐, 也想搞个程序来预测下结果. 本来是想用支付宝小程序写的, 不过没那么多时间玩他的IDE, 只能用摸鱼时间在VsCode里写写Python实现了(主要是布局页面弄的好麻烦,没样式又不好看,调试还慢).

先上成果运行贴图:

 

代码分成两个文件, 一个主要是使用tkinter 的窗体布局, 熟悉输入输出和按钮事件响应, 另一个是读写sqlite以及抽奖逻辑,熟悉数据库操作和集合数据类型的运用.

数据表: 

CREATE TABLE "tb_gaming_result" (
    "id"    INTEGER PRIMARY KEY AUTOINCREMENT,
    "release_time"    INTEGER,
    "game_result"    INTEGER
)

上代码:

#gaming.py  主入口

from tkinter import *
import tkinter.messagebox
from gamingsql import *


class GamingDialog():

    # 类构造函数, 初始化数据库连接
    def __init__(self, tk):
        self.dialog = tk
        self.sqlOper = GamingSql('./gaming.db3')
        self.pgOne = 0

    #对话框窗体布局
    def initiate_dialog(self):
        self.predictText=[]
        for i in range(4) :
            self.predictText.append(StringVar())
            self.predictText[i].set("0")

        self.dialog.title("收益周周乐")
        self.topFrame = Frame(self.dialog, height=20, width=320)
        self.topFrame.grid(row=0, column=0, columnspan=8)
        self.btnPredict = Button(
            self.dialog, text="马上预测", command=self.predictNext)
        self.btnPredict.grid(row=1, column=1)
        self.lbPedict = Label(self.dialog, text=":")
        self.lbPedict.grid(row=1, column=2)

        self.lbPedictContent1 = Label(
            self.dialog, textvariable=self.predictText[0], bd=2, relief="solid")
        self.lbPedictContent1.grid(row=1, column=3)
        self.lbPedictContent2 = Label(
            self.dialog, textvariable=self.predictText[1], bd=2, relief="solid")
        self.lbPedictContent2.grid(row=1, column=4)
        self.lbPedictContent3 = Label(
            self.dialog, textvariable=self.predictText[2], bd=2, relief="solid")
        self.lbPedictContent3.grid(row=1, column=5)
        self.lbPedictContent4 = Label(
            self.dialog, textvariable=self.predictText[3], bd=2, relief="solid")
        self.lbPedictContent4.grid(row=1, column=6)

        self.middleFrame = Frame(self.dialog, height=20, width=320)
        self.middleFrame.grid(row=2, column=0, columnspan=8)
        self.lbFrame = LabelFrame(self.dialog, text="上期开奖结果")
        self.lbFrame.grid(row=3, column=0, columnspan=8)
        self.lbGameDay = Label(self.lbFrame, text="开奖日")
        self.lbGameDay.grid(row=0, column=1)
        self.lbGameResult = Label(self.lbFrame, text="结果")
        self.lbGameResult.grid(row=0, column=3)
        self.tbGameDay = Entry(self.lbFrame)
        self.tbGameDay.grid(row=1, column=1)
        self.tbGameResult = Entry(self.lbFrame)
        self.tbGameResult.grid(row=1, column=3)
        self.lbbFrame = Frame(self.lbFrame, height=20, width=320)
        self.lbbFrame.grid(row=2, column=0, columnspan=8)
        self.btnResult = Button(self.lbFrame, text="保存",
                                command=self.addResult)
        self.btnResult.grid(row=3, column=0, columnspan=6)

        self.bottomFrame = Frame(self.dialog, height=20, width=320)
        self.bottomFrame.grid(row=4, column=0, columnspan=8)
        self.botFrame = LabelFrame(self.dialog, text="开奖历史", width=320)
        self.botFrame.grid(row=6, column=0, columnspan=8)
        self.lbRes = []
        for i in range(4) :
            self.lbRes.append( Label(self.botFrame, text="") )
            self.lbRes[i].grid(row=i, columnspan=6)

    # 马上预测按钮事件
    def predictNext(self):
        predict = self.sqlOper.GetPredict()
        for i in range(4):
            self.predictText[i].set(predict[i])

    # 保存按钮事件
    def addResult(self):
        txDate = self.tbGameDay.get()
        txResult = self.tbGameResult.get()
        if len(txDate) == 0 or len(txResult) == 0 :
            tkinter.messagebox.showwarning("温馨提醒","请输入正确信息")
        else:
            self.sqlOper.NewGameResult(self.tbGameDay.get(), self.tbGameResult.get())
            tkinter.messagebox.showinfo("记录保存", "添加成功")

    def refresh_data(self):
        # 需要刷新数据的操作
        pgRow = 4
        total = self.sqlOper.GetTotalResult()
        totalP = total//2 

        result = self.sqlOper.GetPageResult(self.pgOne, pgRow)
        tit = self.pgOne 
        for i in range(4) :
            if tit + i + 1 <= total:
                self.lbRes[i]["text"]= ' %s  %s: (%04d) ' % (tit +i + 1, result[i][0], result[i][1] )
            else :
                self.lbRes[i]["text"]= ''
        self.pgOne += 2
        if self.pgOne >= totalP:
           self.pgOne = 0 
        self.dialog.after(3800, self.refresh_data) 
#主入口
if __name__ == '__main__':
    top = Tk()
    gaming = GamingDialog(top)
    # 设置根窗口默认属性
    gaming.initiate_dialog()
    gaming.refresh_data()
    # 进入消息循环
    top.mainloop()

#gamingsql.py 负责将开奖结果保存进数据库, 以及查出历史开奖结果进行预测.

import sqlite3
import random
import time


class GamingSql():
    def __init__(self, dbFile):
        self.dbFile = dbFile

    def connect(self):
        self.con = sqlite3.connect(self.dbFile)
        self.dbCursor = self.con.cursor()
        
    # 分页查询历史中奖结果
    def GetAllResult(self, pageNo, pageRow):
        self.connect()
        sql = "select release_time,game_result from tb_gaming_result order by release_time desc"
        if pageRow > 0:
            sql = sql + " limit %d,%d " % (pageNo*pageRow, pageRow)
        dbResults = self.dbCursor.execute(sql)
        allDatas = dbResults.fetchall()
        self.dbCursor.close()
        self.con.close()
        return allDatas

    def GetPageResult(self, index, pageRow):
        self.connect()
        sql = "select release_time,game_result from tb_gaming_result order by release_time desc"
        if pageRow > 0:
            sql = sql + " limit %d,%d " % (index, pageRow)
        dbResults = self.dbCursor.execute(sql)
        allDatas = dbResults.fetchall()
        self.dbCursor.close()
        self.con.close()
        return allDatas

    # 新增或更新开奖记录
    def NewGameResult(self, rtime, gresult):
        self.connect()
        sql = "select id from tb_gaming_result where release_time=:rtime "
        dbResults = self.dbCursor.execute(sql, {'rtime': rtime})
        aid = dbResults.fetchone()
        if aid is None:
            sql = ' insert into tb_gaming_result(release_time, game_result) values (:rtime, :gresult)'
            self.dbCursor.execute(sql, {'rtime': rtime, 'gresult': gresult})
            self.con.commit()
        else:
            sql = ' update tb_gaming_result set game_result=:gresult where release_time=:rtime'
            self.dbCursor.execute(sql, {'rtime': rtime, 'gresult': gresult})
            self.con.commit()
        self.dbCursor.close()
        self.con.close()

    #获取总记录数量
    def GetTotalResult(self):
        self.connect()
        sql = "select count(1) as total from tb_gaming_result "
        dbResults = self.dbCursor.execute(sql)
        allDatas = dbResults.fetchone()
        total = 0
        if allDatas is not None:
            total = allDatas[0]
        self.dbCursor.close()
        self.con.close()
        return total

    #概率预测
    def GetPredict(self):
        totalCount = self.GetTotalResult()
        gamecount = totalCount + 1
        t = []
        for x in range(4):
            u = []
            for y in range(10):
                u.append(gamecount)
            t.append(u)
        n = 0
        pageno = 0
        while n < totalCount:
            pageResult = self.GetAllResult(pageno, 20)
            if pageResult is not None:
                arrLen = len(pageResult)
                for x in range(arrLen):
                    gr = str('%04d' % pageResult[x][1])
                    for y in range(4):
                        t[y][int(gr[y])] -= 1
            n = n + 20
            pageno = pageno+1
        gameResult = ''
        for x in range(4):
            kr = []
            for y in range(10):
                for z in range(t[x][y]):
                    kr.append(y)
            krlen = len(kr)
            gameResult = gameResult+self.randomGameble(kr, krlen)
        return gameResult

    #单位数随机抽取
    def randomGameble(self, alist, alen):
        ranlist = random.sample(alist, alen)
        time.sleep(random.randrange(10, 500)/1000)
        gindex = random.randrange(alen)
        return str(ranlist[gindex])

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值