def handle(self, event_to_handle): if event_to_handle is None: logger.critical("OMG! No such object") return else: missions=obj2dict(event_to_handle) logger.info(u'Трофеи:') if missions["action"]=="getMissions": for id in missions["missions"]: if id["type"]=="achievement": item=obj2dict(self.__item_reader.get(id["item"])) if (id['completed']+1)==4: if len(item["name"])>13: logger.info(u'\t%s:\tзавершен, получен приз "%s"'%(item["name"],self.__item_reader.get(item['achievementPrizes'][2]["prizes"][0]["item"]).name)) else: logger.info(u'\t%s:\t\tзавершен, получен приз "%s"'%(item["name"],self.__item_reader.get(item['achievementPrizes'][2]["prizes"][0]["item"]).name)) else: try: num1=id['tasks'][item['id']+'_'+str(id['completed']+1)]["count"] except: num1=id['tasks'][item['id']+'-'+str(id['completed']+1)]["count"] try: for i in item['tasks']: if (item['id']+'_'+str(id['completed']+1))==i['id']: num2=i["count"] except: for i in item['tasks']: if (item['id']+'-'+str(id['completed']+1))==i['id']: num2=i["count"] if len(item["name"])>13: logger.info(u'\t%s:\tстадия %d (%d/%d)'%(item["name"],id['completed']+1,num1,num2)) else: logger.info(u'\t%s:\t\tстадия %d (%d/%d)'%(item["name"],id['completed']+1,num1,num2)) #raw_input() logger.info(u'')
def handle(self, event_to_handle): if event_to_handle is None: logger.critical("OMG! No such object") return else: missions = obj2dict(event_to_handle) logger.info(u'Трофеи:') if missions["action"] == "getMissions": for id in missions["missions"]: if id["type"] == "achievement": item = obj2dict(self.__item_reader.get(id["item"])) if (id['completed'] + 1) == 4: if len(item["name"]) > 13: logger.info( u'\t%s:\tзавершен, получен приз "%s"' % (item["name"], self.__item_reader.get( item['achievementPrizes'][2]["prizes"] [0]["item"]).name)) else: logger.info( u'\t%s:\t\tзавершен, получен приз "%s"' % (item["name"], self.__item_reader.get( item['achievementPrizes'][2]["prizes"] [0]["item"]).name)) else: try: num1 = id['tasks'][item['id'] + '_' + str(id['completed'] + 1)]["count"] except: num1 = id['tasks'][item['id'] + '-' + str(id['completed'] + 1)]["count"] try: for i in item['tasks']: if (item['id'] + '_' + str(id['completed'] + 1)) == i['id']: num2 = i["count"] except: for i in item['tasks']: if (item['id'] + '-' + str(id['completed'] + 1)) == i['id']: num2 = i["count"] if len(item["name"]) > 13: logger.info(u'\t%s:\tстадия %d (%d/%d)' % (item["name"], id['completed'] + 1, num1, num2)) else: logger.info(u'\t%s:\t\tстадия %d (%d/%d)' % (item["name"], id['completed'] + 1, num1, num2)) #raw_input() logger.info(u'')
def perform_action(self): #graves = self._get_game_location().get_all_objects_by_types(self.get_worker_types()) loc_obj = self._get_game_location().get_all_objects_by_types( self.get_worker_types()) for _obj in loc_obj: if "SC_TRADER_GRAVE" in _obj.item: #print _obj.item #print _obj.x + _obj.y #print getattr(obj2dict(_obj.give), 'item') #print obj2dict(_obj.give) + obj2dict(_obj.want) if _obj.started == False: trader_event = { "objId": _obj.id, "type": "item", "action": "start" } self._get_events_sender().send_game_events([trader_event]) #print u'Выгоняем на работу торгаша № ',_obj.id logger.info("Отправляем работаеть торговца №%s", _obj.id) _obj.started = True if _obj.countCompleted == 1: trader_event = { "objId": _obj.id, "type": "item", "action": "pick" } self._get_events_sender().send_game_events([trader_event]) #print u'Забираем коробку у торгаша № ',_obj.id logger.info("Забираем коробку у торговца №%s", _obj.id) print obj2dict(_obj.give) + obj2dict(_obj.want) open('trader.txt', 'a').write( str(obj2dict(_obj.give)) + str(obj2dict(_obj.want)) + "\n") _obj.countCompleted = 0 if _obj.countExchange == 0 and _obj.countCompleted == 0: trader_event = { "objId": _obj.id, "type": "trader", "want": _obj.want, "give": _obj.give, "action": "change", "countExchange": 1 } self._get_events_sender().send_game_events([trader_event]) logger.info("Обновляем торговца №%s", _obj.id) _obj.countExchange = 1
def remove_coll_from_storage(self, coll, count): CollIt = obj2dict(self._get_game_state().get_state().collectionItems) for itemid in CollIt.keys(): if itemid in coll: #print u'удаляем %d шт. %s' % (count, itemid) CollIt[itemid] -= count self._get_game_state().get_state().collectionItems = dict2obj(CollIt)
def perform_action(self): if self.if_location_pirate(): return par = self.mega().send_coll_options() saveCollection = par.get('saveCollection', []) send_user = self._get_options() if send_user <> None: CollIt = obj2dict( self._get_game_state().get_state().collectionItems) saveCollection.extend(['C_42', 'C_29']) for item_id in CollIt.keys(): send = False for save in saveCollection: if save in item_id: send = True if send: continue #print item_id + '\t-\t' + str(CollIt[item_id]) #{"gift":{"msg":"","item":"C_4_1","count":1,"user":"******"},"action":"sendGift","type":"gift"} if CollIt[item_id] > 0: send_gift = { "item": '@' + item_id, "msg": "", "count": CollIt[item_id], "user": send_user } event = GameSendGift(gift=send_gift) self._get_events_sender().send_game_events([event]) #print 'Otpravleno\t'+str(CollIt[item_id])+'\t'+item_id logger.info(u"Отправили %d '%s' пользователю %d" % (CollIt[item_id], self._get_item_reader().get(item_id).name, int(send_user))) self._get_game_state().remove_from_storage( '@' + item_id, CollIt[item_id]) CollIt[item_id] = 0 self._get_game_state().get_state().collectionItems = dict2obj( CollIt)
def perform_action(self): if self.if_location_pirate(): return #loc_obj = self._get_game_location().get_all_objects_by_types(self.get_worker_types()) loc_obj = self._get_game_location().get_game_objects() for _obj in loc_obj: if 'SC_TRADER_GRAVE' in _obj.item: if _obj.started == False: trader_event = { "objId": _obj.id, "type": "item", "action": "start" } self._get_events_sender().send_game_events([trader_event]) print u'Выгоняем на работу торгаша № ', _obj.id _obj.started = True if _obj.countCompleted == 1: trader_event = { "objId": _obj.id, "type": "item", "action": "pick" } self._get_events_sender().send_game_events([trader_event]) print u'Забираем коробку у торгаша № ', _obj.id _obj.countCompleted = 0 if _obj.countExchange == 0 and _obj.countCompleted == 0: give_list = obj2dict(_obj.give) # print '_obj.give', give_list give_t = {} for giv in give_list: give_t[giv['item']] = giv['count'] check_give, problem_item = self.check_give(give_t) if not check_give: name = self._get_item_reader().get(problem_item).name self.cprint( u"4Для выставления обмена торговцу не хватает '" + name + "'") continue trader_event = { "objId": _obj.id, "type": "trader", "want": _obj.want, "give": _obj.give, "action": "change", "countExchange": 1 } self._get_events_sender().send_game_events([trader_event]) print u'Ставим торг у торгаша № ', _obj.id _obj.countExchange = 1 self.remove_tovar(give_t)
def perform_action(self): #graves = self._get_game_location().get_all_objects_by_types(self.get_worker_types()) loc_obj = self._get_game_location().get_all_objects_by_types(self.get_worker_types()) for _obj in loc_obj: if "SC_TRADER_GRAVE" in _obj.item: #print _obj.item #print _obj.x + _obj.y #print getattr(obj2dict(_obj.give), 'item') #print obj2dict(_obj.give) + obj2dict(_obj.want) if _obj.started == False: trader_event = {"objId":_obj.id, "type":"item", "action":"start"} self._get_events_sender().send_game_events([trader_event]) #print u'Выгоняем на работу торгаша № ',_obj.id logger.info("Отправляем работаеть торговца №%s",_obj.id) _obj.started = True if _obj.countCompleted == 1: trader_event = {"objId":_obj.id, "type":"item", "action":"pick"} self._get_events_sender().send_game_events([trader_event]) #print u'Забираем коробку у торгаша № ',_obj.id logger.info("Забираем коробку у торговца №%s",_obj.id) print obj2dict(_obj.give) + obj2dict(_obj.want) open('trader.txt','a').write(str(obj2dict(_obj.give)) + str(obj2dict(_obj.want)) + "\n") _obj.countCompleted = 0 if _obj.countExchange == 0 and _obj.countCompleted == 0: trader_event = {"objId":_obj.id, "type":"trader", "want":_obj.want, "give":_obj.give, "action":"change", "countExchange":1} self._get_events_sender().send_game_events([trader_event]) logger.info("Обновляем торговца №%s",_obj.id) _obj.countExchange = 1
def perform_action(self): # Продажа sell_items = self._get_options()['sell_item'] if sell_items <> None: #sell_items={u'S_51':20} #item_id=u'S_51' # Красные яблоки #item_save_count=20 for item_id in sell_items.keys(): item_save_count = sell_items[item_id] itm_count = self._get_game_state().count_in_storage('@' + item_id) item_count = itm_count - item_save_count if item_count > 0: sell_event = GameSellItem(count=long(item_count), itemId=unicode(item_id)) self._get_events_sender().send_game_events([sell_event]) self._get_game_state().remove_from_storage( '@' + item_id, item_count) itm_count = self._get_game_state().count_in_storage( '@' + item_id) logger.info( u"Продали %d '%s' осталось %d" % ((item_count), self._get_item_reader().get(item_id).name, itm_count)) CollIt = obj2dict(self._get_game_state().get_state().collectionItems) send_user = self._get_options()['send_user'] # "26586292" if send_user <> None: for item_id in CollIt.keys(): #print item_id+'\t-\t'+str(CollIt[item_id]) #{"gift":{"item":"@CR_53","msg":"","count":1,"user":"******"},"action":"sendGift","id":55,"type":"gift"} #{"gift":{"msg":"","item":"C_4_1","count":1,"user":"******"},"action":"sendGift","type":"gift"} if CollIt[item_id] > 0: send_gift = { "item": '@' + item_id, "msg": "", "count": CollIt[item_id], "user": send_user } event = GameSendGift(gift=send_gift) self._get_events_sender().send_game_events([event]) #print 'Otpravleno\t'+str(CollIt[item_id])+'\t'+item_id logger.info(u"Отправили %d '%s' пользователю %d" % (CollIt[item_id], self._get_item_reader().get(item_id).name, int(send_user))) self._get_game_state().remove_from_storage( '@' + item_id, CollIt[item_id]) CollIt[item_id] = 0 self._get_game_state().get_state().collectionItems = dict2obj(CollIt)
def perform_action(self): count = 1 #сколько менять itemId = 'C_2' #C_1,C_2 = номер коллекции coll=obj2dict(self._get_game_state().get_state().collectionItems) max_coll = [int(coll[itemId+'_'+str(_i)]) for _i in range(1,6) if (itemId+'_'+str(_i) in coll.keys())] if len(max_coll) == 5 and min(max_coll)>=count: #меняем коллекции col_exchange = {"count":count, "itemId":itemId, "action":"collect", "type":"item"} self._get_events_sender().send_game_events([col_exchange]) logger.info(u'Обмениваем '+str(self._get_item_reader().get('@'+itemId).name) + ' ' + str(count)+u' раз') else: logger.info(u'Не хватает чего-то для обмена')
def perform_action(self): # Продажа sell_items = self._get_options()['sell_item'] if sell_items<>None: #sell_items={u'S_51':20} #item_id=u'S_51' # Красные яблоки #item_save_count=20 for item_id in sell_items.keys(): item_save_count=sell_items[item_id] itm_count=self._get_game_state().count_in_storage('@'+item_id) item_count=itm_count-item_save_count if item_count>0: sell_event = GameSellItem(count=long(item_count), itemId = unicode(item_id)) self._get_events_sender().send_game_events([sell_event]) self._get_game_state().remove_from_storage('@'+item_id,item_count) itm_count=self._get_game_state().count_in_storage('@'+item_id) logger.info(u"Продали %d '%s' осталось %d"%((item_count),self._get_item_reader().get(item_id).name,itm_count)) CollIt=obj2dict(self._get_game_state().get_state().collectionItems) send_user = self._get_options()['send_user'] # "26586292" if send_user<>None: for item_id in CollIt.keys(): #print item_id+'\t-\t'+str(CollIt[item_id]) #{"gift":{"item":"@CR_53","msg":"","count":1,"user":"******"},"action":"sendGift","id":55,"type":"gift"} #{"gift":{"msg":"","item":"C_4_1","count":1,"user":"******"},"action":"sendGift","type":"gift"} if CollIt[item_id]>0: send_gift={ "item":'@'+item_id, "msg":"", "count":CollIt[item_id], "user":send_user } event=GameSendGift(gift=send_gift) self._get_events_sender().send_game_events([event]) #print 'Otpravleno\t'+str(CollIt[item_id])+'\t'+item_id logger.info(u"Отправили %d '%s' пользователю %d"%(CollIt[item_id],self._get_item_reader().get(item_id).name,int(send_user))) self._get_game_state().remove_from_storage('@'+item_id, CollIt[item_id]) CollIt[item_id]=0 self._get_game_state().get_state().collectionItems=dict2obj(CollIt)
def perform_action(self): count = 1 #сколько менять itemId = 'C_2' #C_1,C_2 = номер коллекции coll = obj2dict(self._get_game_state().get_state().collectionItems) max_coll = [ int(coll[itemId + '_' + str(_i)]) for _i in range(1, 6) if (itemId + '_' + str(_i) in coll.keys()) ] if len(max_coll) == 5 and min(max_coll) >= count: #меняем коллекции col_exchange = { "count": count, "itemId": itemId, "action": "collect", "type": "item" } self._get_events_sender().send_game_events([col_exchange]) logger.info(u'Обмениваем ' + str(self._get_item_reader().get('@' + itemId).name) + ' ' + str(count) + u' раз') else: logger.info(u'Не хватает чего-то для обмена')
u'jobEndTime': JOB_END_TIME, u'materials': [], u'doneCounter': 12L, u'y': 70L, u'x': 60L, u'type': u'woodGraveDouble', u'id': GRAVE_ID }] }) game_location = GameLocation(Test.game_item_reader, location) wood_grave = game_location.get_object_by_id(GRAVE_ID) event_to_handle = dict2obj({ u'action': u'stop', u'objId': GRAVE_ID, u'targetId': TARGET_ID, u'type': u'gainMaterial' }) # exercise GainMaterialEventHandler(Test.game_item_reader, game_location, Mock()).handle(event_to_handle) # verify self.assertEqual([ obj2dict(wood_grave), { 'item': u'@SC_PICKUP_BOX_WOOD6', 'id': TARGET_ID, 'type': u'pickup' } ], obj2dict(location.gameObjects))
def perform_action(self): # Сколько оставлять коллекций collections = { #"C_1":10000, # Звёздная "C_2":10, # Луксорская #"C_3":10000, # Байкерская #"C_4":10000, # Знаков #"C_5":10000, # Ручная #"C_6":10000, # Обувная "C_7":10, # Страшная #"C_8":10000, # Строительная #"C_9":10000, # Столовая #"C_10":10000, # Редкая #"C_11":10000, # Автомобильная #"C_12":10000, # Туристическая #"C_13":10000, # Домашняя #"C_14":10000, # Игрушек #"C_15":10000, # Ёлочная #"C_16":10000, # Кролика #"C_17":10000, # Цветов #"C_18":10000, # Деда Мороза #"C_19":10000, # Анти-зомби #"C_20":10000, # Брендов #"C_21":10, # Весенняя "C_22":10, # Тинейджерская #"C_23":10000, # Компа "C_24":1, # Морская "C_25":1, # Пляжная "C_26":200, # Майя "C_27":1, # Секретная "C_28":1, # Гипер #"C_29":10000, # Хэллоуин #"C_30":10000, # Президентская #"C_31":10000, # Зимняя #"C_32":10000, # Подземельная "C_33":1, # Любовная #"C_34":10000, # Адская "C_35":1, # Райская #"C_36":10000, # Японская #"C_37":10000, # Школьная #"C_38":10000, # Пиратская #"C_39":10000, # Рыбака #"C_40":10000, # Военная #"C_41":10000, # Футбольная #"C_42":10000, # Изумрудная #"C_43":10000, # Песочная #"C_44":10000, # Котят #"C_45":10000, # Щенков "C_46":1, # Тропическая "C_47":1, # Плохая #"C_48":10000, # Палача "C_49":1, # Фобий "C_50":1, # Вкусная "C_51":1 # Временная } # Словарь названий коллекций name = {"C_1":u"Звёздная","C_2":u"Луксорская","C_3":u"Байкерская","C_4":u"Знаков","C_5":u"Ручная","C_6":u"Обувная","C_7":u"Страшная","C_8":u"Строительная","C_9":u"Столовая","C_10":u"Редкая","C_11":u"Автомобильная","C_12":u"Туристическая","C_13":u"Домашняя","C_14":u"Игрушек","C_15":u"Ёлочная","C_16":u"Кролика","C_17":u"Цветов","C_18":u"Деда Мороза","C_19":u"Анти-зомби","C_20":u"Брендов","C_21":u"Весенняя","C_22":u"Тинейджерская","C_23":u"Компа","C_24":u"Морская","C_25":u"Пляжная","C_26":u"Майя","C_27":u"Секретная","C_28":u"Гипер","C_29":u"Хэллоуин","C_30":u"Президентская","C_31":u"Зимняя","C_32":u"Подземельная","C_33":u"Любовная","C_34":u"Адская","C_35":u"Райская","C_36":u"Японская","C_37":u"Школьная","C_38":u"Пиратская","C_39":u"Рыбака","C_40":u"Военная","C_41":u"Футбольная","C_42":u"Изумрудная","C_43":u"Песочная","C_44":u"Котят","C_45":u"Щенков","C_46":u"Тропическая","C_47":u"Плохая","C_48":u"Палача","C_49":u"Фобий","C_50":u"Вкусная","C_51":u"Временная"} # Получаем количество на складе cl_items = obj2dict(self._get_game_state().get_state().collectionItems) for collection in collections: # Создаём item всех элементов element_1 = collection + "_1" element_2 = collection + "_2" element_3 = collection + "_3" element_4 = collection + "_4" element_5 = collection + "_5" # Проверка на наличие собранной коллекции if (element_1 in cl_items) and (element_2 in cl_items) and (element_3 in cl_items) and (element_4 in cl_items) and (element_5 in cl_items): # И вычисляем сколько обменять count = min(cl_items[element_1],cl_items[element_2],cl_items[element_3],cl_items[element_4],cl_items[element_5]) - collections[collection] if count > 0: event = [{"type":"item","count":count,"itemId":collection,"action":"collect"}] self._get_events_sender().send_game_events(event) logger.info(u"Обменяли %d коллекций '%s' "%(count,name[collection])) self._get_game_state().remove_from_storage('@'+element_1, cl_items[element_1] - count) self._get_game_state().remove_from_storage('@'+element_2, cl_items[element_2] - count) self._get_game_state().remove_from_storage('@'+element_3, cl_items[element_3] - count) self._get_game_state().remove_from_storage('@'+element_4, cl_items[element_4] - count) self._get_game_state().remove_from_storage('@'+element_5, cl_items[element_5] - count) cl_items[element_1] -= count cl_items[element_2] -= count cl_items[element_3] -= count cl_items[element_4] -= count cl_items[element_5] -= count self._get_game_state().get_state().collectionItems=dict2obj(cl_items)
def perform_action(self): min_coll = 500 # Оставляем Японской коллекции _loc = self._get_game_state().get_game_loc().get_location_id() if not (_loc == u'isle_02' or _loc == u'isle_elephant'): return 1 self._events = [] if _loc == u'isle_02': obj_id_observatory = '' #получаем id bozon=self._get_game_state().count_in_storage('@CR_666') buildings = self._get_game_location().get_all_objects_by_type(GameBuilding.type) jap_1=jap_2=jap_3=jap_4=jap_5=0 for building in list(buildings): if building.item == '@B_OBSERVATORY': obj_id_observatory = building.id if obj_id_observatory != '' : cl_items = obj2dict(self._get_game_state().get_state().collectionItems) if 'C_36_1' in cl_items.keys():jap_1 = cl_items['C_36_1'] # Японская if 'C_36_2' in cl_items.keys():jap_2 = cl_items['C_36_2'] # Японская if 'C_36_3' in cl_items.keys():jap_3 = cl_items['C_36_3'] # Японская if 'C_36_4' in cl_items.keys():jap_4 = cl_items['C_36_4'] # Японская if 'C_36_5' in cl_items.keys():jap_5 = cl_items['C_36_5'] # Японская ##### Изумрудка ##### if obj_id_observatory != '': minreal=min(jap_1,jap_2,jap_3,jap_4,jap_5) countcol=minreal-min_coll needcountbozon=int(round(countcol/10)) if bozon>needcountbozon: if needcountbozon>0: for i in range(needcountbozon): self._get_game_state().remove_from_storage('@CR_666',5) self.create_items(obj_id_observatory, "11") self.create_items(obj_id_observatory, "12") self.create_items(obj_id_observatory, "13") self.create_items(obj_id_observatory, "14") self.create_items(obj_id_observatory, "15") firstcount=(i + 1)*10 endcount=(i + 1)*5 logger.info(u"Создали %d шт. 'Четвертак"%(endcount)) logger.info(u"Создали %d шт. 'Золотой орех"%(endcount)) logger.info(u"Создали %d шт. 'Изумруд"%(endcount)) logger.info(u"Создали %d шт. 'Кленовый листок"%(endcount)) logger.info(u"Создали %d шт. 'Соломинка"%(endcount)) cl_items['C_36_1']-=firstcount cl_items['C_36_2']-=firstcount cl_items['C_36_3']-=firstcount cl_items['C_36_4']-=firstcount cl_items['C_36_5']-=firstcount bozon-=needcountbozon if 'C_42_1' in cl_items.keys():cl_items['C_42_1']+= endcount else:cl_items['C_42_1']= endcount if 'C_42_2' in cl_items.keys(): cl_items['C_42_2']+= endcount else:cl_items['C_42_2']= endcount if 'C_42_3' in cl_items.keys():cl_items['C_42_3']+= endcount else:cl_items['C_42_3']= endcount if 'C_42_4' in cl_items.keys(): cl_items['C_42_4']+= endcount else:cl_items['C_42_4']= endcount if 'C_42_5' in cl_items.keys(): cl_items['C_42_5']+= endcount else:cl_items['C_42_5']= endcount #else:print u'Не хватает БОЗОНА' self.events_free() self._get_game_state().get_state().collectionItems=dict2obj(cl_items) return 1
def perform_action(self): min_coll = 500 # Оставляем ручных и обувных коллекций dread = 1 # Страшная luksor = 1 # Луксорская location_id = u'isle_ufo' # на каком острове #----------------------------------------------------------------------- # обмен коллекций _loc = self._get_game_state().get_game_loc().get_location_id() if _loc != location_id: return 1 self._events = [] obj_id_iz_melnica = obj_id_iz_majak = '' #получаем id buildings = self._get_game_location().get_all_objects_by_type(GameBuilding.type) for building in list(buildings): if building.item == '@B_MILL_EMERALD2': obj_id_iz_melnica = building.id if building.item == '@B_LIGHT_EMERALD2': obj_id_iz_majak = building.id if obj_id_iz_melnica == '' and obj_id_iz_majak == '': return 1 cl_items = obj2dict(self._get_game_state().get_state().collectionItems) #self._get_game_state().get_state().collectionItems hand_1 = hand_2 = hand_3 = hand_4 = hand_5 = 0 shoe_1 = shoe_2 = shoe_3 = shoe_4 = shoe_5 = 0 bike_1 = bike_2 = bike_3 = bike_4 = bike_5 = 0 znak_1 = znak_2 = znak_3 = znak_4 = znak_5 = 0 for _item in cl_items.keys(): if _item == 'C_5_1': hand_1 = cl_items[_item] # Ручная if _item == 'C_5_2': hand_2 = cl_items[_item] # Ручная if _item == 'C_5_3': hand_3 = cl_items[_item] # Ручная if _item == 'C_5_4': hand_4 = cl_items[_item] # Ручная if _item == 'C_5_5': hand_5 = cl_items[_item] # Ручная if _item == 'C_6_1': shoe_1 = cl_items[_item] # Обувная if _item == 'C_6_2': shoe_2 = cl_items[_item] # Обувная if _item == 'C_6_3': shoe_3 = cl_items[_item] # Обувная if _item == 'C_6_4': shoe_4 = cl_items[_item] # Обувная if _item == 'C_6_5': shoe_5 = cl_items[_item] # Обувная if _item == 'C_3_1': bike_1 = cl_items[_item] # Байкерская if _item == 'C_3_2': bike_2 = cl_items[_item] # Байкерская if _item == 'C_3_3': bike_3 = cl_items[_item] # Байкерская if _item == 'C_3_4': bike_4 = cl_items[_item] # Байкерская if _item == 'C_3_5': bike_5 = cl_items[_item] # Байкерская if _item == 'C_4_1': znak_1 = cl_items[_item] # Знаков if _item == 'C_4_2': znak_2 = cl_items[_item] # Знаков if _item == 'C_4_3': znak_3 = cl_items[_item] # Знаков if _item == 'C_4_4': znak_4 = cl_items[_item] # Знаков if _item == 'C_4_5': znak_5 = cl_items[_item] # Знаков # Страшная if(obj_id_iz_melnica != '') and dread: if (hand_1 > min_coll and shoe_1 > min_coll) or (hand_2 > min_coll and shoe_2 > min_coll) or (hand_3 > min_coll and shoe_3 > min_coll) or (hand_4 > min_coll and shoe_4 > min_coll): print print u'Ручная: ', str(hand_1).rjust(6, ' ')+',', str(hand_2).rjust(6, ' ')+',', str(hand_3).rjust(6, ' ')+',', str(hand_4).rjust(6, ' ')+',', str(hand_5).rjust(6, ' ') print u'Обувная: ', str(shoe_1).rjust(6, ' ')+',', str(shoe_2).rjust(6, ' ')+',', str(shoe_3).rjust(6, ' ')+',', str(shoe_4).rjust(6, ' ')+',', str(shoe_5).rjust(6, ' ') if hand_1 > min_coll and shoe_1 > min_coll: if hand_1 > shoe_1: count = shoe_1 - min_coll else: count = hand_1 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "1") cl_items['C_5_1'] -= count cl_items['C_6_1'] -= count logger.info(u'Создали %d перчаток Фредди', i + 1) if 'C_7_1' in cl_items.keys(): cl_items['C_7_1'] += count else:cl_items['C_7_1'] = count if hand_2 > min_coll and shoe_2 > min_coll: if hand_2 > shoe_2: count = shoe_2 - min_coll else: count = hand_2 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "2") cl_items['C_5_2'] -= count cl_items['C_6_2'] -= count logger.info(u'Создали %d шляп Фредди', i + 1) if 'C_7_2' in cl_items.keys(): cl_items['C_7_2'] += count else:cl_items['C_7_2'] = count if hand_3 > min_coll and shoe_3 > min_coll: if hand_3 > shoe_3: count = shoe_3 - min_coll else: count = hand_3 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "3") cl_items['C_5_3'] -= count cl_items['C_6_3'] -= count logger.info(u'Создали %d кофт Фредди', i + 1) if 'C_7_3' in cl_items.keys(): cl_items['C_7_3'] += count else:cl_items['C_7_3'] = count if hand_4 > min_coll and shoe_4 > min_coll: if hand_4 > shoe_4: count = shoe_4 - min_coll else: count = hand_4 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "4") cl_items['C_5_4'] -= count cl_items['C_6_4'] -= count logger.info(u'Создали %d зажигалок Фредди', i + 1) if 'C_7_4' in cl_items.keys(): cl_items['C_7_4'] += count else:cl_items['C_7_4'] = count if hand_5 > min_coll and shoe_5 > min_coll: if hand_5 > shoe_5: count = shoe_5 - min_coll else: count = hand_5 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "5") cl_items['C_5_5'] -= count cl_items['C_6_5'] -= count logger.info(u'Создали %d будильников Фредди', i + 1) if 'C_7_5' in cl_items.keys(): cl_items['C_7_5'] += count else:cl_items['C_7_5'] = count #Луксорская if(obj_id_iz_majak != '') and luksor: if (bike_1 > min_coll and znak_1 > min_coll) or (bike_2 > min_coll and znak_2 > min_coll) or (bike_3 > min_coll and znak_3 > min_coll) or (bike_4 > min_coll and znak_4 > min_coll): print print u'Байкерская:', str(bike_1).rjust(6, ' ')+',', str(bike_2).rjust(6, ' ')+',', str(bike_3).rjust(6, ' ')+',', str(bike_4).rjust(6, ' ')+',', str(bike_5).rjust(6, ' ') print u'Знаков: ', str(znak_1).rjust(6, ' ')+',', str(znak_2).rjust(6, ' ')+',', str(znak_3).rjust(6, ' ')+',', str(znak_4).rjust(6, ' ')+',', str(znak_5).rjust(6, ' ') if bike_1 > min_coll and znak_1 > min_coll: if bike_1 > znak_1: count = znak_1 - min_coll else: count = bike_1 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "1") cl_items['C_3_1'] -= count cl_items['C_4_1'] -= count logger.info(u'Создали %d "Бинты мумии"', i + 1) if 'C_2_1' in cl_items.keys(): cl_items['C_2_1'] += count else:cl_items['C_2_1'] = count if bike_2 > min_coll and znak_2 > min_coll: if bike_2 > znak_2: count = znak_2 - min_coll else: count = bike_2 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "2") cl_items['C_3_2'] -= count cl_items['C_4_2'] -= count logger.info(u'Создали %d "Гребешок"', i + 1) if 'C_2_2' in cl_items.keys(): cl_items['C_2_2'] += count else:cl_items['C_2_2'] = count if bike_3 > min_coll and znak_3 > min_coll: if bike_3 > znak_3: count = znak_3 - min_coll else: count = bike_3 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "3") cl_items['C_3_3'] -= count cl_items['C_4_3'] -= count logger.info(u'Создали %d "Кошечка"', i + 1) if 'C_2_3' in cl_items.keys(): cl_items['C_2_3'] += count else:cl_items['C_2_3'] = count if bike_4 > min_coll and znak_4 > min_coll: if bike_4 > znak_4: count = znak_4 - min_coll else: count = bike_4 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "4") cl_items['C_3_4'] -= count cl_items['C_4_4'] -= count logger.info(u'Создали %d "Скарабей"', i + 1) if 'C_2_4' in cl_items.keys(): cl_items['C_2_4'] += count else:cl_items['C_2_4'] = count if bike_5 > min_coll and znak_5 > min_coll: if bike_5 > znak_5: count = znak_5 - min_coll else: count = bike_5 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "5") cl_items['C_3_5'] -= count cl_items['C_4_5'] -= count logger.info(u'Создали %d "Фараон"', i + 1) if 'C_2_5' in cl_items.keys(): cl_items['C_2_5'] += count else:cl_items['C_2_5'] = count print self.events_free() self._get_game_state().get_state().collectionItems=dict2obj(cl_items)
def log_game_objects(self): for gameObject in self.get_game_objects(): # if gameObject.type != 'base': logger.info(obj2dict(gameObject))
def send(self, data): data = obj2dict(data) assert 'type' in data request = self.__factory.createRequest(data) return dict2obj(request.send(self.__connection))
def logUnknownEvent(self, event_to_handle): logger = logging.getLogger('unknownEventLogger') logger.info(pprint.pformat(obj2dict(event_to_handle)))
def perform_action(self): min_coll = 1 # Оставляем ручных и обувных коллекций _loc = self._get_game_state().get_game_loc().get_location_id() if not (_loc == u'main' or _loc == u'isle_ufo'):# выключать просто - изменяем ид острова на несуществующий и всё (isle_9elephant) return 1 self._events = [] # обмен коллекций if _loc == u'isle_ufo': obj_id_iz_melnica = obj_id_iz_majak = '' #получаем id buildings = self._get_game_location().get_all_objects_by_type(GameBuilding.type) for building in list(buildings): if building.item == '@B_MILL_EMERALD':# выключать просто - изменяем ид объекта на несуществующий и всё (B_MILL_9EMERALD2) obj_id_iz_melnica = building.id if building.item == '@B_LIGHT_EMERALD': obj_id_iz_majak = building.id if(obj_id_iz_melnica != '' or obj_id_iz_majak != ''): cl_items = obj2dict(self._get_game_state().get_state().collectionItems)#self._get_game_state().get_state().collectionItems for _item in cl_items.keys(): if _item == 'C_5_1': hand_1 = cl_items[_item] # Ручная if _item == 'C_5_2': hand_2 = cl_items[_item] # Ручная if _item == 'C_5_3': hand_3 = cl_items[_item] # Ручная if _item == 'C_5_4': hand_4 = cl_items[_item] # Ручная if _item == 'C_5_5': hand_5 = cl_items[_item] # Ручная if _item == 'C_6_1': shoe_1 = cl_items[_item] # Обувная if _item == 'C_6_2': shoe_2 = cl_items[_item] # Обувная if _item == 'C_6_3': shoe_3 = cl_items[_item] # Обувная if _item == 'C_6_4': shoe_4 = cl_items[_item] # Обувная if _item == 'C_6_5': shoe_5 = cl_items[_item] # Обувная if _item == 'C_3_1': bike_1 = cl_items[_item] # Байкерская if _item == 'C_3_2': bike_2 = cl_items[_item] # Байкерская if _item == 'C_3_3': bike_3 = cl_items[_item] # Байкерская if _item == 'C_3_4': bike_4 = cl_items[_item] # Байкерская if _item == 'C_3_5': bike_5 = cl_items[_item] # Байкерская if _item == 'C_4_1': znak_1 = cl_items[_item] # Знаков if _item == 'C_4_2': znak_2 = cl_items[_item] # Знаков if _item == 'C_4_3': znak_3 = cl_items[_item] # Знаков if _item == 'C_4_4': znak_4 = cl_items[_item] # Знаков if _item == 'C_4_5': znak_5 = cl_items[_item] # Знаков #print 'Ручная:', hand_1, ',', hand_2, ',', hand_3, ',', hand_4, ',', hand_5, '; Обувная:', shoe_1, ',', shoe_2, ',', shoe_3, ',', shoe_4, ',', shoe_5 #print 'Байкерская:', bike_1, ',', bike_2, ',', bike_3, ',', bike_4, ',', bike_5, '; Знаков:', znak_1, ',', znak_2, ',', znak_3, ',', znak_4, ',', znak_5 #Стрёмная, очень... if(obj_id_iz_melnica != ''): if hand_1 > min_coll and shoe_1 > min_coll: if hand_1 > shoe_1: count = shoe_1 - min_coll else: count = hand_1 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "1") #logger.info(u'Создаём перчатку фреди %d', i + 1) logger.info(u'Создали %d перчаток Фредди', i + 1) if hand_2 > min_coll and shoe_2 > min_coll: if hand_2 > shoe_2: count = shoe_2 - min_coll else: count = hand_2 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "2") #logger.info(u'Создаём шляпу фреди %d', i + 1) logger.info(u'Создали %d шляп Фредди', i + 1) if hand_3 > min_coll and shoe_3 > min_coll: if hand_3 > shoe_3: count = shoe_3 - min_coll else: count = hand_3 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "3") #logger.info(u'Создаём кофту фреди %d', i + 1) logger.info(u'Создали %d кофт Фредди', i + 1) if hand_4 > min_coll and shoe_4 > min_coll: if hand_4 > shoe_4: count = shoe_4 - min_coll else: count = hand_4 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "4") #logger.info(u'Создаём зажигалку фреди %d', i + 1) logger.info(u'Создали %d зажигалок Фредди', i + 1) if hand_5 > min_coll and shoe_5 > min_coll: if hand_5 > shoe_5: count = shoe_5 - min_coll else: count = hand_5 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "5") #logger.info(u'Создаём будильник фреди %d', i + 1) logger.info(u'Создали %d будильников Фредди', i + 1) #Луксорская if(obj_id_iz_majak != ''): if bike_1 > min_coll and znak_1 > min_coll: if bike_1 > znak_1: count = znak_1 - min_coll else: count = bike_1 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "1") #logger.info(u'Создаём "Бинты мумии" %d', i + 1) logger.info(u'Создали %d "Бинты мумии"', i + 1) if bike_2 > min_coll and znak_2 > min_coll: if bike_2 > znak_2: count = znak_2 - min_coll else: count = bike_2 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "2") #logger.info(u'Создаём "Гребешок" %d', i + 1) logger.info(u'Создали %d "Гребешок"', i + 1) if bike_3 > min_coll and znak_3 > min_coll: if bike_3 > znak_3: count = znak_3 - min_coll else: count = bike_3 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "3") #logger.info(u'Создаём "Кошечка" %d', i + 1) logger.info(u'Создали %d "Кошечка"', i + 1) if bike_4 > min_coll and znak_4 > min_coll: if bike_4 > znak_4: count = znak_4 - min_coll else: count = bike_4 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "4") #logger.info(u'Создаём "Скарабей" %d', i + 1) logger.info(u'Создали %d "Скарабей"', i + 1) if bike_5 > min_coll and znak_5 > min_coll: if bike_5 > znak_5: count = znak_5 - min_coll else: count = bike_5 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "5") #logger.info(u'Создаём "Фараон" %d', i + 1) logger.info(u'Создали %d "Фараон"', i + 1) self.events_free() return 1 #обмен коллекций brains_const = 19 # Указываем нужное постоянное количество без имеющихся у игрока бесплатных want_helly = 60 # Сколько хотим хеллий иметь want_kley = 20 # Клея want_trans = 20 # Трансформаторов want_yekraska= 20# Краски жёлтой min_money = 1000000 # оставляем денег obj_id_ostankino = obj_id_korabl = obj_id_elka = obj_id_pirmida = obj_id_bashnya = obj_id_furgon = '' # Переменные для ID останкино и корабля helly = love = clevhell = garliclily = clever = squashhell = garlic = lily = kley = trans = yekraska = steklo = 0 #получаем id останкино и летучего корабля buildings = self._get_game_location().get_all_objects_by_type(GameBuilding.type) for building in list(buildings): building_item = self._get_item_reader().get(building.item) if building_item.id == 'B_OSTANKINO': # или if building_item.id == 'B_OSTANKINO' obj_id_ostankino = building.id if building_item.name == u'Летучий корабль': # или if building_item.id == 'D_SHIP' obj_id_korabl = building.id if building_item.id == 'B_NYTREE': obj_id_elka = building.id if building_item.id == 'B_PYRAMID': obj_id_pirmida = building.id if building_item.id == 'B_PISA': obj_id_bashnya = building.id if building_item.id == 'B_VAN_ICE_CREAM': obj_id_furgon = building.id travel_time = -1 for l in self._get_game_state().get_state().buffs.list: if 'BUFF_TRAVEL_TICKET_TIME' in l.item: exp_time = float(l.expire.endDate) # l.expire.type (= time) if travel_time < exp_time : travel_time = exp_time if travel_time < 0 and obj_id_furgon != '': logger.info(u'Создаём баф путешествий') self.create_items(obj_id_furgon, "1") st_items = self._get_game_state().get_state().storageItems #with open('storage2.txt', 'w') as f: # f.write(str(obj2dict(st_items)).encode('utf-8')) for _item in list(st_items): if hasattr(_item, 'item'): #it_name = self._get_item_reader().get(_item.item) #print 'it ', _item.item, ' name ', it_name.name # Определяем на складе количество: if _item.item == ('@R_12'): helly = _item.count # Хеллия if _item.item == ('@CR_31'): love = _item.count # Любовь if _item.item == ('@R_02'): clevhell = _item.count # Клеверхелл if _item.item == ('@R_09'): garliclily = _item.count # Чесночная лилия if _item.item == ('@S_14'): squashhell = _item.count # Тыквахелл if _item.item == ('@S_03'): clever = _item.count # Клевер if _item.item == ('@S_15'): lily = _item.count # Лилия if _item.item == ('@S_08'): garlic = _item.count # Чеснок if _item.item == ('@CR_25'): steklo = _item.count # Стекло if _item.item == ('@CR_17'): kley = _item.count # Супер-клей if _item.item == ('@CR_23'): trans = _item.count # Трансформатор if _item.item == ('@CR_10'): yekraska = _item.count # Жёлтая краска need_kley = (want_kley) - kley if need_kley < 0: need_kley = 0 need_trans = (need_kley + want_trans) - kley if need_trans < 0: need_trans = 0 need_yekraska = (need_kley + want_yekraska) - yekraska if need_yekraska < 0: need_yekraska = 0 need_helly = (2 * brains_const + want_helly + (need_kley*2) + (need_trans) + (need_yekraska)) - helly # Максимально необходимое кол-во хеллии if need_helly < 0: need_helly = 0 need_garliclily = (need_helly) - garliclily # Максимально необходимое кол-во чесночных лилий if need_garliclily < 0: need_garliclily = 0 need_love = (10 * brains_const)-love # Максимально необходимое кол-во любви need_clevhell = (4 * need_helly) - clevhell # Максимально необходимое кол-во клеверхелла if need_clevhell < 0: need_clevhell = 0 need_clever = (int(ceil(need_clevhell/20)*20)) - clever # Максимально необходимое кол-во клевера need_squashhell = (int(ceil(need_clevhell/10)*10)) - squashhell # Максимально необходимое кол-во тыквахелла need_garlic = (int(ceil(need_garliclily/40)*40)) - garlic # Максимально необходимое кол-во чеснока need_lily = (int(ceil(need_garliclily/40)*40)) - lily # Максимально необходимое кол-во лилий i = 0 if need_helly > 0: if(obj_id_korabl == ''): logger.info(u'Не хватает хеллий, сварите еще %d шт.',need_helly) return else: if need_clevhell > 0: if need_clever > 0: logger.info(u'Не хватает клевера, посадите еще %d шт.',need_clever) return elif need_squashhell > 0: logger.info(u'Не хватает тыквахелла, посадите еще %d шт.',need_squashhell) return for i in range(int(ceil((need_clevhell)/10))+1): self.create_items(obj_id_korabl, "1") if i > 0: logger.info(u'Создали %d клеверхелла', i*10) if need_garliclily > 0: if need_garlic > 0: logger.info(u'Не хватает чеснока, посадите еще %d шт.',need_garlic) return elif need_lily > 0: logger.info(u'Не хватает лилий, посадите еще %d шт.',need_lily) return else: for i in range(int(ceil((need_garliclily)/10))+1): self.create_items(obj_id_korabl, "2") if i > 0: logger.info(u'Создали %d чесночных лилий', i*10) for i in range(need_helly): self.create_items(obj_id_korabl, "3") if i > 0: logger.info(u'Создали %d хеллий', i) if need_yekraska > 0: if(obj_id_pirmida != ''): if (self._get_game_state().get_state().gameMoney - ((need_yekraska) * 1000)) < min_money: print u'Не хватает денег' return else: for i in range(need_yekraska): self.create_items(obj_id_pirmida, "1") if i > 0: logger.info(u'Создали %d жёлтой краски', i) if need_trans > 0: if(obj_id_bashnya != ''): if (need_trans) > steklo: print u'Не хватает стекла' return else: for i in range(need_trans): self.create_items(obj_id_bashnya, "1") if i > 0: logger.info(u'Создали %d трансформаторов', i) if need_kley > 0: if(obj_id_elka != ''): if 0: return else: for i in range(need_kley): self.create_items(obj_id_elka, "1") if i > 0: logger.info(u'Создали %d клея', i) if need_love > 0: logger.info(u'Не хватает любви для создания мозгов, накопайте еще %d шт.', need_love) return brains_buy = self._get_game_state().get_state().buyedBrains # Кол-во активаций мозгов (не самих мозгов) brains_curr = 0 # Счетчик кол-ва текущих мозгов x=0 # Счетчик кол-ва мозгов с истечением времени < 5 мин. if len(brains_buy)<>0: for buyed_brain in brains_buy: hf = buyed_brain.count brains_curr += hf m = ((int(buyed_brain.endTime)/1000)/60)-((((int(buyed_brain.endTime)/1000)/60)/60)*60) h = ((int(buyed_brain.endTime)/1000)/60)/60 if h==0 and m<=6: x+=hf # Разница между необходимыми и текущими мозгами. brains_lacks = 0 if brains_curr < brains_const: brains_lacks = brains_const - brains_curr brains_lx = x + brains_lacks # Определяем предположительное необходимое ко-во мозгов. brains_need = brains_curr - brains_lx # Если меньше нужного постоянного, то создаем недостающие. if brains_need < brains_const: _i=0 for _i in range(brains_lx): self.create_items(obj_id_ostankino, "1") brains_buy.append(dict2obj({u'count': 1L, u'endTime': u'86400000'})) #Добавляем фейк в список купленных мозгов для увеличения счетчика logger.info (u'Создано мозгов - %d шт.', brains_lx) self.events_free()
def perform_action(self): #logger.info(u"######### Идем к другу ###########") #go_to_friend = {"action":"gameState","locationId":"main","user":'******',"objId":None,"type":"gameState"}#{"id":8,"action":"gameState","objId":null,"locationId":"main","user":"******","type":"gameState"} #,"id":46667 #friends = ['8477452','22656865','27505179','107183826','68030140','163206097']#'476111', friends = self._get_options() # Юдо Чудо #friends = ['7942552'] + friends #friends = ['35908611','7942552'] + friends objtypes = ['decoration'] myid = '35834355' self._get_game_state().shovel = 0 if not hasattr(self._get_game_state(),'countfnyt'):self._get_game_state().countfnyt = 0 if not hasattr(self._get_game_state(), 'countnyt'):self._get_game_state().countnyt = 0 if not hasattr(self._get_game_state(), 'sendNewYearGift'):self._get_game_state().sendNewYearGift = 0 if not hasattr(self._get_game_state(), 'gameObjects') and self._get_game_state().countfnyt < len(friends): user = friends[self._get_game_state().countfnyt] print (u"######### Идем к другу "+str(user)+" "+str(self._get_game_state().countfnyt+1)+"/"+str(len(friends))+" #########").encode('cp866') self._get_events_sender().send_game_events([{"action":"gameState","locationId":"main","user":str(user),"objId":None,"type":"gameState"},{"type":"players","action":"getInfo","players":[str(user)]}]) self._get_game_state().countfnyt += 1 elif hasattr(self._get_game_state(), 'gameObjects'):# and open('objects.txt', 'a').write(str(friends[self._get_game_state().countfnyt])+"\n") print "############### gameObjects #################" countnyt = 0 countmyg = 0 countpickup = 0 objssvl = [] if hasattr(self._get_game_state(),'alldigged'):alldigged = 1 else: alldigged = 0 for object in self._get_game_state().gameObjects: if self._get_game_state().countnyt + countnyt < 148: if hasattr(object, 'type'): tf = 0 if object.type == 'newYearTree': tf = 1 usrs = len(object.users) #object.users = usrs #open('newyeartree.txt', 'a').write(str(obj2dict(object))+"\n") if tf == 1 and not hasattr(self._get_game_state(), 'nytend'): print (u"Ёлка !!!").encode('cp866') #open('gameObjects.txt', 'a').write(str(obj2dict(object))+"\n") #open('newyeartree.txt', 'a').write(object.item + " UsersGift:" + str(len(object.users)) + "\n") tf = 1 f = 0 #Ёлки разной ёмкости. указано не точно. if object.item == u'@B_SPRUCE_SMOLL' and len(object.users) < 3: f = 1 if object.item == u'@B_SPRUCE_MIDDLE' and len(object.users) < 6: f = 1 if object.item == u'@B_SPRUCE_BIG' and len(object.users) < 15: f = 1 #if object.item == u'@B_BASKETS_EASTER_1' and len(object.users) < 15: f = 1 #if object.item == u'@B_BASKETS_EASTER_2' and len(object.users) < 7: f = 1 #if object.item == u'@B_BASKETS_EASTER_3' and len(object.users) < 3: f = 1 for user in object.users: if user.id == myid: countmyg+=1#print "MyGift" f = 0 break #if not check_no_my_gift(object.users): f = 1 if self._get_game_state().countnyt + countnyt > 151 or hasattr(self._get_game_state(),'nyna'): self._get_game_state().nytend = 1 print "################## END ####################" f = 0 #0 - Пряники не ложим, 1 - пряники ложим if f == 1: # Ложим пряник #open('newyeartree.txt', 'a').write(str(obj2dict(object)) + "\n") self._get_events_sender().send_game_events([{"itemId":"CAKE_PACK_FREE1","action":"remoteNewYear","type":"item","objId":object.id}]) countnyt+=1 pass else: print "NO" # Вскрываем сундук if tf == 0 and object.type == 'pickup': open('sunduki.txt', 'a').write(str(obj2dict(object)) + "\n") self._get_events_sender().send_game_events([{"action":"pick","type":"item","objId":object.id}]) countpickup+=1 tf = 2 # Добавляем в список объекты для копания клада if tf == 0 and alldigged == 0: for objtype in objtypes: if object.type == objtype: if object.item == '@DS_SYMBOL_E' or object.item == '@D_BALLOONS' or object.item == '@D_SAKURASMALL': print object.item,object.id objssvl.append(object) break if tf == 0: open('objects.txt', 'a').write(str(obj2dict(object))+"\n") if hasattr(self._get_game_state(),'playersInfo'): open('objects.txt', 'a').write('-------------------------------------' + "\n") #open('objects.txt', 'a').write(str(obj2dict(self._get_game_state().playersInfo))+"\n") open('users.txt', 'a').write(str(obj2dict(self._get_game_state().playersInfo))+"\n") open('objects.txt', 'a').write('-------------------------------------' + "\n") countlop = 0 if len(objssvl) > 0: for i in range(300): objdig = random_number.choice(objssvl) self._get_events_sender().send_game_events([{"objId":objdig.id,"x":objdig.x,"action":"remoteDig","y":objdig.y,"type":"item"}]) countlop+=1 print (u"Использовал: "+str(countlop)+u" лопат").encode('cp866') elif alldigged == 1: print (u'Всё уже выкопано!').encode('cp866') else: print (u'Нечего копать!').encode('cp866') print (u"Вскрыли сундуков: "+str(countpickup)).encode('cp866') if hasattr(self._get_game_state(),'alldigged'): del self._get_game_state().alldigged del self._get_game_state().gameObjects self._get_game_state().countnyt += countnyt print (u"поЛожил пряник(ов): "+str(self._get_game_state().sendNewYearGift)+":"+str(self._get_game_state().countnyt)+"/"+str(countnyt)+" dub: "+str(countmyg)).encode('cp866') self._get_game_state().shovel = 0 #if self._get_game_state().countfnyt + 1 > len(friends):sys.exit(0)
def perform_action(self): min_coll = 500 # Оставляем Японской коллекции _loc = self._get_game_state().get_game_loc().get_location_id() if not (_loc == u'isle_02' or _loc == u'isle_elephant'): return 1 self._events = [] if _loc == u'isle_02': obj_id_observatory = '' #получаем id bozon = self._get_game_state().count_in_storage('@CR_666') buildings = self._get_game_location().get_all_objects_by_type( GameBuilding.type) jap_1 = jap_2 = jap_3 = jap_4 = jap_5 = 0 for building in list(buildings): if building.item == '@B_OBSERVATORY': obj_id_observatory = building.id if obj_id_observatory != '': cl_items = obj2dict( self._get_game_state().get_state().collectionItems) if 'C_36_1' in cl_items.keys(): jap_1 = cl_items['C_36_1'] # Японская if 'C_36_2' in cl_items.keys(): jap_2 = cl_items['C_36_2'] # Японская if 'C_36_3' in cl_items.keys(): jap_3 = cl_items['C_36_3'] # Японская if 'C_36_4' in cl_items.keys(): jap_4 = cl_items['C_36_4'] # Японская if 'C_36_5' in cl_items.keys(): jap_5 = cl_items['C_36_5'] # Японская ##### Изумрудка ##### if obj_id_observatory != '': minreal = min(jap_1, jap_2, jap_3, jap_4, jap_5) countcol = minreal - min_coll needcountbozon = int(round(countcol / 10)) if bozon > needcountbozon: if needcountbozon > 0: for i in range(needcountbozon): self._get_game_state().remove_from_storage( '@CR_666', 5) self.create_items(obj_id_observatory, "11") self.create_items(obj_id_observatory, "12") self.create_items(obj_id_observatory, "13") self.create_items(obj_id_observatory, "14") self.create_items(obj_id_observatory, "15") firstcount = (i + 1) * 10 endcount = (i + 1) * 5 logger.info(u"Создали %d шт. 'Четвертак" % (endcount)) logger.info(u"Создали %d шт. 'Золотой орех" % (endcount)) logger.info(u"Создали %d шт. 'Изумруд" % (endcount)) logger.info(u"Создали %d шт. 'Кленовый листок" % (endcount)) logger.info(u"Создали %d шт. 'Соломинка" % (endcount)) cl_items['C_36_1'] -= firstcount cl_items['C_36_2'] -= firstcount cl_items['C_36_3'] -= firstcount cl_items['C_36_4'] -= firstcount cl_items['C_36_5'] -= firstcount bozon -= needcountbozon if 'C_42_1' in cl_items.keys(): cl_items['C_42_1'] += endcount else: cl_items['C_42_1'] = endcount if 'C_42_2' in cl_items.keys(): cl_items['C_42_2'] += endcount else: cl_items['C_42_2'] = endcount if 'C_42_3' in cl_items.keys(): cl_items['C_42_3'] += endcount else: cl_items['C_42_3'] = endcount if 'C_42_4' in cl_items.keys(): cl_items['C_42_4'] += endcount else: cl_items['C_42_4'] = endcount if 'C_42_5' in cl_items.keys(): cl_items['C_42_5'] += endcount else: cl_items['C_42_5'] = endcount #else:print u'Не хватает БОЗОНА' self.events_free() self._get_game_state().get_state().collectionItems = dict2obj( cl_items) return 1
return string def print_order(class_names, classes, printed=[]): ordered_class_names = [] postponed_classes = [] for klass_ in sorted(class_names): if ( len(classes[klass_].bases) == 1 and klass_ not in printed and (classes[klass_].bases[0] == "CommonEqualityMixin" or classes[klass_].bases[0] == "object") or classes[klass_].bases[0] in printed ): ordered_class_names += [klass_] printed += [klass_] else: postponed_classes += [klass_] if postponed_classes != []: ordered_class_names += print_order(postponed_classes, classes, printed) return ordered_class_names if __name__ == "__main__": with open("game.json") as fp: start_response = json.load(fp) start_response_object = dict2obj(start_response) state_dict = obj2dict(start_response_object) # assert start_response == state_dict print generate_classes(start_response_object), print "if __name__ == '__main__':\n pass"
def coll_count_in_storage(self, item_id): CollIt = obj2dict(self._get_game_state().get_state().collectionItems) for itemid in CollIt.keys(): if itemid == item_id: return CollIt[itemid] return 0
def perform_action(self): par = self.mega().chop_options() options = par.get('action', []) if not (u'квестовый остров' in options): if not self.if_location_pirate(): return # для квестовых островов - отключаем curuser = str(self._get_game_state().get_curuser()) myid = self._get_game_state().get_my_id() par_kt = self.mega().knock_team() seaman = par_kt.get('seaman', []) actor_options = self.mega().actor_options() auto_pirat = False knock_team = False for ap1 in actor_options: if issubclass(ap1, AutoPirat): auto_pirat = True elif issubclass(ap1, KnockTeam) and (curuser in seaman): knock_team = True self.patch = 'statistics\\' + curuser # короткое имя папки юзера sw_name = self.patch + '\\stone_well.txt' try: seaman_return = self.mega().auto_pirate_options()['seaman_return'] except: seaman_return = False if seaman_return and (auto_pirat or knock_team) and\ hasattr(self._get_game_state().get_state().pirate, 'captain') and\ str(self._get_game_state().get_state().pirate.captain) != str(myid): self.cprint(u'14Есть команда автоплавателей и мы НЕ капитан') self.write_log(u'Есть команда автоплавателей и мы НЕ капитан') self.go_home(curuser) # возвращаемся домой return # self.create_map() enemies = self._get_game_location().get_all_objects_by_type( "pirateEnemy") missionEnemy = self._get_game_location().get_all_objects_by_type( u'missionEnemy') enemies.extend(missionEnemy) # читаем список колодцев stone_well.txt self.load_stone_well(sw_name) # читаем список времени кручения sw_run = self.load_sw_run() # подключаем колодец если время кручения позволяет self.add_stone(sw_run) instruments = [] # переменная для инструментов sklad = False resources = self._get_game_location().get_all_objects_by_type('chop') if resources: # Пинатель self.pinatel_silver(options, enemies) if not self.if_location_pirate(): sklad = True # Предметы на складе for item in self._get_game_state().get_state().storageItems: if hasattr(item, 'item'): if '@CHOP_' in item.item: instruments.append( dict2obj({ "item": item.item, "count": item.count })) else: instruments = self._get_game_state().get_state( ).pirate.instruments CHOP_MACHETE, CHOP_AXE, CHOP_HAMMER, CHOP_TRIDENT = self.get_instr_count( instruments) print print u'Инструмента перед рубкой М-Т-К-Тр:', str( CHOP_MACHETE) + '-' + str(CHOP_AXE) + '-' + str( CHOP_HAMMER) + '-' + str(CHOP_TRIDENT) resources_dict = {resource: resource.x for resource in resources} resources_order = resources_dict.items() if (u'хитрые условия' in options): if (CHOP_MACHETE > 250 and CHOP_HAMMER > 250): self._get_game_state( ).many_chop = 1 # проставили many_chop если мачете и кирки за 250 if not hasattr( self._get_game_state(), 'many_chop'): # рублено не много, будем сортировать if (u'ломиться вглубь острова' in options): resources_order.sort( key=lambda x: x[::-1], reverse=True) # ресурсы отсортированные по X else: self._get_game_state().many_chop = 1 if (u'ломиться вглубь острова' in options): resources_order.sort( key=lambda x: x[::-1], reverse=True) # ресурсы отсортированные по X self.cprint(u'1Ресурсов видно:^4_%d' % len(resources_order)) all_block = True for resource in resources_order: resource = resource[0] #print 'Obj: ', resource.item.ljust(27, " "), ' id = ', resource.id #print 'resource ', resource,' ', resource.x #print obj2dict(resource) if enemies: enemy_here = 0 for enemy in enemies: if (((enemy.x - resource.x)**2 + (enemy.y - resource.y)**2)**0.5) <= 15: enemy_here = 1 break if (enemy_here == 1): self._get_game_location().remove_object_by_id( resource.id) logger.info('Сильвер мешает вырубке ' + str(resource.id)) continue tool_needed = resource.chopCount type_of_res = resource.item type_of_instrument = self._get_item_reader().get( type_of_res).chopInstrumentType # сортируем что рубим, а что нет if (not hasattr( self._get_game_state(), 'many_chop')): # рублено не много, ограничиваем траты if type_of_instrument == '@CIT_MACHETE': # мачете pass elif type_of_instrument == '@CIT_TRIDENT': # трезубец pass elif type_of_instrument == '@CIT_AXE': # топоры if CHOP_AXE > 600 or tool_needed == 10 or tool_needed == 15 or tool_needed == 16 or tool_needed > 49: pass else: continue elif type_of_instrument == '@CIT_HAMMER': # кирки if ('CH_BLACKSTONE' in type_of_res) or ( 'CH_GREENSTONE' in type_of_res) or ( 'CH_WHITESTONE' in type_of_res) or ( 'CH_CRYSTALSTONE' in type_of_res) or tool_needed > 49: pass else: continue for tool in instruments: #print "self._get_item_reader().get(tool.item).chopInstrumentType", self._get_item_reader().get(tool.item).chopInstrumentType #print "type_of_instrument", type_of_instrument if not hasattr(tool, "item"): print u'Нет итема', obj2dict(tool) continue if self._get_item_reader().get( tool.item ).chopInstrumentType == type_of_instrument and tool.count > 0: #= tool_needed: # if type_of_instrument == '@CIT_HAMMER' and tool_needed == 100: # tool_needed = 50 # logger.info(u'Снижаем удар киркой до 50') if tool.count < tool_needed: if type_of_instrument == '@CIT_TRIDENT': tool_needed = tool.count logger.info(u'Рубим неполный') else: continue #print "resource ", str(obj2dict(resource)) gain_event = { "type": "chop", "objId": resource.id, "instruments": { self._get_item_reader().get(tool.item).id: tool_needed }, "action": "chop" } logger.info(u'Рубим ' + (self._get_item_reader().get( type_of_res).name).ljust(20, ' ') + (self._get_item_reader().get( tool.item).name).ljust(6, ' ') + str(tool_needed).rjust(2, ' ') + u'L, id ' + str(gain_event['objId'])) # logger.info(u"Рубим " + str(self._get_item_reader().get(tool.item).id).ljust(13, ' ')+str(tool_needed).rjust(3, ' ')+u'L, id '+str(gain_event['objId'])) #logger.info(u"Рубим " + str(self._get_item_reader().get(tool.item).id)+', '+str(tool_needed)+u'L, id '+str(gain_event['objId'])) #logger.info(u"Рубим " + str(type_of_instrument)+u' instruments:'+str(self._get_item_reader().get(tool.item).id)+', '+str(tool_needed)+u'L, id '+str(gain_event['objId'])) self._get_events_sender().send_game_events( [gain_event]) if resource.chopCount == tool_needed: self._get_game_location().remove_object_by_id( resource.id) else: resource.chopCount -= tool_needed tool.count -= tool_needed if sklad: #print 'type_of_instrument', type_of_instrument, 'tool.item', tool.item, 'ins', ins self._get_game_state().remove_from_storage( tool.item, tool_needed) break CHOP_MACHETE2, CHOP_AXE2, CHOP_HAMMER2, CHOP_TRIDENT2 = self.get_instr_count( instruments) if CHOP_MACHETE - CHOP_MACHETE2 or CHOP_AXE - CHOP_AXE2 or CHOP_HAMMER - CHOP_HAMMER2 or CHOP_TRIDENT - CHOP_TRIDENT2: print u'Инструмента после рубки М-Т-К-Тр:', str( CHOP_MACHETE2) + '-' + str(CHOP_AXE2) + '-' + str( CHOP_HAMMER2) + '-' + str(CHOP_TRIDENT2) else: if self.location_id() == 'exploration_isle3_random' and\ self._get_game_location().get_all_objects_by_type('chop'): self.open_treasures(options, enemies) self.wait_rullets(par, enemies) return # открываем сокровища self.open_treasures(options, enemies) return else: logger.info('Не осталось ресурсов для добычи') if auto_pirat: self.go_home(curuser) # возвращаемся домой домой return else: raw_input('------------- END ---------------')
for klass_ in print_order(class_names, classes): string += str(classes[klass_]) return string def print_order(class_names, classes, printed=[]): ordered_class_names = [] postponed_classes = [] for klass_ in sorted(class_names): if (len(classes[klass_].bases) == 1 and klass_ not in printed and (classes[klass_].bases[0] == 'CommonEqualityMixin' or classes[klass_].bases[0] == 'object') or classes[klass_].bases[0] in printed): ordered_class_names += [klass_] printed += [klass_] else: postponed_classes += [klass_] if postponed_classes != []: ordered_class_names += print_order(postponed_classes, classes, printed) return ordered_class_names if __name__ == '__main__': with open('game.json') as fp: start_response = json.load(fp) start_response_object = dict2obj(start_response) state_dict = obj2dict(start_response_object) #assert start_response == state_dict print generate_classes(start_response_object), print "if __name__ == '__main__':\n pass"
def perform_action(self): min_coll = 500 # Оставляем ручных и обувных коллекций dread = 1 # Страшная luksor = 1 # Луксорская location_id = u'isle_ufo' # на каком острове #----------------------------------------------------------------------- # обмен коллекций _loc = self._get_game_state().get_game_loc().get_location_id() if _loc != location_id: return 1 self._events = [] obj_id_iz_melnica = obj_id_iz_majak = '' #получаем id buildings = self._get_game_location().get_all_objects_by_type( GameBuilding.type) for building in list(buildings): if building.item == '@B_MILL_EMERALD2': obj_id_iz_melnica = building.id if building.item == '@B_LIGHT_EMERALD2': obj_id_iz_majak = building.id if obj_id_iz_melnica == '' and obj_id_iz_majak == '': return 1 cl_items = obj2dict(self._get_game_state().get_state().collectionItems) #self._get_game_state().get_state().collectionItems hand_1 = hand_2 = hand_3 = hand_4 = hand_5 = 0 shoe_1 = shoe_2 = shoe_3 = shoe_4 = shoe_5 = 0 bike_1 = bike_2 = bike_3 = bike_4 = bike_5 = 0 znak_1 = znak_2 = znak_3 = znak_4 = znak_5 = 0 for _item in cl_items.keys(): if _item == 'C_5_1': hand_1 = cl_items[_item] # Ручная if _item == 'C_5_2': hand_2 = cl_items[_item] # Ручная if _item == 'C_5_3': hand_3 = cl_items[_item] # Ручная if _item == 'C_5_4': hand_4 = cl_items[_item] # Ручная if _item == 'C_5_5': hand_5 = cl_items[_item] # Ручная if _item == 'C_6_1': shoe_1 = cl_items[_item] # Обувная if _item == 'C_6_2': shoe_2 = cl_items[_item] # Обувная if _item == 'C_6_3': shoe_3 = cl_items[_item] # Обувная if _item == 'C_6_4': shoe_4 = cl_items[_item] # Обувная if _item == 'C_6_5': shoe_5 = cl_items[_item] # Обувная if _item == 'C_3_1': bike_1 = cl_items[_item] # Байкерская if _item == 'C_3_2': bike_2 = cl_items[_item] # Байкерская if _item == 'C_3_3': bike_3 = cl_items[_item] # Байкерская if _item == 'C_3_4': bike_4 = cl_items[_item] # Байкерская if _item == 'C_3_5': bike_5 = cl_items[_item] # Байкерская if _item == 'C_4_1': znak_1 = cl_items[_item] # Знаков if _item == 'C_4_2': znak_2 = cl_items[_item] # Знаков if _item == 'C_4_3': znak_3 = cl_items[_item] # Знаков if _item == 'C_4_4': znak_4 = cl_items[_item] # Знаков if _item == 'C_4_5': znak_5 = cl_items[_item] # Знаков # Страшная if (obj_id_iz_melnica != '') and dread: if (hand_1 > min_coll and shoe_1 > min_coll) or ( hand_2 > min_coll and shoe_2 > min_coll) or ( hand_3 > min_coll and shoe_3 > min_coll) or (hand_4 > min_coll and shoe_4 > min_coll): print print u'Ручная: ', str(hand_1).rjust( 6, ' ') + ',', str(hand_2).rjust( 6, ' ') + ',', str(hand_3).rjust( 6, ' ') + ',', str(hand_4).rjust( 6, ' ') + ',', str(hand_5).rjust(6, ' ') print u'Обувная: ', str(shoe_1).rjust( 6, ' ') + ',', str(shoe_2).rjust( 6, ' ') + ',', str(shoe_3).rjust( 6, ' ') + ',', str(shoe_4).rjust( 6, ' ') + ',', str(shoe_5).rjust(6, ' ') if hand_1 > min_coll and shoe_1 > min_coll: if hand_1 > shoe_1: count = shoe_1 - min_coll else: count = hand_1 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "1") cl_items['C_5_1'] -= count cl_items['C_6_1'] -= count logger.info(u'Создали %d перчаток Фредди', i + 1) if 'C_7_1' in cl_items.keys(): cl_items['C_7_1'] += count else: cl_items['C_7_1'] = count if hand_2 > min_coll and shoe_2 > min_coll: if hand_2 > shoe_2: count = shoe_2 - min_coll else: count = hand_2 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "2") cl_items['C_5_2'] -= count cl_items['C_6_2'] -= count logger.info(u'Создали %d шляп Фредди', i + 1) if 'C_7_2' in cl_items.keys(): cl_items['C_7_2'] += count else: cl_items['C_7_2'] = count if hand_3 > min_coll and shoe_3 > min_coll: if hand_3 > shoe_3: count = shoe_3 - min_coll else: count = hand_3 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "3") cl_items['C_5_3'] -= count cl_items['C_6_3'] -= count logger.info(u'Создали %d кофт Фредди', i + 1) if 'C_7_3' in cl_items.keys(): cl_items['C_7_3'] += count else: cl_items['C_7_3'] = count if hand_4 > min_coll and shoe_4 > min_coll: if hand_4 > shoe_4: count = shoe_4 - min_coll else: count = hand_4 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "4") cl_items['C_5_4'] -= count cl_items['C_6_4'] -= count logger.info(u'Создали %d зажигалок Фредди', i + 1) if 'C_7_4' in cl_items.keys(): cl_items['C_7_4'] += count else: cl_items['C_7_4'] = count if hand_5 > min_coll and shoe_5 > min_coll: if hand_5 > shoe_5: count = shoe_5 - min_coll else: count = hand_5 - min_coll for i in range(count): self.create_items(obj_id_iz_melnica, "5") cl_items['C_5_5'] -= count cl_items['C_6_5'] -= count logger.info(u'Создали %d будильников Фредди', i + 1) if 'C_7_5' in cl_items.keys(): cl_items['C_7_5'] += count else: cl_items['C_7_5'] = count #Луксорская if (obj_id_iz_majak != '') and luksor: if (bike_1 > min_coll and znak_1 > min_coll) or ( bike_2 > min_coll and znak_2 > min_coll) or ( bike_3 > min_coll and znak_3 > min_coll) or (bike_4 > min_coll and znak_4 > min_coll): print print u'Байкерская:', str(bike_1).rjust( 6, ' ') + ',', str(bike_2).rjust( 6, ' ') + ',', str(bike_3).rjust( 6, ' ') + ',', str(bike_4).rjust( 6, ' ') + ',', str(bike_5).rjust(6, ' ') print u'Знаков: ', str(znak_1).rjust( 6, ' ') + ',', str(znak_2).rjust( 6, ' ') + ',', str(znak_3).rjust( 6, ' ') + ',', str(znak_4).rjust( 6, ' ') + ',', str(znak_5).rjust(6, ' ') if bike_1 > min_coll and znak_1 > min_coll: if bike_1 > znak_1: count = znak_1 - min_coll else: count = bike_1 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "1") cl_items['C_3_1'] -= count cl_items['C_4_1'] -= count logger.info(u'Создали %d "Бинты мумии"', i + 1) if 'C_2_1' in cl_items.keys(): cl_items['C_2_1'] += count else: cl_items['C_2_1'] = count if bike_2 > min_coll and znak_2 > min_coll: if bike_2 > znak_2: count = znak_2 - min_coll else: count = bike_2 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "2") cl_items['C_3_2'] -= count cl_items['C_4_2'] -= count logger.info(u'Создали %d "Гребешок"', i + 1) if 'C_2_2' in cl_items.keys(): cl_items['C_2_2'] += count else: cl_items['C_2_2'] = count if bike_3 > min_coll and znak_3 > min_coll: if bike_3 > znak_3: count = znak_3 - min_coll else: count = bike_3 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "3") cl_items['C_3_3'] -= count cl_items['C_4_3'] -= count logger.info(u'Создали %d "Кошечка"', i + 1) if 'C_2_3' in cl_items.keys(): cl_items['C_2_3'] += count else: cl_items['C_2_3'] = count if bike_4 > min_coll and znak_4 > min_coll: if bike_4 > znak_4: count = znak_4 - min_coll else: count = bike_4 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "4") cl_items['C_3_4'] -= count cl_items['C_4_4'] -= count logger.info(u'Создали %d "Скарабей"', i + 1) if 'C_2_4' in cl_items.keys(): cl_items['C_2_4'] += count else: cl_items['C_2_4'] = count if bike_5 > min_coll and znak_5 > min_coll: if bike_5 > znak_5: count = znak_5 - min_coll else: count = bike_5 - min_coll for i in range(count): self.create_items(obj_id_iz_majak, "5") cl_items['C_3_5'] -= count cl_items['C_4_5'] -= count logger.info(u'Создали %d "Фараон"', i + 1) if 'C_2_5' in cl_items.keys(): cl_items['C_2_5'] += count else: cl_items['C_2_5'] = count print self.events_free() self._get_game_state().get_state().collectionItems = dict2obj(cl_items)
def perform_action(self): #logger.info(u"######### Идем к другу ###########") #go_to_friend = {"action":"gameState","locationId":"main","user":'******',"objId":None,"type":"gameState"}#{"id":8,"action":"gameState","objId":null,"locationId":"main","user":"******","type":"gameState"} #,"id":46667 #friends = ['8477452','22656865','27505179','107183826','68030140','163206097']#'476111', friends = self._get_options() # Юдо Чудо #friends = ['7942552'] + friends #friends = ['35908611','7942552'] + friends objtypes = ['decoration'] myid = '35834355' self._get_game_state().shovel = 0 if not hasattr(self._get_game_state(), 'countfnyt'): self._get_game_state().countfnyt = 0 if not hasattr(self._get_game_state(), 'countnyt'): self._get_game_state().countnyt = 0 if not hasattr(self._get_game_state(), 'sendNewYearGift'): self._get_game_state().sendNewYearGift = 0 if not hasattr(self._get_game_state(), 'gameObjects' ) and self._get_game_state().countfnyt < len(friends): user = friends[self._get_game_state().countfnyt] print(u"######### Идем к другу " + str(user) + " " + str(self._get_game_state().countfnyt + 1) + "/" + str(len(friends)) + " #########").encode('cp866') self._get_events_sender().send_game_events([{ "action": "gameState", "locationId": "main", "user": str(user), "objId": None, "type": "gameState" }, { "type": "players", "action": "getInfo", "players": [str(user)] }]) self._get_game_state().countfnyt += 1 elif hasattr(self._get_game_state(), 'gameObjects'): # and open('objects.txt', 'a').write( str(friends[self._get_game_state().countfnyt]) + "\n") print "############### gameObjects #################" countnyt = 0 countmyg = 0 countpickup = 0 objssvl = [] if hasattr(self._get_game_state(), 'alldigged'): alldigged = 1 else: alldigged = 0 for object in self._get_game_state().gameObjects: if self._get_game_state().countnyt + countnyt < 148: if hasattr(object, 'type'): tf = 0 if object.type == 'newYearTree': tf = 1 usrs = len(object.users) #object.users = usrs #open('newyeartree.txt', 'a').write(str(obj2dict(object))+"\n") if tf == 1 and not hasattr(self._get_game_state(), 'nytend'): print(u"Ёлка !!!").encode('cp866') #open('gameObjects.txt', 'a').write(str(obj2dict(object))+"\n") #open('newyeartree.txt', 'a').write(object.item + " UsersGift:" + str(len(object.users)) + "\n") tf = 1 f = 0 #Ёлки разной ёмкости. указано не точно. if object.item == u'@B_SPRUCE_SMOLL' and len( object.users) < 3: f = 1 if object.item == u'@B_SPRUCE_MIDDLE' and len( object.users) < 6: f = 1 if object.item == u'@B_SPRUCE_BIG' and len( object.users) < 15: f = 1 #if object.item == u'@B_BASKETS_EASTER_1' and len(object.users) < 15: f = 1 #if object.item == u'@B_BASKETS_EASTER_2' and len(object.users) < 7: f = 1 #if object.item == u'@B_BASKETS_EASTER_3' and len(object.users) < 3: f = 1 for user in object.users: if user.id == myid: countmyg += 1 #print "MyGift" f = 0 break #if not check_no_my_gift(object.users): f = 1 if self._get_game_state( ).countnyt + countnyt > 151 or hasattr( self._get_game_state(), 'nyna'): self._get_game_state().nytend = 1 print "################## END ####################" f = 0 #0 - Пряники не ложим, 1 - пряники ложим if f == 1: # Ложим пряник #open('newyeartree.txt', 'a').write(str(obj2dict(object)) + "\n") self._get_events_sender().send_game_events([{ "itemId": "CAKE_PACK_FREE1", "action": "remoteNewYear", "type": "item", "objId": object.id }]) countnyt += 1 pass else: print "NO" # Вскрываем сундук if tf == 0 and object.type == 'pickup': open('sunduki.txt', 'a').write(str(obj2dict(object)) + "\n") self._get_events_sender().send_game_events([{ "action": "pick", "type": "item", "objId": object.id }]) countpickup += 1 tf = 2 # Добавляем в список объекты для копания клада if tf == 0 and alldigged == 0: for objtype in objtypes: if object.type == objtype: if object.item == '@DS_SYMBOL_E' or object.item == '@D_BALLOONS' or object.item == '@D_SAKURASMALL': print object.item, object.id objssvl.append(object) break if tf == 0: open('objects.txt', 'a').write(str(obj2dict(object)) + "\n") if hasattr(self._get_game_state(), 'playersInfo'): open('objects.txt', 'a').write('-------------------------------------' + "\n") #open('objects.txt', 'a').write(str(obj2dict(self._get_game_state().playersInfo))+"\n") open('users.txt', 'a').write( str(obj2dict(self._get_game_state().playersInfo)) + "\n") open('objects.txt', 'a').write('-------------------------------------' + "\n") countlop = 0 if len(objssvl) > 0: for i in range(300): objdig = random_number.choice(objssvl) self._get_events_sender().send_game_events([{ "objId": objdig.id, "x": objdig.x, "action": "remoteDig", "y": objdig.y, "type": "item" }]) countlop += 1 print(u"Использовал: " + str(countlop) + u" лопат").encode('cp866') elif alldigged == 1: print(u'Всё уже выкопано!').encode('cp866') else: print(u'Нечего копать!').encode('cp866') print(u"Вскрыли сундуков: " + str(countpickup)).encode('cp866') if hasattr(self._get_game_state(), 'alldigged'): del self._get_game_state().alldigged del self._get_game_state().gameObjects self._get_game_state().countnyt += countnyt print(u"поЛожил пряник(ов): " + str(self._get_game_state().sendNewYearGift) + ":" + str(self._get_game_state().countnyt) + "/" + str(countnyt) + " dub: " + str(countmyg)).encode('cp866') self._get_game_state().shovel = 0
def perform_action(self): if self.if_location_pirate(): return collections = self.mega().collections_sell_options() # Словарь названий коллекций name = { "C_1": u"Звёздная", "C_2": u"Луксорская", "C_3": u"Байкерская", "C_4": u"Знаков", "C_5": u"Ручная", "C_6": u"Обувная", "C_7": u"Страшная", "C_8": u"Строительная", "C_9": u"Столовая", "C_10": u"Редкая", "C_11": u"Автомобильная", "C_12": u"Туристическая", "C_13": u"Домашняя", "C_14": u"Игрушек", "C_15": u"Ёлочная", "C_16": u"Кролика", "C_17": u"Цветов", "C_18": u"Деда Мороза", "C_19": u"Анти-зомби", "C_20": u"Брендов", "C_21": u"Весенняя", "C_22": u"Тинейджерская", "C_23": u"Компа", "C_24": u"Морская", "C_25": u"Пляжная", "C_26": u"Майя", "C_27": u"Секретная", "C_28": u"Гипер", "C_29": u"Хэллоуин", "C_30": u"Президентская", "C_31": u"Зимняя", "C_32": u"Подземельная", "C_33": u"Любовная", "C_34": u"Адская", "C_35": u"Райская", "C_36": u"Японская", "C_37": u"Школьная", "C_38": u"Пиратская", "C_39": u"Рыбака", "C_40": u"Военная", "C_41": u"Футбольная", "C_42": u"Изумрудная", "C_43": u"Песочная", "C_44": u"Котят", "C_45": u"Щенков", "C_46": u"Тропическая", "C_47": u"Плохая", "C_48": u"Палача", "C_49": u"Фобий", "C_50": u"Вкусная", "C_51": u"Временная" } # Получаем количество на складе cl_items = obj2dict(self._get_game_state().get_state().collectionItems) for collection in collections: # Создаём item всех элементов element_1 = collection + "_1" element_2 = collection + "_2" element_3 = collection + "_3" element_4 = collection + "_4" element_5 = collection + "_5" # Проверка на наличие собранной коллекции if (element_1 in cl_items) and (element_2 in cl_items) and ( element_3 in cl_items) and (element_4 in cl_items) and (element_5 in cl_items): # И вычисляем сколько обменять count = min(cl_items[element_1], cl_items[element_2], cl_items[element_3], cl_items[element_4], cl_items[element_5]) - collections[collection] if count > 0: event = [{ "type": "item", "count": count, "itemId": collection, "action": "collect" }] self._get_events_sender().send_game_events(event) logger.info(u"Обменяли %d коллекций '%s' " % (count, name[collection])) self._get_game_state().remove_from_storage( '@' + element_1, cl_items[element_1] - count) self._get_game_state().remove_from_storage( '@' + element_2, cl_items[element_2] - count) self._get_game_state().remove_from_storage( '@' + element_3, cl_items[element_3] - count) self._get_game_state().remove_from_storage( '@' + element_4, cl_items[element_4] - count) self._get_game_state().remove_from_storage( '@' + element_5, cl_items[element_5] - count) cl_items[element_1] -= count cl_items[element_2] -= count cl_items[element_3] -= count cl_items[element_4] -= count cl_items[element_5] -= count self._get_game_state().get_state().collectionItems = dict2obj(cl_items)
"gainStarted": False }, { u'startCounter': 12L, u'target': {u'id': TARGET_ID}, u'item': u'@SC_WOOD_GRAVE2', u'jobEndTime': JOB_END_TIME, u'materials': [], u'doneCounter': 12L, u'y': 70L, u'x': 60L, u'type': u'woodGraveDouble', u'id': GRAVE_ID } ]}) game_location = GameLocation(Test.game_item_reader, location) wood_grave = game_location.get_object_by_id(GRAVE_ID) event_to_handle = dict2obj({u'action': u'stop', u'objId': GRAVE_ID, u'targetId': TARGET_ID, u'type': u'gainMaterial'}) # exercise GainMaterialEventHandler(Test.game_item_reader, game_location, Mock()).handle(event_to_handle) # verify self.assertEqual([obj2dict(wood_grave), { 'item': u'@SC_PICKUP_BOX_WOOD6', 'id': TARGET_ID, 'type': u'pickup'}], obj2dict(location.gameObjects))