码迷,mamicode.com
首页 > 其他好文 > 详细

游戏中的定时刷新实现方式

时间:2015-06-01 16:19:07      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

情景1:现在有一个道具商店,共有10个道具可购买。玩家可使用某道具或钻石刷新道具商店中的道具,或者系统会每隔2小时赠送一次刷新次数。

问题1:如何实现间隔2小时实时刷新?

技术分享
from datetime import datetime

def cal_count(timestamp):
    now_dt  = datetime.now()
    base_dt = datetime.fromtimestamp(0)
    last_dt   = datetime.fromtimestamp(timestamp)
 
    count = ((now_dt.date() - base_dt.date()).days*12 + now_dt.hour/2) -             ((last_dt.date() - base_dt.date()).days*12 + last_dt.hour/2)

    return count

if __name__ == "__main__":
    last_ts = 1433000132
    print cal_count(last_ts)
View Code

 

问题2:刷新后,如何随机出新的10个道具? (注:items=[10001, 10002, 10003, ...], 对应的weight=[1, 2, 3, ...])

技术分享
import random
import time
import sys


def func1(items, weight, times):
    total_weight = sum(weight)
    rand_items   = {}
    all_items    = dict(zip(items, weight))
    for _idx in range(0, times):
        count = 0
        rand  = random.randint(0, total_weight-1)
        for _item, _weight in all_items.iteritems():
            count += _weight
            if rand < count:
                rand_items[(_item, _weight)] = rand_items.setdefault((_item, _weight), 0) + 1
                break

    return rand_items

def func2(items, weight, times):
    ‘‘‘
    len(items) == len(weight)
    ‘‘‘
    _now = time.time()
    if not items:
        return

    rand_pools   = []
    rand_items   = {}
    total_weight = sum(weight)

    for _idx, _item in enumerate(items):
        rand_pools.extend([_item]*weight[_idx])

    for _idx in range(0, times):
        item = random.choice(rand_pools)
        key  = (item, weight[items.index(item)])
        rand_items[key] = rand_items.setdefault(key, 0) + 1

    return rand_items


def pprint(args, debug=False):
    if debug:
        print args

if __name__ == "__main__": 
    debug  = True
    times  = 10 # rand times
    items  = range(1001, 2001)
    weight = range(100, 100100, 100)
    if len(items) != len(weight):
        pprint( data error., debug )
        sys.exit()
 
    pprint( \ntotal items:%s, random times: %s.%(len(items), times), debug )

    _now = time.time()
    rand_items = func1(items, weight, times)
    pprint( "\nfunc 1 total cost %s seconds."%(time.time()-_now), debug )
    pprint( \nresult:%s. % sorted(rand_items.iteritems(), key=lambda dt:dt[0], reverse=True) )

    _now = time.time()
    rand_items = func2(items, weight, times)
    pprint( "\nfunc 2 total cost %s seconds."%(time.time()-_now), debug )
    pprint( \nresult:%s% sorted(rand_items.iteritems(), key=lambda dt:dt[1], reverse=True) )
View Code

 

 

 

游戏中的定时刷新实现方式

标签:

原文地址:http://www.cnblogs.com/tangkaixin/p/4543981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!