Перейти к содержимому
Korean Random
goodman

Динамические макросы в Python

Рекомендуемые сообщения

Кому-нибудь удалось адаптировать и запустить этот код через XVM

нет. временами мне кажется, что это

в работу макросов я не вникал, думаю дойдете сами че куда

если сделаете код более правильным, призовите меня :)

 было сарказмом  :hmm:

 

к слову, запихал mainGun в hitlog, если бы еще кто-нить дал готовый код проверки урона по союзникам (предполагаю, что можно обойтись парой-тройкой строк), то вполне годно (имхо) получается:

'вариант'

post-24956-0-31428000-1464955757_thumb.jpg

 

питон

# Calculation of damage for 'mainGun' / Расчет урона для основного калибра.

import xvm_battle.python.fragCorrelationPanel as panel
import BigWorld

hp_max_enemy = 0
actual_arenaUniqueID = None

@xvm.export('hp.mainGun', deterministic=False)
def mainGun():     
    global actual_arenaUniqueID, hp_max_enemy
    arenaUniqueID = BigWorld.player().arenaUniqueID
    if actual_arenaUniqueID != arenaUniqueID:
        actual_arenaUniqueID = arenaUniqueID
        hp_max_enemy = panel.teams_totalhp[1]
    return int( round(0.2 * hp_max_enemy, 4) ) if int(hp_max_enemy) >= 5000 else 1000

# Subtraction / Вычитание

@xvm.export('math.diff')
def diff(a, b):
    return a - b

код для хитлога, работает в "defaultHeader" (как ни странно) и в "formatHeader" (расстояние в <tabstops> для экрана 1366х768, отступ от края экрана всего 780рх (510 плюс "х": 270)

<textformat tabstops='[510]'> ... ... ... <tab><img src='img://gui/maps/icons/achievement/32x32/mainGun.png' vspace='-12'><font size='18' color='#FFFFAA'><b>{{dmg-total>={{py:hp.mainGun()}}?<font color='#80d580'>+{{py:math.diff({{dmg-total}}, {{py:hp.mainGun()}})}}</font>|{{py:math.diff({{py:hp.mainGun()}}, {{dmg-total}})}}}}</b></font>

поскольку в "hpLeft": "header" макросы точно не работают (в отличие от "defaultHeader"), сделал отображение картинки и трех точек (см. скрин)

      "header": "<textformat tabstops='[510]'> ... ... ... <tab><img src='img://gui/maps/icons/achievement/32x32/mainGun.png' vspace='-12'><font size='18' color='#FFFFAA'><b>...</b></font>",

  • Нравится 2

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах
(редактировалось)

сдаюсь)  как вывести через  {{py:блаблабла()}} ?

from gui.Scaleform.Battle import DebugPanel
from gui.Scaleform.Battle import Battle
class Battle_Info(object):
  
    def __init__(self):
        self.fps = 0
        self.fpsRep = 0
        self.ping = 0

      
battle_info = Battle_Info()
             
def updateDebugInfo(self, ping, fps, lag, fpsReplay = -1):
    self.flashObject.visible = False # standart panel off
    battle_info.fpsRep = fpsReplay if fpsReplay != 0 and fpsReplay != -1 else ''
    battle_info.fps = '({fps})'.format(fps=fps) if fpsReplay != 0 and fpsReplay != -1 else fps
    battle_info.ping = ping


DebugPanel.updateDebugInfo = updateDebugInfo

@xvm.export('DebugInfo', deterministic=False)
def DebugInfo():
    fps = battle_info.fps,
    ping = battle_info.ping
    fpsRep = battle_info.fpsRep
    # тут выполняй что нужно
   
@registerEvent(Battle, 'beforeDelete')
def beforeDelete(self):
    battle_info.fps = 0
    battle_info.fpsRep = 0
    battle_info.ping = 0

может так

Изменено пользователем Ekspoint
  • Нравится 2

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах
(редактировалось)

к слову, запихал mainGun в hitlog

Интересный метод, но все же, хотелось бы иметь способ без костылей выводить данную инфу.

============

@Ekspoint, если будет время, можешь адаптировать этот код под вывод через макросы в XVM?

Изменено пользователем neLeax

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

Интересный метод, но все же, хотелось бы иметь способ без костылей выводить данную инфу.

============

@Ekspoint, если будет время, можешь адаптировать этот код под вывод через макросы в XVM?

ну как то так наверно

from constants import VEHICLE_HIT_FLAGS
import BigWorld
from Avatar import PlayerAvatar
from Vehicle import Vehicle
from gui.Scaleform.Battle import Battle

def IsLive(vehicleID):
    player = BigWorld.player()
    vehicles = player.arena.vehicles
    return vehicles[vehicleID]['isAlive'] if player is not None else None


def IsFriendly(vehicleID):
    player = BigWorld.player()
    vehicles = player.arena.vehicles
    return vehicles[player.playerVehicleID]['team'] == vehicles[vehicleID]['team'] if player is not None else None


def get_all_health():
    for vehicleID in BigWorld.entities.values():
        if type(vehicleID) is Vehicle:
            if IsLive(vehicleID.id) and not IsFriendly(vehicleID.id):
                battle_info.enemy_hp[vehicleID.id] = vehicleID.health


def damage_helth(self, newHealth, attackerID, attackReasonID):
    if self.id in battle_info.enemy_hp.keys():
        if attackerID == BigWorld.player().playerVehicleID:
            damage = battle_info.enemy_hp[self.id] - newHealth
            in_arr = False
            for key, value in battle_info.damage_log.items():
                if self.id == value['id']:
                    value['damage'] = value['damage'] + damage
                    in_arr = True

            if not in_arr:
                battle_info.damage_log[len(battle_info.damage_log)] = {'id': self.id, 'damage': damage}
        battle_info.enemy_hp[self.id] = newHealth
    get_all_health()


def damage_helth_team(self, newHealth, attackerID, attackReasonID):
    damaged = []
    if self.id in battle_info.enemy_hp.keys():
        if attackerID in battle_info.total_damag_team.keys():
            battle_info.total_damag_team[attackerID] += battle_info.enemy_hp[self.id] - newHealth
        else:
            battle_info.total_damag_team[attackerID] = battle_info.enemy_hp[self.id] - newHealth
        for vehicleID in BigWorld.entities.values():
            if type(vehicleID) is Vehicle:
                if not attackerID == BigWorld.player().playerVehicleID and IsFriendly(vehicleID.id):
                    for id, total_damag in battle_info.total_damag_team.items():
                        damaged.append(total_damag)
                    in_arr = False
                    for key, value in battle_info.damage_log_team.items():
                        if self.id == value['id']:
                            value['damage'] = max(damaged)
                            in_arr = True

                    if not in_arr:
                        battle_info.damage_log_team[len(battle_info.damage_log_team)] = {'id': self.id, 'damage': max(damaged)}
                        
        battle_info.enemy_hp[self.id] = newHealth
    get_all_health()
    
    
@registerEvent(PlayerAvatar, 'vehicle_onEnterWorld')
def vehicle_onEnterWorld(self, vehicle):
    PlayerAvatar.rezults = []
    get_all_health()


@registerEvent(PlayerAvatar, 'showShotResults')
def showShotResults(self, results):
    PlayerAvatar.rezults = results


@registerEvent(Vehicle, 'onHealthChanged')
def onHealthChanged(self, newHealth, attackerID, attackReasonID):
    damage_helth(self, newHealth, attackerID, attackReasonID)
    damage_helth_team(self, newHealth, attackerID, attackReasonID)
    
    
def total_damage():
    damage = 0
    for key, value in battle_info.damage_log.items():
        damage = damage + value['damage']
    return damage
    

def total_damage_team():
    for key, value in battle_info.damage_log_team.items():
        return value['damage']


class Battle_Info(object):
    
    def __init__(self):
        self.allyDetect = False
        self.enemy_hp = {}
        self.damage_log = {}
        self.damage_log_team = {}
        self.total_damag_team = {}
        
battle_info = Battle_Info()
        
def main_guns(damage, damage_team):
    max_health = 0
    damagedAllies = []
    player = BigWorld.player()
    for vehicle, veh in player.arena.vehicles.iteritems():
        if not veh['team'] == player.team:
            max_health += player.arena.vehicles[vehicle]['vehicleType'].maxHealth

    for r in PlayerAvatar.rezults:
        vehicleID = r & 4294967295L
        flags = r >> 32 & 4294967295L
        if player.team == player.arena.vehicles[vehicleID]['team'] and player.playerVehicleID != vehicleID:
            if flags & (VEHICLE_HIT_FLAGS.IS_ANY_DAMAGE_MASK | VEHICLE_HIT_FLAGS.ATTACK_IS_DIRECT_PROJECTILE):
                damagedAllies.append(vehicleID)
    
    for vehicleID in damagedAllies:
        if player.arena.vehicles[vehicleID]['isAlive']:
            battle_info.allyDetect = True
    result = int(max(round(max_health * 0.2), 1000)) - damage
    if damage_team >= int(max(round(max_health * 0.2), 1000)) - damage:
        result = damage_team - damage
    if result <= 0:
        result = "<img src='img://gui/maps/icons/library/done.png' width='22' height='22' vspace='-3'>"
    return result
                             

def main_gun(damage, damage_team):
    player = BigWorld.player()
    if player.arena.guiType == 1:
        if not battle_info.allyDetect:
            result = main_guns(damage, damage_team)
        else:
            result = "<img src='img://gui/maps/icons/library/errorIcon.png' width='22' height='22' vspace='-4'>"
    else:
        result = "<img src='img://gui/maps/icons/library/errorIcon.png' width='22' height='22' vspace='-4'>"
    return result
    

@registerEvent(Battle, 'beforeDelete')
def beforeDelete(self):
    battle_info.allyDetect = False
    battle_info.enemy_hp.clear()
    battle_info.damage_log.clear()
    battle_info.damage_log_team.clear()
    battle_info.total_damag_team.clear()


@xvm.export('mainGun', deterministic=False)
def mainGun():
    def mainGunUpdate():
        BigWorld.callback(0.5, lambda: main_gun(total_damage(), total_damage_team()))
        
    return mainGunUpdate()

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

ну как то так наверно

from constants import VEHICLE_HIT_FLAGS
import BigWorld
from Avatar import PlayerAvatar
from Vehicle import Vehicle
from gui.Scaleform.Battle import Battle

def IsLive(vehicleID):
    player = BigWorld.player()
    vehicles = player.arena.vehicles
    return vehicles[vehicleID]['isAlive'] if player is not None else None


def IsFriendly(vehicleID):
    player = BigWorld.player()
    vehicles = player.arena.vehicles
    return vehicles[player.playerVehicleID]['team'] == vehicles[vehicleID]['team'] if player is not None else None


def get_all_health():
    for vehicleID in BigWorld.entities.values():
        if type(vehicleID) is Vehicle:
            if IsLive(vehicleID.id) and not IsFriendly(vehicleID.id):
                battle_info.enemy_hp[vehicleID.id] = vehicleID.health


def damage_helth(self, newHealth, attackerID, attackReasonID):
    if self.id in battle_info.enemy_hp.keys():
        if attackerID == BigWorld.player().playerVehicleID:
            damage = battle_info.enemy_hp[self.id] - newHealth
            in_arr = False
            for key, value in battle_info.damage_log.items():
                if self.id == value['id']:
                    value['damage'] = value['damage'] + damage
                    in_arr = True

            if not in_arr:
                battle_info.damage_log[len(battle_info.damage_log)] = {'id': self.id, 'damage': damage}
        battle_info.enemy_hp[self.id] = newHealth
    get_all_health()


def damage_helth_team(self, newHealth, attackerID, attackReasonID):
    damaged = []
    if self.id in battle_info.enemy_hp.keys():
        if attackerID in battle_info.total_damag_team.keys():
            battle_info.total_damag_team[attackerID] += battle_info.enemy_hp[self.id] - newHealth
        else:
            battle_info.total_damag_team[attackerID] = battle_info.enemy_hp[self.id] - newHealth
        for vehicleID in BigWorld.entities.values():
            if type(vehicleID) is Vehicle:
                if not attackerID == BigWorld.player().playerVehicleID and IsFriendly(vehicleID.id):
                    for id, total_damag in battle_info.total_damag_team.items():
                        damaged.append(total_damag)
                    in_arr = False
                    for key, value in battle_info.damage_log_team.items():
                        if self.id == value['id']:
                            value['damage'] = max(damaged)
                            in_arr = True

                    if not in_arr:
                        battle_info.damage_log_team[len(battle_info.damage_log_team)] = {'id': self.id, 'damage': max(damaged)}
                        
        battle_info.enemy_hp[self.id] = newHealth
    get_all_health()
    
    
@registerEvent(PlayerAvatar, 'vehicle_onEnterWorld')
def vehicle_onEnterWorld(self, vehicle):
    PlayerAvatar.rezults = []
    get_all_health()


@registerEvent(PlayerAvatar, 'showShotResults')
def showShotResults(self, results):
    PlayerAvatar.rezults = results


@registerEvent(Vehicle, 'onHealthChanged')
def onHealthChanged(self, newHealth, attackerID, attackReasonID):
    damage_helth(self, newHealth, attackerID, attackReasonID)
    damage_helth_team(self, newHealth, attackerID, attackReasonID)
    
    
def total_damage():
    damage = 0
    for key, value in battle_info.damage_log.items():
        damage = damage + value['damage']
    return damage
    

def total_damage_team():
    for key, value in battle_info.damage_log_team.items():
        return value['damage']


class Battle_Info(object):
    
    def __init__(self):
        self.allyDetect = False
        self.enemy_hp = {}
        self.damage_log = {}
        self.damage_log_team = {}
        self.total_damag_team = {}
        
battle_info = Battle_Info()
        
def main_guns(damage, damage_team):
    max_health = 0
    damagedAllies = []
    player = BigWorld.player()
    for vehicle, veh in player.arena.vehicles.iteritems():
        if not veh['team'] == player.team:
            max_health += player.arena.vehicles[vehicle]['vehicleType'].maxHealth

    for r in PlayerAvatar.rezults:
        vehicleID = r & 4294967295L
        flags = r >> 32 & 4294967295L
        if player.team == player.arena.vehicles[vehicleID]['team'] and player.playerVehicleID != vehicleID:
            if flags & (VEHICLE_HIT_FLAGS.IS_ANY_DAMAGE_MASK | VEHICLE_HIT_FLAGS.ATTACK_IS_DIRECT_PROJECTILE):
                damagedAllies.append(vehicleID)
    
    for vehicleID in damagedAllies:
        if player.arena.vehicles[vehicleID]['isAlive']:
            battle_info.allyDetect = True
    result = int(max(round(max_health * 0.2), 1000)) - damage
    if damage_team >= int(max(round(max_health * 0.2), 1000)) - damage:
        result = damage_team - damage
    if result <= 0:
        result = "<img src='img://gui/maps/icons/library/done.png' width='22' height='22' vspace='-3'>"
    return result
                             

def main_gun(damage, damage_team):
    player = BigWorld.player()
    if player.arena.guiType == 1:
        if not battle_info.allyDetect:
            result = main_guns(damage, damage_team)
        else:
            result = "<img src='img://gui/maps/icons/library/errorIcon.png' width='22' height='22' vspace='-4'>"
    else:
        result = "<img src='img://gui/maps/icons/library/errorIcon.png' width='22' height='22' vspace='-4'>"
    return result
    

@registerEvent(Battle, 'beforeDelete')
def beforeDelete(self):
    battle_info.allyDetect = False
    battle_info.enemy_hp.clear()
    battle_info.damage_log.clear()
    battle_info.damage_log_team.clear()
    battle_info.total_damag_team.clear()


@xvm.export('mainGun', deterministic=False)
def mainGun():
    def mainGunUpdate():
        BigWorld.callback(0.5, lambda: main_gun(total_damage(), total_damage_team()))
        
    return mainGunUpdate()

 

Все равно не хочет заводиться.

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

Все равно не хочет заводиться.

логи покажи

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах
(редактировалось)

логи покажи

python.log

xvm.log

Изменено пользователем neLeax

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

емае, а импор на хук функций не добавить?

добавь

from xfw import *
  • Нравится 1

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

 

 

может так
Спасибо! это работает.
в логе только это есть 
2016-06-03 21:17:50: [ERROR] Traceback (most recent call last):
  File "xvm_main/python_macro.py", line 125, in load_macros_lib
  File "xvm_main/python_macro.py", line 110, in execute
ExecutionException: NameError at line 30: name 'registerEvent' is not defined

@sirmax,@wotunion,

		{//dbg
		"enabled":true,
		"updateEvent":"?????????",
		"x":0,"y":100,"width":200,"height":20,
		"currentFieldDefaultStyle":{"name":"GF","size":12,"align":"center"},
		"autoSize":"none","align":"center",
		"format":"{{py:DebugInfo()}}"
			},

каким ивентом запускать то? ради прикола привязал к 

"updateEvent":"ON_PLAYERS_HP_CHANGED"

но мне нужен настраиваемый интервал  :ok: 
или решение совсем другое? :hmm:

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах
(редактировалось)

емае, а импор на хук функций не добавить?

добавь

from xfw import *

 

Никакой реакции. На всякий случай удалил свои скрипты, оставил только этот. Вот логи:

xvm.log

python.log

 

Код на дебаг панель, как уже отписались выше, работает.

Изменено пользователем neLeax

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

Спасибо! это работает.

в логе только это есть 

2016-06-03 21:17:50: [ERROR] Traceback (most recent call last):
  File "xvm_main/python_macro.py", line 125, in load_macros_lib
  File "xvm_main/python_macro.py", line 110, in execute
ExecutionException: NameError at line 30: name 'registerEvent' is not defined

@sirmax,@wotunion,

		{//dbg
		"enabled":true,
		"updateEvent":"?????????",
		"x":0,"y":100,"width":200,"height":20,
		"currentFieldDefaultStyle":{"name":"GF","size":12,"align":"center"},
		"autoSize":"none","align":"center",
		"format":"{{py:DebugInfo()}}"
			},

каким ивентом запускать то? ради прикола привязал к 

"updateEvent":"ON_PLAYERS_HP_CHANGED"

но мне нужен настраиваемый интервал  :ok: 

или решение совсем другое? :hmm:

 

from xfw import * добавь

Никакой реакции. На всякий случай удалил свои скрипты, оставил только этот. Вот логи:

attachicon.gifxvm.log

attachicon.gifpython.log

 

Код на дебаг панель, как уже отписались выше, работает.

from constants import VEHICLE_HIT_FLAGS
import BigWorld
from Avatar import PlayerAvatar
from Vehicle import Vehicle
from gui.Scaleform.Battle import Battle
from xfw import *

def IsLive(vehicleID):
    player = BigWorld.player()
    vehicles = player.arena.vehicles
    return vehicles[vehicleID]['isAlive'] if player is not None else None


def IsFriendly(vehicleID):
    player = BigWorld.player()
    vehicles = player.arena.vehicles
    return vehicles[player.playerVehicleID]['team'] == vehicles[vehicleID]['team'] if player is not None else None


def get_all_health():
    for vehicleID in BigWorld.entities.values():
        if type(vehicleID) is Vehicle:
            if IsLive(vehicleID.id) and not IsFriendly(vehicleID.id):
                battle_info.enemy_hp[vehicleID.id] = vehicleID.health


def damage_helth(self, newHealth, attackerID, attackReasonID):
    if self.id in battle_info.enemy_hp.keys():
        if attackerID == BigWorld.player().playerVehicleID:
            damage = battle_info.enemy_hp[self.id] - newHealth
            in_arr = False
            for key, value in battle_info.damage_log.items():
                if self.id == value['id']:
                    value['damage'] = value['damage'] + damage
                    in_arr = True

            if not in_arr:
                battle_info.damage_log[len(battle_info.damage_log)] = {'id': self.id, 'damage': damage}
        battle_info.enemy_hp[self.id] = newHealth
    get_all_health()


def damage_helth_team(self, newHealth, attackerID, attackReasonID):
    damaged = []
    if self.id in battle_info.enemy_hp.keys():
        if attackerID in battle_info.total_damag_team.keys():
            battle_info.total_damag_team[attackerID] += battle_info.enemy_hp[self.id] - newHealth
        else:
            battle_info.total_damag_team[attackerID] = battle_info.enemy_hp[self.id] - newHealth
        for vehicleID in BigWorld.entities.values():
            if type(vehicleID) is Vehicle:
                if not attackerID == BigWorld.player().playerVehicleID and IsFriendly(vehicleID.id):
                    for id, total_damag in battle_info.total_damag_team.items():
                        damaged.append(total_damag)
                    in_arr = False
                    for key, value in battle_info.damage_log_team.items():
                        if self.id == value['id']:
                            value['damage'] = max(damaged)
                            in_arr = True

                    if not in_arr:
                        battle_info.damage_log_team[len(battle_info.damage_log_team)] = {'id': self.id, 'damage': max(damaged)}
                        
        battle_info.enemy_hp[self.id] = newHealth
    get_all_health()
    
    
@registerEvent(PlayerAvatar, 'vehicle_onEnterWorld')
def vehicle_onEnterWorld(self, vehicle):
    PlayerAvatar.rezults = []
    get_all_health()


@registerEvent(PlayerAvatar, 'showShotResults')
def showShotResults(self, results):
    PlayerAvatar.rezults = results


@registerEvent(Vehicle, 'onHealthChanged')
def onHealthChanged(self, newHealth, attackerID, attackReasonID):
    damage_helth(self, newHealth, attackerID, attackReasonID)
    damage_helth_team(self, newHealth, attackerID, attackReasonID)
    
    
def total_damage():
    damage = 0
    for key, value in battle_info.damage_log.items():
        damage = damage + value['damage']
    return damage
    

def total_damage_team():
    for key, value in battle_info.damage_log_team.items():
        return value['damage']


class Battle_Info(object):
    
    def __init__(self):
        self.allyDetect = False
        self.enemy_hp = {}
        self.main_gun = 0
        self.damage_log = {}
        self.damage_log_team = {}
        self.total_damag_team = {}
        
battle_info = Battle_Info()
        
def main_guns(damage, damage_team):
    max_health = 0
    damagedAllies = []
    player = BigWorld.player()
    for vehicle, veh in player.arena.vehicles.iteritems():
        if not veh['team'] == player.team:
            max_health += player.arena.vehicles[vehicle]['vehicleType'].maxHealth

    for r in PlayerAvatar.rezults:
        vehicleID = r & 4294967295L
        flags = r >> 32 & 4294967295L
        if player.team == player.arena.vehicles[vehicleID]['team'] and player.playerVehicleID != vehicleID:
            if flags & (VEHICLE_HIT_FLAGS.IS_ANY_DAMAGE_MASK | VEHICLE_HIT_FLAGS.ATTACK_IS_DIRECT_PROJECTILE):
                damagedAllies.append(vehicleID)
    
    for vehicleID in damagedAllies:
        if player.arena.vehicles[vehicleID]['isAlive']:
            battle_info.allyDetect = True
    result = int(max(round(max_health * 0.2), 1000)) - damage
    if damage_team >= int(max(round(max_health * 0.2), 1000)) - damage:
        result = damage_team - damage
    if result <= 0:
        result = "<img src='img://gui/maps/icons/library/done.png' width='22' height='22' vspace='-3'>"
    return result
                             

def main_gun(damage, damage_team):
    player = BigWorld.player()
    if player.arena.guiType == 1:
        if not battle_info.allyDetect:
            result = main_guns(damage, damage_team)
        else:
            result = "<img src='img://gui/maps/icons/library/errorIcon.png' width='22' height='22' vspace='-4'>"
    else:
        result = "<img src='img://gui/maps/icons/library/errorIcon.png' width='22' height='22' vspace='-4'>"
    return result
    

@registerEvent(Battle, 'beforeDelete')
def beforeDelete(self):
    battle_info.allyDetect = False
    battle_info.enemy_hp.clear()
    battle_info.damage_log.clear()
    battle_info.main_gun = 0
    battle_info.damage_log_team.clear()
    battle_info.total_damag_team.clear()

def mainGunUpdate():
    return main_gun(total_damage(), total_damage_team())
    BigWorld.callback(0.5, lambda: mainGunUpdate())    


#@registerEvent(Battle, 'afterCreate')        
#def afterCreate(self):
#    mainGunUpdate()
        
            
@xvm.export('mainGun', deterministic=False)
def mainGun():
    battle_info.main_gun = mainGunUpdate()
    return battle_info.main_gun

  • Нравится 1

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

from constants import VEHICLE_HIT_FLAGS
import BigWorld
from Avatar import PlayerAvatar
from Vehicle import Vehicle
from gui.Scaleform.Battle import Battle
from xfw import *

def IsLive(vehicleID):
    player = BigWorld.player()
    vehicles = player.arena.vehicles
    return vehicles[vehicleID]['isAlive'] if player is not None else None


def IsFriendly(vehicleID):
    player = BigWorld.player()
    vehicles = player.arena.vehicles
    return vehicles[player.playerVehicleID]['team'] == vehicles[vehicleID]['team'] if player is not None else None


def get_all_health():
    for vehicleID in BigWorld.entities.values():
        if type(vehicleID) is Vehicle:
            if IsLive(vehicleID.id) and not IsFriendly(vehicleID.id):
                battle_info.enemy_hp[vehicleID.id] = vehicleID.health


def damage_helth(self, newHealth, attackerID, attackReasonID):
    if self.id in battle_info.enemy_hp.keys():
        if attackerID == BigWorld.player().playerVehicleID:
            damage = battle_info.enemy_hp[self.id] - newHealth
            in_arr = False
            for key, value in battle_info.damage_log.items():
                if self.id == value['id']:
                    value['damage'] = value['damage'] + damage
                    in_arr = True

            if not in_arr:
                battle_info.damage_log[len(battle_info.damage_log)] = {'id': self.id, 'damage': damage}
        battle_info.enemy_hp[self.id] = newHealth
    get_all_health()


def damage_helth_team(self, newHealth, attackerID, attackReasonID):
    damaged = []
    if self.id in battle_info.enemy_hp.keys():
        if attackerID in battle_info.total_damag_team.keys():
            battle_info.total_damag_team[attackerID] += battle_info.enemy_hp[self.id] - newHealth
        else:
            battle_info.total_damag_team[attackerID] = battle_info.enemy_hp[self.id] - newHealth
        for vehicleID in BigWorld.entities.values():
            if type(vehicleID) is Vehicle:
                if not attackerID == BigWorld.player().playerVehicleID and IsFriendly(vehicleID.id):
                    for id, total_damag in battle_info.total_damag_team.items():
                        damaged.append(total_damag)
                    in_arr = False
                    for key, value in battle_info.damage_log_team.items():
                        if self.id == value['id']:
                            value['damage'] = max(damaged)
                            in_arr = True

                    if not in_arr:
                        battle_info.damage_log_team[len(battle_info.damage_log_team)] = {'id': self.id, 'damage': max(damaged)}
                        
        battle_info.enemy_hp[self.id] = newHealth
    get_all_health()
    
    
@registerEvent(PlayerAvatar, 'vehicle_onEnterWorld')
def vehicle_onEnterWorld(self, vehicle):
    PlayerAvatar.rezults = []
    get_all_health()


@registerEvent(PlayerAvatar, 'showShotResults')
def showShotResults(self, results):
    PlayerAvatar.rezults = results


@registerEvent(Vehicle, 'onHealthChanged')
def onHealthChanged(self, newHealth, attackerID, attackReasonID):
    damage_helth(self, newHealth, attackerID, attackReasonID)
    damage_helth_team(self, newHealth, attackerID, attackReasonID)
    
    
def total_damage():
    damage = 0
    for key, value in battle_info.damage_log.items():
        damage = damage + value['damage']
    return damage
    

def total_damage_team():
    for key, value in battle_info.damage_log_team.items():
        return value['damage']


class Battle_Info(object):
    
    def __init__(self):
        self.allyDetect = False
        self.enemy_hp = {}
        self.main_gun = 0
        self.damage_log = {}
        self.damage_log_team = {}
        self.total_damag_team = {}
        
battle_info = Battle_Info()
        
def main_guns(damage, damage_team):
    max_health = 0
    damagedAllies = []
    player = BigWorld.player()
    for vehicle, veh in player.arena.vehicles.iteritems():
        if not veh['team'] == player.team:
            max_health += player.arena.vehicles[vehicle]['vehicleType'].maxHealth

    for r in PlayerAvatar.rezults:
        vehicleID = r & 4294967295L
        flags = r >> 32 & 4294967295L
        if player.team == player.arena.vehicles[vehicleID]['team'] and player.playerVehicleID != vehicleID:
            if flags & (VEHICLE_HIT_FLAGS.IS_ANY_DAMAGE_MASK | VEHICLE_HIT_FLAGS.ATTACK_IS_DIRECT_PROJECTILE):
                damagedAllies.append(vehicleID)
    
    for vehicleID in damagedAllies:
        if player.arena.vehicles[vehicleID]['isAlive']:
            battle_info.allyDetect = True
    result = int(max(round(max_health * 0.2), 1000)) - damage
    if damage_team >= int(max(round(max_health * 0.2), 1000)) - damage:
        result = damage_team - damage
    if result <= 0:
        result = "<img src='img://gui/maps/icons/library/done.png' width='22' height='22' vspace='-3'>"
    return result
                             

def main_gun(damage, damage_team):
    player = BigWorld.player()
    if player.arena.guiType == 1:
        if not battle_info.allyDetect:
            result = main_guns(damage, damage_team)
        else:
            result = "<img src='img://gui/maps/icons/library/errorIcon.png' width='22' height='22' vspace='-4'>"
    else:
        result = "<img src='img://gui/maps/icons/library/errorIcon.png' width='22' height='22' vspace='-4'>"
    return result
    

@registerEvent(Battle, 'beforeDelete')
def beforeDelete(self):
    battle_info.allyDetect = False
    battle_info.enemy_hp.clear()
    battle_info.damage_log.clear()
    battle_info.main_gun = 0
    battle_info.damage_log_team.clear()
    battle_info.total_damag_team.clear()

def mainGunUpdate():
    return main_gun(total_damage(), total_damage_team())
    BigWorld.callback(0.5, lambda: mainGunUpdate())    


#@registerEvent(Battle, 'afterCreate')        
#def afterCreate(self):
#    mainGunUpdate()
        
            
@xvm.export('mainGun', deterministic=False)
def mainGun():
    battle_info.main_gun = mainGunUpdate()
    return battle_info.main_gun

 

Спасибо:) Работает.

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах
(редактировалось)

все, я требую премиум статус :)


только код конечно ооочень говяный :ok:

в релиз выкатить не дадут

Изменено пользователем Ekspoint

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

 

 

from xfw import * добавь
добавил..., но значение выводится один раз, в начале боя и висит без обновления :hmm:  

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах
(редактировалось)

добавил..., но значение выводится один раз, в начале боя и висит без обновления :hmm:  

ой, забылЮ ща

import BigWorld
from gui.Scaleform.Battle import DebugPanel
from gui.Scaleform.Battle import Battle
from xfw import *

class Battle_Info(object):
 
    def __init__(self):
        self.fps = 0
        self.fpsRep = 0
        self.ping = 0

     
battle_info = Battle_Info()
            
def updateDebugInfo(self, ping, fps, lag, fpsReplay = -1):
    self.flashObject.visible = False # standart panel off
    battle_info.fpsRep = fpsReplay if fpsReplay != 0 and fpsReplay != -1 else ''
    battle_info.fps = '({fps})'.format(fps=fps) if fpsReplay != 0 and fpsReplay != -1 else fps
    battle_info.ping = ping


DebugPanel.updateDebugInfo = updateDebugInfo

class Update_Debug(object):
 
    def fps_update(self):
        return battle_info.fps
        BigWorld.callback(0, lambda: fps_update())

    def fpsRep_update(self):
        return battle_info.fpsRep
        BigWorld.callback(0, lambda: fpsRep_update())
   
    def ping_update(self):
        return battle_info.ping
        BigWorld.callback(0, lambda: ping_update())
   
   
update_debug = Update_Debug()

@xvm.export('DebugInfo', deterministic=False)
def DebugInfo():
    fps = update_debug.fps_update()
    ping = update_debug.ping_update()
    fpsRep = update_debug.fpsRep_update()
  
@registerEvent(Battle, 'beforeDelete')
def beforeDelete(self):
    battle_info.fps = 0
    battle_info.fpsRep = 0
    battle_info.ping = 0

боюсь спросить, а замена часиков картошки не нужно?

Изменено пользователем Ekspoint

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

@Ekspoint,либо лыжи у меня не те, либо снега нет..   сам толком не понимаю, но не обновляется и всё тут :(

import BigWorld
from gui.Scaleform.Battle import DebugPanel
from gui.Scaleform.Battle import Battle
from xfw import *

class Battle_Info(object):

    def __init__(self):
        self.fps = 0
        self.fpsRep = 0
        self.ping = 0

battle_info = Battle_Info()

def updateDebugInfo(self, ping, fps, lag, fpsReplay = -1):
    self.flashObject.visible = False # standart panel off
    battle_info.fpsRep = fpsReplay if fpsReplay != 0 and fpsReplay != -1 else ''
    battle_info.fps = '({fps})'.format(fps=fps) if fpsReplay != 0 and fpsReplay != -1 else fps
    battle_info.ping = ping

DebugPanel.updateDebugInfo = updateDebugInfo

class Update_Debug(object):
 
    def fps_update(self):
        return battle_info.fps
        BigWorld.callback(0, lambda: fps_update())

    def fpsRep_update(self):
        return battle_info.fpsRep
        BigWorld.callback(0, lambda: fpsRep_update())
   
    def ping_update(self):
        return battle_info.ping
        BigWorld.callback(0, lambda: ping_update())

update_debug = Update_Debug()

@xvm.export('DebugInfo', deterministic=False)
def DebugInfo():
    fps = update_debug.fps_update()
    ping = update_debug.ping_update()
    fpsRep = update_debug.fpsRep_update()
    return fps
    # тут выполняй что нужно

@registerEvent(Battle, 'beforeDelete')
def beforeDelete(self):
    battle_info.fps = 0
    battle_info.fpsRep = 0
    battle_info.ping = 0 

 

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

@Ekspoint,либо лыжи у меня не те, либо снега нет..   сам толком не понимаю, но не обновляется и всё тут :(

import BigWorld
from gui.Scaleform.Battle import DebugPanel
from gui.Scaleform.Battle import Battle
from xfw import *

class Battle_Info(object):

    def __init__(self):
        self.fps = 0
        self.fpsRep = 0
        self.ping = 0

battle_info = Battle_Info()

def updateDebugInfo(self, ping, fps, lag, fpsReplay = -1):
    self.flashObject.visible = False # standart panel off
    battle_info.fpsRep = fpsReplay if fpsReplay != 0 and fpsReplay != -1 else ''
    battle_info.fps = '({fps})'.format(fps=fps) if fpsReplay != 0 and fpsReplay != -1 else fps
    battle_info.ping = ping

DebugPanel.updateDebugInfo = updateDebugInfo

class Update_Debug(object):
 
    def fps_update(self):
        return battle_info.fps
        BigWorld.callback(0, lambda: fps_update())

    def fpsRep_update(self):
        return battle_info.fpsRep
        BigWorld.callback(0, lambda: fpsRep_update())
   
    def ping_update(self):
        return battle_info.ping
        BigWorld.callback(0, lambda: ping_update())

update_debug = Update_Debug()

@xvm.export('DebugInfo', deterministic=False)
def DebugInfo():
    fps = update_debug.fps_update()
    ping = update_debug.ping_update()
    fpsRep = update_debug.fpsRep_update()
    return fps
    # тут выполняй что нужно

@registerEvent(Battle, 'beforeDelete')
def beforeDelete(self):
    battle_info.fps = 0
    battle_info.fpsRep = 0
    battle_info.ping = 0 

 

логи скинь

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

боюсь спросить, а замена часиков картошки не нужно?

Если не сложно. Лишним не будет:)

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

логи

не вижу я там ничего критического..  xvm.log

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

не вижу я там ничего критического..  attachicon.gifxvm.log

а питон?

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

Создайте аккаунт или войдите в него для комментирования

Вы должны быть пользователем, чтобы оставить комментарий

Создать аккаунт

Зарегистрируйтесь для получения аккаунта. Это просто!

Зарегистрировать аккаунт

Войти

Уже зарегистрированы? Войдите здесь.

Войти сейчас


  • Сейчас на странице   0 пользователей

    Нет пользователей, просматривающих эту страницу

×