游戏中的定时刷新实现方式
情景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)
问题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) )