Ejemplo n.º 1
0
    def testHandleGameResultEvent(self):
        # setup
        BUILDING_ID = 278L
        logging.basicConfig(level=logging.INFO)
        event_to_handle = dict2obj({u'action': u'play',
                                    u'extraId': u'B_EMERALD_ROULETTE',
                                    u'nextPlayDate': u'43250684',
                                    u'objId': BUILDING_ID,
                                    u'result': {u'pos': 5L},
                                    u'type': u'game'}
                                   )
        building_dict = {
                             u'level': 2L,
                             u'nextPlayTimes': {u'B_EMERALD_ROULETTE':
                                                u'40061197'},
                             u'item': u'@B_FLAG_EMERALD',
                             u'y': 99L,
                             u'x': 62L,
                             u'type': u'building',
                             u'id': BUILDING_ID
                        }
        game_location = GameLocation(Test.game_item_reader,
                                     dict2obj({"gameObjects":
                                               [building_dict]}))
        building = game_location.get_object_by_id(BUILDING_ID)

        # exercise
        result_handler = GameResultHandler(Test.game_item_reader,
                                           game_location)
        result_handler.handle(event_to_handle)

        # verify
        expected = event_to_handle.nextPlayDate
        actual = building.nextPlayTimes.__dict__[event_to_handle.extraId]
        self.assertEqual(expected, actual)
Ejemplo n.º 2
0
    def perform_action(self):

        max_harv_time = 0
        for l in self._get_game_state().get_state().buffs.list:
            if 'BUFF_FIX_COOK' in l.item:      #BUFF_FIX_COOK_1
                exp_time = float(l.expire.endDate)
                if max_harv_time < exp_time :
                    max_harv_time = exp_time

        time_harvest = (max_harv_time-self._get_timer()._get_current_client_time())/1000.0
        time_harvest=int(time_harvest)
        if time_harvest<0: time_harvest=0
        s=time_harvest-int((int(time_harvest/60.0)-(int(int(time_harvest/60.0)/60.0)*60))*60)-int((int(int(time_harvest/60.0)/60.0))*60*60)
        m=int(time_harvest/60.0)-(int(int(time_harvest/60.0)/60.0)*60)
        h=int(int(time_harvest/60.0)/60.0)
        if time_harvest<>0: logger.info(u'Осталось минутки-на-день: %d:%d:%d' % (h,m,s))

        is_there_harvest_buff = False
        buff_list = self._get_game_state().get_state().buffs.list
        for buff in buff_list:
            if buff.item == "@BUFF_FIX_COOK_1":
                time_exp = buff.expire.endDate
                is_there_harvest_buff = True
        if is_there_harvest_buff == False or self._get_timer().has_elapsed(time_exp) or time_harvest<30:
            if self._get_game_state().has_in_storage("@BS_BUFF_FIX_COOK_1", 1):
                event = {"x":20,"type":"item","y":7,"action":"useStorageItem","itemId":"BS_BUFF_FIX_COOK_1"}
                self._get_events_sender().send_game_events([event])
                logger.info(u"Применяю минутки-на-день на 24 часа")
                buff_list.append(dict2obj({"item":"@BUFF_FIX_COOK_1", "expire": dict2obj({"type":"time", "endDate": str(int(self._get_timer()._get_current_client_time())+86400000)})}))
                self._get_game_state().remove_from_storage("@BUFF_FIX_COOK_1", 1)
Ejemplo n.º 3
0
 def perform_action(self):
     is_there_digger_buff = False
     buff_list = self._get_game_state().get_state().buffs.list
     for buff in buff_list:
         if buff.item == "@BS_BUFF_FIX_DIGGER1":
             time_exp = buff.expire.endDate
             is_there_digger_buff = True
     if is_there_digger_buff == False or self._get_timer().has_elapsed(time_exp):
         if self._get_game_state().has_in_storage("@BS_BUFF_FIX_DIGGER1", 1):
             event = {"x":20,"type":"item","y":7,"action":"useStorageItem","itemId":"@BS_BUFF_FIX_DIGGER1"}
             self._get_events_sender().send_game_events([event])
             logger.info(u"Применяю супер-поиск на 1 день")
             buff_list.append(dict2obj({"item":"@BS_BUFF_FIX_DIGGER1", "expire": dict2obj({"type":"time", "endDate": str(int(self._get_timer()._get_current_client_time())+86400000)})}))
             self._get_game_state().remove_from_storage("@BS_BUFF_FIX_DIGGER1", 1)
Ejemplo n.º 4
0
 def updateJobDone(self, wood_grave):
     if hasattr(wood_grave, 'jobEndTime'):
         logger.info('jobEndTime:' + wood_grave.jobEndTime +
                     ', current time:' +
                     str(self._get_timer()._get_current_client_time()))
         if (self._get_timer().has_elapsed(wood_grave.jobEndTime)):
             if hasattr(wood_grave, 'target'):
                 target_id = wood_grave.target.id
                 target = self.get_game_loc().get_object_by_id(target_id)
                 target.materialCount -= 1
                 target_item = self.__item_reader.get(target.item)
                 logger.info("Материал добыт")
                 wood_grave.materials.append(target_item.material)
                 if target.materialCount == 0:
                     logger.info("Ресурсы исчерпаны!")
                     box_item = self.__item_reader.get(target_item.box)
                     new_obj = dict2obj({
                         'item': '@' + box_item.id,
                         'type': GamePickup.type,
                         'id': target_id
                     })
                     self.get_game_loc().remove_object_by_id(target_id)
                     self.get_game_loc().append_object(new_obj)
                     logger.info(u"'%s' превращён в '%s'" %
                                 (target_item.name, box_item.name))
                     # add free brains
                     delattr(wood_grave, 'target')
             delattr(wood_grave, 'jobEndTime')
     else:
         logger.info("There's no jobEndTime")
Ejemplo n.º 5
0
 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)
Ejemplo n.º 6
0
 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)
Ejemplo n.º 7
0
 def testHandleStopGainMaterialConvertsTarget(self):
     # setup
     TARGET_ID = -190
     GRAVE_ID = 307L
     JOB_END_TIME = u'2458640'
     location = dict2obj(
             {"gameObjects": [
                 {
                     "type":"woodTree",
                     "item":"@SC_OAK5",
                     "id": TARGET_ID,
                     "x":43,
                     "y":19,
                     "materialCount":1,
                     "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
                 }
            ]})
Ejemplo n.º 8
0
 def handle(self, event_to_handle):
     try:
         gameObject = self.__game_location.get_object_by_id(
             event_to_handle.objId
         )
         self.updateJobDone(gameObject)
         if event_to_handle.action == 'start':
                 ms1=event_to_handle.jobEndTime-((event_to_handle.jobEndTime/1000)*1000)
                 s1=(event_to_handle.jobEndTime/1000)-(((event_to_handle.jobEndTime/1000)/60)*60)
                 m1=((event_to_handle.jobEndTime/1000)/60)-((((event_to_handle.jobEndTime/1000)/60)/60)*60)
                 h1=((event_to_handle.jobEndTime/1000)/60)/60
                 ms2=self._get_timer()._get_current_client_time()-((self._get_timer()._get_current_client_time()/1000)*1000)
                 s2=(self._get_timer()._get_current_client_time()/1000)-(((self._get_timer()._get_current_client_time()/1000)/60)*60)
                 m2=((self._get_timer()._get_current_client_time()/1000)/60)-((((self._get_timer()._get_current_client_time()/1000)/60)/60)*60)
                 h2=((self._get_timer()._get_current_client_time()/1000)/60)/60
                 logger.info("Начата работа" + '. jobEndTime:'
                             + str(h1)+':'+str(m1)+':'+str(s1)+'.'+str(ms1) +
                             ', current time:' +
                             str(h2)+':'+str(m2)+':'+str(s2)+'.'+str(ms2))
                 gameObject.target = dict2obj({'id': event_to_handle.targetId})
                 gameObject.jobStartTime = event_to_handle.jobStartTime
                 gameObject.jobEndTime = event_to_handle.jobEndTime
         elif event_to_handle.action == 'stop':
             logger.info("Окончена работа")
     except:
         pass
Ejemplo n.º 9
0
    def new_rulets(self, resource):
        id = resource.id
        new_item = self._get_item_reader().get(resource.item).success.inside
        new_reader = self._get_item_reader().get(new_item)
        print u'Переделываем %s id %s в рулетку %s' % (resource.item, id,
                                                       new_item)
        new_obj = {
            u'rotate': 0L,
            u'level': 0L,
            u'nextPlayTimes': {
                new_reader.games[0].id: u"-90000"
            },
            u'playsCounts': {},
            u'item': new_item,
            u'y': resource.y,
            u'x': resource.x,
            u'type': new_reader.type,
            u'id': id
        }
        # print 'new_obj', new_obj
        # удаляем старый
        self._get_game_location().remove_object_by_id(id)

        self._get_game_location().get_game_objects().append(dict2obj(new_obj))
        time.sleep(0.2)
        self._get_game().handle_all_events()
Ejemplo n.º 10
0
 def updateJobDone(self, wood_grave):
     if hasattr(wood_grave, 'jobEndTime'):
         logger.info('jobEndTime:' + wood_grave.jobEndTime +
                     ', current time:' +
                     str(self._get_timer()._get_current_client_time()))
         if (self._get_timer().has_elapsed(wood_grave.jobEndTime)):
             if hasattr(wood_grave, 'target'):
                 target_id = wood_grave.target.id
                 target = self.get_game_loc().get_object_by_id(target_id)
                 target.materialCount -= 1
                 target_item = self.__item_reader.get(target.item)
                 logger.info("Материал добыт")
                 wood_grave.materials.append(target_item.material)
                 if target.materialCount == 0:
                     logger.info("Ресурсы исчерпаны!")
                     box_item = self.__item_reader.get(target_item.box)
                     new_obj = dict2obj({'item': '@' + box_item.id,
                                         'type': GamePickup.type,
                                         'id': target_id})
                     self.get_game_loc().remove_object_by_id(target_id)
                     self.get_game_loc().append_object(new_obj)
                     logger.info(u"'%s' превращён в '%s'" %
                                 (target_item.name, box_item.name))
                     # add free brains
                     delattr(wood_grave, 'target')
             delattr(wood_grave, 'jobEndTime')
     else:
         logger.info("There's no jobEndTime")
Ejemplo n.º 11
0
 def updateJobDone(self, wood_grave):
     if hasattr(wood_grave, 'jobEndTime'):
         logger.info("Время окончания работы:")
         nextplay = int(wood_grave.jobEndTime)
         x1 = int(wood_grave.jobEndTime)
         ms = nextplay - ((nextplay / 1000) * 1000)
         s = (nextplay / 1000) - (((nextplay / 1000) / 60) * 60)
         m = ((nextplay / 1000) / 60) - (((
             (nextplay / 1000) / 60) / 60) * 60)
         h = ((nextplay / 1000) / 60) / 60
         logger.info(str(h) + ':' + str(m) + ':' + str(s) + '.' + str(ms))
         logger.info("Текущее время:")
         nextplay = int(self._get_timer()._get_current_client_time())
         ms1 = nextplay - ((nextplay / 1000) * 1000)
         s1 = (nextplay / 1000) - (((nextplay / 1000) / 60) * 60)
         m1 = ((nextplay / 1000) / 60) - (((
             (nextplay / 1000) / 60) / 60) * 60)
         h1 = ((nextplay / 1000) / 60) / 60
         logger.info(
             str(h1) + ':' + str(m1) + ':' + str(s1) + '.' + str(ms1))
         logger.info("Время на работу:")
         nextplay1 = (h * 60 * 60 * 1000) + (m * 60 * 1000) + (s *
                                                               1000) + ms
         nextplay2 = (h1 * 60 * 60 * 1000) + (m1 * 60 * 1000) + (s1 *
                                                                 1000) + ms1
         nextplay = nextplay2 - nextplay1
         ms = nextplay - ((nextplay / 1000) * 1000)
         s = (nextplay / 1000) - (((nextplay / 1000) / 60) * 60)
         m = ((nextplay / 1000) / 60) - (((
             (nextplay / 1000) / 60) / 60) * 60)
         h = ((nextplay / 1000) / 60) / 60
         logger.info(str(h) + ':' + str(m) + ':' + str(s) + '.' + str(ms))
         if (self._get_timer().has_elapsed(wood_grave.jobEndTime)):
             if hasattr(wood_grave, 'target'):
                 target_id = wood_grave.target.id
                 target = self.get_game_loc().get_object_by_id(target_id)
                 target.materialCount -= 1
                 target_item = self.__item_reader.get(target.item)
                 logger.info("Материал добыт")
                 wood_grave.materials.append(target_item.material)
                 if target.materialCount == 0:
                     logger.info("Ресурсы исчерпаны!")
                     box_item = self.__item_reader.get(target_item.box)
                     new_obj = dict2obj({
                         'item': '@' + box_item.id,
                         'type': GamePickup.type,
                         'id': target_id
                     })
                     self.get_game_loc().remove_object_by_id(target_id)
                     self.get_game_loc().append_object(new_obj)
                     logger.info(u"'%s' превращён в '%s'" %
                                 (target_item.name, box_item.name))
                     # add free brains
                     delattr(wood_grave, 'target')
             delattr(wood_grave, 'jobEndTime')
     else:
         logger.info("Ещё не конец работы")
Ejemplo n.º 12
0
    def _pick_harvest(self, harvestItem, pick_name):
        if self._get_timer().has_elapsed(harvestItem.jobFinishTime):
            item = self._get_item_reader().get(harvestItem.item)

            if item.name in pick_name.keys(): pick_name[item.name] += 1
            else: pick_name[item.name] = 1
            pick_event = GamePickItem(objId=harvestItem.id)

            # Добавляем в game_state информацию о собранном предмете
            item_count = 0
            if harvestItem.type == GameFruitTree.type:
                item_id = self._get_item_reader().get(
                    harvestItem.item).storageItem

            else:
                item_id = harvestItem.item
            #item_id = '@S'+item_id[2:]
            #item_id= self._get_game_state().seed2storage_plant(item_id)

            #print item_id
            self._get_game_state().add_from_storage(item_id, 1)

            # Если собрали золиан - удалить обьект т.к. грядки больше нет
            if harvestItem.item in u'@P_43':
                self._get_game_location().remove_object_by_id(harvestItem.id)

            if harvestItem.type == GamePlant.type:
                # convert plant to slag
                harvestItem.type = GameSlag.type
                harvestItem.item = GameSlag(0L, 0L, 0L).item
            elif harvestItem.type == GameFruitTree.type:
                harvestItem.fruitingCount -= 1
                #self._get_timer().has_elapsed(harvestItem.jobFinishTime)

                if harvestItem.fruitingCount == 0:

                    # remove fruit tree
                    self._get_game_location().remove_object_by_id(
                        harvestItem.id)
                    pickup_box = dict2obj({
                        'item':
                        '@FT_PICKUP_BOX_' + harvestItem.item[4:],
                        'type':
                        "pickup",
                        'id':
                        harvestItem.id,
                        u'y':
                        harvestItem.y,
                        u'x':
                        harvestItem.x
                    })
                    self._get_game_location().append_object(pickup_box)
                    #print u'Сундук'
                    # harvestItem.type = GamePickItem.type
                    # TODO convert to pickup box
                    # convert tree to pick item
            return pick_event
Ejemplo n.º 13
0
 def testHandleGainMaterialEventAddsJobTime(self):
     # setup
     JOB_END_TIME = u'2458640'
     event_to_handle = dict2obj({u'action': u'start',
                                 u'doneCounter': 181L,
                                 u'jobEndTime': JOB_END_TIME,
                                 u'jobStartTime': u'1558640',
                                 u'objId': 267L,
                                 u'startCounter': 182L,
                                 u'targetId': -190L,
                                 u'type': u'gainMaterial'})
Ejemplo n.º 14
0
    def perform_action(self):
        buff_list = self._get_game_state().get_state().buffs.list
        time_digger = 0
        max_dig_time = 0

        for l in buff_list:
            if 'BUFF_FIX_DIGGER' in l.item:
                exp_time = float(l.expire.endDate)
                if max_dig_time < exp_time :
                    max_dig_time = exp_time

                    time_digger = (max_dig_time-self._get_timer()._get_current_client_time())/1000.0
        time_digger=int(time_digger)
        if time_digger<0: time_digger=0
        s=time_digger-int((int(time_digger/60.0)-(int(int(time_digger/60.0)/60.0)*60))*60)-int((int(int(time_digger/60.0)/60.0))*60*60)
        m=int(time_digger/60.0)-(int(int(time_digger/60.0)/60.0)*60)
        h=int(int(time_digger/60.0)/60.0)
        if time_digger>0: logger.info(u'Осталось супер-поиск: %d:%d:%d' % (h,m,s))
        else:
            if self._get_game_state().has_in_storage("@BS_BUFF_FIX_DIGGER3", 1):
                event = {"x":20,"type":"item","y":7,"action":"useStorageItem","itemId":"BS_BUFF_FIX_DIGGER3"}
                self._get_events_sender().send_game_events([event])
                logger.info(u"Применяю супер-поиск на 3 дня")
                buff_list.append(dict2obj({"item":"@BS_BUFF_FIX_DIGGER3", "expire": dict2obj({"type":"time", "endDate": str(int(self._get_timer()._get_current_client_time())+86400000*3)})}))
                self._get_game_state().remove_from_storage("@BS_BUFF_FIX_DIGGER3", 1)

            else:
               if self._get_game_state().has_in_storage("@BS_BUFF_FIX_DIGGER2", 1):
                   event = {"x":20,"type":"item","y":7,"action":"useStorageItem","itemId":"BS_BUFF_FIX_DIGGER2"}
                   self._get_events_sender().send_game_events([event])
                   logger.info(u"Применяю супер-поиск на 2 дня")
                   buff_list.append(dict2obj({"item":"@BS_BUFF_FIX_DIGGER2", "expire": dict2obj({"type":"time", "endDate": str(int(self._get_timer()._get_current_client_time())+86400000*2)})}))
                   self._get_game_state().remove_from_storage("@BS_BUFF_FIX_DIGGER2", 1)

               else:
                  if self._get_game_state().has_in_storage("@BS_BUFF_FIX_DIGGER1", 1):
                      event = {"x":20,"type":"item","y":7,"action":"useStorageItem","itemId":"BS_BUFF_FIX_DIGGER1"}
                      self._get_events_sender().send_game_events([event])
                      logger.info(u"Применяю супер-поиск на 1 день")
                      buff_list.append(dict2obj({"item":"@BS_BUFF_FIX_DIGGER1", "expire": dict2obj({"type":"time", "endDate": str(int(self._get_timer()._get_current_client_time())+86400000)})}))
                      self._get_game_state().remove_from_storage("@BS_BUFF_FIX_DIGGER1", 1)
Ejemplo n.º 15
0
    def _pick_harvest(self, harvestItem,pick_name):
        if self._get_timer().has_elapsed(harvestItem.jobFinishTime):
            # print u'время собирать', self._get_timer().has_elapsed(harvestItem.jobFinishTime), harvestItem.jobFinishTime
            item = self._get_item_reader().get(harvestItem.item)
            if item.name in pick_name.keys(): pick_name[item.name] += 1
            else: pick_name[item.name] = 1
            pick_event = GamePickItem(objId = harvestItem.id)

            # Добавляем в game_state информацию о собранном предмете
            if harvestItem.type == GameFruitTree.type:
                item_id = self._get_item_reader().get(harvestItem.item).storageItem
                temp = item_id
            else:
                item_id = harvestItem.item
                temp = item_id
                item_id = self._get_item_reader().get(item_id).storageItem
            # print temp, item_id, self._get_game_state().count_in_storage(item_id)
            # item_id = self.seed2storage_plant(item_id)
            # print u'Добавляем', item_id, u'на склад'
            self._get_game_state().add_from_storage(item_id,1)

            harvestItem.fertilized = False
            # Если собрали золиан - удалить обьект т.к. грядки больше нет
            if harvestItem.item in u'@P_43':
                self._get_game_location().remove_object_by_id(harvestItem.id)

            if harvestItem.type == GamePlant.type:
                # convert plant to slag
                harvestItem.type = GameSlag.type
                harvestItem.item = GameSlag(0L, 0L, 0L).item
            elif harvestItem.type == GameFruitTree.type:
                harvestItem.fruitingCount -= 1
                item = self._get_item_reader().get(harvestItem.item)
                harvestItem.jobFinishTime = self._get_timer()._get_current_client_time() + (item.fruitingTime+5)*1000
                if harvestItem.fruitingCount == 0:
                    pickup_box = dict2obj({'item': item.box,'type': "pickup",'id': harvestItem.id, u'y': harvestItem.y, u'x': harvestItem.x})
                    """
                    name = harvestItem.item[4:]
                    if name == 'MANDARINE': name = 'MANDARIN'
                    if name == 'CHERRY_WHITE': # FT_CHERRY_WHITE
                        name = '@D_MAIL_BOX_CHERRY'
                    else:
                        name = '@FT_PICKUP_BOX_' + name
                    pickup_box = dict2obj({'item': name,'type': "pickup",'id': harvestItem.id, u'y': harvestItem.y, u'x': harvestItem.x})
                    """
                    # remove fruit tree
                    self._get_game_location().remove_object_by_id(harvestItem.id)
                    self._get_game_location().append_object(pickup_box)
                    #print 'pickup_box', obj2dict(pickup_box)
                    
                    #FIND:  @FT_PICKUP_BOX_CHERRY   id =  23314
                    #{u'rotate': 0L, u'item': u'@FT_PICKUP_BOX_CHERRY', u'y': 4L, u'x': 116L, u'type': u'pickup', u'id': 23314L}
            return pick_event
Ejemplo n.º 16
0
 def handle(self, event_to_handle):
     gameObject = self.__game_location.get_object_by_id(
         event_to_handle.objId)
     self.updateJobDone(gameObject)
     if event_to_handle.action == 'start':
         logger.info("Начата работа" + '. jobEndTime:' +
                     str(event_to_handle.jobEndTime) + ', current time:' +
                     str(self._get_timer()._get_current_client_time()))
         gameObject.target = dict2obj({'id': event_to_handle.targetId})
         gameObject.jobStartTime = event_to_handle.jobStartTime
         gameObject.jobEndTime = event_to_handle.jobEndTime
     elif event_to_handle.action == 'stop':
         logger.info("Окончена работа")
Ejemplo n.º 17
0
 def handle(self, event_to_handle):
     gameObject = self.__game_location.get_object_by_id(
         event_to_handle.objId)
     if not gameObject: return
     self.updateJobDone(gameObject)
     if event_to_handle.action == 'start':
         gameObject.target = dict2obj({'id': event_to_handle.targetId})
         gameObject.jobStartTime = event_to_handle.jobStartTime
         gameObject.jobEndTime = event_to_handle.jobEndTime
     elif event_to_handle.action == 'stop':
         delattr(gameObject, 'target')
         delattr(gameObject, 'jobStartTime')
         delattr(gameObject, 'jobEndTime')
Ejemplo n.º 18
0
    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)
Ejemplo n.º 19
0
 def updateJobDone(self, wood_grave):
     if hasattr(wood_grave, 'jobEndTime'):
         logger.info("Время окончания работы:")
         nextplay=int(wood_grave.jobEndTime)
         x1=int(wood_grave.jobEndTime)
         ms=nextplay-((nextplay/1000)*1000)
         s=(nextplay/1000)-(((nextplay/1000)/60)*60)
         m=((nextplay/1000)/60)-((((nextplay/1000)/60)/60)*60)
         h=((nextplay/1000)/60)/60
         logger.info(str(h)+':'+str(m)+':'+str(s)+'.'+str(ms))
         logger.info("Текущее время:")
         nextplay=int(self._get_timer()._get_current_client_time())
         ms1=nextplay-((nextplay/1000)*1000)
         s1=(nextplay/1000)-(((nextplay/1000)/60)*60)
         m1=((nextplay/1000)/60)-((((nextplay/1000)/60)/60)*60)
         h1=((nextplay/1000)/60)/60
         logger.info(str(h1)+':'+str(m1)+':'+str(s1)+'.'+str(ms1))
         logger.info("Время на работу:")
         nextplay1=(h*60*60*1000)+(m*60*1000)+(s*1000)+ms
         nextplay2=(h1*60*60*1000)+(m1*60*1000)+(s1*1000)+ms1
         nextplay=nextplay2-nextplay1
         ms=nextplay-((nextplay/1000)*1000)
         s=(nextplay/1000)-(((nextplay/1000)/60)*60)
         m=((nextplay/1000)/60)-((((nextplay/1000)/60)/60)*60)
         h=((nextplay/1000)/60)/60
         logger.info(str(h)+':'+str(m)+':'+str(s)+'.'+str(ms))
         if (self._get_timer().has_elapsed(wood_grave.jobEndTime)):
             if hasattr(wood_grave, 'target'):
                 target_id = wood_grave.target.id
                 target = self.get_game_loc().get_object_by_id(target_id)
                 target.materialCount -= 1
                 target_item = self.__item_reader.get(target.item)
                 logger.info("Материал добыт")
                 wood_grave.materials.append(target_item.material)
                 if target.materialCount == 0:
                     logger.info("Ресурсы исчерпаны!")
                     box_item = self.__item_reader.get(target_item.box)
                     new_obj = dict2obj({'item': '@' + box_item.id,
                                         'type': GamePickup.type,
                                         'id': target_id})
                     self.get_game_loc().remove_object_by_id(target_id)
                     self.get_game_loc().append_object(new_obj)
                     logger.info(u"'%s' превращён в '%s'" %
                                 (target_item.name, box_item.name))
                     # add free brains
                     delattr(wood_grave, 'target')
             delattr(wood_grave, 'jobEndTime')
     else:
         logger.info("Ещё не конец работы")
Ejemplo n.º 20
0
 def handle(self, event_to_handle):
     gameObject = self.__game_location.get_object_by_id(
         event_to_handle.objId
     )
     self.updateJobDone(gameObject)
     if event_to_handle.action == 'start':
         logger.info("Начата работа" + '. jobEndTime:'
                     + str(event_to_handle.jobEndTime) +
                     ', current time:' +
                     str(self._get_timer()._get_current_client_time()))
         gameObject.target = dict2obj({'id': event_to_handle.targetId})
         gameObject.jobStartTime = event_to_handle.jobStartTime
         gameObject.jobEndTime = event_to_handle.jobEndTime
     elif event_to_handle.action == 'stop':
         logger.info("Окончена работа")
Ejemplo n.º 21
0
    def _pick_harvest(self, harvestItem,pick_name):
        if self._get_timer().has_elapsed(harvestItem.jobFinishTime):
            item = self._get_item_reader().get(harvestItem.item)
            
            if item.name in pick_name.keys(): pick_name[item.name]+=1
            else: pick_name[item.name]=1
            pick_event = GamePickItem(objId=harvestItem.id)

            # Добавляем в game_state информацию о собранном предмете
            item_count=0
            if harvestItem.type == GameFruitTree.type:
                item_id=self._get_item_reader().get(harvestItem.item).storageItem
                
            else: item_id=harvestItem.item
            #item_id = '@S'+item_id[2:]
            #item_id= self._get_game_state().seed2storage_plant(item_id)
            
            #print item_id
            self._get_game_state().add_from_storage(item_id,1)
            
            # Если собрали золиан - удалить обьект т.к. грядки больше нет
            if harvestItem.item in u'@P_43':
                self._get_game_location().remove_object_by_id(harvestItem.id)
                
            if harvestItem.type == GamePlant.type:
                # convert plant to slag
                harvestItem.type = GameSlag.type
                harvestItem.item = GameSlag(0L, 0L, 0L).item
            elif harvestItem.type == GameFruitTree.type:
                harvestItem.fruitingCount -= 1
                #self._get_timer().has_elapsed(harvestItem.jobFinishTime)
                
                if harvestItem.fruitingCount == 0:
                    
                    # remove fruit tree
                    self._get_game_location().remove_object_by_id(
                                                                harvestItem.id)
                    pickup_box = dict2obj({'item': '@FT_PICKUP_BOX_' + harvestItem.item[4:],'type': "pickup",'id': harvestItem.id, u'y': harvestItem.y, u'x': harvestItem.x})  
                    self._get_game_location().append_object(pickup_box)
                    #print u'Сундук'  
                    # harvestItem.type = GamePickItem.type
                    # TODO convert to pickup box
                    # convert tree to pick item
            return pick_event
Ejemplo n.º 22
0
 def updateJobDone(self, wood_grave):
     if not hasattr(wood_grave, 'jobEndTime'): return
     if not hasattr(wood_grave, 'target'): return
     target_id = wood_grave.target.id
     target = self.get_game_loc().get_object_by_id(target_id)
     target.materialCount -= 1
     target_item = self.__item_reader.get(target.item)
     wood_grave.materials.append(target_item.material)
     if target.materialCount == 0:
         box_item = self.__item_reader.get(target_item.box)
         new_obj = dict2obj({
             'item': '@' + box_item.id,
             'type': GamePickup.type,
             'id': target_id
         })
         self.get_game_loc().remove_object_by_id(target_id)
         self.get_game_loc().append_object(new_obj)
         print u' "%s" превращён в "%s"' % (target_item.name.upper(),
                                            box_item.name)
Ejemplo n.º 23
0
 def add_stone(self,
               sw_run):  # подключаем колодец если время кручения позволяет
     add = {}
     for stone in self.stone_well:
         if self._get_game_location().get_object_by_id(stone[u'id']):
             #print u'Этот колодец уже открыт', stone[u'id']
             continue
         else:
             if sw_run.get(stone[u'id']) == None or sw_run.get(
                     stone[u'id']) < time.time():
                 print u'Добавляем колодец', stone[u'id']
                 # self._get_game_state().get_state().gameObjects.append(dict2obj(stone))
                 self._get_game_location().get_game_objects().append(
                     dict2obj(stone))
                 add[stone[u'id']] = time.time() + 308
     if add != {}:
         sw_run.update(add)
         with open(self.patch + '\\sw_run.txt', 'w') as f:
             f.write(str(sw_run))
Ejemplo n.º 24
0
 def perform_action(self):
     is_there_travel_buff = False
     buff_list = self._get_game_state().get_state().buffs.list
     o_id = False
     for buff in buff_list:
         if buff.item == "@BUFF_TRAVEL_TICKET_TIME" or buff.item == "@BUFF_TRAVEL_TICKET_TIME2":
             time_exp = buff.expire.endDate
             is_there_travel_buff = True
         elif buff.item == "@BUFF_TRAVEL_TICKET_COUNT" or buff.item == "@BUFF_TRAVEL_TICKET_COUNT2":
             #time_exp = buff.expire.count
             time_exp = self._get_timer()._get_current_client_time() + 86400000
             is_there_travel_buff = True
     if is_there_travel_buff == False or self._get_timer().has_elapsed(time_exp):
         for item in self._get_game_state().get_state().gameObjects:
             if item.item == "@B_VAN_ICE_CREAM":
                 exchange = self._get_item_reader().get("B_VAN_ICE_CREAM").crafts
                 o_id = item.id
             elif  item.item == "@B_VAN_ICE_CREAM_CASH":
                 exchange = self._get_item_reader().get("@B_VAN_ICE_CREAM_CASH").crafts
                 o_id = item.id
         if o_id:
             craft = "1"
             exchange = self._get_item_reader().get("B_VAN_ICE_CREAM").crafts
             for one_item in exchange:
                 if one_item.id == craft:
                     sharp = one_item.materials[0].item
                     sharp_count = one_item.materials[0].count
                     books = one_item.materials[1].item
                     books_count = one_item.materials[1].count
             storage = self._get_game_state().get_state().storageItems
             for item in storage:
                 if item.item == sharp:
                     storage_sharp = item.count
                 elif item.item == books:
                     storage_books = item.count
             event = {"itemId":craft,"objId":o_id,"type":"item","action":"craft"}
             self._get_events_sender().send_game_events([event])
             logger.info(self._get_item_reader().get("@BUFF_TRAVEL_TICKET_TIME").name)
             buff_list.append(dict2obj({"item":"@BUFF_TRAVEL_TICKET_TIME", "expire": dict2obj({"type":"time", "time": str(int(self._get_timer()._get_current_client_time())+86400000*5)})}))
             self._get_game_state().remove_from_storage(sharp, sharp_count)
             self._get_game_state().remove_from_storage(books, books_count)
Ejemplo n.º 25
0
    def testGetTimeShouldReturnKeyAndTime(self):
        # setup
        expected_key = '678652045157661214'
        expected_time = 1353868293322
        request_string = ({"cmd": "TIME", "key": expected_key,
                         "redirect":
                         "http://95.163.80.23/zombievk",
                         "id": "45", "time": expected_time})
        request_string = (request_string)
        request_sender = Mock()
        request_sender.send = Mock(return_value=dict2obj(request_string))
        game_initializer = GameInitializer(Mock(),
                                           request_sender,
                                           Mock(),
                                           Mock(), Mock())

        # exercise
        actual_key, actual_time = game_initializer.get_time()
        # verify
        self.assertEqual(expected_time, actual_time)
        self.assertEqual(expected_key, actual_key)
Ejemplo n.º 26
0
    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)
Ejemplo n.º 27
0
    def testGetTimeShouldReturnKeyAndTime(self):
        # setup
        expected_key = '678652045157661214'
        expected_time = 1353868293322
        request_string = ({
            "cmd": "TIME",
            "key": expected_key,
            "redirect": "http://95.163.80.23/zombievk",
            "id": "45",
            "time": expected_time
        })
        request_string = (request_string)
        request_sender = Mock()
        request_sender.send = Mock(return_value=dict2obj(request_string))
        game_initializer = GameInitializer(Mock(), request_sender, Mock(),
                                           Mock(), Mock())

        # exercise
        actual_key, actual_time = game_initializer.get_time()
        # verify
        self.assertEqual(expected_time, actual_time)
        self.assertEqual(expected_key, actual_key)
Ejemplo n.º 28
0
    def testHandleGameResultEvent(self):
        # setup
        BUILDING_ID = 278L
        logging.basicConfig(level=logging.INFO)
        event_to_handle = dict2obj({
            u'action': u'play',
            u'extraId': u'B_EMERALD_ROULETTE',
            u'nextPlayDate': u'43250684',
            u'objId': BUILDING_ID,
            u'result': {
                u'pos': 5L
            },
            u'type': u'game'
        })
        building_dict = {
            u'level': 2L,
            u'nextPlayTimes': {
                u'B_EMERALD_ROULETTE': u'40061197'
            },
            u'item': u'@B_FLAG_EMERALD',
            u'y': 99L,
            u'x': 62L,
            u'type': u'building',
            u'id': BUILDING_ID
        }
        game_location = GameLocation(
            Test.game_item_reader, dict2obj({"gameObjects": [building_dict]}))
        building = game_location.get_object_by_id(BUILDING_ID)

        # exercise
        result_handler = GameResultHandler(Test.game_item_reader,
                                           game_location)
        result_handler.handle(event_to_handle)

        # verify
        expected = event_to_handle.nextPlayDate
        actual = building.nextPlayTimes.__dict__[event_to_handle.extraId]
        self.assertEqual(expected, actual)
Ejemplo n.º 29
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
Ejemplo n.º 30
0
    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"
Ejemplo n.º 31
0
    def perform_action(self):
        min_money = 0  # оставляем денег
        # Что где сажаем   u'FT_CHERRY', u'FT_APPLE' , u'FT_MANDARINE', "FT_EYE"
        plant_tree = {
            #u'main':u'FT_CHERRY',               # Домашний
            #u'isle_polar':u'GROUND',                # Домашний
            #u'main':u'CANDY_BOX2',                # Домашний
            #u'isle_03':u'GROUND',             # Любви
            #u'isle_02':u'FT_CHERRY',             # Майя
            #u'isle_x':u'GROUND',              # X
            #u'isle_faith':u'FT_EYE',          # Веры
            #u'isle_hope':u'GROUND',           # Надежды
            #u'isle_scary':u'GROUND',          # Страшный
            #u'isle_alpha':u'GROUND',          # Альфа
            u'isle_omega': u'GROUND',  # Омега
            #u'isle_sand':u'FT_CHERRY',           # Песочный
            #u'isle_polar':u'FT_CHERRY',          # Полярной ночи
            #u'isle_wild':u'GROUND',           # Дремучий
            #u'isle_mobile':u'FT_CHERRY',         # Мобильный
            #u'isle_ufo':u'FT_CHERRY',            # НЛО
            #u'isle_dream':u'GROUND',          # Мечты
            #u'isle_scarecrow':u'FT_CHERRY',      # Пик Админа
            #u'isle_elephant':u'FT_CHERRY',       # Ужасный
            #u'isle_emerald':u'GROUND',        # Город Призрак
            #u'isle_monster':u'FT_CHERRY',        # Чудовища
            #u'isle_halloween':u'FT_CHERRY',      # Лысая гора
            #
            ###############     Платные     ###############
            #
            #u'isle_01':u'FT_CHERRY',             # Секретный
            #u'isle_small':u'FT_CHERRY',          # Маленькой ёлочки
            #u'isle_star':u'FT_CHERRY',           # Звездный
            #u'isle_large':u'FT_CHERRY',          # Большой ёлки
            #u'isle_moon':u'FT_CHERRY',           # Лунный
            #u'isle_giant':u'FT_CHERRY',          # Гигантов
            #u'isle_xxl':u'FT_CHERRY',            # Огромной ёлки
            #u'isle_desert':u'FT_CHERRY'          # Необитаемый
        }

        current_loc = self._get_game_state().get_location_id()
        if not current_loc in plant_tree:
            logger.info(u"Пропускаем " + current_loc)
            return 1
        need = plant_tree[current_loc]

        next_id = max([
            _i.maxGameObjectId
            for _i in self._get_game_state().get_state().locationInfos
        ]) + 1

        need = self._get_item_reader().get(need)
        space_crd = self.space(current_loc, need)
        build_cost = self._get_item_reader().get(need.id).buyCoins

        num = 0
        if space_crd:
            for k in space_crd:
                if len(k) == 5:
                    x = int(k[:3])
                    y = int(k[3:])
                elif len(k) == 4:
                    x = int(k[:2])
                    y = int(k[2:])
                elif len(k) == 2:
                    x = int(k[:1])
                    y = int(k[1:])
                else:
                    if k[0] == '8' or k[0] == '9':
                        x = int(k[:1])
                        y = int(k[1:])
                    else:
                        x = int(k[:2])
                        y = int(k[2:])

                if self._get_game_state().get_state().gameMoney > min_money:
                    num += 1
                    buy = {
                        "x": x,
                        "y": y,
                        "action": "buy",
                        "itemId": need.id,
                        "type": "item",
                        "objId": next_id
                    }
                    self._get_events_sender().send_game_events([buy])
                    self._get_game_state().get_state().gameMoney -= build_cost
                    logger.info(u'' + str(num) + u" Сажаем " + need.id +
                                u" на X: " + str(x) + u", Y: " + str(y))
                    self._get_game_state().get_state().gameObjects.append(
                        dict2obj({
                            u'rotate': u'0L',
                            u'fruitingCount': u'25L',
                            u'fertilized': False,
                            u'item': u'@' + need.id,
                            u'jobFinishTime': u'79200000',
                            u'jobStartTime': u'0',
                            u'y': str(y),
                            u'x': str(x),
                            u'type': u'fruitTree',
                            u'id': next_id
                        }))
                    next_id += 1
Ejemplo n.º 32
0
    def handle(self, event_to_handle):
        pirate_locs_id = [
            'exploration_isle1_random', 'exploration_isle2_random',
            'exploration_isle3_random', 'exploration_snow1',
            'exploration_isle1_1', 'exploration_isle4_random',
            'exploration_independent_asteroid_random'
        ]
        _loc = self.__game_state_.get_location_id()  # текущая локация
        if event_to_handle is None:
            logger.critical("OMG! No such object")
            return
        else:
            tmp = {}
            for pickup in event_to_handle.pickups:
                item_type_msg = {
                    'coins': lambda pickup: u'денег',
                    'xp': lambda pickup: u'опыта',
                    'collection': lambda pickup: u'предмет(ов) коллекции ',
                    'storageItem': lambda pickup: u'предмет(ов) ',
                    'shovel': lambda pickup: u'лопат',
                    'scrapItem': lambda pickup: u'шт. металлолома'
                }.get(pickup.type, lambda pickup: pickup.type)(pickup)
                if (pickup.type == 'collection') or (pickup.type
                                                     == 'storageItem'):
                    item_type_msg = ('%s%s' %
                                     (item_type_msg,
                                      self.__item_reader.get(pickup.id).name))
                if item_type_msg in tmp.keys():
                    tmp[item_type_msg] += pickup.count
                else:
                    tmp[item_type_msg] = pickup.count
                # Добавление в game_state
                if hasattr(pickup, 'id'):
                    if (_loc in pirate_locs_id) and (pickup.id == 'CHOP_MACHETE' or\
                            pickup.id == 'CHOP_AXE' or pickup.id == 'CHOP_HAMMER'):
                        self.__game_state_.add_pirate_instruments(
                            '@' + pickup.id, pickup.count)
                    elif _loc in pirate_locs_id:
                        pass
                    else:
                        self.__game_state_.add_from_storage(
                            '@' + pickup.id, pickup.count)

                if not hasattr(self.__game_state_, 'all_pickups'):
                    self.__game_state_.all_pickups = []

                new = True
                for info in self.__game_state_.all_pickups:
                    if pickup.type == info.type:
                        if pickup.type in [
                                'coins', 'xp'
                        ] or (hasattr(pickup, 'id') and pickup.id == info.id):
                            new = False
                            info.count += pickup.count
                            break
                if new:
                    if (hasattr(pickup, 'id')): id = pickup.id
                    else: id = ''
                    add_pickup = dict2obj({
                        u'type': pickup.type,
                        u'count': pickup.count,
                        u'id': id
                    })
                    self.__game_state_.all_pickups.append(add_pickup)

            if self.__setting_view['pickup']:
                if len(tmp.keys()) > 0:
                    #for i in tmp.keys():
                    #logger.info(u'Подобрали %d %s' % (tmp[i], i))
                    if not hasattr(self.__game_state_, 'getcoins'):
                        self.__game_state_.getcoins = 0
                    if not hasattr(self.__game_state_, 'getxp'):
                        self.__game_state_.getxp = 0
                    for i in tmp.keys():
                        self.write_log(u'\t\t\t\tдроп %d %s' % (tmp[i], i))
                        if i == u'денег': self.__game_state_.getcoins += tmp[i]
                        elif i == u'опыта': self.__game_state_.getxp += tmp[i]
                        else:
                            logger.info(u'Подобрали %d %s' % (tmp[i], i))

            self.__game_loc.add_pickups(event_to_handle.pickups)
Ejemplo n.º 33
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)
Ejemplo n.º 34
0
  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()
Ejemplo n.º 35
0
    def perform_action(self):
        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)
            for game in building_item.games:
                game_id = game.id
                  

                play_cost = None
                if hasattr(game, 'playCost'):
                    play_cost = game.playCost

                if hasattr(game, 'playsCount'):
                    plays = building.playsCounts.__dict__
                    if plays[game_id] >= game.playsCount:
                        continue

                next_play = None
                next_play_times = building.nextPlayTimes.__dict__

                if game_id in next_play_times:
                    next_play = int(next_play_times[game_id])

                # Рулетка в таверне
                if game_id == "B_TAVERNA_ROULETTE_1":
                    pirate_box = 0
                    for _obj in list(self._get_game_state().get_state().storageGameObjects):
                       if _obj.item == '@PIRATE_BOX' or _obj.item == '@PIRATE_BOX_2': pirate_box = 1
                    if pirate_box!=1 and (self._get_game_state().get_state().pirate.state != 'PIRATE'): play_cost = None
                    else: play_cost = game.unconditionalPlayCost

                if hasattr(game, 'playsCount'):
                    Play_Count=building.playsCounts.__dict__
                    if game_id in Play_Count:
                        play_Count = int(building.playsCounts.__dict__[game_id])
                        if play_Count<game.playsCount:play_cost = None
                        else:play_cost = 'Nul'

                    

                # Ежедневный бонус
                dailyBonus = self._get_game_state().get_state().dailyBonus
                if int(dailyBonus.playFrom) and self._get_timer().has_elapsed(dailyBonus.playFrom):
                    daily = DailyBonus()
                    self._get_events_sender().send_game_events([daily])
                    logger.info(u"Крутим рулетку: Ежедневный бонус")
                    dailyBonus.playFrom = 0
                #конец ежедневной рулетке
                
                if next_play is None: get_next_play = False
                else: get_next_play = self._get_timer().has_elapsed(next_play)
                
                # Крутить рулетку в аисте за 25 малины
                item_count=self._get_game_state().count_in_storage('@S_57')
                if building_item.id == 'B_TREE_STORK' and game_id == 'B_TREE_STORK_ROULETTE' and item_count>=25:
                    self._get_game_state().remove_from_storage('@S_57',25)
                    play_cost = None
                # Конец аиста
                
                '''# Крутить рулетку  загадочная клетка за 1 шляпу и перо павлина
                if game_id.find('B_DOVE') != -1 and game.playCost.item == '@CR_151':
                    item_count = self._get_game_state().count_in_storage('@CR_151') 
                    if item_count >= game.playCost.count: 
                        self._get_game_state().remove_from_storage('@CR_151', game.playCost.count) 
                        play_cost = None 
                    else:
                        continue
                # Конец
				
				# Крутить рулетку  загадочная клетка за 1 шляпу и перо павлина
                if game_id.find('B_DOVE') != -1 and game.playCost.item == '@CR_150':
                    item_count = self._get_game_state().count_in_storage('@CR_150') 
                    if item_count >= game.playCost.count: 
                        self._get_game_state().remove_from_storage('@CR_150', game.playCost.count) 
                        play_cost = None 
                    else:
                        continue
                # Конец'''
                
                
                # Крутить рулетку в Адмирале за 1 глазной суп
                item_count=self._get_game_state().count_in_storage ('@R_60')
                if building_item.id == 'B_SOLDIER' and game_id == 'B_SOLDIER_ROULETTE' and item_count>=1:
                    self._get_game_state().remove_from_storage('@R_60' ,1)
                    play_cost = None
                # Конец Адмирала 

                # Крутить рулетку в Вишнёвом автомате за 1 вишеневый джем
                item_count=self._get_game_state().count_in_storage ('@R_57')
                if building_item.id == 'B_SLOT_CHERRY' and game_id == 'B_SLOT_CHERRY_ROULETTE2' and item_count>=1000:
                    self._get_game_state().remove_from_storage('@R_57' ,1)
                    play_cost = None
                # Конец Вишнёвого автомата

                '''# Крутить рулетку в Вишнёвом автомате за 5 вишен
                item_count=self._get_game_state().count_in_storage ('@S_52')
                if building_item.id == 'B_SLOT_CHERRY' and game_id == 'B_SLOT_B_ROULETTE1' and item_count>=1000:
                    self._get_game_state().remove_from_storage('@S_52' ,5)
                    play_cost = None
                    logger.info(u"Осталось %d вишни" %(item_count))
                # Конец Вишнёвого автомата

                # Крутить рулетку в Мандариновом автомате за 5 мандарин
                item_count=self._get_game_state().count_in_storage ('@S_53')
                if building_item.id == 'B_SLOT_MANDARIN' and game_id == 'B_SLOT_B_ROULETTE1' and item_count>=1000:
                    self._get_game_state().remove_from_storage('@S_52' ,5)
                    play_cost = None
                    logger.info(u"Осталось %d мандарин" %(item_count))
                # Конец мандаринового автомата


                # Крутить рулетку в Адмирале за 5 глазных яблок, item_count - сколько оставить на складе
                item_count=self._get_game_state().count_in_storage ('@S_55')
                if building_item.id == 'B_SOLDIER' and game_id == 'B_SOLDIER_ROULETTE2' and item_count>=2000:
                    self._get_game_state().remove_from_storage('@S_55' ,5)
                    play_cost = None
                # Конец Адмирала''' 


                # Крутить рулетку в казино если фишек = 0
                item_count=self._get_game_state().count_in_storage("@O_CHIPS")
                if (building_item.name==u'Казино'):
                    if (item_count==0):
                        play_cost = None
                    else: 
                        play_cost = 'Nul'
                # Конец казино

                # Зомби фортуна за 5 фишек
                if (building_item.name==u'Зомби-фортуна') and (game_id == 'B_SLOT_B_ROULETTE1') and item_count>=5:
                    self._get_game_state().remove_from_storage('@O_CHIPS',5)
                    play_cost = None
                    next_play = False
                # Конец зомби фортуны
                
                
                #print building_item.name
                #print next_play_times
                #print next_play
                #print get_next_play
                #print play_cost
                #print (play_cost is None)
                #print ((not next_play) and (game.level == building.level))
                #print ((next_play and self._get_timer().has_elapsed(next_play)) or ((not next_play) and (game.level == building.level)))
                #raw_input()
                    
                #if (
                #        (play_cost is None) and
                #        ((next_play and get_next_play) or ((not next_play) and (game.level == building.level)))
                #):
                #    logger.info(
                #        u"Крутим рулетку в '" +
                #        building_item.name + "' " +
                #        str(building.id) +
                #        u" по координатам (" +
                #        str(building.x) + u", " + str(building.y) + u")")
                #    roll = GamePlayGame(building.id, game_id)
                #    self._get_events_sender().send_game_events([roll])

                if ((play_cost is None) and ((next_play and get_next_play) or ((not next_play) and (game.level == building.level)))):
                    enemies = self._get_game_location().get_all_objects_by_type("pirateEnemy")
                    enemy_here = 0
                    if enemies:
                        for enemy in enemies:
                            if(((enemy.x - building.x)**2+(enemy.y - building.y)**2)**0.5 < 15):
                                enemy_here = 1
                                break
                    if(enemy_here == 1):
                        logger.info("Сильвер мешает крутить рулетку "+str(building.id))
                        continue

                    if hasattr(game, 'playsCount'):
                        if game_id in Play_Count:
                            if play_Count<game.playsCount:play_Count += 1
                            else:continue
                            count_last=game.playsCount-play_Count
                            logger.info(u"Крутим рулетку в '%s' осталось %d/%d"%(building_item.name,count_last,game.playsCount))
                            building.playsCounts.__dict__[game_id]=dict2obj(play_Count)
                        else:logger.info(u"Крутим рулетку в '%s'"%(building_item.name))
                    
                    else:
                        logger.info(
                            u"Крутим рулетку в '" +
                            building_item.name + "' " +
                            str(building.id) +
                            u" по координатам (" +
                            str(building.x) + u", " + str(building.y) + u")")
                    roll = GamePlayGame(building.id, game_id)
                    self._get_events_sender().send_game_events([roll]) 
Ejemplo n.º 36
0
    def testDictToObjMixin(self):
        myObject = dict2obj({'attribute': ''}, 'MyObject')

        # exercise & verify
        self.assertEqual("GameMyObject: {'attribute': ''}",
                         repr(myObject))
Ejemplo n.º 37
0
    def perform_action(self):
        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)
            for game in building_item.games:
                game_id = game.id

                play_cost = None
                if hasattr(game, 'playCost'):
                    play_cost = game.playCost

                if hasattr(game, 'playsCount'):
                    plays = building.playsCounts.__dict__
                    if plays[game_id] >= game.playsCount:
                        continue

                next_play = None
                next_play_times = building.nextPlayTimes.__dict__

                if game_id in next_play_times:
                    next_play = int(next_play_times[game_id])

                # Рулетка в таверне
                if game_id == "B_TAVERNA_ROULETTE_1":
                    pirate_box = 0
                    for _obj in list(self._get_game_state().get_state().
                                     storageGameObjects):
                        if _obj.item == '@PIRATE_BOX' or _obj.item == '@PIRATE_BOX_2':
                            pirate_box = 1
                    if pirate_box != 1 and (
                            self._get_game_state().get_state().pirate.state !=
                            'PIRATE'):
                        play_cost = None
                    else:
                        play_cost = game.unconditionalPlayCost

                if hasattr(game, 'playsCount'):
                    Play_Count = building.playsCounts.__dict__
                    if game_id in Play_Count:
                        play_Count = int(
                            building.playsCounts.__dict__[game_id])
                        if play_Count < game.playsCount: play_cost = None
                        else: play_cost = 'Nul'

                # Ежедневный бонус
                dailyBonus = self._get_game_state().get_state().dailyBonus
                if int(dailyBonus.playFrom) and self._get_timer().has_elapsed(
                        dailyBonus.playFrom):
                    daily = DailyBonus()
                    self._get_events_sender().send_game_events([daily])
                    logger.info(u"Крутим рулетку: Ежедневный бонус")
                    dailyBonus.playFrom = 0
                #конец ежедневной рулетке

                if next_play is None: get_next_play = False
                else: get_next_play = self._get_timer().has_elapsed(next_play)

                # Крутить рулетку в аисте за 25 малины
                item_count = self._get_game_state().count_in_storage('@S_57')
                if building_item.id == 'B_TREE_STORK' and game_id == 'B_TREE_STORK_ROULETTE' and item_count >= 25:
                    self._get_game_state().remove_from_storage('@S_57', 25)
                    play_cost = None
                # Конец аиста
                '''# Крутить рулетку  загадочная клетка за 1 шляпу и перо павлина
                if game_id.find('B_DOVE') != -1 and game.playCost.item == '@CR_151':
                    item_count = self._get_game_state().count_in_storage('@CR_151') 
                    if item_count >= game.playCost.count: 
                        self._get_game_state().remove_from_storage('@CR_151', game.playCost.count) 
                        play_cost = None 
                    else:
                        continue
                # Конец
				
				# Крутить рулетку  загадочная клетка за 1 шляпу и перо павлина
                if game_id.find('B_DOVE') != -1 and game.playCost.item == '@CR_150':
                    item_count = self._get_game_state().count_in_storage('@CR_150') 
                    if item_count >= game.playCost.count: 
                        self._get_game_state().remove_from_storage('@CR_150', game.playCost.count) 
                        play_cost = None 
                    else:
                        continue
                # Конец'''

                # Крутить рулетку в Адмирале за 1 глазной суп
                item_count = self._get_game_state().count_in_storage('@R_60')
                if building_item.id == 'B_SOLDIER' and game_id == 'B_SOLDIER_ROULETTE' and item_count >= 1:
                    self._get_game_state().remove_from_storage('@R_60', 1)
                    play_cost = None
                # Конец Адмирала

                # Крутить рулетку в Вишнёвом автомате за 1 вишеневый джем
                item_count = self._get_game_state().count_in_storage('@R_57')
                if building_item.id == 'B_SLOT_CHERRY' and game_id == 'B_SLOT_CHERRY_ROULETTE2' and item_count >= 1000:
                    self._get_game_state().remove_from_storage('@R_57', 1)
                    play_cost = None
                # Конец Вишнёвого автомата
                '''# Крутить рулетку в Вишнёвом автомате за 5 вишен
                item_count=self._get_game_state().count_in_storage ('@S_52')
                if building_item.id == 'B_SLOT_CHERRY' and game_id == 'B_SLOT_B_ROULETTE1' and item_count>=1000:
                    self._get_game_state().remove_from_storage('@S_52' ,5)
                    play_cost = None
                    logger.info(u"Осталось %d вишни" %(item_count))
                # Конец Вишнёвого автомата

                # Крутить рулетку в Мандариновом автомате за 5 мандарин
                item_count=self._get_game_state().count_in_storage ('@S_53')
                if building_item.id == 'B_SLOT_MANDARIN' and game_id == 'B_SLOT_B_ROULETTE1' and item_count>=1000:
                    self._get_game_state().remove_from_storage('@S_52' ,5)
                    play_cost = None
                    logger.info(u"Осталось %d мандарин" %(item_count))
                # Конец мандаринового автомата


                # Крутить рулетку в Адмирале за 5 глазных яблок, item_count - сколько оставить на складе
                item_count=self._get_game_state().count_in_storage ('@S_55')
                if building_item.id == 'B_SOLDIER' and game_id == 'B_SOLDIER_ROULETTE2' and item_count>=2000:
                    self._get_game_state().remove_from_storage('@S_55' ,5)
                    play_cost = None
                # Конец Адмирала'''

                # Крутить рулетку в казино если фишек = 0
                item_count = self._get_game_state().count_in_storage(
                    "@O_CHIPS")
                if (building_item.name == u'Казино'):
                    if (item_count == 0):
                        play_cost = None
                    else:
                        play_cost = 'Nul'
                # Конец казино

                # Зомби фортуна за 5 фишек
                if (building_item.name == u'Зомби-фортуна') and (
                        game_id == 'B_SLOT_B_ROULETTE1') and item_count >= 5:
                    self._get_game_state().remove_from_storage('@O_CHIPS', 5)
                    play_cost = None
                    next_play = False
                # Конец зомби фортуны

                #print building_item.name
                #print next_play_times
                #print next_play
                #print get_next_play
                #print play_cost
                #print (play_cost is None)
                #print ((not next_play) and (game.level == building.level))
                #print ((next_play and self._get_timer().has_elapsed(next_play)) or ((not next_play) and (game.level == building.level)))
                #raw_input()

                #if (
                #        (play_cost is None) and
                #        ((next_play and get_next_play) or ((not next_play) and (game.level == building.level)))
                #):
                #    logger.info(
                #        u"Крутим рулетку в '" +
                #        building_item.name + "' " +
                #        str(building.id) +
                #        u" по координатам (" +
                #        str(building.x) + u", " + str(building.y) + u")")
                #    roll = GamePlayGame(building.id, game_id)
                #    self._get_events_sender().send_game_events([roll])

                if ((play_cost is None) and
                    ((next_play and get_next_play) or
                     ((not next_play) and (game.level == building.level)))):
                    enemies = self._get_game_location(
                    ).get_all_objects_by_type("pirateEnemy")
                    enemy_here = 0
                    if enemies:
                        for enemy in enemies:
                            if (((enemy.x - building.x)**2 +
                                 (enemy.y - building.y)**2)**0.5 < 15):
                                enemy_here = 1
                                break
                    if (enemy_here == 1):
                        logger.info("Сильвер мешает крутить рулетку " +
                                    str(building.id))
                        continue

                    if hasattr(game, 'playsCount'):
                        if game_id in Play_Count:
                            if play_Count < game.playsCount: play_Count += 1
                            else: continue
                            count_last = game.playsCount - play_Count
                            logger.info(
                                u"Крутим рулетку в '%s' осталось %d/%d" %
                                (building_item.name, count_last,
                                 game.playsCount))
                            building.playsCounts.__dict__[game_id] = dict2obj(
                                play_Count)
                        else:
                            logger.info(u"Крутим рулетку в '%s'" %
                                        (building_item.name))

                    else:
                        logger.info(u"Крутим рулетку в '" +
                                    building_item.name + "' " +
                                    str(building.id) + u" по координатам (" +
                                    str(building.x) + u", " + str(building.y) +
                                    u")")
                    roll = GamePlayGame(building.id, game_id)
                    self._get_events_sender().send_game_events([roll])
Ejemplo n.º 38
0
                },
                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))
Ejemplo n.º 39
0
 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)
Ejemplo n.º 40
0
    def perform_action(self):
        num = 1              # партиями по ... шт.
        #------------------------------------------

        """
        # инфа
        for object in self._get_game_location().get_game_objects():
            print u'ищем...'
            if object.item[:4] == '@CH_':   
                print 'FIND: ', object.item, ' id = ', object.id
                print "Find ", str(obj2dict(object))         
                raw_input('-------------   END   ---------------')
        """
                
        """
        # Убираем ненужное
        for object in self._get_game_location().get_game_objects():
            print u'ищем...'
            if object.item[:16] == '@PIRATE_CAPTURE_':   
                print 'FIND: ', object.item, ' id = ', object.id
                print "Find ", str(obj2dict(pirate_obj)) 
                self._get_events_sender().send_game_events([{"type":"item","action":"moveToStorage","objId":object.id}])        
        raw_input('-------------   END   ---------------')
        """

        current_loc = self._get_game_state().get_location_id()
        storage = self._get_game_state().get_state().storageGameObjects
        next_id = max([_i.maxGameObjectId for _i in self._get_game_state().get_state().locationInfos] +[_m.id for _m in self._get_game_location().get_game_objects()]) + 1
        num_put = 0
        for pirate_obj in storage:                                 
            if num_put == num: break
            if not hasattr(pirate_obj, 'item'): continue
            if pirate_obj.item[:11] == '@PIRATE_BOX' and pirate_obj.item[:13] == '@SYMBOL_D_BOX':     #BIRTHDAY_GIFT_BOX4
                #print "Find ", str(obj2dict(pirate_obj))     
                obj = self._get_item_reader().get(pirate_obj.item)
                #print 'obj ', obj
                #logger.info(str(obj2dict(obj)).encode('utf-8'))
                space_crd = self.space(current_loc, obj)
                #print space_crd
                #raw_input('-------------   END   ---------------')  
                
                if space_crd == []: continue
                                
                if pirate_obj.count > num - num_put:
                    run = num - num_put
                else:
                    run = pirate_obj.count
                
                #events = []
                for n in range(run):                               
                    if n < len(space_crd):
                        k = space_crd[n]
                    else:
                        break

                    if len(k) == 5:
                        x = int(k[:3])
                        y = int(k[3:])
                    elif len(k) == 4:
                        if current_loc == u'main' and int(k[:2])<13:
                            x = int(k[:3])
                            y = int(k[3:])
                        else:                           
                            x = int(k[:2])
                            y = int(k[2:])
                    elif len(k) == 2:
                        x = int(k[:1])
                        y = int(k[1:])
                    else:
                        if k[0] == '8' or k[0] == '9':
                            x = int(k[:1])
                            y = int(k[1:])
                        else:
                            x = int(k[:2])
                            y = int(k[2:])
                  
                    event = {
                        "x":x,
                        "y":y,
                        "action":"placeFromStorage",
                        "itemId":pirate_obj.item[1:],
                        "type":"item",
                        "objId":next_id}
                    #print event 
                    self._get_events_sender().send_game_events([event])
                    #events.append(event)
                    #print u''+str(num_put)+u" Ставим "+pirate_obj.item+u" на X/Y: "+str(x)+u"/"+str(y)
                    logger.info(u''+str(num_put)+u" Ставим "+pirate_obj.item+u" на X/Y: "+str(x)+u"/"+str(y))
                    # добавляем инфу
                    self._get_game_state().get_state().gameObjects.append(dict2obj({u'item': pirate_obj.item, u'y': str(y), u'x': str(x), u'type': u'chop', u'id': next_id}))#, "chopCount":obj.chopCount}))
                    next_id += 1
                    num_put += 1                                       
                    
                #self._get_events_sender().send_game_events([events])                    
                # учёт
                if run == pirate_obj.count:
                    self._get_game_state().get_state().storageGameObjects.remove(pirate_obj)
                else:
                    pirate_obj.count -= run
        logger.info(u"Поставили "+str(num_put)+u" предметов")
Ejemplo n.º 41
0
    def testDictToObjMixin(self):
        myObject = dict2obj({'attribute': ''}, 'MyObject')

        # exercise & verify
        self.assertEqual("GameMyObject: {'attribute': ''}", repr(myObject))
Ejemplo n.º 42
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   ---------------')
Ejemplo n.º 43
0
    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)
Ejemplo n.º 44
0
 def get(self, item_id):
     item_id = str(item_id).lstrip('@')
     return dict2obj(self.content_dict[item_id])
Ejemplo n.º 45
0
    def perform_action(self):
        num = 50              # партиями по ... шт.
        current_loc = self._get_game_state().get_location_id()
        storage = self._get_game_state().get_state().storageGameObjects
        put_in=['@BIRTHDAY_GIFT_BOX1','@BIRTHDAY_GIFT_BOX2','@BIRTHDAY_GIFT_BOX3','@BIRTHDAY_GIFT_BOX4','@BIRTHDAY_GIFT_BOX5','@SYMBOL_D_BOX']
        next_id = max([_i.maxGameObjectId for _i in self._get_game_state().get_state().locationInfos] +[_m.id for _m in self._get_game_location().get_game_objects()]) + 1
        num_put = 0
        if current_loc=='main':
            for pirate_obj in storage:
                if num_put == num: break
                if not hasattr(pirate_obj, 'item'): continue
                if pirate_obj.item in put_in:
                    obj = self._get_item_reader().get(pirate_obj.item)
                    space_crd = self.space(current_loc, obj)
                    if space_crd == []: continue

                    if pirate_obj.count > num - num_put:
                        run = num - num_put
                    else:
                        run = pirate_obj.count

                    #events = []
                    for n in range(run):
                        if n < len(space_crd):
                            k = space_crd[n]
                        else:
                            break

                        if len(k) == 5:
                            x = int(k[:3])
                            y = int(k[3:])
                        elif len(k) == 4:
                            if current_loc == u'main' and int(k[:2])<13:
                                x = int(k[:3])
                                y = int(k[3:])
                            else:
                                x = int(k[:2])
                                y = int(k[2:])
                        elif len(k) == 2:
                            x = int(k[:1])
                            y = int(k[1:])
                        else:
                            if k[0] == '8' or k[0] == '9':
                                x = int(k[:1])
                                y = int(k[1:])
                            else:
                                x = int(k[:2])
                                y = int(k[2:])

                        event = {
                            "x":x,
                            "y":y,
                            "action":"placeFromStorage",
                            "itemId":pirate_obj.item[1:],
                            "type":"item",
                            "objId":next_id}
                        self._get_events_sender().send_game_events([event])
                        logger.info(u" Ставим "+pirate_obj.item+u" на X/Y: "+str(x)+u"/"+str(y))
                        if pirate_obj.item == '@PIRATE_BOX' or pirate_obj.item == '@PIRATE_BOX_2':
                            self._get_game_state().get_state().pirate.state = 'PIRATE'
                            self._get_game_state().get_state().gameObjects.append(dict2obj({ u'item': pirate_obj.item, u'y': str(y), u'x': str(x), u'type': u'pirateBox', u'id': next_id}))
                        else:
                            self._get_game_state().get_state().gameObjects.append(dict2obj({u'item': pirate_obj.item, u'y': str(y), u'x': str(x), u'type': u'chop', u'id': next_id}))
                        next_id += 1
                        num_put += 1

                    if run == pirate_obj.count:
                        self._get_game_state().get_state().storageGameObjects.remove(pirate_obj)
                    else:
                        pirate_obj.count -= run
            if num_put>0:
                logger.info(u" Поставили %s предметов"%(str(num_put)))
Ejemplo n.º 46
0
    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)
Ejemplo n.º 47
0
    def perform_action(self):
        if self.if_location_pirate(): return
        is_there_travel_buff = False
        buff_list = self._get_game_state().get_state().buffs.list
        o_id = False
        max_travel_time = 0
        for buff in buff_list:
            if '@BUFF_TRAVEL_TICKET_TIME' in buff.item:
                time_exp = int(buff.expire.endDate)
                # print 'time_exp', time_exp
                is_there_travel_buff = True
                if max_travel_time < time_exp:
                    max_travel_time = time_exp
            elif buff.item == '@BUFF_TRAVEL_TICKET_COUNT' or buff.item == '@BUFF_TRAVEL_TICKET_COUNT2':
                #time_exp = buff.expire.count
                time_exp = self._get_timer()._get_current_client_time(
                ) + 86400000
                is_there_travel_buff = True

        # if max_travel_time > 0:
        # time_travel = (max_travel_time-self._get_timer()._get_current_client_time())/1000.0
        # time_travel = int(time_travel)
        # if time_travel < 0: time_travel = 0
        # d = int(time_travel/86400)
        # h = (time_travel - 86400*d)/3600
        # m = (time_travel - 86400*d - 3600*h)/60
        # s = time_travel - 86400*d  - 3600*h - 60*m

        # if time_travel <> 0:
        # if d == 0:
        # logger.info(u'Осталось времени проездного: %d:%d:%d' % (h,m,s))
        # elif d == 1:
        # logger.info(u'Осталось времени проездного: 1 день %d:%d:%d' % (h,m,s))
        # else:
        # logger.info(u'Осталось времени проездного: %d дня %d:%d:%d' % (d,h,m,s))

        if is_there_travel_buff == False or self._get_timer().has_elapsed(
                time_exp):
            result, name_result = self.craft({}, 'B_VAN_ICE_CREAM', '1', 1)
            # print result, name_result
            if not result:
                result, name_result = self.craft({}, 'B_VAN_ICE_CREAM_CASH',
                                                 '1', 1)
            if result:
                logger.info(self._get_item_reader().get(
                    "@BUFF_TRAVEL_TICKET_TIME").name)
                buff_list.append(
                    dict2obj({
                        "item":
                        "@BUFF_TRAVEL_TICKET_TIME",
                        "expire":
                        dict2obj({
                            "type":
                            "time",
                            "endDate":
                            str(
                                int(self._get_timer()._get_current_client_time(
                                )) + 86400000 * 5)
                        })
                    }))
                logger.info(u'Активирован %s' % (self._get_item_reader().get(
                    "@BUFF_TRAVEL_TICKET_TIME").name))
Ejemplo n.º 48
0
  def perform_action(self):             
  
    brains_const = 19
 # Указываем нужное постоянное количество без имеющихся у игрока бесплатных  
     
    max_need_helly = max_need_garliclily = 2 * brains_const # Максимально необходимое кол-во хеллии и чесночных лилий
    max_need_love = 10 * brains_const # Максимально необходимое кол-во любви
    max_need_clevhell = 4 * max_need_garliclily # Максимально необходимое кол-во клеверхелла
    max_need_clever = ceil(max_need_clevhell/20)*20 # Максимально необходимое кол-во клевера 
    max_need_squashhell = ceil(max_need_clevhell/10)*10 # Максимально необходимое кол-во тыквахелла
    max_need_garlic = max_need_lily = ceil(max_need_garliclily/40)*40 # Максимально необходимое кол-во лилий и чеснока       
    
    obj_id_1 = obj_id_2 = '' # Переменные для ID останкино и корабля
         
    helly = love = clevhell = garliclily = clever = squashhell = garlic = lily = 0
                                                                   
    _loc = self._get_game_state().get_game_loc().get_location_id()                                                      
    
    
    if _loc == u'main':         

      #получаем 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.name == u'Останкино за монеты': # или if building_item.id == 'B_OSTANKINO'
          obj_id_1 = building.id
        if building_item.name == u'Летучий корабль': # или if building_item.id == 'D_SHIP'
          obj_id_2 = building.id
          
      st_items = self._get_game_state().get_state().storageItems
                
      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 love < max_need_love : 
        logger.info(u'Не хватает любви для создания мозгов, накопайте еще %d шт.',max_need_love-love)      
        if helly < max_need_helly and obj_id_2 == '':                                           
          logger.info(u'Не хватает хеллии для создания мозгов, сварите еще %d шт.',max_need_helly-helly)
        return
      
      elif helly < max_need_helly and obj_id_2 == '':                                           
        logger.info(u'Не хватает хеллии для создания мозгов, сварите еще %d шт.',max_need_helly-helly)
        return  
          
      elif helly < max_need_helly and obj_id_2 != '': 
        print u'QQQ'
        
        if clevhell < max_need_clevhell:
          if (clever < max_need_clever) and (squashhell < max_need_squashhell):
            logger.info(u'Не хватает клевера, посадите еще %d шт.',max_need_clever-clever)
            logger.info(u'Не хватает тыквахелла, посадите еще %d шт.',max_need_squashhell-squashhell)
            return
          elif clever < max_need_clever:
            logger.info(u'Не хватает клевера, посадите еще %d шт.',max_need_clever-clever)
            return
          elif squashhell < max_need_squashhell:
            logger.info(u'Не хватает тыквахелла, посадите еще %d шт.',max_need_squashhell-squashhell)
            return
          else:
            _i=0
            for _i in range(ceil((max_need_clevhell-clevhell)/10)):
              self.create_items(obj_id_2, "1")      
              
        if garliclily < max_need_garliclily:
          if (garlic < max_need_garlic) and (lily < max_need_lily):
            logger.info(u'Не хватает чеснока, посадите еще %d шт.',max_need_garlic-garlic)
            logger.info(u'Не хватает лилий, посадите еще %d шт.',max_need_lily-lily)    
            return
          elif garlic < max_need_garlic:
            logger.info(u'Не хватает чеснока, посадите еще %d шт.',max_need_garlic-garlic)
            return
          elif lily < max_need_lily:
            logger.info(u'Не хватает лилий, посадите еще %d шт.',max_need_lily-lily)
            return
          else:
            _i=0
            for _i in range(ceil((max_need_garliclily-garliclily)/10)):
              self.create_items(obj_id_2, "2")                     
                  
        _i=0
        for _i in range(max_need_clevhell-clevhell):
            self.create_items(obj_id_2, "3")
        
        
      
      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<=5:
                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_1, "1")                                       
            brains_buy.append(dict2obj({u'count': 1L, u'endTime': u'86400000'})) #Добавляем фейк в список купленных мозгов для увеличения счетчика
          logger.info (u'Создано мозгов - %d шт.', brains_lx)     
Ejemplo n.º 49
0
        expected = event_to_handle.nextPlayDate
        actual = building.nextPlayTimes.__dict__[event_to_handle.extraId]
        self.assertEqual(expected, actual)

    def testHandleGainMaterialEventAddsJobTime(self):
        # setup
        JOB_END_TIME = u'2458640'
        event_to_handle = dict2obj({u'action': u'start',
                                    u'doneCounter': 181L,
                                    u'jobEndTime': JOB_END_TIME,
                                    u'jobStartTime': u'1558640',
                                    u'objId': 267L,
                                    u'startCounter': 182L,
                                    u'targetId': -190L,
                                    u'type': u'gainMaterial'})
        wood_grave = dict2obj({u'startCounter': 12L,
                               u'item': u'@SC_WOOD_GRAVE2',
                               u'materials': [u'@S_19', u'@S_19', u'@S_19'],
                               u'doneCounter': 12L, u'y': 70L, u'x': 60L,
                               u'type': u'woodGraveDouble', u'id': 307L})
        game_location = Mock()
        game_location.get_object_by_id = Mock(return_value=wood_grave)

        # exercise
        GainMaterialEventHandler(Test.game_item_reader,
                                 game_location, Mock()).handle(event_to_handle)

        # verify
        self.assertEqual(wood_grave.jobEndTime, event_to_handle.jobEndTime)
        self.assertEqual(wood_grave.jobStartTime, event_to_handle.jobStartTime)
Ejemplo n.º 50
0
 def testGameState(self):
     start_response = dict2obj({
         "cmd": "START",
         "id": "1",
         "state": {
                     "registerDate": "-2147483648",
                     "playerStatus": "@PS_ZOMBIE",
                     "dailyBonus": {},
                     "mailBonus": {
                       "bonuses": [],
                       "acceptedBonuses": []
                     },
                     "magic": {"expire": "80000000", "used": 0},
                     "definedBonuses": ["ITEM_ID", ],
                     "playerSettings": {"userName": "******",
                                       "dressId": "ITEM_ID",
                                       "hatId": "ITEM_ID"},
                     "gameSettings": {"sound": False,
                                     "music": False,
                                     "tutorialState": 0},
                     "brainsCount": 3,
                     "buyedBrains": [],
                     "experience": 50000,
                     "level": 20,
                     "gameMoney": 1000000,
                     "cashMoney": 10,
                     "gameMoneyReal": 0,
                     "cashMoneyReal": 0,
                     "burySlots": [{"enabled": True}, ],
                     "shopOpened": ["P_09"],
                     "collectionItems": {"C_ITEM_ID": 2, },
                     "giftId": 3000,
                     "gifts": [],
                     "receivedGiftsExpire": "80000000",
                     "receivedGiftsCoins": 0,
                     "freeGiftUsers": [],
                     "storageItems": [],
                     "remoteTreasure": [],
                     "treasureHide": "-80000000",
                     "treasureExpire": "80000000",
                     "treasureCount": 0,
                     "remoteTrickTreating": [],
                     "remoteThanksgiving": [],
                     "remoteNewYearExpire": "80000000",
                     "remoteNewYear": [],
                     "remoteFertilizeFruitTreeCount": 0,
                     "remoteFertilizeFruitTree": [],
                     "wishlist": [None, None, None, None, None],
                     "buyedClothing": ["ITEM_ID"],
                     "retentionBonuses": False,
                     "npcs": {"npcClientId": 1},
                     "buffs": {"list": []}
         },
         "params": {
             "event": {
                 "action": 'gameState',
                 "locationId": 'main',
                 "haveTreasure": True,
                 "isAway": False,
                 "haveAttempts": True,
                 "treasureRehide": 100,
                 "haveTrickTreating": True,
                 "haveThanksgivingAttempt": True,
                 "haveRemoteFertilizeFruit": True,
                 "playerStatus": "@PS_ZOMBIE",
                 "locationInfos": [],
                 "wishlist": [],
                 "location": {},
                 "playerSettings": {"userName": "******",
                                   "dressId": "ITEM_ID",
                                   "hatId": "ITEM_ID"},
             },
             "magicLimit": 500
         }
     })
     item = start_response.params.event.wishlist
     self.assertEqual([], item)
     game_items = GameItemReader()
     game_items.download('items.txt')
     game_items.read('items.txt')
     location = start_response.params.event.playerStatus
     self.assertEqual(u"Зомби", (game_items.get(location).name))
Ejemplo n.º 51
0
    def newObject(self, need):
        has_max_id = [
            _i.maxGameObjectId
            for _i in self._get_game_state().get_state().locationInfos
        ] + [_m.id for _m in self._get_game_state().get_state().gameObjects]
        if len(has_max_id) > 1:
            next_id = max(has_max_id) + 1
        elif len(has_max_id) == 1:
            next_id = has_max_id[0] + 1
        else:
            next_id = 1

        # print 'locationInfos', [_i.maxGameObjectId for _i in self._get_game_state().get_state().locationInfos]
        # print 'objects', [_m.id for _m in self._get_game_state().get_state().gameObjects]
        # print
        # print 'sum', [_i.maxGameObjectId for _i in self._get_game_state().get_state().locationInfos] + [_m.id for _m in self._get_game_state().get_state().gameObjects]
        # print 'next_id', next_id

        need = self._get_item_reader().get(need)
        for obj in self._get_game_state().get_state().rectsObjects:
            if str(need.objAnim[0]) == str(obj.objAnim):
                need.w = int(obj.rects.rectW)
                need.h = int(obj.rects.rectH)
        newObjects = []
        bad_crd = []
        space = self.spaces()
        for coord in space:
            if coord in bad_crd: continue
            x = int(coord[:coord.find(':')])
            y = int(coord[coord.find(':') + 1:])
            space_need = [
                str(i + x) + ':' + str(j + y) for i in range(need.w)
                for j in range(need.h)
            ]
            free = True
            for coord_need in space_need:
                #if not coord_need in space: free = False
                if not coord_need in space or coord_need in bad_crd:
                    free = False
            if free:
                if need.type == 'woodTree' or need.type == 'stone':
                    mat_count = int(need.materialCount)
                    new = {
                        u'rotate': 0L,
                        u'materialCount': mat_count,
                        u'item': u'@' + need.id,
                        u'gainStarted': False,
                        u'y': long(y),
                        u'x': long(x),
                        u'type': need.type,
                        u'id': next_id
                    }
                elif need.type == 'decoration':
                    new = {
                        u'rotate': 0L,
                        u'placeTime': u'-69191572',
                        u'item': u'@' + need.id,
                        u'y': long(y),
                        u'x': long(x),
                        u'type': u'decoration',
                        u'id': next_id
                    }
                elif need.type == 'building':
                    new = {
                        u'rotate': 0L,
                        u'level': 0,
                        u'nextPlayTimes': {},
                        u'playsCounts': {},
                        u'item': u'@' + need.id,
                        u'y': long(y),
                        u'x': long(x),
                        u'type': u'building',
                        u'id': next_id
                    }
                elif need.type == 'ground' or need.type == 'pirateBox':
                    new = {
                        u'rotate': 0L,
                        u'item': u'@' + need.id,
                        u'y': long(y),
                        u'x': long(x),
                        u'type': need.type,
                        u'id': next_id
                    }
                elif need.type == 'pickupBox':
                    new = {
                        u'rotate': 0L,
                        u'item': u'@' + need.id,
                        u'y': long(y),
                        u'x': long(x),
                        u'type': u'pickup',
                        u'id': next_id
                    }
                elif need.type == 'fruitTree':
                    jobFinishTime = int(need.fruitingTime) * 1000
                    fruitingCount = int(need.fruitingCount)
                    new = {
                        u'rotate': 0,
                        u'fruitingCount': fruitingCount,
                        u'fertilized': False,
                        u'item': u'@' + need.id,
                        u'jobFinishTime': jobFinishTime,
                        u'jobStartTime': 0,
                        u'y': long(y),
                        u'x': long(x),
                        u'type': need.type,
                        u'id': next_id
                    }
                elif need.type == 'pirateShip':
                    new = {
                        u'rotate': 0L,
                        u'level': 0,
                        u'team': [],
                        u'item': u'@' + need.id,
                        u'y': long(y),
                        u'x': long(x),
                        u'type': need.type,
                        u'id': next_id
                    }
                elif need.type == 'pirateBox':
                    new = {
                        u'rotate': 0L,
                        u'item': u'@' + need.id,
                        u'y': long(y),
                        u'x': long(x),
                        u'type': u'pirateBox',
                        u'id': next_id
                    }
                else:
                    new = {
                        u'rotate': 0L,
                        u'item': u'@' + need.id,
                        u'y': long(y),
                        u'x': long(x),
                        u'type': u'notype',
                        u'id': next_id
                    }
                newObjects.append(dict2obj(new))
                bad_crd.extend(space_need)
                next_id += 1
        return newObjects
Ejemplo n.º 52
0
    def perform_action(self):
        min_money = 0  # оставляем денег    
        # Что где сажаем   u'FT_CHERRY', u'FT_APPLE' , u'FT_MANDARINE', "FT_EYE"
        plant_tree = {
                #u'main':u'FT_CHERRY',               # Домашний
                #u'isle_polar':u'GROUND',                # Домашний
                #u'main':u'CANDY_BOX2',                # Домашний
                #u'isle_03':u'GROUND',             # Любви
                #u'isle_02':u'FT_CHERRY',             # Майя
                #u'isle_x':u'GROUND',              # X
                #u'isle_faith':u'FT_EYE',          # Веры
                #u'isle_hope':u'GROUND',           # Надежды
                #u'isle_scary':u'GROUND',          # Страшный
                #u'isle_alpha':u'GROUND',          # Альфа
                u'isle_omega':u'GROUND',          # Омега
                #u'isle_sand':u'FT_CHERRY',           # Песочный
                #u'isle_polar':u'FT_CHERRY',          # Полярной ночи
                #u'isle_wild':u'GROUND',           # Дремучий
                #u'isle_mobile':u'FT_CHERRY',         # Мобильный
                #u'isle_ufo':u'FT_CHERRY',            # НЛО
                #u'isle_dream':u'GROUND',          # Мечты
                #u'isle_scarecrow':u'FT_CHERRY',      # Пик Админа
                #u'isle_elephant':u'FT_CHERRY',       # Ужасный
                #u'isle_emerald':u'GROUND',        # Город Призрак
                #u'isle_monster':u'FT_CHERRY',        # Чудовища
                #u'isle_halloween':u'FT_CHERRY',      # Лысая гора
                #
                ###############     Платные     ###############
                #
                #u'isle_01':u'FT_CHERRY',             # Секретный
                #u'isle_small':u'FT_CHERRY',          # Маленькой ёлочки
                #u'isle_star':u'FT_CHERRY',           # Звездный
                #u'isle_large':u'FT_CHERRY',          # Большой ёлки
                #u'isle_moon':u'FT_CHERRY',           # Лунный
                #u'isle_giant':u'FT_CHERRY',          # Гигантов
                #u'isle_xxl':u'FT_CHERRY',            # Огромной ёлки
                #u'isle_desert':u'FT_CHERRY'          # Необитаемый
                }

        current_loc = self._get_game_state().get_location_id()
        if not current_loc in plant_tree:
            logger.info(u"Пропускаем "+current_loc)
            return 1
        need = plant_tree [current_loc]
                 
        next_id = max([_i.maxGameObjectId for _i in self._get_game_state().get_state().locationInfos]) + 1
        
        need = self._get_item_reader().get(need)
        space_crd = self.space(current_loc, need)
        build_cost = self._get_item_reader().get(need.id).buyCoins
        
        num = 0
        if space_crd:
            for k in space_crd:
                if len(k) == 5:
                    x = int(k[:3])
                    y = int(k[3:])
                elif len(k) == 4:
                    x = int(k[:2])
                    y = int(k[2:])
                elif len(k) == 2:
                    x = int(k[:1])
                    y = int(k[1:])
                else:
                    if k[0] == '8' or k[0] == '9':
                        x = int(k[:1])
                        y = int(k[1:])
                    else:
                        x = int(k[:2])
                        y = int(k[2:])
                    
                if self._get_game_state().get_state().gameMoney > min_money:
                    num += 1                
                    buy = {"x":x,"y":y,"action":"buy","itemId":need.id,"type":"item","objId":next_id}                    
                    self._get_events_sender().send_game_events([buy])
                    self._get_game_state().get_state().gameMoney -= build_cost
                    logger.info(u''+str(num)+u" Сажаем "+need.id+u" на X: "+str(x)+u", Y: "+str(y))
                    self._get_game_state().get_state().gameObjects.append(dict2obj({u'rotate': u'0L', u'fruitingCount': u'25L', u'fertilized': False, u'item': u'@'+need.id, u'jobFinishTime': u'79200000', u'jobStartTime': u'0', u'y': str(y), u'x': str(x), u'type': u'fruitTree', u'id': next_id}))
                    next_id += 1                     
Ejemplo n.º 53
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
Ejemplo n.º 54
0
 def testGameState(self):
     start_response = dict2obj({
         "cmd": "START",
         "id": "1",
         "state": {
             "registerDate": "-2147483648",
             "playerStatus": "@PS_ZOMBIE",
             "dailyBonus": {},
             "mailBonus": {
                 "bonuses": [],
                 "acceptedBonuses": []
             },
             "magic": {
                 "expire": "80000000",
                 "used": 0
             },
             "definedBonuses": [
                 "ITEM_ID",
             ],
             "playerSettings": {
                 "userName": "******",
                 "dressId": "ITEM_ID",
                 "hatId": "ITEM_ID"
             },
             "gameSettings": {
                 "sound": False,
                 "music": False,
                 "tutorialState": 0
             },
             "brainsCount": 3,
             "buyedBrains": [],
             "experience": 50000,
             "level": 20,
             "gameMoney": 1000000,
             "cashMoney": 10,
             "gameMoneyReal": 0,
             "cashMoneyReal": 0,
             "burySlots": [
                 {
                     "enabled": True
                 },
             ],
             "shopOpened": ["P_09"],
             "collectionItems": {
                 "C_ITEM_ID": 2,
             },
             "giftId": 3000,
             "gifts": [],
             "receivedGiftsExpire": "80000000",
             "receivedGiftsCoins": 0,
             "freeGiftUsers": [],
             "storageItems": [],
             "remoteTreasure": [],
             "treasureHide": "-80000000",
             "treasureExpire": "80000000",
             "treasureCount": 0,
             "remoteTrickTreating": [],
             "remoteThanksgiving": [],
             "remoteNewYearExpire": "80000000",
             "remoteNewYear": [],
             "remoteFertilizeFruitTreeCount": 0,
             "remoteFertilizeFruitTree": [],
             "wishlist": [None, None, None, None, None],
             "buyedClothing": ["ITEM_ID"],
             "retentionBonuses": False,
             "npcs": {
                 "npcClientId": 1
             },
             "buffs": {
                 "list": []
             }
         },
         "params": {
             "event": {
                 "action": 'gameState',
                 "locationId": 'main',
                 "haveTreasure": True,
                 "isAway": False,
                 "haveAttempts": True,
                 "treasureRehide": 100,
                 "haveTrickTreating": True,
                 "haveThanksgivingAttempt": True,
                 "haveRemoteFertilizeFruit": True,
                 "playerStatus": "@PS_ZOMBIE",
                 "locationInfos": [],
                 "wishlist": [],
                 "location": {},
                 "playerSettings": {
                     "userName": "******",
                     "dressId": "ITEM_ID",
                     "hatId": "ITEM_ID"
                 },
             },
             "magicLimit": 500
         }
     })
     item = start_response.params.event.wishlist
     self.assertEqual([], item)
     game_items = GameItemReader()
     game_items.download('items.txt')
     game_items.read('items.txt')
     location = start_response.params.event.playerStatus
     self.assertEqual(u"Зомби", (game_items.get(location).name))
Ejemplo n.º 55
0
 def send(self, data):
     data = obj2dict(data)
     assert 'type' in data
     request = self.__factory.createRequest(data)
     return dict2obj(request.send(self.__connection))
Ejemplo n.º 56
0
    def perform_action(self):
        # Предупреждает, что через "day_count" дней закончится супер-урожай на складе
        day_count = self.mega().buff_options()['day_count']
        # Активировать за "time_activation" секунд до окончания
        time_activation = self.mega().buff_options()['time_activation']

        if self.if_location_pirate(): return
        day_1 = day_2 = day_3 = exp_time = 0
        for materials in self._get_game_state().get_state().storageItems:
            if hasattr(materials, 'item'):
                if "BUFF_FIX_HARVEST_1" in materials.item:
                    day_1 = materials.count
                if "BUFF_FIX_HARVEST_2" in materials.item:
                    day_2 = materials.count
                if "BUFF_FIX_HARVEST_3" in materials.item:
                    day_3 = materials.count
        day = day_1 + day_2 * 2 + day_3 * 3
        if int(str(day)[-1:]) == 0 or 9 < int(str(day)[-2:]) < 21 or 4 < int(
                str(day)[-1:]) < 10:
            days = u'дней'
        elif 1 < int(str(day)[-1:]) < 5:
            days = u'дня'
        else:
            days = u'день'
        if day < day_count:
            logger.info(
                u'Внимание!!! Супер-урожая на складе осталось на %d %s' %
                (day, days))

        buff_list = self._get_game_state().get_state().buffs.list
        max_time = 0
        for l in buff_list:
            if "BUFF_FIX_HARVEST" in l.item:
                exp_time = int(
                    (float(l.expire.endDate) -
                     self._get_timer()._get_current_client_time()) / 1000)
                if exp_time < 0:
                    exp_time = 0
                if exp_time > max_time: max_time = exp_time
                # d = exp_time/86400
                # h = (exp_time - 86400*d)/3600
                # m = (exp_time - 86400*d - 3600*h)/60
                # s = exp_time - 86400*d  - 3600*h - 60*m
                # if d == 0:
                # logger.info(u'Осталось 5-мин урожая: %d:%d:%d' % (h,m,s))
                # elif d == 1:
                # logger.info(u'Осталось 5-мин урожая: 1 день %d:%d:%d' % (h,m,s))
                # elif d == 2:
                # logger.info(u'Осталось 5-мин урожая: 2 дня %d:%d:%d' % (h,m,s))

        if max_time < time_activation:
            if day_3 > 0:
                event = {
                    "x": 20,
                    "type": "item",
                    "y": 7,
                    "action": "useStorageItem",
                    "itemId": "BS_BUFF_FIX_HARVEST_3"
                }
                self._get_events_sender().send_game_events([event])
                self._get_game_state().remove_from_storage(
                    "@BS_BUFF_FIX_HARVEST_3", 1)
                buff_list.append(
                    dict2obj({
                        "item":
                        "@BUFF_FIX_HARVEST_3",
                        "expire":
                        dict2obj({
                            "type":
                            "time",
                            "endDate":
                            str(
                                int(self._get_timer()._get_current_client_time(
                                )) + 259200000)
                        })
                    }))
                logger.info(u'Активирован супер-урожай на 3 дня')
            elif day_2 > 0:
                event = {
                    "x": 20,
                    "type": "item",
                    "y": 7,
                    "action": "useStorageItem",
                    "itemId": "BS_BUFF_FIX_HARVEST_2"
                }
                self._get_events_sender().send_game_events([event])
                self._get_game_state().remove_from_storage(
                    "@BS_BUFF_FIX_HARVEST_2", 1)
                buff_list.append(
                    dict2obj({
                        "item":
                        "@BUFF_FIX_HARVEST_2",
                        "expire":
                        dict2obj({
                            "type":
                            "time",
                            "endDate":
                            str(
                                int(self._get_timer()._get_current_client_time(
                                )) + 172800000)
                        })
                    }))
                logger.info(u'Активирован супер-урожай на 2 дня')
            elif day_1 > 0:
                event = {
                    "x": 20,
                    "type": "item",
                    "y": 7,
                    "action": "useStorageItem",
                    "itemId": "BS_BUFF_FIX_HARVEST_1"
                }
                self._get_events_sender().send_game_events([event])
                self._get_game_state().remove_from_storage(
                    "@BS_BUFF_FIX_HARVEST_1", 1)
                buff_list.append(
                    dict2obj({
                        "item":
                        "@BUFF_FIX_HARVEST_1",
                        "expire":
                        dict2obj({
                            "type":
                            "time",
                            "endDate":
                            str(
                                int(self._get_timer()._get_current_client_time(
                                )) + 86400000)
                        })
                    }))
                logger.info(u'Активирован супер-урожай на 1 день')
            else:
                logger.info(u'На складе нет супер-урожая!!!')
Ejemplo n.º 57
0
    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"