原神抽卡模拟器

特色:用MD5生成随机种子,还原了原神中的抽卡概率
直接上代码


# -*- coding:utf-8 -*-
"""
作者:锡
作用:用tk抽卡
时间:
    1.0.0           11:16:30 2023年06月25日 五月初八
"""


import time
import hashlib
import random
import tkinter
import tkinter.ttk
import tkinter.messagebox


def computeMD5(message):
    m = hashlib.md5()
    m.update(message.encode(encoding='utf-8'))
    return m.hexdigest()


class DataObj:

    def __init__(self):
        self._cz_init_prb = [[0.006] * 73 + [min(0.066+i*0.06, 1) for i in range(17)], [0.051] * 8 + [0.561, 1]]
        self._upjs_init_prb = self._cz_init_prb
        self._upwq_init_prb = [[0.007] * 62 + [min(0.077+i*0.07, 1) for i in range(18)], [0.051] * 8 + [0.561, 1]]
        self._huo_form: dict = {
            'cz5js': ['迪希雅', '提纳里', '刻晴', '莫娜', '七七', '迪卢克', '琴'],
            'cz5wq': ['阿莫斯之弓', '天空之翼', '四风原典', '天空之卷', '和璞鸢', '天空之脊', '狼的末路',
                      '天空之傲', '天空之刃', '风鹰剑'
                      ],
            'up5js': ['白术', '艾尔海森', '流浪者', '纳西妲', '妮露', '赛诺', '夜兰', '神里绫人',
                      '八重神子', '申鹤', '荒泷一斗', '珊瑚宫心海', '雷电将军', '宵宫', '神里绫华',
                      '枫原万叶', '优菈', '胡桃', '魈', '甘雨', '阿贝多', '钟离', '达达利亚', '可莉',
                      '温迪'
                      ],
            'up5wq': ['裁叶萃光', '圣显之钥', '磐岩结绿', '波乱月白经津', '斫峰之刃', '雾切之回光',
                      '苍古自由之誓', '苇海信标', '赤角石溃杵', '松籁响起之时', '无工之剑', '终末嗟叹之诗',
                      '飞雷之弦振', '若水', '冬极白星', '猎人之径', '不灭月华', '尘世之锁', '千夜浮梦',
                      '碧落之珑', '图莱杜拉的回忆', '神乐之真意', '薙草之稻光', '护摩之杖', '赤沙之杖',
                      '贯虹之槊', '息灾'
                      ],
            '4js': ['卡维', '米卡', '瑶瑶', '珐露珊', '莱依拉', '坎蒂丝', '多莉', '柯莱', '久岐忍',
                    '云堇', '鹿野院平藏', '九条裟罗', '五郎', '早柚', '托马', '烟绯', '罗莎莉亚', '辛焱',
                    '砂糖', '迪奥娜', '重云', '诺艾尔', '班尼特', '菲谢尔', '凝光', '行秋', '北斗', '香菱',
                    '安柏', '雷泽', '凯亚', '芭芭拉', '丽莎'
                    ],
            'cz4wq': ['弓藏', '祭礼弓', '绝弦', '西风猎弓', '昭心', '祭礼残章', '流浪乐章', '西风秘典',
                      '西风长枪', '匣里灭辰', '雨裁', '祭礼大剑', '钟剑', '西风大剑', '匣里龙吟', '祭礼剑',
                      '笛剑', '西风剑'
                      ],
            'up4wq': ['暗巷闪光', '西福斯的月光', '玛海菈的水色', '千岩古剑', '恶王丸', '曚云之月', '暗巷猎手',
                      '幽夜华尔兹', '暗巷的酒与诗', '流浪的晚星', '千岩长枪', '断浪长鳍'
                      ],
            '3': ['弹弓', '神射手之誓', '鸦羽弓', '翡玉法球', '讨龙英杰谭', '魔导绪论', '黑缨枪', '以理服人',
                  '沐浴龙血的剑', '铁影阔剑', '飞天御剑', '黎明神剑', '冷刃'
                  ]
            }
        self._huo_datas: dict = {}

        for i, j in self._huo_form.items():
            for i0 in j:
                self._huo_datas[i0] = i

    @property
    def huo_form(self):
        return self._huo_form

    @property
    def huo_datas(self):
        return self._huo_datas

    @property
    def cz_init_prb(self):
        return self._cz_init_prb

    @property
    def upjs_init_prb(self):
        return self._upjs_init_prb

    @property
    def upwq_init_prb(self):
        return self._upwq_init_prb


def cz_prb_func(nothing_times, data_obj: DataObj):
    jin = data_obj.cz_init_prb[0][nothing_times[0]]
    try:
        zi = data_obj.cz_init_prb[1][nothing_times[1]]
    except IndexError:
        return tuple((jin, 1 - jin, 0))
    return tuple((jin, min(1 - jin, zi), 1 - min(1 - jin, zi) - jin))


def upjs_prb_func(nothing_times, data_obj):
    jin = data_obj.upjs_init_prb[0][nothing_times[0]]
    try:
        zi = data_obj.upjs_init_prb[1][nothing_times[1]]
    except IndexError:
        return tuple((jin, 1 - jin, 0))
    return tuple((jin, min(1 - jin, zi), 1 - min(1 - jin, zi) - jin))


def upwq_prb_func(nothing_times, data_obj):
    jin = data_obj.upwq_init_prb[0][nothing_times[0]]
    try:
        zi = data_obj.upwq_init_prb[1][nothing_times[1]]
    except IndexError:
        return tuple((jin, 1 - jin, 0))
    return tuple((jin, min(1 - jin, zi), 1 - min(1 - jin, zi) - jin))


class GlobalGame:

    def __init__(self, in_canvas: tkinter.Canvas, back_print):
        self._in_canvas = in_canvas
        self._back_print = back_print
        self._width = 17
        self._elements = []
        self.__data_obj = DataObj()
        self._mod = 'cz'        # 'cz'为常驻池,'upjs'为角色up池,'upwq'为武器up池,默认为cz
        self._huo_pos_set: dict = {(0, 0): None}      # huo_datas
        self._huo_index: dict = {'cz': [], 'upjs': [], 'upwq': []}
        self._nothing_times: dict = {'cz': [0, 0], 'upjs': [0, 0], 'upwq': [0, 0]}
        self._bk_times: dict = {'upjs': [0, 0], 'upwq': [0, 0, 0]}        # 第倒三和第倒二的0分别对应定轨和保底       # bottom keeping
        self._bk_count_his: dict = {'upjs': [0, 0], 'upwq': [0, 0, 0]}        # 第倒三和第倒二的0分别对应定轨和保底,吃保底的次数
        self._up_huo = {'upjs': [['温迪'], ['香菱', '菲谢尔', '芭芭拉']],
                        'upwq': [['风鹰剑'], ['风鹰剑', '阿莫斯之弓'], ['笛剑', '钟剑', '绝弦', '西风长枪', '流浪乐章']]}       # rd定轨, upwq中[[定轨], [5星up], [4星up]]
        self._coord = [0, 0]
        self._update()

        # init event binding
        self._in_canvas.bind('<ButtonRelease-1>', self._cin)

    @property
    def mod(self):
        return self._mod

    @property
    def huo_index(self) -> dict:
        return self._huo_index

    @property
    def up_huo(self):
        return self._up_huo

    @property
    def bk_count_his(self):
        return self._bk_count_his

    def _to_real(self, ix, iy) -> tuple:
        if isinstance(ix, tuple):
            return (ix[0] - self._coord[0] + 9) * 30, (-ix[1] + self._coord[1] + 9) * 30
        else:
            return (ix - self._coord[0] + 9) * 30, (-iy + self._coord[1] + 9) * 30

    def _real_to(self, rx, ry) -> tuple:
        if isinstance(rx, tuple):
            return (round(rx[0] / 30) - 9 + self._coord[0]), -(round(rx[1] / 30) - 9 - self._coord[1])
        else:
            return (round(rx / 30) - 9 + self._coord[0]), -(round(ry / 30) - 9 - self._coord[1])

    def _update(self):
        for i in self._elements:
            cav.delete(i)
        w = self._width

        huo_datas = DataObj().huo_datas
        for ix, iy in tuple((i % w - 8 + self._coord[0], i // w - 8 + self._coord[1]) for i in range(w ** 2)):
            rc = self._to_real(ix, iy)
            block = self._huo_pos_set.get((ix, iy))
            color = ''
            if block:
                if '5' in huo_datas[block]:
                    color = '#FAFE85'
                if '4' in huo_datas[block]:
                    color = '#D48BE6'
                if '3' in huo_datas[block]:
                    color = '#6686E9'
                self._elements.append(self._in_canvas.create_oval(rc[0] - 9, rc[1] - 9, rc[0] + 9, rc[1] + 9, outline=color, fill=color))
        if self.mod != 'cz':
            self._elements.append(self._in_canvas.create_text(255, 30, text=self._nothing_times[self.mod][0], fill='#BC6A32', font=('微软雅黑', 15), anchor='s'))
            self._elements.append(self._in_canvas.create_text(285, 30, text=self._nothing_times[self.mod][1], fill='#A356E2', font=('微软雅黑', 15), anchor='s'))
        if self.mod == 'upjs':
            self._elements.append(self._in_canvas.create_text(255, 30, text=self._bk_times[self.mod][0], fill='#BC6A32', font=('微软雅黑', 15), anchor='n'))
            self._elements.append(self._in_canvas.create_text(285, 30, text=self._bk_times[self.mod][1], fill='#A356E2', font=('微软雅黑', 15), anchor='n'))
        if self.mod == 'upwq':
            self._elements.append(self._in_canvas.create_text(240, 30, text=self._bk_times[self.mod][0], fill='#BC6A32', font=('微软雅黑', 15), anchor='n'))
            self._elements.append(self._in_canvas.create_text(270, 30, text=self._bk_times[self.mod][1], fill='#BC6A32', font=('微软雅黑', 15), anchor='n'))
            self._elements.append(self._in_canvas.create_text(300, 30, text=self._bk_times[self.mod][2], fill='#A356E2', font=('微软雅黑', 15), anchor='n'))

    def _chou(self, coord: tuple):
        # print(coord)

        if self._huo_pos_set.get(coord) is None:        # 抽!!!
            huo = ''
            self._nothing_times[self.mod][0] += 1
            self._nothing_times[self.mod][1] += 1

            if self.mod == 'cz':
                # print(self._nothing_times['cz'])
                t: tuple = cz_prb_func(tuple(self._nothing_times['cz']), self.__data_obj)
                rd = random.random()
                if rd < t[0]:      # 出金了
                    ls = self.__data_obj.huo_form['cz5js'] + self.__data_obj.huo_form['cz5wq']
                    huo = ls[random.randrange(len(ls))]
                    self._nothing_times['cz'][0] = 0
                elif rd < t[0] + t[1]:
                    ls = self.__data_obj.huo_form['4js'] + self.__data_obj.huo_form['cz4wq']
                    huo = ls[random.randrange(len(ls))]
                    self._nothing_times['cz'][1] = 0
                    # print(t)
                else:
                    huo = self.__data_obj.huo_form['3'][random.randrange(len(self.__data_obj.huo_form['3']))]


            elif self.mod == 'upjs':
                t: tuple = upjs_prb_func(tuple(self._nothing_times['upjs']), self.__data_obj)
                rd = random.random()
                if rd < t[0]:      # 出金了
                    if self._bk_times['upjs'][0] >= 1:      # 吃保底
                        huo = self._up_huo['upjs'][0][0]
                        self._bk_times['upjs'][0] = 0
                    elif random.random() < 0.5:     # 没歪
                        huo = self._up_huo['upjs'][0][0]
                    else:
                        huo = self.__data_obj.huo_form['cz5js'][random.randrange(len(self.__data_obj.huo_form['cz5js']))]
                        self._bk_times['upjs'][0] += 1
                        self._bk_count_his['upjs'][0] += 1
                    self._nothing_times['upjs'][0] = 0
                elif rd < t[0] + t[1]:
                    if self._bk_times['upjs'][1] >= 1:      # 吃保底
                        huo = self._up_huo['upjs'][1][random.randrange(len(self._up_huo['upjs'][1]))]
                        self._bk_times['upjs'][1] = 0
                    elif random.random() < 0.5:       # 没歪
                        huo = self._up_huo['upjs'][1][random.randrange(len(self._up_huo['upjs'][1]))]
                    else:
                        ls = self.__data_obj.huo_form['4js'] + self.__data_obj.huo_form['cz4wq']
                        huo = ls[random.randrange(len(ls))]
                        self._bk_times['upjs'][1] += 1
                        self._bk_count_his['upjs'][1] += 1
                    # print(t)
                    self._nothing_times['upjs'][1] = 0
                else:
                    huo = self.__data_obj.huo_form['3'][random.randrange(len(self.__data_obj.huo_form['3']))]

            elif self.mod == 'upwq':
                t: tuple = upwq_prb_func(tuple(self._nothing_times['upwq']), self.__data_obj)
                # print(t, self._bk_times['upwq'], self._nothing_times['upwq'])
                rd = random.random()
                if rd < t[0]:      # 出金了
                    if self._bk_times['upwq'][0] >= 2:      # 吃掉定轨
                        huo = self._up_huo['upwq'][0][0]
                        self._bk_times['upwq'][0] = 0
                    elif self._bk_times['upwq'][1] >= 1:        # 吃掉保底
                        huo = self._up_huo['upwq'][1][random.randrange(len(self._up_huo['upwq'][1]))]
                        self._bk_times['upwq'][1] = 0
                    else:
                        if random.random() < 0.25:      # 怎么连武器池都歪啊
                            ls = self.__data_obj.huo_form['cz5wq']
                        else:
                            ls = self._up_huo['upwq'][1]
                        huo = ls[random.randrange(len(ls))]
                    if huo != self._up_huo['upwq'][0][0]:       # +吃定轨
                        self._bk_times['upwq'][0] += 1
                        self._bk_count_his['upwq'][0] += 1
                    if huo not in self._up_huo['upwq'][1]:      # +吃保底
                        self._bk_times['upwq'][1] += 1
                        self._bk_count_his['upwq'][1] += 1
                    self._nothing_times['upwq'][0] = 0
                elif rd < t[0] + t[1]:
                    if self._bk_times['upwq'][2] >= 1:
                        huo = self._up_huo['upwq'][2][random.randrange(len(self._up_huo['upwq'][2]))]
                        self._bk_times['upwq'][2] = 0
                    elif random.random() < 0.5:     # 没歪
                        huo = self._up_huo['upwq'][2][random.randrange(len(self._up_huo['upwq'][2]))]
                    else:
                        ls = self.__data_obj.huo_form['4js'] + self.__data_obj.huo_form['cz4wq']
                        huo = ls[random.randrange(len(ls))]
                        self._bk_times['upwq'][2] += 1
                        self._bk_count_his['upwq'][2] += 1
                    # print(t)
                    self._nothing_times['upwq'][1] = 0
                else:
                    huo = self.__data_obj.huo_form['3'][random.randrange(len(self.__data_obj.huo_form['3']))]

            self._huo_index[self.mod].append(huo)
            self._back_print(huo + '\n')
            self._huo_pos_set[coord] = huo
            # print(coord)
        else:
            self._back_print('此处有货,是{}\n'.format(self._huo_pos_set[coord]))

    def _cin(self, event):
        # 随机数初始化
        # print(int(computeMD5('{},{},{}'.format(time.time(), event.x, event.y)), 16), '{},{},{}'.format(time.time(), event.x, event.y))
        random.seed(int(computeMD5('{},{},{}'.format(time.time(), event.x, event.y)), 16) ^ random.randrange(1 << 128))

        coord = self._real_to(event.x, event.y)
        # print(self.real_to(event.x, event.y))
        self._chou(coord)
        self._update()

    def clear_screen(self):
        self._huo_pos_set = {(0, 0): None}
        self._update()
        self._back_print('已清空屏幕\n')

    def clear(self):
        self.clear_screen()
        self._huo_index = {'cz': [], 'upjs': [], 'upwq': []}
        self._nothing_times = {'cz': [0, 0], 'upjs': [0, 0], 'upwq': [0, 0]}
        self._back_print('已重置\n')

    def set_mod(self, mod: str):
        if isinstance(mod, str):
            if mod == 'cz' or mod == 'upjs' or mod == 'upwq':
                self._mod = mod
                self._back_print('已切换模式为{}\n'.format({'cz': '常驻祈愿', 'upjs': '限定角色祈愿', 'upwq': '限定武器祈愿'}[mod]))
                self._update()
            else:
                self._back_print('模式错误\n')
        else:
            self._back_print('模式错误\n')

    def set_up(self, mod: str, up: list):
        self._up_huo[mod] = up
        # print(up)

    def clear_dinggui(self):
        self._bk_times['upwq'][0] = 0
        self._update()

    def lian(self):
        # 随机数初始化
        random.seed(int(computeMD5(str(time.time())), 16) ^ random.randrange(1 << 128))

        i = j = 0
        block_list = []
        while i < 10 and j < self._width ** 2:
            if not self._huo_pos_set.get((j % self._width - self._width // 2, self._width // 2 - j // self._width)):
                block_list.append((j % self._width - self._width // 2, self._width // 2 - j // self._width))
                i += 1
            j += 1
        if len(block_list) == 10:
            for i in block_list:
                self._chou(i)       # 十连!!!!!!!!!!
            self._update()
        else:
            self._back_print('无空余位置\n')


def set_up(root: tkinter.Tk, game: GlobalGame, call_back):
    if game.mod == 'cz':
        call_back('常驻无该设置\n')
    else:
        data_obj = DataObj()

        if game.mod == 'upjs':
            win = tkinter.Toplevel(root)
            win.title('限定角色祈愿-大幅提升获取角色设置')
            win.geometry('360x180')
            win.minsize(360, 180)  # 设置窗口最小值
            frs = [tkinter.Frame(win) for i in range(3)]
            for i in range(3):
                frs[i].place(relx=0.0, rely=i/3, relwidth=1, relheight=1/3)

            cbb = tkinter.ttk.Combobox(frs[0], width=10)
            cbb['value'] = data_obj.huo_form['up5js']
            # cbb.current(0)      # 默认初始索引
            cbb.insert(0, game.up_huo['upjs'][0][0])
            cbbs = []
            for i in range(3):
                cbbs.append(tkinter.ttk.Combobox(frs[1], width=10))
                cbbs[i]['value'] = data_obj.huo_form['4js']
                cbbs[i].insert(0, game.up_huo['upjs'][1][i])

            tkinter.Label(frs[0], text='5星up').pack(side=tkinter.LEFT)
            cbb.pack(side=tkinter.LEFT)
            tkinter.Label(frs[1], text='4星up').pack(side=tkinter.LEFT)
            for i in range(3):
                cbbs[i].pack(side=tkinter.LEFT)

            def f():
                ls = [[cbb.get()], [cbbs[i].get() for i in range(3)]]
                if ls[0][0] not in data_obj.huo_form['up5js']:
                    tkinter.messagebox.showinfo(title="信息", message="角色错误")
                    return
                for i in range(3):
                    if ls[1][i] not in data_obj.huo_form['4js']:
                        tkinter.messagebox.showinfo(title="信息", message="角色错误")
                        return
                    for i0 in range(i):
                        if ls[1][i] == ls[1][i0]:
                            tkinter.messagebox.showinfo(title="信息", message="角色重复")
                            return
                game.set_up('upjs', ls)
                tkinter.messagebox.showinfo(title="信息", message="设置成功")
                win.destroy()

            tkinter.Button(frs[2], bg='#FFFFFF', text='确定', command=f).pack(side=tkinter.RIGHT)

        elif game.mod == 'upwq':
            win = tkinter.Toplevel(root)
            win.title('限定武器祈愿-定轨以及大幅提升获取武器设置')
            win.geometry('540x240')
            win.minsize(540, 240)
            frs = [tkinter.Frame(win) for i in range(4)]
            for i in range(4):
                frs[i].place(relx=0.0, rely=i/4, relwidth=1, relheight=1/4)

            cbb = tkinter.ttk.Combobox(frs[0], width=10)
            cbb['value'] = data_obj.huo_form['up5wq']
            # cbb.current(0)      # 默认初始索引
            cbb.insert(0, game.up_huo['upwq'][0][0])
            cbbs1 = []
            for i in range(2):
                cbbs1.append(tkinter.ttk.Combobox(frs[1], width=10))
                cbbs1[i]['value'] = data_obj.huo_form['up5wq']
                cbbs1[i].insert(0, game.up_huo['upwq'][1][i])
            cbbs2 = []
            for i in range(5):
                cbbs2.append(tkinter.ttk.Combobox(frs[2], width=10))
                cbbs2[i]['value'] = data_obj.huo_form['cz4wq'] + data_obj.huo_form['up4wq']
                cbbs2[i].insert(0, game.up_huo['upwq'][2][i])

            tkinter.Label(frs[0], text='5星up定轨').pack(side=tkinter.LEFT)
            cbb.pack(side=tkinter.LEFT)
            tkinter.Label(frs[1], text='5星up').pack(side=tkinter.LEFT)
            for i in range(2):
                cbbs1[i].pack(side=tkinter.LEFT)
            tkinter.Label(frs[2], text='4星up').pack(side=tkinter.LEFT)
            for i in range(5):
                cbbs2[i].pack(side=tkinter.LEFT)

            def f():
                ls = [[cbb.get()], [cbbs1[i].get() for i in range(2)], [cbbs2[i].get() for i in range(5)]]
                if ls[0][0] not in ls[1]:
                    tkinter.messagebox.showinfo(title="信息", message="武器错误")
                    return
                for i in range(2):
                    if ls[1][i] not in data_obj.huo_form['cz5wq'] + data_obj.huo_form['up5wq']:
                        tkinter.messagebox.showinfo(title="信息", message="武器错误")
                        return
                    for i0 in range(i):
                        if ls[1][i] == ls[1][i0]:
                            tkinter.messagebox.showinfo(title="信息", message="武器重复")
                            return
                for i in range(5):
                    if ls[2][i] not in data_obj.huo_form['cz4wq'] + data_obj.huo_form['up4wq']:
                        tkinter.messagebox.showinfo(title="信息", message="武器错误")
                        return
                    for i0 in range(i):
                        if ls[2][i] == ls[2][i0]:
                            tkinter.messagebox.showinfo(title="信息", message="武器重复")
                            return
                game.set_up('upwq', ls)
                tkinter.messagebox.showinfo(title="信息", message="设置成功")
                win.destroy()

            def f2():
                f()
                game.clear_dinggui()

            tkinter.Button(frs[3], bg='#FFFFFF', text='确定', command=f).pack(side=tkinter.RIGHT)
            tkinter.Button(frs[3], bg='#FFFFFF', text='清空定轨并确定', command=f2).pack(side=tkinter.RIGHT)


def chouka_history(root: tkinter.Tk, game: GlobalGame):
    data_obj = DataObj()

    win = tkinter.Toplevel(root)
    win.title('历史记录')
    win.geometry('960x540')
    win.minsize(960, 540)
    frs = [tkinter.Frame(win, bg='#6F778A') for i in range(3)]
    for i, item in enumerate(['upjs', 'upwq', 'cz']):
        tkinter.Label(frs[i], text={'cz': '常驻祈愿', 'upjs': '限定角色祈愿', 'upwq': '限定武器祈愿'}[item], foreground='#FFFFFF',
                      font=('微软雅黑', 20), bg='#6F778A').pack(side=tkinter.TOP, padx=15, pady=15)
        frs[i].place(relx=i/3, rely=0.0, relwidth=1/3, relheight=1)
        txt_his = tkinter.Text(frs[i], bg='#EAE6DE', font=('微软雅黑', 9))
        txt_his.pack(expand=True, fill=tkinter.BOTH, side=tkinter.TOP, padx=15, pady=15)

        nothing_times = [0, 0]
        for i0 in game.huo_index[item]:
            nothing_times[0] += 1
            nothing_times[1] += 1
            if '5' in data_obj.huo_datas[i0]:
                txt_his.insert(0.0, '{}[{}]\n'.format(i0, nothing_times[0]), 'jin')
                nothing_times[0] = 0
            elif '4' in data_obj.huo_datas[i0]:
                txt_his.insert(0.0, '{}[{}]\n'.format(i0, nothing_times[1]), 'zi')
                nothing_times[1] = 0
            else:
                txt_his.insert(0.0, i0 + '\n', 'lan')
        txt_his.tag_config('jin', foreground='#BC6A32', font=('微软雅黑', 25))
        txt_his.tag_config('zi', foreground='#A356E2', font=('微软雅黑', 15))
        txt_his.tag_config('lan', foreground='#6686E9')


def chouka_analysis(root: tkinter.Tk, game: GlobalGame):
    data_obj = DataObj()

    win = tkinter.Toplevel(root)
    win.title('抽卡分析')
    win.geometry('960x540')
    win.minsize(960, 540)
    fr_up = tkinter.Frame(win, bg='#6F778A')
    fr_down = tkinter.Frame(win, bg='#6F778A')
    fr_up.pack(side=tkinter.TOP, fill=tkinter.BOTH)
    # tkinter.Label(fr_up, text='666').pack()
    fr_down.pack(side=tkinter.TOP, expand=True, fill=tkinter.BOTH)

    frs = [tkinter.Frame(fr_down, bg='#6F778A') for i in range(3)]
    huo_info: dict = {}
    huo_counters: list = [[], [], []]
    for i, mod in enumerate(['upjs', 'upwq', 'cz']):
        huo_info.update({mod: {i: 0 for i in data_obj.huo_datas.keys()}})
        tkinter.Label(frs[i], text={'cz': '常驻祈愿', 'upjs': '限定角色祈愿', 'upwq': '限定武器祈愿'}[mod], foreground='#FFFFFF',
                      font=('微软雅黑', 20), bg='#6F778A').pack(side=tkinter.TOP, padx=5, pady=5)
        frs[i].place(relx=i/3, rely=0.0, relwidth=1/3, relheight=1)
        txt_his = tkinter.Text(frs[i], bg='#EAE6DE', font=('微软雅黑', 9))

        huo_counter = {'jin': 0, 'zi': 0, 'lan': 0, 'sum': 0}
        for i0 in game.huo_index[mod]:
            huo_info[mod][i0] += 1
        for i0 in ('cz5js', 'cz5wq', 'up5js', 'up5wq', '4js', 'cz4wq', 'up4wq', '3'):
            for i00 in data_obj.huo_form[i0]:
                if '5' in i0:
                    tag = 'jin'
                elif '4' in i0:
                    tag = 'zi'
                else:
                    tag = 'lan'
                huo_counter[tag] += huo_info[mod][i00]
                huo_counter['sum'] += huo_info[mod][i00]
                huo_counters[i] = huo_counter['sum']
        for i0 in ('cz5js', 'cz5wq', 'up5js', 'up5wq', '4js', 'cz4wq', 'up4wq', '3'):
            for i00 in data_obj.huo_form[i0]:
                if '5' in i0:
                    tag = 'jin'
                elif '4' in i0:
                    tag = 'zi'
                else:
                    tag = 'lan'
                if huo_info[mod][i00]:
                    txt_his.insert(tkinter.END, '{}x{}\t{:.2%}\n'.format(i00, huo_info[mod][i00], huo_info[mod][i00] / huo_counter[tag]), tag)
        txt_his.tag_config('jin', foreground='#BC6A32')
        txt_his.tag_config('zi', foreground='#A356E2')
        txt_his.tag_config('lan', foreground='#6686E9')
        text = '{}抽 {}原石'.format(huo_counter.get('sum'), huo_counter.get('sum') * 160)
        tkinter.Label(frs[i], text=text, foreground='#FFFFFF', font=('微软雅黑', 20), bg='#6F778A').pack(side=tkinter.TOP, padx=0, pady=5)
        if mod == 'upwq' and huo_counter['jin']:
            if huo_counter['jin']:
                text1 = '定轨{:.2%}'.format(1 - game.bk_count_his[mod][0] / huo_counter['jin'])
                text2 = '小保{:.2%}'.format(1 - game.bk_count_his[mod][1] / huo_counter['jin'])
                tkinter.Label(frs[i], text=text1+text2, foreground='#FFFFFF', font=('微软雅黑', 15), bg='#6F778A').pack(side=tkinter.TOP, padx=0, pady=5)
            if huo_counter['jin'] - game.bk_count_his[mod][0]:
                text = '{:.2f}抽/定轨 {:.2f}原石/定轨'.format(huo_counter.get('sum') / (huo_counter['jin'] - game.bk_count_his[mod][0]),
                                                       huo_counter.get('sum') * 160 / (huo_counter['jin'] - game.bk_count_his[mod][0]))
                tkinter.Label(frs[i], text=text, foreground='#FFFFFF', font=('微软雅黑', 15), bg='#6F778A').pack(side=tkinter.TOP, padx=0, pady=5)
        if mod == 'upjs' and huo_counter['jin']:
            if huo_counter['jin']:
                text = '小保{:.2%}'.format(1 - game.bk_count_his[mod][0] / huo_counter['jin'])
                tkinter.Label(frs[i], text=text, foreground='#FFFFFF', font=('微软雅黑', 15), bg='#6F778A').pack(side=tkinter.TOP, padx=0, pady=5)

            if huo_counter['jin'] - game.bk_count_his[mod][0]:
                text = '{:.2f}抽/小保 {:.2f}原石/小保'.format(huo_counter.get('sum') / (huo_counter['jin'] - game.bk_count_his[mod][0]),
                                                       huo_counter.get('sum') / (huo_counter['jin'] - game.bk_count_his[mod][0]) * 160)
                tkinter.Label(frs[i], text=text, foreground='#FFFFFF', font=('微软雅黑', 15), bg='#6F778A').pack(side=tkinter.TOP, padx=0, pady=5)
        txt_his.pack(expand=True, fill=tkinter.BOTH, side=tkinter.TOP, padx=15, pady=5)
    text = '共{}抽,共消耗{}蓝球,{}粉球,对应的粉球为{}原石'.format(sum(huo_counters), huo_counters[2], sum(huo_counters) - huo_counters[2], (sum(huo_counters) - huo_counters[2]) * 160)
    tkinter.Label(fr_up, text=text, foreground='#FFFFFF', font=('微软雅黑', 9), bg='#6F778A').pack(side=tkinter.LEFT)


if __name__ == '__main__':
    root = tkinter.Tk()
    root.title('chouka')
    root.geometry('960x540')
    root.minsize(960, 540)  # 设置窗口最小值

    fr1 = tkinter.Frame(root, bg='#FFFFFF', width=540)
    fr1.place(relx=0.0, rely=0.0, relwidth=0.5625, relheight=1.0)
    fr2 = tkinter.Frame(root, bg='#FFFFFF')
    fr2.place(relx=0.5625, rely=0.0, relwidth=0.4375, relheight=1.0)

    cav = tkinter.Canvas(fr1, bg='#9BC3DD', width=540, height=540)
    cav.pack(side=tkinter.TOP)

    fr20 = tkinter.Frame(fr2, bg='#FFFFFF', height=45)
    fr20.pack(side=tkinter.TOP, fill=tkinter.X)
    fr21 = tkinter.Frame(fr2, bg='#FFFFFF')
    fr21.pack(side=tkinter.BOTTOM, fill=tkinter.X)
    fr211 = tkinter.Frame(fr21, bg='#FFFFFF', width=180, height=180)
    fr212 = tkinter.Frame(fr21, bg='#FFFFFF', width=180, height=180)
    fr211.pack(side=tkinter.LEFT)
    fr212.pack(side=tkinter.RIGHT)

    fr201 = tkinter.Frame(fr20, bg='#FFFFFF')
    fr202 = tkinter.Frame(fr20, bg='#FFFFFF')
    fr203 = tkinter.Frame(fr20, bg='#FFFFFF')
    fr201.place(relx=0.0, rely=0.0, relwidth=1/3, relheight=1)
    fr202.place(relx=1/3, rely=0.0, relwidth=1/3, relheight=1)
    fr203.place(relx=2/3, rely=0.0, relwidth=1/3, relheight=1)

    bt_upjs = tkinter.Button(fr201, bg='#FFFFFF', text='限定角色祈愿')
    bt_upjs.pack(expand=True, fill=tkinter.BOTH, padx=3, pady=6)
    bt_upwq = tkinter.Button(fr202, bg='#FFFFFF', text='限定武器祈愿')
    bt_upwq.pack(expand=True, fill=tkinter.BOTH, padx=3, pady=6)
    bt_cz = tkinter.Button(fr203, bg='#FFFFFF', text='常驻祈愿')
    bt_cz.pack(expand=True, fill=tkinter.BOTH, padx=3, pady=6)
    bt_setter = tkinter.Button(fr211, bg='#FFFFFF', text='卡池设置')
    bt_setter.place(relx=0.0, rely=0.25, relwidth=0.5, relheight=0.25)
    bt_history = tkinter.Button(fr211, bg='#FFFFFF', text='历史记录')
    bt_history.place(relx=0.0, rely=0.5, relwidth=0.5, relheight=0.25)
    bt_analysis = tkinter.Button(fr211, bg='#FFFFFF', text='记录分析')
    bt_analysis.place(relx=0.0, rely=0.75, relwidth=0.5, relheight=0.25)
    bt_clear_screen = tkinter.Button(fr211, bg='#FFFFFF', text='清空屏幕')
    bt_clear_screen.place(relx=0.5, rely=0.5, relwidth=0.5, relheight=0.25)
    bt_clear = tkinter.Button(fr211, bg='#FFFFFF', text='清空记录')
    bt_clear.place(relx=0.5, rely=0.75, relwidth=0.5, relheight=0.25)
    bt_lian = tkinter.Button(fr212, bg='#FFFFFF', text='祈愿十次')
    bt_lian.place(relx=0.5, rely=0.75, relwidth=0.5, relheight=0.25)

    txt = tkinter.Text(fr2, bg='#FFFFFF', font=('微软雅黑', 9))
    txt.pack(padx=30, pady=30)

    game = GlobalGame(cav, lambda x: txt.insert(0.0, x))

    bt_setter.config(command=lambda: set_up(root, game, lambda x: txt.insert(0.0, x)))
    bt_upjs.config(command=lambda: game.set_mod('upjs'))
    bt_upwq.config(command=lambda: game.set_mod('upwq'))
    bt_cz.config(command=lambda: game.set_mod('cz'))
    bt_history.config(command=lambda: chouka_history(root, game))
    bt_analysis.config(command=lambda: chouka_analysis(root, game))
    bt_clear_screen.config(command=game.clear_screen)
    bt_clear.config(command=game.clear)
    bt_lian.config(command=game.lian)

    root.mainloop()

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
抽卡系统的实现可以分为以下几个步骤: 1. 定义卡牌属性:包括卡牌名称、稀有度、图片等。 2. 定义卡池:包括卡池名称、包含的卡牌列表、每种卡牌的出现概率等。 3. 实现抽卡逻辑:根据卡池中每种卡牌的出现概率,随机生成一张卡牌并返回给玩家。 下面是一个简单的Unity C#脚本示例: ```csharp using System.Collections.Generic; using UnityEngine; public class Card { public string name; public int rarity; public Sprite image; } public class CardPool { public string name; public List<Card> cards; public List<float> probabilities; } public class GachaSystem : MonoBehaviour { public List<CardPool> pools; public Card DrawCard(string poolName) { CardPool pool = pools.Find(p => p.name == poolName); if (pool == null) { Debug.LogError("Invalid pool name: " + poolName); return null; } float rand = Random.Range(0f, 1f); float probSum = 0; for (int i = 0; i < pool.probabilities.Count; i++) { probSum += pool.probabilities[i]; if (rand <= probSum) { return pool.cards[i]; } } Debug.LogError("Failed to draw card from pool: " + poolName); return null; } } ``` 在上面的脚本中,我们定义了一个Card类来表示卡牌属性,一个CardPool类来表示卡池,并实现了一个GachaSystem类来处理抽卡逻辑。具体实现中,我们首先在GachaSystem中定义了一个包含多个CardPool的列表pools,用来存储所有的卡池。然后,我们在GachaSystem中实现了一个DrawCard方法,用来从指定的卡池中随机抽取一张卡牌。在DrawCard方法中,我们首先通过poolName参数找到对应的卡池,然后根据每种卡牌的出现概率,随机生成一个0~1的随机数rand,并依次累加每种卡牌的出现概率,直到rand小于等于累加的概率和probSum,此时返回对应的卡牌即可。如果遍历完所有的卡牌后仍未能找到符合条件的卡牌,则返回null。 当我们需要使用抽卡系统时,只需要在场景中添加一个GachaSystem对象,并在Inspector面板中设置对应的卡池和卡牌信息即可。例如,下面是一个包含两个卡池的GachaSystem对象的Inspector设置: ![Unity Inspector设置示例](https://img-blog.csdnimg.cn/20211019102205996.png) 在上图中,我们设置了两个卡池,分别为“普通池”和“精选池”,每个卡池中包含了若干张卡牌,并设置了每种卡牌的出现概率。在实际使用时,我们可以通过调用GachaSystem的DrawCard方法来进行抽卡操作,例如: ```csharp GachaSystem gachaSystem = FindObjectOfType<GachaSystem>(); Card card = gachaSystem.DrawCard("普通池"); if (card != null) { Debug.Log("抽到了一张卡牌:" + card.name); } ``` 上面的代码会从名为“普通池”的卡池中随机抽取一张卡牌,并打印出卡牌名称。如果卡池名称无效或抽卡失败,则会返回null并打印相应的错误信息。 以上是一个简单的Unity仿原神抽卡脚本示例,供参考。当然,具体的实现还需要根据实际需求进行调整和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值