if tridents < 25 and \ int(next_play_time) < 0: # if time elapsed event = { 'type': 'game', 'action': 'play', 'objId': tower.id, 'extraId': 'FILL_TRIDENT', 'id': 2 } self._get_events_sender().send_game_events([event]) time.sleep(3) tridents = 25
if tridents == 0: # just in case print '\t* no tridents, passing...' return
resources = self._get_game_location().get_all_objects_by_type('chop') if resources: for resource in resources: tool_needed = resource.chopCount # tools required print '\t* tool_needed: %d' % tool_needed print '\t* tridents:', tridents
if int(tridents) == 0: return
if tridents > tool_needed: # if have more than needed tool_count = tool_needed # use max else: continue # search for smaller resource # OR tool_count = tridents # use all we have
tridents = tridents - tool_count
event = { 'instruments':{'CHOP_TRIDENT':tool_count}, 'action':'chop', 'type':'chop', 'objId':resource.id } print 'Chop %s with %d tridents' % (resource.item, tool_count) self._get_events_sender().send_game_events([event]) else: print u'Не осталось ресурсов для добычи'
if tridents < 25 and \
int(next_play_time) < 0: # if time elapsed
event = {
'type': 'game',
'action': 'play',
'objId': tower.id,
'extraId': 'FILL_TRIDENT',
'id': 2
}
self._get_events_sender().send_game_events([event])
time.sleep(3)
tridents = 25
if tridents == 0: # just in case
print '\t* no tridents, passing...'
return
resources = self._get_game_location().get_all_objects_by_type('chop')
if resources:
for resource in resources:
tool_needed = resource.chopCount # tools required
print '\t* tool_needed: %d' % tool_needed
print '\t* tridents:', tridents
if int(tridents) == 0: return
if tridents > tool_needed: # if have more than needed
tool_count = tool_needed # use max
else:
continue # search for smaller resource
# OR
tool_count = tridents # use all we have
tridents = tridents - tool_count
event = {
'instruments':{'CHOP_TRIDENT':tool_count},
'action':'chop',
'type':'chop',
'objId':resource.id
}
print 'Chop %s with %d tridents' % (resource.item, tool_count)
self._get_events_sender().send_game_events([event])
else:
print u'Не осталось ресурсов для добычи'
просто добавил в рулетки
PHP код:
if game_id == 'FILL_TRIDENT':
limit=game.limit
item_count=self._get_game_state().count_in_storage(game.item)
if item_count<limit:play_cost = None
else:play_cost = False
и в GameResultHandler
PHP код:
if extraId=='FILL_TRIDENT':
limit=game.limit
count=self.__game_state_.count_in_storage(game.item)
fill=limit-count
game_prize = dict2obj({"count":fill,"item":game.item})
рубит стандартным чопом
Последний раз редактировалось greyzza; 30.12.2014 в 23:29.
Re: Zombot (Клиент для игры Зомби ферма) [Обсуждение]
ребята, поздравляю всех с наступающим новым годом!!!
ну и выложу свой вариант рулеток, да простят меня за удобочитаемость и прямоту кода))
Код:
class RouletteRoller(BaseActor):
def playCostGame(self,game,building_item):
rulettes = {
# не комментировать ,а то будет крутить до упора,лучше остаток больше поставить
# рулетка |сколько оставлять фруктов |сколько оставлять рецептов
'B_SLOT_APPLE':{'B_SLOT_B_ROULETTE1':5000,'B_SLOT_APPLE_ROULETTE2':100},# Яблочный автомат
'B_SLOT_CHERRY':{'B_SLOT_B_ROULETTE1':5000,'B_SLOT_CHERRY_ROULETTE2':100},# Вишнёвый автомат
'B_SLOT_MANDARIN':{'B_SLOT_B_ROULETTE1':5000,'B_SLOT_MANDARIN_ROULETTE2':100},# Мандариновый автомат
'B_SLOT_LEMON':{'B_SLOT_B_ROULETTE1':100000,'B_SLOT_LEMON_ROULETTE2':10000},# Лимонный автомат
'B_SOLDIER':{'B_SOLDIER_ROULETTE2':100000,'B_SOLDIER_ROULETTE':10000},# Адмирал
}
game_id=game.id
play_cost = game.playCost
need_item=play_cost.item
storageCount=self._get_game_state().count_in_storage(need_item)
need_count=int(play_cost.count)
if rulettes.has_key(building_item):
needGame=rulettes[building_item]
if not needGame.has_key(game_id):return False
if storageCount<=needGame[game_id]:return False
if storageCount<play_cost.count:return False
self._get_game_state().remove_from_storage(play_cost.item,play_cost.count)
return True
else:
if storageCount<need_count:return False
self._get_game_state().remove_from_storage(need_item,need_count)
return True
def unconditionalPlayCost(self,game,next_play):
pirateBox=['@PIRATE_BOX','@PIRATE_BOX_2']
play_cost = game.unconditionalPlayCost
if game.id == "B_TAVERNA_ROULETTE_1":
state=self._get_game_state().get_state().pirate.state
if state == 'PIRATE' or state == 'AWAY':return False
for box in pirateBox:
if self._get_game_state().count_in_storageObjects(box)>0:return False
dublon=self._get_game_state().count_in_storage(play_cost.item)
if dublon<play_cost.count:return False
if self._get_timer().has_elapsed(next_play):return True
else:
self._get_game_state().remove_from_storage(play_cost.item,play_cost.count)
return True
#logger.info(u'No game_id:',game.id)
return False
def enemyStatus(self,building,enemies):
if not enemies:return False
for enemy in enemies:
if((enemy.x - building.x)**2+(enemy.y - building.y)**2)**0.5 < 15:
return True
return False
def fillToLimit(self,game):
storageCount=self._get_game_state().count_in_storage(game.item)
if storageCount<game.limit:return True
else:return False
def perform_action(self):
buildings = self._get_game_location().get_all_objects_by_type('building')
enemies = self._get_game_location().get_all_objects_by_type("pirateEnemy")
# Ежедневный бонус
dailyBonus = self._get_game_state().get_state().dailyBonus
if self._get_timer().has_elapsed(dailyBonus.playFrom):
daily = DailyBonus()
self._get_events_sender().send_game_events([daily])
dailyBonus.playFrom = 0
# Крутим рулетку в волшебнике и т.д
if hasattr(self._get_game_state().get_state().npcs,'list'):
wizards=self._get_game_state().get_state().npcs.list
else:wizards=[]
if wizards:
for wizard in wizards:
if wizard.type!='wizard':continue
if hasattr(wizard,'prize'):continue
events={"type":"npc","id":None,"npcId":wizard.id,"action":"play"}
self._get_events_sender().send_game_events([events])
eventRoll=[]
for building in buildings:
building_item = self._get_item_reader().get(building.item)
if not building_item.games:continue
for game in building_item.games:
if building.level<game.level:continue
game_id = game.id
roller=True
next_play_times = building.nextPlayTimes.__dict__
if not next_play_times.has_key(game_id):
next_play_times[game_id]=-90000
next_play = int(next_play_times[game_id])
if hasattr(game,'unconditionalPlayCost'):
roller=self.unconditionalPlayCost(game,next_play)
elif game.type=='fillToLimit':
roller=self.fillToLimit(game)
elif hasattr(game, 'playCost'):
roller=self.playCostGame(game,building_item.id)
if not self._get_timer().has_elapsed(next_play):continue
if hasattr(game, 'playsCount'):
playsCounts=building.playsCounts.__dict__
if playsCounts.has_key(game_id):
play_Count = int(playsCounts[game_id])
else:
playsCounts[game_id]=0
play_Count=playsCounts[game_id]
if play_Count>=game.playsCount:continue
playsCounts[game_id]+=1
building.playsCounts=dict2obj(playsCounts)
if not enemies:enemy_here=False
else:enemy_here = self.enemyStatus(building,enemies)
if enemy_here:
logger.info(u"Сильвер мешает крутить '%s'"%building_item.name)
self._get_game_location().remove_object_by_id(building.id)
roller=False
if not roller:continue
roll = GamePlayGame(building.id, game_id)
eventRoll.append(roll)
if eventRoll:self._get_events_sender().send_game_events(eventRoll)
class GameResultHandler(object):
def __init__(self, item_reader, game_location,game_state):
self.__item_reader = item_reader
self.__game_location = game_location
self.__game_state_ = game_state
self.__collection = game_state.get_state().collectionItems.__dict__
def handle(self, event_to_handle):
self.cprint=self.__game_state_.cprint
_loc = self.__game_state_.get_location_id()
readerloc = self.__item_reader.get(_loc)
if hasattr (event_to_handle,'dailyBonus'):
daily=self.__game_state_.get_state().dailyBonus
prize_pos = event_to_handle.pos
game_prize = daily.prizes[prize_pos]
prize = self.__item_reader.get(game_prize.item)
logger.info(u"Крутанул: Ежедневный бонус Приз: %d %s "%(game_prize.count,prize.name.upper()))
elif event_to_handle.type == 'wizardNpcPlay':
npcsAll=self.__game_state_.get_state().npcs.list
for npcs in npcsAll:
if npcs.id!=event_to_handle.npcId:continue
npcsRead=self.__item_reader.get(npcs.item)
prize=npcsRead.prizes[event_to_handle.pos]
prizeRead=self.__item_reader.get(prize.item)
prizeSTR=u'Выиграл %s %s шт.'%(prizeRead.name.upper(),str(prize.count))
logger.info(u"Крутанул '%s' %s"%(npcsRead.name,prizeSTR))
setattr(npcs,'prize',dict2obj({u'count': prize.count, u'item': prize.item}))
self.__game_state_.get_state().npcs.list=dict2obj(npcsAll)
elif event_to_handle.action==u'play':
gameObject = self.__game_location.get_object_by_id(event_to_handle.objId)
if gameObject is None:return
extraId = event_to_handle.extraId
if hasattr(event_to_handle,'nextPlayDate'):
nextPlayDate = event_to_handle.nextPlayDate
gameObject.nextPlayTimes.__setattr__(extraId,nextPlayDate)
building = self.__item_reader.get(gameObject.item)
for game in building.games:
if game.id != extraId:continue
game_prize = False
if extraId=='FILL_TRIDENT':
fill=game.limit-self.__game_state_.count_in_storage(game.item)
game_prize = dict2obj({"count":fill,"item":game.item})
elif hasattr(event_to_handle.result, 'pos'):
prize_pos = event_to_handle.result.pos
game_prize = game.prizes[prize_pos]
elif hasattr(event_to_handle.result, 'won'):
prize_pos = event_to_handle.result.won
if prize_pos is not None:game_prize = game.combinations[prize_pos].prize
if not game_prize:
prizeSTR=u'Ничего не выиграл.'
logger.info(u"Крутанул '%s' %s"%(building.name,prizeSTR))
return
prize = self.__item_reader.get(game_prize.item)
if readerloc.type=='explorationLocation' and prize.type=='chopInstrument':
if not readerloc.disableUseTicketFromGlobus:
self.__game_state_.add_pirate_instruments(game_prize.item, game_prize.count)
else:self.__game_state_.add_from_storage(game_prize.item, game_prize.count)
elif prize.type=='collectionItem':
if self.__collection.has_key(prize.id):
self.__collection[prize.id]+=game_prize.count
else:self.__collection[prize.id]=game_prize.count
self.__game_state_.get_state().collectionItems=dict2obj(self.__collection)
elif hasattr(prize,'moved') and prize.moved:
self.__game_state_.add_from_storageObjects(game_prize.item, game_prize.count)
else:self.__game_state_.add_from_storage(game_prize.item, game_prize.count)
prizeSTR=u'приз: %s %s шт.'%(prize.name.upper(),str(game_prize.count))
logger.info(u"Крутанул '%s' %s"%(building.name,prizeSTR))
есть правда в этом деле ньюансы, если в GameState нет add_from_storageObjects ,добавить
Код:
def count_in_storageObjects(self, item_id):
for itemid in self.__game_state.storageGameObjects:
if hasattr(itemid, "item"):
if itemid.item == item_id:
return itemid.count
return 0
def remove_from_storageObjects(self, item_id, count):
item_id = item_id.lstrip('@')
item_id='@'+item_id
for itemid in self.__game_state.storageGameObjects:
if hasattr(itemid, "item"):
if itemid.item == item_id:
itemid.count -= count
return True
return False
def add_from_storageObjects(self, item_id, count):
item_id = item_id.lstrip('@')
item_id='@'+item_id
for itemid in self.__game_state.storageGameObjects:
if hasattr(itemid, "item"):
if itemid.item == item_id:
itemid.count += count
return
self.set_from_storageObjects(item_id, count)
def set_from_storageObjects(self, item_id, count):
itemid=dict2obj({u'item': item_id, u'count': count})
self.__game_state.storageGameObjects.append(itemid)
и также если в GameState нет add_pirate_instruments
Код:
def count_in_pirate_instruments(self, item_id):
item_id = item_id.lstrip('@')
item_id = '@'+item_id
for itemid in self.__game_state.pirate.instruments:
if itemid.item == item_id:return itemid.count
return 0
def remove_from_pirate_instruments(self, item_id, count):
item_id = item_id.lstrip('@')
item_id = '@'+item_id
for itemid in self.__game_state.pirate.instruments:
if hasattr(itemid, "item"):
if itemid.item != item_id:continue
itemid.count -= count
return True
return False
def add_pirate_instruments(self, item_id, count):
item_id = item_id.lstrip('@')
item_id = '@'+item_id
for itemid in self.__game_state.pirate.instruments:
if hasattr(itemid, "item"):
if itemid.item != item_id:continue
itemid.count += count
return
self.set_pirate_instruments(item_id, count)
def set_pirate_instruments(self, item_id, count):
itemid=dict2obj({u'item': item_id, u'count': count})
self.__game_state.pirate.instruments.append(itemid)
или воспользоваться методами megabyte0 по поводу склада и сделать также обьекты на складе и инструменты на пиратском, под спойлер не умею делать, извините))
Добавлено через 8 минут
ах ,да, чуть не забыл
в классе Game
в def handleEvent(self, event_to_handle):
поменять эту строку
elif event_to_handle.type == GamePlayGame.type:
на эту
elif event_to_handle.type == 'dailyBonus' or event_to_handle.type == 'wizardNpcPlay' or event_to_handle.type == GamePlayGame.type:
Последний раз редактировалось greyzza; 03.01.2015 в 22:31.
Причина: Добавлено сообщение
Re: Zombot (Клиент для игры Зомби ферма) [Обсуждение]
Всем привет
все ни как не могу найти решение с вишнями(
У меня одного бот вишни не сажает?
Цитата:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "D:\ZombiFarmInterface\app.py", line 35, in run
self.run_function(self)
File "D:\ZombiFarmInterface\main.py", line 79, in run_game
Game(site, settings, UserPrompt(gui_input), gui_input=gui_input).start()
File "D:\ZombiFarmInterface\game_engine.py", line 482, in start
self.eventLoop()
File "D:\ZombiFarmInterface\game_engine.py", line 538, in eventLoop
self.perform_all_actions()
File "D:\ZombiFarmInterface\game_engine.py", line 619, in perform_all_actions
actor.perform_action()
File "D:\ZombiFarmInterface\game_actors_and_handlers\tr ee_plant.py", line 65,
in perform_action
space_crd = self.space(current_loc, need, submap)
File "D:\ZombiFarmInterface\game_actors_and_handlers\tr ee_plant.py", line 120,
in space
for rect in list(need.rects):
AttributeError: 'GameFruitTree' object has no attribute 'rects'
Re: Zombot (Клиент для игры Зомби ферма) [Обсуждение]
Цитата:
Сообщение от maks_maks)
Всем привет
все ни как не могу найти решение с вишнями(
У меня одного бот вишни не сажает?
дружище, ты только проснулся? не будет он у тебя сажать в итемс больше нет размеров ищи альтернативные способы получать размеры обьектов меняй код для посадки под то как ты получил размеры и будет тебе щас я)), в твоем случае я так понял для тебя лучшим методом будет отключить посадку деревьев и выставление обьектов со склада
Re: Zombot (Клиент для игры Зомби ферма) [Обсуждение]
Цитата:
Сообщение от Shurup240
Сделал сразу, но в лог пишет, что ничего не выиграл. Да и лан) Это не столь важно
это важно потому что бот не увидит появившихся трезубцев до перезагрузки отсюда вывод 1: не будет рубить 2:когда подойдет время крутнуть рулетку он выхватит эррор
Re: Zombot (Клиент для игры Зомби ферма) [Обсуждение]
Здравствуйте! Хочу обратиться к Вам за помощью, очень надеюсь, что Вы мне не откажете. На сегодняшний день у меня на руках 4 бота: пиратский, копалка, и две разных сеялки. В каждой из них есть свой функционал, которого нет в других. Все они собраны разными людьми. Спаять в одно целое мне не под силу, поэтому я решил обратиться к Вам. Вы вместе делаете одно большое дело: с одной стороны упрощая игру себе, с другой - познавая программирование на практике в прикладных целях. Вероятно, существует версия программы, объединяющая все возможности в одной сборке, можно у Вас ее попросить?
Поделитесь, пожалуйста, со мной!
P.S. Всех с Новым Годом!
Re: Zombot (Клиент для игры Зомби ферма) [Обсуждение]
Бесплатная версия не только не приносит положительного эффекта, но и напрягает. А у меня порой большое желание выбросить бота и забыть. Играть давно надоело. Для меня игра закончилась, когда запретили передавать изумрудные коллекции.
В принципе сообщество могло бы написать версию с нуля, но я так понимаю мало желающих вкладывать силы и время.
Дошли руки сделать версию [Ссылки могут видеть только зарегистрированные пользователи. ] для линукса. Для работы должно хватить самого дешевого тарифа с 256 мегабайтами памяти. Раньше брал VPS тут [Ссылки могут видеть только зарегистрированные пользователи. ] , но тарифы по 60 рублей закончились. Где-то еще было, но уже не найду.
Вроде работает. Кому интересно, обращайтесь, подскажу как настроить.
Re: Zombot (Клиент для игры Зомби ферма) [Обсуждение]
Цитата:
Для меня игра закончилась, когда запретили передавать изумрудные коллекции
ну это уж ребята смех на палочке, было время когда этих коллекций не было, и ведь играли, я не в коем случае не защищаю разрабов, но "игра закончилась когда запретили передачу коллекций" я считаю это бред, зажрались просто
Re: Zombot (Клиент для игры Зомби ферма) [Обсуждение]
хелл был практически изначально, и почти сразу же его размножили до неприличия много... это стало одной из основных причин такой высокой популлярности игры - возможность получить игровую валюту не вкладывая реал