### SDK Installation
Source: https://docs.wotstat.info/guide/integrations/wotstat-widgets/data-provider
Instructions on how to install the wotstat-widgets-sdk using npm or bun, and how to include it via a script tag.
```APIDOC
## SDK Installation
### Description
Provides instructions for adding the `wotstat-widgets-sdk` to your project.
### Methods
**Using npm:**
```bash
npm add -D wotstat-widgets-sdk
```
**Using bun:**
```bash
bun add -D wotstat-widgets-sdk
```
**Using a script tag:**
```html
```
```
--------------------------------
### Install WOTStat Widgets SDK using npm or bun
Source: https://docs.wotstat.info/guide/integrations/wotstat-widgets/remote-control
This snippet shows how to install the WOTStat Widgets SDK using either npm or bun package managers. It adds the SDK as a development dependency.
```sh
$ npm add -D wotstat-widgets-sdk
```
```sh
$ bun add -D wotstat-widgets-sdk
```
--------------------------------
### Example Meta.xml for Quick Demount Mod
Source: https://docs.wotstat.info/guide/first-steps/introduction
Provides a concrete example of a meta.xml file for a specific mod, 'Quick demount'. This illustrates how to fill in the details for the mod's ID, version, display name, and a brief description of its functionality.
```xml
panikaxa.quick_demount
2.1.0
Quick demount
Мод предоставляет возможность при нажатии правой кнопки мыши на слоте оборудования выбрать из контекстного меню танк, на котором установлено данное оборудование и автоматически демонтировать его с выбранного танка.
```
--------------------------------
### Python: Setup Game Settings and Event Listener
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
This function sets up game view settings and registers an event listener for application initialization. It defines view settings for the 'PiercingMainView' and listens for the `AppLifeCycleEvent.INITIALIZED` event to load the view when the battle namespace is initialized.
```python
def setup():
settingsViewSettings = ViewSettings(
MY_FIRST_MOD_PIERCING_MAIN_VIEW,
PiercingMainView,
"my.first_mod.PiercingMainView.swf",
WindowLayer.WINDOW,
None,
ScopeTemplates.DEFAULT_SCOPE,
)
g_entitiesFactories.addSettings(settingsViewSettings)
def onAppInitialized(event):
if event.ns == APP_NAME_SPACE.SF_BATTLE:
app = ServicesLocator.appLoader.getApp(event.ns) # type: AppEntry
app.loadView(SFViewLoadParams(MY_FIRST_MOD_PIERCING_MAIN_VIEW))
g_eventBus.addListener(events.AppLifeCycleEvent.INITIALIZED, onAppInitialized, EVENT_BUS_SCOPE.GLOBAL)
```
--------------------------------
### Example Python Code
Source: https://docs.wotstat.info/guide/first-steps/environment/as3
An example of a Python script for a WOT mod, HelloWorldWindow.py. This file would contain the implementation of mod features or UI elements using Python, likely interacting with game APIs.
```python
from gui.Scaleform.framework.managers.utils import ClientUIRoot
def create_hello_world_window():
print("Creating Hello World Window...")
# Example: Instantiate a UI element
# window = SomeUIElement()
# return window
# Example usage within the mod framework
# if __name__ == "__main__":
# create_hello_world_window()
```
--------------------------------
### Example AS3 Code
Source: https://docs.wotstat.info/guide/first-steps/environment/as3
An example of an ActionScript 3 (AS3) source file, HelloWorldWindow.as. This file would contain the core logic for a graphical user interface element or mod functionality written in AS3.
```actionscript
package my.first_mod {
import flash.display.Sprite;
public class HelloWorldWindow extends Sprite {
public function HelloWorldWindow() {
// Constructor logic here
trace("Hello World Window initialized!");
}
}
}
```
--------------------------------
### Markdown Link Example
Source: https://docs.wotstat.info/guide/other/edit-docs
Explains how to create hyperlinks in Markdown, with the text to display and the URL.
```markdown
[Текст ссылки](https://example.com)
```
--------------------------------
### Markdown Tip Block Example
Source: https://docs.wotstat.info/guide/other/edit-docs
Illustrates how to create highlighted blocks for different types of information in Markdown, such as tips, warnings, and collapsible details.
```markdown
::: tip СОВЕТ
Это блок с подсветкой для советов.
:::
::: warning ВНИМАНИЕ
Это блок с подсветкой для предупреждений.
:::
::: details ПОДРОБНЕЕ
Это блок с возможностью сворачивания.
:::
```
--------------------------------
### Initialize custom mod functionality in Python
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
This Python script serves as the entry point for a custom game mod. It imports and calls the `setup` function from the `PiercingMainView` module, ensuring that the custom UI element is initialized when the mod is loaded. It also defines a `MOD_VERSION` constant.
```python
from .my_first_mod.PiercingMainView import setup as setupPiercingMainView
MOD_VERSION = '{{VERSION}}'
def init():
setupPiercingMainView()
```
--------------------------------
### Markdown Ordered List Example
Source: https://docs.wotstat.info/guide/other/edit-docs
Demonstrates how to create ordered (numbered) lists in Markdown.
```markdown
1. Первый пункт
2. Второй пункт
```
--------------------------------
### Markdown Header Example
Source: https://docs.wotstat.info/guide/other/edit-docs
Shows how to create different levels of headers in Markdown using hash symbols.
```markdown
# Заголовок 1 уровня
## Заголовок 2 уровня
### Заголовок 3 уровня
```
--------------------------------
### Markdown Image Sizing Example
Source: https://docs.wotstat.info/guide/other/edit-docs
Shows how to specify the display size of an image in Markdown using attributes.
```markdown
{width=400}
```
--------------------------------
### Accessing Battle Data with IBattleSessionProvider (Python)
Source: https://docs.wotstat.info/articles/how-to-work-with-di
Demonstrates using the IBattleSessionProvider interface to get information about the current battle session and subscribe to battle-related events. It also shows how to check if a replay is currently playing.
```python
from helpers import dependency
from skeletons.gui.battle_session import IBattleSessionProvider
sessionProvider = dependency.instance(IBattleSessionProvider) # type: IBattleSessionProvider
sessionProvider.onBattleSessionStart += lambda: print("Battle started")
sessionProvider.onBattleSessionStop += lambda: print("Battle ended")
print(sessionProvider.isReplayPlaying) # Check if replay is playing
```
--------------------------------
### Extension Registration API
Source: https://docs.wotstat.info/guide/integrations/wotstat-widgets/data-provider
This section describes how to register a new extension using the BigWorld API. It provides a Python code example for registering an extension named 'exampleExtension'.
```APIDOC
## Register Extension
### Description
Registers a new extension with the BigWorld WOTStat data provider.
### Method
N/A (Python function call)
### Endpoint
N/A
### Parameters
None
### Request Example
```python
demo_extension = BigWorld.wotstat_dataProvider.registerExtension('exampleExtension')
```
### Response
Returns an extension object.
### Response Example
```python
# demo_extension object representing the registered extension
```
```
--------------------------------
### Initialize Mod and Subscribe to Hangar Load
Source: https://docs.wotstat.info/guide/first-steps/environment/python
This Python function initializes the mod by printing a welcome message and subscribing to the hangar space creation event. It ensures that the mod's initial setup is performed upon game launch.
```python
def init():
print("[MY_FIRST_MOD] Hello, World! Mod version is %s" % MOD_VERSION)
# Подписываемся на загрузку ангара
hangarSpace.onSpaceCreate += onHangarSpaceCreate
```
--------------------------------
### Manage State in Python
Source: https://docs.wotstat.info/guide/integrations/wotstat-widgets/data-provider
Demonstrates how to create, get, and set values for a state within a registered extension. States represent data that can be tracked and modified. The `createState` function takes a path and an initial value, while `getValue` retrieves the current value and `setValue` updates it.
```python
# регистрация состояния
state = demo_extension.createState(['demo', 'state'], 'Hello World!')
# получить текущее значение
value = state.getValue()
# установить новое значение
state.setValue('Hello World, Again!')
```
--------------------------------
### Create Settings Templates with Dictionary (Python)
Source: https://docs.wotstat.info/guide/integrations/mods-settings
This example shows how to manually create a settings template using Python dictionaries. It mirrors the functionality of the `templates` API, defining elements like checkboxes, dropdowns, sliders, numeric steppers, and range sliders with their respective properties and values.
```python
from gui.modsSettingsApi import g_modsSettingsApi, templates
template = {
'modDisplayName': 'Mod Name',
'enabled': True,
'column1': [
{
'type': 'CheckBox',
'text': 'Demo CheckBox',
'varName': 'var-name-checkbox',
'value': True,
'tooltip': '{HEADER}Tooltip{/HEADER}{BODY}text{/BODY}',
},
{
'type': 'Dropdown',
'text': 'Demo Dropdown',
'varName': 'var-name-dropdown',
'options': [
{ 'label': 'Variant 1' },
{ 'label': 'Variant 2' },
{ 'label': 'Variant 3' }
],
'value': 0,
'tooltip': '{HEADER}Tooltip{/HEADER}{BODY}text{/BODY}',
'button': {
'width': 30, 'height': 23, 'offsetTop': 0, 'offsetLeft': 0,
'iconSource': '../maps/icons/buttons/sound.png',
'iconOffsetTop': 0, 'iconOffsetLeft': 1,
},
'width': 200
},
{
'type': 'Slider',
'text': 'Demo Slider',
'varName': 'var-name-slider',
'value': 5,
'minimum': 1,
'maximum': 15,
'snapInterval': 1,
'format': '{{value}}',
},
{
'type': 'NumericStepper',
'text': 'Demo NumericStepper',
'varName': 'var-name-stepper',
'value': 5,
'minimum': 1,
'maximum': 15,
'snapInterval': 0.1,
},
{
'type': 'RangeSlider',
'text': 'Demo range slider',
'varName': 'var-name-slider',
'value': [20, 50],
'minimum': 0,
'maximum': 100,
'snapInterval': 1,
'divisionLabelStep': 50,
'minRangeDistance': 10,
'divisionStep': 50,
'divisionLabelPostfix': '',
},
]
}
```
--------------------------------
### Get Installed Slot Index (Basic)
Source: https://docs.wotstat.info/guide/first-steps/first-mod
This Python function retrieves the index of an installed module (like equipment) for a given vehicle. It iterates through the currently installed optional devices. It does not account for modules in alternate equipment sets.
```python
from helpers import dependency
from skeletons.gui.shared import IItemsCache
def getInstalledSlotIdx(vehicleCD, moduleIntCD):
itemsCache = dependency.instance(IItemsCache) # type: IItemsCache
# Получаем танк по intCD
vehicle = itemsCache.items.getItemByCD(vehicleCD)
# Перебираем установленное оборудование
for idx, op in enumerate(vehicle.optDevices.installed):
if op is not None and moduleIntCD == op.intCD:
return idx
return -1
print(getInstalledSlotIdx(4737, 25593)) # подставьте свои значения
```
--------------------------------
### State Management API
Source: https://docs.wotstat.info/guide/integrations/wotstat-widgets/data-provider
This section details how to create, get, and set values for states within a registered extension. It includes Python examples for state management.
```APIDOC
## State Management
### Description
Manages state values within a registered extension. Allows for creation, retrieval, and updating of state data.
### Method
N/A (Python function calls)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
# Registering a state
state = demo_extension.createState(['demo', 'state'], 'Hello World!')
# Getting the current value
value = state.getValue()
# Setting a new value
state.setValue('Hello World, Again!')
```
### Response
- **value** (any) - The current value of the state.
### Response Example
```python
# After getValue(): 'Hello World!' or 'Hello World, Again!' depending on previous operations.
```
```
--------------------------------
### WidgetSDK Initialization and Status
Source: https://docs.wotstat.info/guide/integrations/wotstat-widgets/data-provider
This section covers the initialization of the WidgetSDK and how to subscribe to connection status changes with the game.
```APIDOC
## WidgetSDK Initialization and Status
### Description
Initializes the SDK and subscribes to connection status updates.
### Method
JavaScript (client-side)
### Code Example
```javascript
import { WidgetSDK } from 'wotstat-widgets-sdk'
// Initialize the SDK
const sdk = new WidgetSDK()
// Subscribe to status changes (waiting for game to open)
sdk.onStatusChange(status => console.log(status))
```
```
--------------------------------
### Get Installed Vehicles (Python)
Source: https://docs.wotstat.info/guide/first-steps/first-mod
Retrieves a list of all vehicles in the player's garage and their installed equipment. It uses the `IItemsCache` and `REQ_CRITERIA.INVENTORY` to fetch vehicle data. The output is a set of `Vehicle` objects, which can then be processed to extract specific information like vehicle ID and name.
```python
from helpers import dependency
from skeletons.gui.shared import IItemsCache
from gui.shared.utils.requesters import REQ_CRITERIA
itemsCache = dependency.instance(IItemsCache) # type: IItemsCache
inventoryVehicles = itemsCache.items.getVehicles(REQ_CRITERIA.INVENTORY)
installedVehicles = last_OptDeviceItemContextMenu._getItem().getInstalledVehicles(inventoryVehicles.itervalues())
print([(v.intCD, v.userName) for v in installedVehicles])
```
--------------------------------
### Initialize Mod and Display Window (Python)
Source: https://docs.wotstat.info/guide/first-steps/environment/as3
This Python script serves as the main entry point for a mod. It initializes the mod, registers the 'HelloWorldWindow' view using the setup function, and subscribes to the hangar space creation event. Upon hangar creation, it displays system messages and shows the 'HelloWorldWindow'.
```python
from gui import SystemMessages
from helpers import dependency
from skeletons.gui.shared.utils import IHangarSpace
from .my_first_mod.HelloWorldWindow import setup, show
MOD_VERSION = '{{VERSION}}'
# получаем ссылку на IHangarSpace
hangarSpace = dependency.instance(IHangarSpace) # type: IHangarSpace
# Мод загрузился
def init():
print("[MY_FIRST_MOD] Hello, World! Mod version is %s" % MOD_VERSION)
# Регистрируем SWF файл
setup()
# Подписываемся на загрузку ангара
hangarSpace.onSpaceCreate += onHangarSpaceCreate
def onHangarSpaceCreate():
# Отписываемся от загрузки ангара
hangarSpace.onSpaceCreate -= onHangarSpaceCreate
# Выводим уведомление в ангаре
SystemMessages.pushMessage(
text='Привет мир! Версия мода: %s' % MOD_VERSION,
type=SystemMessages.SM_TYPE.InformationHeader,
messageData={ 'header': 'MY_FIRST_MOD' }
)
# Отображаем окно в интерфейсе
show()
```
--------------------------------
### TankSetupGroupsId Enum Usage
Source: https://docs.wotstat.info/guide/first-steps/first-mod
Illustrates the usage of TankSetupGroupsId enum in Python for specifying equipment groups when changing setups. Examples show its use with CHANGE_SETUP_EQUIPMENTS_INDEX, differentiating between equipment/shells and optional devices/boosters.
```python
from post_progression_common import TankSetupGroupsId
...
def _getEquipmentsPairs(self, groupID):
...
if groupID == TankSetupGroupsId.EQUIPMENT_AND_SHELLS:
elif groupID == TankSetupGroupsId.OPTIONAL_DEVICES_AND_BOOSTERS:
...
```
--------------------------------
### Подписка на onGunMarkerStateChanged и обновление текста в Python
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
Подписывается на событие onGunMarkerStateChanged в конструкторе __init__ и обновляет текст отображения результатов выстрела в методе onGunMarkerStateChanged. Использует рассчитанные значения для определения цвета текста.
```python
... class PiercingMainView(View):
...
def __init__(self, *args, **kwargs):
...
self.sessionProvider.shared.crosshair.onGunMarkerStateChanged += self.onGunMarkerStateChanged
def onGunMarkerStateChanged(self, markerType, hitPoint, direction, collision):
result = self.computeResult(hitPoint, direction, collision)
if result is None: return self.as_setText('', 0)
piercing, totalArmor, isRicochet, hitArmor, jetLoss, piercingPowerRandomization = result
if piercing is None: return self.as_setText('', 0)
if totalArmor is None: return self.as_setText('%d/-' % round(piercing), GREEN_COLOR)
# Уменьшаем пробитие на потери кумулятивной струи
realPiercing = piercing * max(0, (1 - jetLoss))
targetColor = GREEN_COLOR
if isRicochet: targetColor = RICOCHET_COLOR
elif not hitArmor: targetColor = NOT_ARMOR_COLOR
elif realPiercing <= 0.0: targetColor = RED_COLOR
elif totalArmor <= 0.0: targetColor = GREEN_COLOR
else:
prob = penetrationProbability(realPiercing, totalArmor, piercingPowerRandomization)
if prob <= 0: targetColor = RED_COLOR
elif prob >= 1: targetColor = GREEN_COLOR
# Преобразование цвета от SOFT_RED_COLOR к SOFT_GREEN_COLOR в зависимости от вероятности пробития
else:
targetColor = lerpColor(
SOFT_RED_COLOR,
SOFT_GREEN_COLOR,
prob,
mid_L_shift=+10.0,
mid_C_boost=1.15
)
self.as_setText('%d/%d' % (round(realPiercing), round(totalArmor)), targetColor)
```
--------------------------------
### Get Installed Slot Index (Advanced with Sets)
Source: https://docs.wotstat.info/guide/first-steps/first-mod
An improved Python function to find the slot index of a module, capable of searching across different equipment sets. It first checks the current set, and if not found, switches to the alternate set and checks again. It uses asynchronous operations and callbacks.
```python
from adisp import adisp_process, adisp_async
from helpers import dependency
from skeletons.gui.shared import IItemsCache
from post_progression_common import TankSetupGroupsId
from gui.shared.gui_items.items_actions import factory as ActionsFactory
@adisp_async
@adisp_process
def getInstalledSlotIdx(vehicleCD, moduleIntCD, callback):
itemsCache = dependency.instance(IItemsCache) # type: IItemsCache
# Функция проверки текущего комплекта, если наши, вызываем callback и возвращаем True
def checkDevices():
vehicle = itemsCache.items.getItemByCD(vehicleCD)
for idx, op in enumerate(vehicle.optDevices.installed):
if op is not None and moduleIntCD == op.intCD:
callback(idx)
return True
return False
# Проверяем текущий комплект, если True, значит нашли и можно выйти из фукнции
if checkDevices(): return
# Меняем комплект на противоположный
vehicle = itemsCache.items.getItemByCD(vehicleCD)
targetIndex = 1 if vehicle.optDevices.setupLayouts.layoutIndex == 0 else 0
action = ActionsFactory.getAction(
ActionsFactory.CHANGE_SETUP_EQUIPMENTS_INDEX,
vehicle,
TankSetupGroupsId.OPTIONAL_DEVICES_AND_BOOSTERS,
targetIndex
)
# Дожидаемся смены
result = yield ActionsFactory.asyncDoAction(action)
# Проверяем новый текущий комплект
if checkDevices(): return
# Ничего не нашли
callback(-1)
@adisp_process
def getSlot():
res = yield getInstalledSlotIdx(4737, 25593) # подставьте свои значения
print(res)
getSlot()
```
--------------------------------
### Markdown Table Example
Source: https://docs.wotstat.info/guide/other/edit-docs
Provides an example of creating a table in Markdown with headers and rows.
```markdown
| Заголовок 1 | Заголовок 2 |
| ----------- | ----------- |
| Ячейка 1 | Ячейка 2 |
```
--------------------------------
### Инициализация и вызов вычислений
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
Эта функция инициализирует вычисления, проверяет столкновения и получает информацию о снаряде и игроке. Она является точкой входа для всех дальнейших расчетов.
```python
from Vehicle import Vehicle as VehicleEntity
from DestructibleEntity import DestructibleEntity
from AvatarInputHandler import gun_marker_ctrl
shotResultResolver = gun_marker_ctrl.createShotResultResolver()
def computeResult(hitPoint, direction, collision):
if not collision: return
entity = collision.entity
if not isinstance(entity, (VehicleEntity, DestructibleEntity)): return
player = BigWorld.player()
if player is None: return
vDesc = player.getVehicleDescriptor()
shell = vDesc.shot.shell
shellKind = shell.kind
ppDesc = vDesc.shot.piercingPower
maxDist = vDesc.shot.maxDistance
piercingPowerRandomization = shell.piercingPowerRandomization
dist = (hitPoint - player.getOwnVehiclePosition()).length
# Актуальное пробитие на дистанции
distPiercingPower = shotResultResolver._computePiercingPowerAtDist(ppDesc, dist, maxDist, 1)
# Список всех столкновений с колиженом танка
collisionsDetails = shotResultResolver._getAllCollisionDetails(hitPoint, direction, entity)
if collisionsDetails is None: return
totalArmor, isRicochet, hitArmor, jetLoss = computeTotalEffectiveArmor(hitPoint, collision, direction, shell)
print("Result: dist=%.1f distPP=%.1f armor=%.1f ricochet=%s hitArmor=%s jetLoss=%.2f" % (
```
--------------------------------
### Initialize and Inject Stylesheets (JavaScript)
Source: https://docs.wotstat.info/guide/integrations/wotstat-widgets/data-provider
Use the 'injectStylesheet' or 'setupStyles' functions from the 'wotstat-widgets-sdk' to apply CSS styles to your widgets. 'injectStylesheet' adds CSS to the head, while 'setupStyles' does the same and adds handlers for style updates based on query parameters.
```javascript
import { injectStylesheet, setupStyles } from 'wotstat-widgets-sdk'
// Injects CSS code into the document's head
injectStylesheet()
// Injects CSS code into the document's head and adds handlers for style updates via query parameters.
// Calling injectStylesheet() is not required when using setupStyles().
setupStyles()
```
--------------------------------
### Load custom SWF view in Python
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
This Python script sets up a custom Scaleform view for the game. It defines a `PiercingMainView` class that inherits from `View` and registers it with the game's entity factory. The `setup()` function listens for application initialization events and loads the `PiercingMainView.swf` when the battle interface is ready. It requires access to `wulf`, `gui.Scaleform`, and `gui.shared` modules.
```python
from frameworks.wulf import WindowLayer
from gui.Scaleform.framework.entities.View import View
from gui.Scaleform.framework import g_entitiesFactories, ScopeTemplates, ViewSettings
from gui.shared import events, EVENT_BUS_SCOPE, g_eventBus
MY_FIRST_MOD_PIERCING_MAIN_VIEW = "MY_FIRST_MOD_PIERCING_MAIN_VIEW"
class PiercingMainView(View):
def __init__(self, *args, **kwargs):
super(PiercingMainView, self).__init__(*args, **kwargs)
def setup():
settingsViewSettings = ViewSettings(
MY_FIRST_MOD_PIERCING_MAIN_VIEW,
PiercingMainView,
"my.first_mod.PiercingMainView.swf",
WindowLayer.TOP_WINDOW,
None,
ScopeTemplates.VIEW_SCOPE,
)
g_entitiesFactories.addSettings(settingsViewSettings)
def onAppInitialized(event):
if event.ns == APP_NAME_SPACE.SF_BATTLE:
app = ServicesLocator.appLoader.getApp(event.ns) # type: AppEntry
app.loadView(SFViewLoadParams(MY_FIRST_MOD_PIERCING_MAIN_VIEW))
g_eventBus.addListener(events.AppLifeCycleEvent.INITIALIZED, onAppInitialized, EVENT_BUS_SCOPE.GLOBAL)
```
--------------------------------
### Полный код my_first_mod/PiercingMainView.py
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
Представляет собой полный исходный код файла PiercingMainView.py, включающий все добавленные и изменённые функции, классы и импорты.
```python
import typing
import math
from ProjectileMover import EntityCollisionData
from frameworks.wulf import WindowLayer
from gui.Scaleform.framework.entities.View import View
from gui.Scaleform.framework import g_entitiesFactories, ScopeTemplates, ViewSettings
from gui.shared import events, EVENT_BUS_SCOPE, g_eventBus
from gui.app_loader.settings import APP_NAME_SPACE
class PiercingMainView(View):
...
def as_setText(self, text, color):
self.flashObject.as_setText(text, color)
def penetrationProbability(piercing, totalArmor, piercingPowerRandomization):
P0 = float(piercing)
A = float(totalArmor)
x = float(piercingPowerRandomization)
# Допустимый диапазон пробития
L = P0 * (1.0 - x)
U = P0 * (1.0 + x)
k = 3
sigma = (x * P0) / k
mu = P0
# Быстрые случаи
if A <= L: return 1.0
if A >= U: return 0.0
# Стандартная нормальная CDF через erf
def Phi(z): return 0.5 * (1.0 + math.erf(z / math.sqrt(2.0)))
zL = (L - mu) / sigma
zU = (U - mu) / sigma
zA = (A - mu) / sigma
denom = Phi(zU) - Phi(zL)
if denom <= 1e-15: return 1.0 if A <= mu else 0.0
p = (Phi(zU) - Phi(zA)) / denom
# Численная обрезка
if p < 0.0: p = 0.0
if p > 1.0: p = 1.0
return p
RICOCHET_COLOR = 0xa85dfc
NOT_ARMOR_COLOR = 0xbbbbbb
GREEN_COLOR = 0x00FF00
RED_COLOR = 0xFF0000
SOFT_GREEN_COLOR = 0x48f32c
SOFT_RED_COLOR = 0xf32c2c
```
--------------------------------
### Initialize WidgetSDK and subscribe to status changes
Source: https://docs.wotstat.info/guide/integrations/wotstat-widgets/data-provider
This JavaScript code initializes the WidgetSDK and sets up a listener for changes in the connection status with the game. It logs the status whenever it changes.
```js
import { WidgetSDK } from 'wotstat-widgets-sdk'
// инициализация SDK
const sdk = new WidgetSDK()
// подписка на изменение статуса (ожидание открытия игры)
sdk.onStatusChange(status => console.log(status))
```
--------------------------------
### Example Insignia Alphabet Definition (XML)
Source: https://docs.wotstat.info/guide/integrations/user-customization
Provides an example structure for an insignia 'alphabet' XML file. This file defines the coordinates for rendering specific parts of an insignia texture. Each 'glyph' has a name and defines 'begin' and 'end' coordinates as percentages.
```xml
*
0.0 0.0
1.0 1.0
```
--------------------------------
### Интеграция функций расчёта брони и результатов в Python
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
Переносит функции computeTotalEffectiveArmor, computeResult и onGunMarkerStateChanged из PjOrion в класс PiercingMainView. Эти функции необходимы для расчёта характеристик попадания.
```python
... class PiercingMainView(View):
...
sessionProvider = dependency.descriptor(IBattleSessionProvider) # type: IBattleSessionProvider
def __init__(self, *args, **kwargs):
super(PiercingMainView, self).__init__(*args, **kwargs)
self.shotResultResolver = gun_marker_ctrl.createShotResultResolver() # type: gun_marker_ctrl._CrosshairShotResults
def computeTotalEffectiveArmor(self, hitPoint, collision, direction, shell):
...
def computeResult(self, hitPoint, direction, collision):
...
print("Result: dist=%.1f distPP=%.1f armor=%.1f ricochet=%s hitArmor=%s jetLoss=%.2f" % (
dist, distPiercingPower, totalArmor, isRicochet, hitArmor, jetLoss
))
return (distPiercingPower, totalArmor, isRicochet, hitArmor, jetLoss, piercingPowerRandomization)
```
--------------------------------
### Change Setup Equipment Index Action
Source: https://docs.wotstat.info/guide/first-steps/first-mod
Demonstrates how to use the CHANGE_SETUP_EQUIPMENTS_INDEX action from ActionsFactory in Python. This action is used to change the index of equipment within a vehicle's setup. It requires the vehicle object, a group ID, and the target index.
```python
@adisp.adisp_process
def __doChangeSetupIndex(self, groupId, currentIndex):
action = ActionsFactory.getAction(
ActionsFactory.CHANGE_SETUP_EQUIPMENTS_INDEX,
self.__getVehicle(),
groupId,
currentIndex
demountFromSetup, который вызывает)
...
```
--------------------------------
### Импорт функции lerpColor в Python
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
Импортирует функцию lerpColor из модуля color для использования в PiercingMainView. Эта функция необходима для плавного перехода между цветами при отображении вероятности пробития.
```python
from .color import lerpColor
...
```
--------------------------------
### Update Context Menu for Real Vehicles (Python)
Source: https://docs.wotstat.info/guide/first-steps/first-mod
Modifies the `_generateOptions` method of `OptDeviceItemContextMenu` to display actual vehicle names in the context menu when equipment is installed. It fetches installed vehicles and creates submenu items for dismounting equipment, enhancing user experience by showing relevant vehicle information.
```python
itemsCache = dependency.instance(IItemsCache) # type: IItemsCache
inventoryVehicles = itemsCache.items.getVehicles(REQ_CRITERIA.INVENTORY)
def new_generateOptionsRealVehicles(obj, *a, **k):
original_result = orig_generateOptions(obj, *a, **k)
installedVehicles = obj._getItem().getInstalledVehicles(inventoryVehicles.itervalues())
submenuItems = [
obj._makeItem('demountFrom:%d' % v.intCD, v.userName) for v in installedVehicles
]
original_result.append(obj._makeSeparator())
original_result.append(obj._makeItem('demount', 'Demount from:', optSubMenu=submenuItems))
return original_result
OptDeviceItemContextMenu._generateOptions = new_generateOptionsRealVehicles
```
--------------------------------
### Batch: Configure Build Settings
Source: https://docs.wotstat.info/guide/first-steps/environment/python
Configures essential build variables such as the path to the 7-Zip executable, the mod's name, and the entry point script. Ensure paths and names are correctly set for your project. The SEVENZIP variable should point to your 7-Zip installation, MOD_NAME follows the 'author.modname' format, and MOD_ENTRY is the main Python script.
```batch
rem ==== настройки ====
set "SEVENZIP=C:\ Program Files\7-Zip\7z.exe"
set "MOD_NAME=my.first-mod"
set "MOD_ENTRY=mod_myFirstMod.py"
```
--------------------------------
### Обёртка AS3 метода as_setText в Python
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
Добавляет функцию-обёртку над вызовом AS3 метода as_setText для установки текста и цвета в классе PiercingMainView. Эта функция упрощает взаимодействие с Flash объектом.
```python
class PiercingMainView(View):
...
def as_setText(self, text, color):
self.flashObject.as_setText(text, color)
```
--------------------------------
### Markdown Inline Code Example
Source: https://docs.wotstat.info/guide/other/edit-docs
Illustrates how to format inline code snippets within Markdown text.
```markdown
Вставки `кода`
```
--------------------------------
### Расчёт вероятности пробития (Python)
Source: https://docs.wotstat.info/guide/first-steps/first-ui-mod
Реализует функцию для вычисления вероятности пробития снаряда сквозь броню с учётом Гауссового распределения случайности пробития. Использует стандартную формулу для нормального распределения.
```python
def penetrationProbability(piercing, totalArmor, piercingPowerRandomization):
P0 = float(piercing)
A = float(totalArmor)
x = float(piercingPowerRandomization)
# Допустимый диапазон пробития
L = P0 * (1.0 - x)
U = P0 * (1.0 + x)
k = 3
sigma = (x * P0) / k
mu = P0
# Быстрые случаи
if A <= L: return 1.0
if A >= U: return 0.0
# Стандартная нормальная CDF через erf
def Phi(z): return 0.5 * (1.0 + math.erf(z / math.sqrt(2.0)))
zL = (L - mu) / sigma
zU = (U - mu) / sigma
zA = (A - mu) / sigma
denom = Phi(zU) - Phi(zL)
if denom <= 1e-15: return 1.0 if A <= mu else 0.0
p = (Phi(zU) - Phi(zA)) / denom
# Численная обрезка
if p < 0.0: p = 0.0
if p > 1.0: p = 1.0
return p
```
--------------------------------
### Markdown Image Example
Source: https://docs.wotstat.info/guide/other/edit-docs
Demonstrates how to embed images in Markdown, specifying the alt text and the image path.
```markdown

```