Помогите с режимом тд

  • Автор темы Автор темы aizek
  • Дата начала Дата начала

aizek

Пользователь
20 Мар 2017
30
0
Всем привет, я уже задавал вопрос: https://customgames.ru/forum/index.php?topic=1390.new#new . У меня почему то не появляются крипы
код addon_game_mod
-- Required files to be visible from anywhere
require( 'timers' )
require( 'barebones' )

GAME_ROUND = 0 - номер текущего раунда
MAX_ROUNDS = 5 - номер конечного раунда
ROUND_UNITS = 5 - кол-во юнитов на 1 раунде

function Precache( context )
PrecacheUnitByNameSync("example_unit_1", context)
--[[
This function is used to precache resources/units/items/abilities that will be needed
for sure in your game and that cannot or should not be precached asynchronously or
after the game loads.
See GameMode:PostLoadPrecache() in barebones.lua for more information
]]

print("[BAREBONES] Performing pre-load precache")

-- Particles can be precached individually or by folder
-- It it likely that precaching a single particle system will precache all of its children, but this may not be guaranteed
PrecacheResource("particle", "particles/econ/generic/generic_aoe_explosion_sphere_1/generic_aoe_explosion_sphere_1.vpcf", context)
PrecacheResource("particle_folder", "particles/test_particle", context)

-- Models can also be precached by folder or individually
-- PrecacheModel should generally used over PrecacheResource for individual models
PrecacheResource("model_folder", "particles/heroes/antimage", context)
PrecacheResource("model", "particles/heroes/viper/viper.vmdl", context)
PrecacheModel("models/heroes/viper/viper.vmdl", context)

-- Sounds can precached here like anything else
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_gyrocopter.vsndevts", context)

-- Entire items can be precached by name
-- Abilities can also be precached in this way despite the name
PrecacheItemByNameSync("example_ability", context)
PrecacheItemByNameSync("item_example_item", context)

-- Entire heroes (sound effects/voice/models/particles) can be precached with PrecacheUnitByNameSync
-- Custom units from npc_units_custom.txt can also have all of their abilities and precache{} blocks precached in this way
PrecacheUnitByNameSync("npc_dota_hero_ancient_apparition", context)
PrecacheUnitByNameSync("npc_dota_hero_enigma", context)
end

-- Create the game mode when we activate
function Activate()
GameRules.GameMode = GameMode()
GameRules.GameMode:InitGameMode()
end
function GameMode:OnGameInProgress() // Функция начнет выполняться, когда начнется матч( на часах будет 00:00 ).
local point = Entities:FindByName( nil, "spawnerino"):GetAbsOrigin() // Записываем в переменную 'point' координаты нашего спавнера 'spawnerino'
local waypoint = Entities:FindByName( nil, "way1") // Записываем в переменную 'waypoint' координаты первого бокса way1.
local return_time = 10 // Записываем в переменную значение '10'
Timers:CreateTimer(15, function() // Создаем таймер, который запустится через 15 секунд после начала матча и запустит следующую функцию.
GAME_ROUND = GAME_ROUND + 1 // Значение GAME_ROUND увеличивается на 1.
if GAME_ROUND == MAX_ROUNDS // Если GAME_ROUND равно MAX_ROUNDS, THEN переменная return_time получит нулевое значение.
return_time = nil
end
Say(nil,"Wave №" .. GAME_ROUND, false) // Выводим в чат сообщение 'Wave №', в конце к которому добавится значение GAME_ROUND.
for i=1, ROUND_UNITS do // Произведет нижние действия столько раз, сколько указано в ROUND_UNITS. То есть в нашем случае создаст 5 юнита.
local unit = CreateUnitByName( "example_unit_" .. GAME_ROUND, point + RandomVector( RandomFloat( 0, 200 ) ), true, nil, nil, DOTA_TEAM_GOODGUYS ) // Создаем юнита 'example_unit_', в конце к названию добавится 1,2,3,4 или 5, в зависимости от раунда, и в итоге получатся наши example_unit_1, example_unit_2 и т.д.. Юнит появится в векторе point + RandomVector( RandomFloat( 0, 200 ) ) - point - наша переменная, а рандомный вектор добавляется для того, чтобы мобы не появлялись в одной точке и не застревали. Мобы будут за силы света.
unit:SetInitialGoalEntity( waypoint ) // Посылаем мобов на наш way1, координаты которого мы записали в переменную 'waypoint'
end
return return_time // Возвращаем таймеру время, через которое он должен снова сработать. Когда пройдет последний раунд таймер получит значение 'nil' и выключится.
end)
end

код крипов npc_unit_custom
// Units File
"DOTAUnits"
{
"Version" "1"

//=================================================================================
// Creature: Gnoll_Assassin
//=================================================================================
"example_unit_1"
{
// General
//----------------------------------------------------------------
"Model" "models/creeps/neutral_creeps/n_creep_gnoll/n_creep_gnoll_frost.vmdl" // Model.
"BaseClass" "npc_dota_creature"
"SoundSet" "n_creep_Ranged"
"GameSoundsFile" "soundevents/game_sounds_creeps.vsndevts"
"Level" "1"
"ModelScale" ".9"

// Abilities
//----------------------------------------------------------------
"Ability1" "" // Ability 1
"Ability2" "" // Ability 2
"Ability3" "" // Ability 3
"Ability4" "" // Ability 4

// Armor
//----------------------------------------------------------------
"ArmorPhysical" "10" // Physical protection.

// Attack
//----------------------------------------------------------------
"AttackCapabilities" "DOTA_UNIT_CAP_RANGED_ATTACK"
"AttackDamageMin" "30" // Damage range min.
"AttackDamageMax" "36" // Damage range max.
"AttackRate" "1.6" // Speed of attack.
"AttackAnimationPoint" "0.4" // Normalized time in animation cycle to attack.
"AttackAcquisitionRange" "800" // Range within a target can be acquired.
"AttackRange" "500" // Range within a target can be attacked.
"ProjectileModel" "particles/neutral_fx/gnoll_base_attack.vpcf" // Particle system model for projectile.
"ProjectileSpeed" "1500" // Speed of projectile.

// Bounds
//----------------------------------------------------------------
"RingRadius" "40"
"HealthBarOffset" "170"

// Bounty
//----------------------------------------------------------------
"BountyXP" "24" // Experience earn.
"BountyGoldMin" "21" // Gold earned min.
"BountyGoldMax" "29" // Gold earned max.

// Movement
//----------------------------------------------------------------
"MovementCapabilities" "DOTA_UNIT_CAP_MOVE_GROUND"
"MovementSpeed" "300" // Speed.

// Status
//----------------------------------------------------------------
"StatusHealth" "75" // Base health.
"StatusHealthRegen" "0.5" // Health regeneration rate.
"StatusMana" "0" // Base mana.
"StatusManaRegen" "0.0" // Mana regeneration rate.

// Vision
//----------------------------------------------------------------
"VisionDaytimeRange" "400" // Range of vision during day light.
"VisionNighttimeRange" "400" // Range of vision at night time.

// Team
//----------------------------------------------------------------
"TeamName" "DOTA_TEAM_GOODGUYS" // Team name.
"CombatClassAttack" "DOTA_COMBAT_CLASS_ATTACK_PIERCE"
"CombatClassDefend" "DOTA_COMBAT_CLASS_DEFEND_BASIC"
"UnitRelationshipClass" "DOTA_NPC_UNIT_RELATIONSHIP_TYPE_DEFAULT"

// Creature Data
//----------------------------------------------------------------
"Creature"
{
//Level Up
"HPGain" "50"
"DamageGain" "2"
"ArmorGain" "0.25"
"MagicResistGain" "0.1"
"MoveSpeedGain" "1"
"BountyGain" "3"
"XPGain" "15"
}
}

"example_unit_2"
{
// General
//----------------------------------------------------------------
"Model" "models/creeps/neutral_creeps/n_creep_gnoll/n_creep_gnoll_frost.vmdl" // Model.
"BaseClass" "npc_dota_creature"
"SoundSet" "n_creep_Ranged"
"GameSoundsFile" "soundevents/game_sounds_creeps.vsndevts"
"Level" "1"
"ModelScale" "1.4"

// Abilities
//----------------------------------------------------------------
"Ability1" "" // Ability 1
"Ability2" "" // Ability 2
"Ability3" "" // Ability 3
"Ability4" "" // Ability 4

// Armor
//----------------------------------------------------------------
"ArmorPhysical" "10" // Physical protection.

// Attack
//----------------------------------------------------------------
"AttackCapabilities" "DOTA_UNIT_CAP_RANGED_ATTACK"
"AttackDamageMin" "30" // Damage range min.
"AttackDamageMax" "36" // Damage range max.
"AttackRate" "1.6" // Speed of attack.
"AttackAnimationPoint" "0.4" // Normalized time in animation cycle to attack.
"AttackAcquisitionRange" "800" // Range within a target can be acquired.
"AttackRange" "500" // Range within a target can be attacked.
"ProjectileModel" "particles/neutral_fx/gnoll_base_attack.vpcf" // Particle system model for projectile.
"ProjectileSpeed" "1500" // Speed of projectile.

// Bounds
//----------------------------------------------------------------
"RingRadius" "40"
"HealthBarOffset" "170"

// Bounty
//----------------------------------------------------------------
"BountyXP" "24" // Experience earn.
"BountyGoldMin" "21" // Gold earned min.
"BountyGoldMax" "29" // Gold earned max.

// Movement
//----------------------------------------------------------------
"MovementCapabilities" "DOTA_UNIT_CAP_MOVE_GROUND"
"MovementSpeed" "270" // Speed.

// Status
//----------------------------------------------------------------
"StatusHealth" "75" // Base health.
"StatusHealthRegen" "0.5" // Health regeneration rate.
"StatusMana" "0" // Base mana.
"StatusManaRegen" "0.0" // Mana regeneration rate.

// Vision
//----------------------------------------------------------------
"VisionDaytimeRange" "400" // Range of vision during day light.
"VisionNighttimeRange" "400" // Range of vision at night time.

// Team
//----------------------------------------------------------------
"TeamName" "DOTA_TEAM_GOODGUYS" // Team name.
"CombatClassAttack" "DOTA_COMBAT_CLASS_ATTACK_PIERCE"
"CombatClassDefend" "DOTA_COMBAT_CLASS_DEFEND_BASIC"
"UnitRelationshipClass" "DOTA_NPC_UNIT_RELATIONSHIP_TYPE_DEFAULT"

// Creature Data
//----------------------------------------------------------------
"Creature"
{
//Level Up
"HPGain" "50"
"DamageGain" "2"
"ArmorGain" "0.25"
"MagicResistGain" "0.1"
"MoveSpeedGain" "1"
"BountyGain" "3"
"XPGain" "15"
}
}

"example_unit_3"
{
// General
//----------------------------------------------------------------
"Model" "models/creeps/neutral_creeps/n_creep_gnoll/n_creep_gnoll_frost.vmdl" // Model.
"BaseClass" "npc_dota_creature"
"SoundSet" "n_creep_Ranged"
"GameSoundsFile" "soundevents/game_sounds_creeps.vsndevts"
"Level" "1"
"ModelScale" ".9"

// Abilities
//----------------------------------------------------------------
"Ability1" "" // Ability 1
"Ability2" "" // Ability 2
"Ability3" "" // Ability 3
"Ability4" "" // Ability 4

// Armor
//----------------------------------------------------------------
"ArmorPhysical" "10" // Physical protection.

// Attack
//----------------------------------------------------------------
"AttackCapabilities" "DOTA_UNIT_CAP_RANGED_ATTACK"
"AttackDamageMin" "30" // Damage range min.
"AttackDamageMax" "36" // Damage range max.
"AttackRate" "1.6" // Speed of attack.
"AttackAnimationPoint" "0.4" // Normalized time in animation cycle to attack.
"AttackAcquisitionRange" "800" // Range within a target can be acquired.
"AttackRange" "500" // Range within a target can be attacked.
"ProjectileModel" "particles/neutral_fx/gnoll_base_attack.vpcf" // Particle system model for projectile.
"ProjectileSpeed" "1500" // Speed of projectile.

// Bounds
//----------------------------------------------------------------
"RingRadius" "40"
"HealthBarOffset" "170"

// Bounty
//----------------------------------------------------------------
"BountyXP" "24" // Experience earn.
"BountyGoldMin" "21" // Gold earned min.
"BountyGoldMax" "29" // Gold earned max.

// Movement
//----------------------------------------------------------------
"MovementCapabilities" "DOTA_UNIT_CAP_MOVE_GROUND"
"MovementSpeed" "270" // Speed.

// Status
//----------------------------------------------------------------
"StatusHealth" "75" // Base health.
"StatusHealthRegen" "0.5" // Health regeneration rate.
"StatusMana" "0" // Base mana.
"StatusManaRegen" "0.0" // Mana regeneration rate.

// Vision
//----------------------------------------------------------------
"VisionDaytimeRange" "400" // Range of vision during day light.
"VisionNighttimeRange" "400" // Range of vision at night time.

// Team
//----------------------------------------------------------------
"TeamName" "DOTA_TEAM_GOODGUYS" // Team name.
"CombatClassAttack" "DOTA_COMBAT_CLASS_ATTACK_PIERCE"
"CombatClassDefend" "DOTA_COMBAT_CLASS_DEFEND_BASIC"
"UnitRelationshipClass" "DOTA_NPC_UNIT_RELATIONSHIP_TYPE_DEFAULT"

// Creature Data
//----------------------------------------------------------------
"Creature"
{
//Level Up
"HPGain" "50"
"DamageGain" "2"
"ArmorGain" "0.25"
"MagicResistGain" "0.1"
"MoveSpeedGain" "1"
"BountyGain" "3"
"XPGain" "15"
}
}

"example_unit_4"
{
// General
//----------------------------------------------------------------
"Model" "models/creeps/neutral_creeps/n_creep_gnoll/n_creep_gnoll_frost.vmdl" // Model.
"BaseClass" "npc_dota_creature"
"SoundSet" "n_creep_Ranged"
"GameSoundsFile" "soundevents/game_sounds_creeps.vsndevts"
"Level" "1"
"ModelScale" ".9"

// Abilities
//----------------------------------------------------------------
"Ability1" "" // Ability 1
"Ability2" "" // Ability 2
"Ability3" "" // Ability 3
"Ability4" "" // Ability 4

// Armor
//----------------------------------------------------------------
"ArmorPhysical" "10" // Physical protection.

// Attack
//----------------------------------------------------------------
"AttackCapabilities" "DOTA_UNIT_CAP_RANGED_ATTACK"
"AttackDamageMin" "30" // Damage range min.
"AttackDamageMax" "36" // Damage range max.
"AttackRate" "1.6" // Speed of attack.
"AttackAnimationPoint" "0.4" // Normalized time in animation cycle to attack.
"AttackAcquisitionRange" "800" // Range within a target can be acquired.
"AttackRange" "500" // Range within a target can be attacked.
"ProjectileModel" "particles/neutral_fx/gnoll_base_attack.vpcf" // Particle system model for projectile.
"ProjectileSpeed" "1500" // Speed of projectile.

// Bounds
//----------------------------------------------------------------
"RingRadius" "40"
"HealthBarOffset" "170"

// Bounty
//----------------------------------------------------------------
"BountyXP" "24" // Experience earn.
"BountyGoldMin" "21" // Gold earned min.
"BountyGoldMax" "29" // Gold earned max.

// Movement
//----------------------------------------------------------------
"MovementCapabilities" "DOTA_UNIT_CAP_MOVE_GROUND"
"MovementSpeed" "270" // Speed.

// Status
//----------------------------------------------------------------
"StatusHealth" "75" // Base health.
"StatusHealthRegen" "0.5" // Health regeneration rate.
"StatusMana" "0" // Base mana.
"StatusManaRegen" "0.0" // Mana regeneration rate.

// Vision
//----------------------------------------------------------------
"VisionDaytimeRange" "400" // Range of vision during day light.
"VisionNighttimeRange" "400" // Range of vision at night time.

// Team
//----------------------------------------------------------------
"TeamName" "DOTA_TEAM_GOODGUYS" // Team name.
"CombatClassAttack" "DOTA_COMBAT_CLASS_ATTACK_PIERCE"
"CombatClassDefend" "DOTA_COMBAT_CLASS_DEFEND_BASIC"
"UnitRelationshipClass" "DOTA_NPC_UNIT_RELATIONSHIP_TYPE_DEFAULT"

// Creature Data
//----------------------------------------------------------------
"Creature"
{
//Level Up
"HPGain" "50"
"DamageGain" "2"
"ArmorGain" "0.25"
"MagicResistGain" "0.1"
"MoveSpeedGain" "1"
"BountyGain" "3"
"XPGain" "15"
}
}

"example_unit_5"
{
// General
//----------------------------------------------------------------
"Model" "models/creeps/neutral_creeps/n_creep_gnoll/n_creep_gnoll_frost.vmdl" // Model.
"BaseClass" "npc_dota_creature"
"SoundSet" "n_creep_Ranged"
"GameSoundsFile" "soundevents/game_sounds_creeps.vsndevts"
"Level" "1"
"ModelScale" ".9"

// Abilities
//----------------------------------------------------------------
"Ability1" "" // Ability 1
"Ability2" "" // Ability 2
"Ability3" "" // Ability 3
"Ability4" "" // Ability 4

// Armor
//----------------------------------------------------------------
"ArmorPhysical" "10" // Physical protection.

// Attack
//----------------------------------------------------------------
"AttackCapabilities" "DOTA_UNIT_CAP_RANGED_ATTACK"
"AttackDamageMin" "30" // Damage range min.
"AttackDamageMax" "36" // Damage range max.
"AttackRate" "1.6" // Speed of attack.
"AttackAnimationPoint" "0.4" // Normalized time in animation cycle to attack.
"AttackAcquisitionRange" "800" // Range within a target can be acquired.
"AttackRange" "500" // Range within a target can be attacked.
"ProjectileModel" "particles/neutral_fx/gnoll_base_attack.vpcf" // Particle system model for projectile.
"ProjectileSpeed" "1500" // Speed of projectile.

// Bounds
//----------------------------------------------------------------
"RingRadius" "40"
"HealthBarOffset" "170"

// Bounty
//----------------------------------------------------------------
"BountyXP" "24" // Experience earn.
"BountyGoldMin" "21" // Gold earned min.
"BountyGoldMax" "29" // Gold earned max.

// Movement
//----------------------------------------------------------------
"MovementCapabilities" "DOTA_UNIT_CAP_MOVE_GROUND"
"MovementSpeed" "270" // Speed.

// Status
//----------------------------------------------------------------
"StatusHealth" "75" // Base health.
"StatusHealthRegen" "0.5" // Health regeneration rate.
"StatusMana" "0" // Base mana.
"StatusManaRegen" "0.0" // Mana regeneration rate.

// Vision
//----------------------------------------------------------------
"VisionDaytimeRange" "400" // Range of vision during day light.
"VisionNighttimeRange" "400" // Range of vision at night time.

// Team
//----------------------------------------------------------------
"TeamName" "DOTA_TEAM_GOODGUYS" // Team name.
"CombatClassAttack" "DOTA_COMBAT_CLASS_ATTACK_PIERCE"
"CombatClassDefend" "DOTA_COMBAT_CLASS_DEFEND_BASIC"
"UnitRelationshipClass" "DOTA_NPC_UNIT_RELATIONSHIP_TYPE_DEFAULT"

// Creature Data
//----------------------------------------------------------------
"Creature"
{
//Level Up
"HPGain" "50"
"DamageGain" "2"
"ArmorGain" "0.25"
"MagicResistGain" "0.1"
"MoveSpeedGain" "1"
"BountyGain" "3"
"XPGain" "15"
}
}
}
 
Последнее редактирование модератором:
Для начала, найди в barebones.lua функцию OnGameInProgress и удали от туда таймер.
function GameMode:OnGameInProgress()
print("[BAREBONES] The game has officially begun")

end

Затем возьми и вырежи тело функции OnGameInProgress из addon_game_mode.lua и вставь его в barebones.lua в ту же функцию OnGameInProgress. Ну и удали остатки от функции OnGameInProgress() (это её объявление и конец) из addon_game_mode.lua.

Чтобы тебе было понятнее, что я написал - объясню: у тебя в данный момент есть две одинаковые функции OnGameInProgress(). Одна в barebones.lua, другая в addon_game_mode.lua. Из-за того, что их две, не выполняется ни одна (либо какая-нибудь из них, точно не помню). Представь, что ты шел по тропе и на случай перекрестков у тебя был инструкция, куда свернуть. А тут тебе говорят одновременно пойти и налево и направо. Но ты же не электрон, который может одновременно в две двери влетать, верно? Тоже самое и здесь. Тебе надо избавиться от двойственности.

Как сделаешь это, отписывайся, что там дальше происходит.
 
Последнее редактирование модератором:
Ну вообщем все так и осталось, крипы из точки не идут. Все время после генерации карта пишет addon_game_mode.lua 5 = ????????
addon_game_mode тот который сейчас
-- Required files to be visible from anywhere
require( 'timers' )
require( 'barebones' )

GAME_ROUND = 0 - номер текущего раунда
MAX_ROUNDS = 5 - номер конечного раунда
ROUND_UNITS = 5 - кол-во юнитов на 1 раунде

function Precache( context )
PrecacheUnitByNameSync("example_unit_1", context)
--[[
This function is used to precache resources/units/items/abilities that will be needed
for sure in your game and that cannot or should not be precached asynchronously or
after the game loads.
See GameMode:PostLoadPrecache() in barebones.lua for more information
]]

print("[BAREBONES] Performing pre-load precache")

-- Particles can be precached individually or by folder
-- It it likely that precaching a single particle system will precache all of its children, but this may not be guaranteed
PrecacheResource("particle", "particles/econ/generic/generic_aoe_explosion_sphere_1/generic_aoe_explosion_sphere_1.vpcf", context)
PrecacheResource("particle_folder", "particles/test_particle", context)

-- Models can also be precached by folder or individually
-- PrecacheModel should generally used over PrecacheResource for individual models
PrecacheResource("model_folder", "particles/heroes/antimage", context)
PrecacheResource("model", "particles/heroes/viper/viper.vmdl", context)
PrecacheModel("models/heroes/viper/viper.vmdl", context)

-- Sounds can precached here like anything else
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_gyrocopter.vsndevts", context)

-- Entire items can be precached by name
-- Abilities can also be precached in this way despite the name
PrecacheItemByNameSync("example_ability", context)
PrecacheItemByNameSync("item_example_item", context)

-- Entire heroes (sound effects/voice/models/particles) can be precached with PrecacheUnitByNameSync
-- Custom units from npc_units_custom.txt can also have all of their abilities and precache{} blocks precached in this way
PrecacheUnitByNameSync("npc_dota_hero_ancient_apparition", context)
PrecacheUnitByNameSync("npc_dota_hero_enigma", context)
end

-- Create the game mode when we activate
function Activate()
GameRules.GameMode = GameMode()
GameRules.GameMode:InitGameMode()
end
барбонсы
print ('[BAREBONES] barebones.lua' )

-- GameRules Variables
ENABLE_HERO_RESPAWN = true -- Should the heroes automatically respawn on a timer or stay dead until manually respawned
UNIVERSAL_SHOP_MODE = false -- Should the main shop contain Secret Shop items as well as regular items
ALLOW_SAME_HERO_SELECTION = true -- Should we let people select the same hero as each other

HERO_SELECTION_TIME = 1.0 -- How long should we let people select their hero?
PRE_GAME_TIME = 0.0 -- How long after people select their heroes should the horn blow and the game start?
POST_GAME_TIME = 60.0 -- How long should we let people look at the scoreboard before closing the server automatically?
TREE_REGROW_TIME = 60.0 -- How long should it take individual trees to respawn after being cut down/destroyed?

GOLD_PER_TICK = 100 -- How much gold should players get per tick?
GOLD_TICK_TIME = 5 -- How long should we wait in seconds between gold ticks?

RECOMMENDED_BUILDS_DISABLED = false -- Should we disable the recommened builds for heroes (Note: this is not working currently I believe)
CAMERA_DISTANCE_OVERRIDE = 1134.0 -- How far out should we allow the camera to go? 1134 is the default in Dota

MINIMAP_ICON_SIZE = 1 -- What icon size should we use for our heroes?
MINIMAP_CREEP_ICON_SIZE = 1 -- What icon size should we use for creeps?
MINIMAP_RUNE_ICON_SIZE = 1 -- What icon size should we use for runes?

RUNE_SPAWN_TIME = 120 -- How long in seconds should we wait between rune spawns?
CUSTOM_BUYBACK_COST_ENABLED = true -- Should we use a custom buyback cost setting?
CUSTOM_BUYBACK_COOLDOWN_ENABLED = true -- Should we use a custom buyback time?
BUYBACK_ENABLED = false -- Should we allow people to buyback when they die?

DISABLE_FOG_OF_WAR_ENTIRELY = true -- Should we disable fog of war entirely for both teams?
USE_STANDARD_HERO_GOLD_BOUNTY = true -- Should we give gold for hero kills the same as in Dota, or allow those values to be changed?

USE_CUSTOM_TOP_BAR_VALUES = true -- Should we do customized top bar values or use the default kill count per team?
TOP_BAR_VISIBLE = true -- Should we display the top bar score/count at all?
SHOW_KILLS_ON_TOPBAR = true -- Should we display kills only on the top bar? (No denies, suicides, kills by neutrals) Requires USE_CUSTOM_TOP_BAR_VALUES

ENABLE_TOWER_BACKDOOR_PROTECTION = false -- Should we enable backdoor protection for our towers?
REMOVE_ILLUSIONS_ON_DEATH = false -- Should we remove all illusions if the main hero dies?
DISABLE_GOLD_SOUNDS = false -- Should we disable the gold sound when players get gold?

END_GAME_ON_KILLS = true -- Should the game end after a certain number of kills?
KILLS_TO_END_GAME_FOR_TEAM = 50 -- How many kills for a team should signify an end of game?

USE_CUSTOM_HERO_LEVELS = true -- Should we allow heroes to have custom levels?
MAX_LEVEL = 50 -- What level should we let heroes get to?
USE_CUSTOM_XP_VALUES = true -- Should we use custom XP values to level up heroes, or the default Dota numbers?

-- Fill this table up with the required XP per level if you want to change it
XP_PER_LEVEL_TABLE = {}
for i=1,MAX_LEVEL do
XP_PER_LEVEL_TABLE = i * 100
end

-- Generated from template
if GameMode == nil then
print ( '[BAREBONES] creating barebones game mode' )
GameMode = class({})
end

-- This function initializes the game mode and is called before anyone loads into the game
-- It can be used to pre-initialize any values/tables that will be needed later
function GameMode:InitGameMode()
GameMode = self
print('[BAREBONES] Starting to load Barebones gamemode...')

-- Setup rules
GameRules:SetHeroRespawnEnabled( ENABLE_HERO_RESPAWN )
GameRules:SetUseUniversalShopMode( UNIVERSAL_SHOP_MODE )
GameRules:SetSameHeroSelectionEnabled( ALLOW_SAME_HERO_SELECTION )
GameRules:SetHeroSelectionTime( HERO_SELECTION_TIME )
GameRules:SetPreGameTime( PRE_GAME_TIME)
GameRules:SetPostGameTime( POST_GAME_TIME )
GameRules:SetTreeRegrowTime( TREE_REGROW_TIME )
GameRules:SetUseCustomHeroXPValues ( USE_CUSTOM_XP_VALUES )
GameRules:SetGoldPerTick(GOLD_PER_TICK)
GameRules:SetGoldTickTime(GOLD_TICK_TIME)
GameRules:SetRuneSpawnTime(RUNE_SPAWN_TIME)
GameRules:SetUseBaseGoldBountyOnHeroes(USE_STANDARD_HERO_GOLD_BOUNTY)
GameRules:SetHeroMinimapIconScale( MINIMAP_ICON_SIZE )
GameRules:SetCreepMinimapIconScale( MINIMAP_CREEP_ICON_SIZE )
GameRules:SetRuneMinimapIconScale( MINIMAP_RUNE_ICON_SIZE )
print('[BAREBONES] GameRules set')

-- Listeners - Event Hooks
-- All of these events can potentially be fired by the game, though only the uncommented ones have had
-- Functions supplied for them.
ListenToGameEvent('dota_player_gained_level', Dynamic_Wrap(GameMode, 'OnPlayerLevelUp'), self)
ListenToGameEvent('dota_ability_channel_finished', Dynamic_Wrap(GameMode, 'OnAbilityChannelFinished'), self)
ListenToGameEvent('dota_player_learned_ability', Dynamic_Wrap(GameMode, 'OnPlayerLearnedAbility'), self)
ListenToGameEvent('entity_killed', Dynamic_Wrap(GameMode, 'OnEntityKilled'), self)
ListenToGameEvent('player_connect_full', Dynamic_Wrap(GameMode, 'OnConnectFull'), self)
ListenToGameEvent('player_disconnect', Dynamic_Wrap(GameMode, 'OnDisconnect'), self)
ListenToGameEvent('dota_item_purchased', Dynamic_Wrap(GameMode, 'OnItemPurchased'), self)
ListenToGameEvent('dota_item_picked_up', Dynamic_Wrap(GameMode, 'OnItemPickedUp'), self)
ListenToGameEvent('last_hit', Dynamic_Wrap(GameMode, 'OnLastHit'), self)
ListenToGameEvent('dota_non_player_used_ability', Dynamic_Wrap(GameMode, 'OnNonPlayerUsedAbility'), self)
ListenToGameEvent('player_changename', Dynamic_Wrap(GameMode, 'OnPlayerChangedName'), self)
ListenToGameEvent('dota_rune_activated_server', Dynamic_Wrap(GameMode, 'OnRuneActivated'), self)
ListenToGameEvent('dota_player_take_tower_damage', Dynamic_Wrap(GameMode, 'OnPlayerTakeTowerDamage'), self)
ListenToGameEvent('tree_cut', Dynamic_Wrap(GameMode, 'OnTreeCut'), self)
ListenToGameEvent('entity_hurt', Dynamic_Wrap(GameMode, 'OnEntityHurt'), self)
ListenToGameEvent('player_connect', Dynamic_Wrap(GameMode, 'PlayerConnect'), self)
ListenToGameEvent('dota_player_used_ability', Dynamic_Wrap(GameMode, 'OnAbilityUsed'), self)
ListenToGameEvent('game_rules_state_change', Dynamic_Wrap(GameMode, 'OnGameRulesStateChange'), self)
ListenToGameEvent('npc_spawned', Dynamic_Wrap(GameMode, 'OnNPCSpawned'), self)
ListenToGameEvent('dota_player_pick_hero', Dynamic_Wrap(GameMode, 'OnPlayerPickHero'), self)
ListenToGameEvent('dota_team_kill_credit', Dynamic_Wrap(GameMode, 'OnTeamKillCredit'), self)
ListenToGameEvent("player_reconnected", Dynamic_Wrap(GameMode, 'OnPlayerReconnect'), self)

-- Change random seed
local timeTxt = string.gsub(string.gsub(GetSystemTime(), ':', ''), '0','')
math.randomseed(tonumber(timeTxt))

-- Initialized tables for tracking state
self.vUserIds = {}
self.vSteamIds = {}
self.vBots = {}
self.vBroadcasters = {}

self.vPlayers = {}
self.vRadiant = {}
self.vDire = {}

self.nRadiantKills = 0
self.nDireKills = 0

self.bSeenWaitForPlayers = false

-- Commands can be registered for debugging purposes or as functions that can be called by the custom Scaleform UI
Convars:RegisterCommand( "command_example", Dynamic_Wrap(GameMode, 'ExampleConsoleCommand'), "A console command example", 0 )

print('[BAREBONES] Done loading Barebones gamemode!\n\n')
end

mode = nil

-- This function is called 1 to 2 times as the player connects initially but before they
-- have completely connected
function GameMode:PlayerConnect(keys)
print('[BAREBONES] PlayerConnect')
DeepPrintTable(keys)

if keys.bot == 1 then
-- This user is a Bot, so add it to the bots table
self.vBots[keys.userid] = 1
end
end

-- This function is called once when the player fully connects and becomes "Ready" during Loading
function GameMode:OnConnectFull(keys)
print ('[BAREBONES] OnConnectFull')
DeepPrintTable(keys)
GameMode:CaptureGameMode()

local entIndex = keys.index+1
-- The Player entity of the joining user
local ply = EntIndexToHScript(entIndex)

-- The Player ID of the joining player
local playerID = ply:GetPlayerID()

-- Update the user ID table with this user
self.vUserIds[keys.userid] = ply

-- Update the Steam ID table
self.vSteamIds[PlayerResource:GetSteamAccountID(playerID)] = ply

-- If the player is a broadcaster flag it in the Broadcasters table
if PlayerResource:IsBroadcaster(playerID) then
self.vBroadcasters[keys.userid] = 1
return
end
end

-- This function is called as the first player loads and sets up the GameMode parameters
function GameMode:CaptureGameMode()
if mode == nil then
-- Set GameMode parameters
mode = GameRules:GetGameModeEntity()
mode:SetRecommendedItemsDisabled( RECOMMENDED_BUILDS_DISABLED )
mode:SetCameraDistanceOverride( CAMERA_DISTANCE_OVERRIDE )
mode:SetCustomBuybackCostEnabled( CUSTOM_BUYBACK_COST_ENABLED )
mode:SetCustomBuybackCooldownEnabled( CUSTOM_BUYBACK_COOLDOWN_ENABLED )
mode:SetBuybackEnabled( BUYBACK_ENABLED )
mode:SetTopBarTeamValuesOverride ( USE_CUSTOM_TOP_BAR_VALUES )
mode:SetTopBarTeamValuesVisible( TOP_BAR_VISIBLE )
mode:SetUseCustomHeroLevels ( USE_CUSTOM_HERO_LEVELS )
mode:SetCustomHeroMaxLevel ( MAX_LEVEL )
mode:SetCustomXPRequiredToReachNextLevel( XP_PER_LEVEL_TABLE )

--mode:SetBotThinkingEnabled( USE_STANDARD_DOTA_BOT_THINKING )
mode:SetTowerBackdoorProtectionEnabled( ENABLE_TOWER_BACKDOOR_PROTECTION )

mode:SetFogOfWarDisabled(DISABLE_FOG_OF_WAR_ENTIRELY)
mode:SetGoldSoundDisabled( DISABLE_GOLD_SOUNDS )
mode:SetRemoveIllusionsOnDeath( REMOVE_ILLUSIONS_ON_DEATH )

self:OnFirstPlayerLoaded()
end
end

-- This is an example console command
function GameMode:ExampleConsoleCommand()
print( '******* Example Console Command ***************' )
local cmdPlayer = Convars:GetCommandClient()
if cmdPlayer then
local playerID = cmdPlayer:GetPlayerID()
if playerID ~= nil and playerID ~= -1 then
-- Do something here for the player who called this command
PlayerResource:ReplaceHeroWith(playerID, "npc_dota_hero_viper", 1000, 1000)
end
end
print( '*********************************************' )
end

--[[
This function should be used to set up Async precache calls at the beginning of the game. The Precache() function
in addon_game_mode.lua used to and may still sometimes have issues with client's appropriately precaching stuff.
If this occurs it causes the client to never precache things configured in that block.
In this function, place all of your PrecacheItemByNameAsync and PrecacheUnitByNameAsync. These calls will be made
after all players have loaded in, but before they have selected their heroes. PrecacheItemByNameAsync can also
be used to precache dynamically-added datadriven abilities instead of items. PrecacheUnitByNameAsync will
precache the precache{} block statement of the unit and all precache{} block statements for every Ability#
defined on the unit.
This function should only be called once. If you want to/need to precache more items/abilities/units at a later
time, you can call the functions individually (for example if you want to precache units in a new wave of
holdout).
]]
function GameMode:PostLoadPrecache()
print("[BAREBONES] Performing Post-Load precache")

end

--[[
This function is called once and only once as soon as the first player (almost certain to be the server in local lobbies) loads in.
It can be used to initialize state that isn't initializeable in InitGameMode() but needs to be done before everyone loads in.
]]
function GameMode:OnFirstPlayerLoaded()
print("[BAREBONES] First Player has loaded")
end

--[[
This function is called once and only once after all players have loaded into the game, right as the hero selection time begins.
It can be used to initialize non-hero player state or adjust the hero selection (i.e. force random etc)
]]
function GameMode:OnAllPlayersLoaded()
print("[BAREBONES] All Players have loaded into the game")
end

--[[
This function is called once and only once for every player when they spawn into the game for the first time. It is also called
if the player's hero is replaced with a new hero for any reason. This function is useful for initializing heroes, such as adding
levels, changing the starting gold, removing/adding abilities, adding physics, etc.
The hero parameter is the hero entity that just spawned in.
]]
function GameMode:OnHeroInGame(hero)
print("[BAREBONES] Hero spawned in game for first time -- " .. hero:GetUnitName())

-- Store a reference to the player handle inside this hero handle.
hero.player = PlayerResource:GetPlayer(hero:GetPlayerID())
-- Store the player's name inside this hero handle.
hero.playerName = PlayerResource:GetPlayerName(hero:GetPlayerID())
-- Store this hero handle in this table.
table.insert(self.vPlayers, hero)

-- This line for example will set the starting gold of every hero to 500 unreliable gold
hero:SetGold(500, false)

-- These lines will create an item and add it to the player, effectively ensuring they start with the item
local item = CreateItem("item_example_item", hero, hero)
hero:AddItem(item)
end

--[[
This function is called once and only once when the game completely begins (about 0:00 on the clock). At this point,
gold will begin to go up in ticks if configured, creeps will spawn, towers will become damageable etc. This function
is useful for starting any game logic timers/thinkers, beginning the first round, etc.
]]
function GameMode:OnGameInProgress()
print("[BAREBONES] The game has officially begun")

local point = Entities:FindByName( nil, "spawnerino"):GetAbsOrigin() // Записываем в переменную 'point' координаты нашего спавнера 'spawnerino'
local waypoint = Entities:FindByName( nil, "way1") // Записываем в переменную 'waypoint' координаты первого бокса way1.
local return_time = 10 // Записываем в переменную значение '10'
Timers:CreateTimer(15, function() // Создаем таймер, который запустится через 15 секунд после начала матча и запустит следующую функцию.
GAME_ROUND = GAME_ROUND + 1 // Значение GAME_ROUND увеличивается на 1.
if GAME_ROUND == MAX_ROUNDS // Если GAME_ROUND равно MAX_ROUNDS, THEN переменная return_time получит нулевое значение.
return_time = nil
end
Say(nil,"Wave №" .. GAME_ROUND, false) // Выводим в чат сообщение 'Wave №', в конце к которому добавится значение GAME_ROUND.
for i=1, ROUND_UNITS do // Произведет нижние действия столько раз, сколько указано в ROUND_UNITS. То есть в нашем случае создаст 5 юнита.
local unit = CreateUnitByName( "example_unit_" .. GAME_ROUND, point + RandomVector( RandomFloat( 0, 200 ) ), true, nil, nil, DOTA_TEAM_GOODGUYS ) // Создаем юнита 'example_unit_', в конце к названию добавится 1,2,3,4 или 5, в зависимости от раунда, и в итоге получатся наши example_unit_1, example_unit_2 и т.д.. Юнит появится в векторе point + RandomVector( RandomFloat( 0, 200 ) ) - point - наша переменная, а рандомный вектор добавляется для того, чтобы мобы не появлялись в одной точке и не застревали. Мобы будут за силы света.
unit:SetInitialGoalEntity( waypoint ) // Посылаем мобов на наш way1, координаты которого мы записали в переменную 'waypoint'
end
return return_time // Возвращаем таймеру время, через которое
end

-- Cleanup a player when they leave
function GameMode:OnDisconnect(keys)
print('[BAREBONES] Player Disconnected ' .. tostring(keys.userid))
DeepPrintTable(keys)

local name = keys.name
local networkid = keys.networkid
local reason = keys.reason
local userid = keys.userid
end

-- The overall game state has changed
function GameMode:OnGameRulesStateChange(keys)
print("[BAREBONES] GameRules State Changed")
DeepPrintTable(keys)

local newState = GameRules:State_Get()
if newState == DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD then
self.bSeenWaitForPlayers = true
elseif newState == DOTA_GAMERULES_STATE_INIT then
Timers:RemoveTimer("alljointimer")
elseif newState == DOTA_GAMERULES_STATE_HERO_SELECTION then
local et = 6
if self.bSeenWaitForPlayers then
et = .01
end
Timers:CreateTimer("alljointimer", {
useGameTime = true,
endTime = et,
callback = function()
if PlayerResource:HaveAllPlayersJoined() then
GameMode:PostLoadPrecache()
GameMode:OnAllPlayersLoaded()
return
end
return 1
end})
elseif newState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
GameMode:OnGameInProgress()
end
end

-- An NPC has spawned somewhere in game. This includes heroes
function GameMode:OnNPCSpawned(keys)
print("[BAREBONES] NPC Spawned")
DeepPrintTable(keys)
local npc = EntIndexToHScript(keys.entindex)

if npc:IsRealHero() and npc.bFirstSpawned == nil then
npc.bFirstSpawned = true
GameMode:OnHeroInGame(npc)
end
end

-- An entity somewhere has been hurt. This event fires very often with many units so don't do too many expensive
-- operations here
function GameMode:OnEntityHurt(keys)
--print("[BAREBONES] Entity Hurt")
--DeepPrintTable(keys)
local entCause = EntIndexToHScript(keys.entindex_attacker)
local entVictim = EntIndexToHScript(keys.entindex_killed)
end

-- An item was picked up off the ground
function GameMode:OnItemPickedUp(keys)
print ( '[BAREBONES] OnItemPurchased' )
DeepPrintTable(keys)

local heroEntity = EntIndexToHScript(keys.HeroEntityIndex)
local itemEntity = EntIndexToHScript(keys.ItemEntityIndex)
local player = PlayerResource:GetPlayer(keys.PlayerID)
local itemname = keys.itemname
end

-- A player has reconnected to the game. This function can be used to repaint Player-based particles or change
-- state as necessary
function GameMode:OnPlayerReconnect(keys)
print ( '[BAREBONES] OnPlayerReconnect' )
DeepPrintTable(keys)
end

-- An item was purchased by a player
function GameMode:OnItemPurchased( keys )
print ( '[BAREBONES] OnItemPurchased' )
DeepPrintTable(keys)

-- The playerID of the hero who is buying something
local plyID = keys.PlayerID
if not plyID then return end

-- The name of the item purchased
local itemName = keys.itemname

-- The cost of the item purchased
local itemcost = keys.itemcost

end

-- An ability was used by a player
function GameMode:OnAbilityUsed(keys)
print('[BAREBONES] AbilityUsed')
DeepPrintTable(keys)

local player = EntIndexToHScript(keys.PlayerID)
local abilityname = keys.abilityname
end

-- A non-player entity (necro-book, chen creep, etc) used an ability
function GameMode:OnNonPlayerUsedAbility(keys)
print('[BAREBONES] OnNonPlayerUsedAbility')
DeepPrintTable(keys)

local abilityname= keys.abilityname
end

-- A player changed their name
function GameMode:OnPlayerChangedName(keys)
print('[BAREBONES] OnPlayerChangedName')
DeepPrintTable(keys)

local newName = keys.newname
local oldName = keys.oldName
end

-- A player leveled up an ability
function GameMode:OnPlayerLearnedAbility( keys)
print ('[BAREBONES] OnPlayerLearnedAbility')
DeepPrintTable(keys)

local player = EntIndexToHScript(keys.player)
local abilityname = keys.abilityname
end

-- A channelled ability finished by either completing or being interrupted
function GameMode:OnAbilityChannelFinished(keys)
print ('[BAREBONES] OnAbilityChannelFinished')
DeepPrintTable(keys)

local abilityname = keys.abilityname
local interrupted = keys.interrupted == 1
end

-- A player leveled up
function GameMode:OnPlayerLevelUp(keys)
print ('[BAREBONES] OnPlayerLevelUp')
DeepPrintTable(keys)

local player = EntIndexToHScript(keys.player)
local level = keys.level
end

-- A player last hit a creep, a tower, or a hero
function GameMode:OnLastHit(keys)
print ('[BAREBONES] OnLastHit')
DeepPrintTable(keys)

local isFirstBlood = keys.FirstBlood == 1
local isHeroKill = keys.HeroKill == 1
local isTowerKill = keys.TowerKill == 1
local player = PlayerResource:GetPlayer(keys.PlayerID)
end

-- A tree was cut down by tango, quelling blade, etc
function GameMode:OnTreeCut(keys)
print ('[BAREBONES] OnTreeCut')
DeepPrintTable(keys)

local treeX = keys.tree_x
local treeY = keys.tree_y
end

-- A rune was activated by a player
function GameMode:OnRuneActivated (keys)
print ('[BAREBONES] OnRuneActivated')
DeepPrintTable(keys)

local player = PlayerResource:GetPlayer(keys.PlayerID)
local rune = keys.rune

end

-- A player took damage from a tower
function GameMode:OnPlayerTakeTowerDamage(keys)
print ('[BAREBONES] OnPlayerTakeTowerDamage')
DeepPrintTable(keys)

local player = PlayerResource:GetPlayer(keys.PlayerID)
local damage = keys.damage
end

-- A player picked a hero
function GameMode:OnPlayerPickHero(keys)
print ('[BAREBONES] OnPlayerPickHero')
DeepPrintTable(keys)

local heroClass = keys.hero
local heroEntity = EntIndexToHScript(keys.heroindex)
local player = EntIndexToHScript(keys.player)
end

-- A player killed another player in a multi-team context
function GameMode:OnTeamKillCredit(keys)
print ('[BAREBONES] OnTeamKillCredit')
DeepPrintTable(keys)

local killerPlayer = PlayerResource:GetPlayer(keys.killer_userid)
local victimPlayer = PlayerResource:GetPlayer(keys.victim_userid)
local numKills = keys.herokills
local killerTeamNumber = keys.teamnumber
end

-- An entity died
function GameMode:OnEntityKilled( keys )
print( '[BAREBONES] OnEntityKilled Called' )
DeepPrintTable( keys )

-- The Unit that was Killed
local killedUnit = EntIndexToHScript( keys.entindex_killed )
-- The Killing entity
local killerEntity = nil

if keys.entindex_attacker ~= nil then
killerEntity = EntIndexToHScript( keys.entindex_attacker )
end

-- Put code here to handle when an entity gets killed
end

и таймер
--[[
-- A timer running every second that starts immediately on the next frame, respects pauses
Timers:CreateTimer(function()
print ("Hello. I'm running immediately and then every second thereafter.")
return 1.0
end
)
-- A timer running every second that starts 5 seconds in the future, respects pauses
Timers:CreateTimer(5, function()
print ("Hello. I'm running 5 seconds after you called me and then every second thereafter.")
return 1.0
end
)
-- 10 second delayed, run once using gametime (respect pauses)
Timers:CreateTimer({
endTime = 10, -- when this timer should first execute, you can omit this if you want it to run first on the next frame
callback = function()
print ("Hello. I'm running 10 seconds after when I was started.")
end
})
-- 10 second delayed, run once regardless of pauses
Timers:CreateTimer({
useGameTime = false,
endTime = 10, -- when this timer should first execute, you can omit this if you want it to run first on the next frame
callback = function()
print ("Hello. I'm running 10 seconds after I was started even if someone paused the game.")
end
})
-- A timer running every second that starts after 2 minutes regardless of pauses
Timers:CreateTimer("uniqueTimerString3", {
useGameTime = false,
endTime = 120,
callback = function()
print ("Hello. I'm running after 2 minutes and then every second thereafter.")
return 1
end
})
-- A timer using the old style to repeat every second starting 5 seconds ahead
Timers:CreateTimer("uniqueTimerString3", {
useOldStyle = true,
endTime = GameRules:GetGameTime() + 5,
callback = function()
print ("Hello. I'm running after 5 seconds and then every second thereafter.")
return GameRules:GetGameTime() + 1
end
})
]]

TIMERS_THINK = 0.01

if Timers == nil then
print ( '[Timers] creating Timers' )
Timers = {}
Timers.__index = Timers
end

function Timers:new( o )
o = o or {}
setmetatable( o, Timers )
return o
end

function Timers:start()
Timers = self
self.timers = {}

local ent = Entities:CreateByClassname("info_target") -- Entities:FindByClassname(nil, 'CWorld')
ent:SetThink("Think", self, "timers", TIMERS_THINK)
end

function Timers:Think()
if GameRules:State_Get() >= DOTA_GAMERULES_STATE_POST_GAME then
return
end

-- Track game time, since the dt passed in to think is actually wall-clock time not simulation time.
local now = GameRules:GetGameTime()

-- Process timers
for k,v in pairs(Timers.timers) do
local bUseGameTime = true
if v.useGameTime ~= nil and v.useGameTime == false then
bUseGameTime = false
end
local bOldStyle = false
if v.useOldStyle ~= nil and v.useOldStyle == true then
bOldStyle = true
end

local now = GameRules:GetGameTime()
if not bUseGameTime then
now = Time()
end

if v.endTime == nil then
v.endTime = now
end
-- Check if the timer has finished
if now >= v.endTime then
-- Remove from timers list
Timers.timers[k] = nil

-- Run the callback
local status, nextCall = pcall(v.callback, GameRules:GetGameModeEntity(), v)

-- Make sure it worked
if status then
-- Check if it needs to loop
if nextCall then
-- Change its end time

if bOldStyle then
v.endTime = v.endTime + nextCall - now
else
v.endTime = v.endTime + nextCall
end

Timers.timers[k] = v
end

-- Update timer data
--self:UpdateTimerData()
else
-- Nope, handle the error
Timers:HandleEventError('Timer', k, nextCall)
end
end
end

return TIMERS_THINK
end

function Timers:HandleEventError(name, event, err)
print(err)

-- Ensure we have data
name = tostring(name or 'unknown')
event = tostring(event or 'unknown')
err = tostring(err or 'unknown')

-- Tell everyone there was an error
--Say(nil, name .. ' threw an error on event '..event, false)
--Say(nil, err, false)

-- Prevent loop arounds
if not self.errorHandled then
-- Store that we handled an error
self.errorHandled = true
end
end

function Timers:CreateTimer(name, args)
if type(name) == "function" then
args = {callback = name}
name = DoUniqueString("timer")
elseif type(name) == "table" then
args = name
name = DoUniqueString("timer")
elseif type(name) == "number" then
args = {endTime = name, callback = args}
name = DoUniqueString("timer")
end
if not args.callback then
print("Invalid timer created: "..name)
return
end


local now = GameRules:GetGameTime()
if args.useGameTime ~= nil and args.useGameTime == false then
now = Time()
end

if args.endTime == nil then
args.endTime = now
elseif args.useOldStyle == nil or args.useOldStyle == false then
args.endTime = now + args.endTime
end

Timers.timers[name] = args

return name
end

function Timers:RemoveTimer(name)
Timers.timers[name] = nil
end

function Timers:RemoveTimers(killAll)
local timers = {}

if not killAll then
for k,v in pairs(Timers.timers) do
if v.persist then
timers[k] = v
end
end
end

Timers.timers = timers
end

Timers:start()
остальное на карте как по иструкции есть, точка спавна и блоки с направлениями
 
Последнее редактирование модератором:
Теперь тебе надо перекинуть эти константы

Код:
GAME_ROUND = 0 - номер текущего раунда
 MAX_ROUNDS = 5 - номер конечного раунда
 ROUND_UNITS = 5 - кол-во юнитов на 1 раунде

Из addon_game_mode.lua к константам в файл barebones.lua. Ну то есть в первом их удалить, а во втором прописать либо над, либо под его константами (GameRules Variables).

И в следующий раз оформляй в спойлерах еще блоки кода, а то без них тяжело воспринимать код. И начни наконец скидывать логи консоли с ошибкой (не весь лог, а ток несколько строк до, с и после ошибки).
 
Я просто несколько без понятия где там ошибка, это консоль. С запуска карты до появления героя. Кстати после тех махинаций у меня добавились еще 3 ошибки с барбонсами в начале игры светятся. Ну я и рачина в кастомках ужас)
Код:
[  VConComm       ]: VConsole Connected.
[  VConComm       ]: ==========================================================
[  VConComm       ]: =============== VConsole Buffered Messages ===============
[  VConComm       ]: ==========================================================
[  General       ]: ChangeGameUIState: DOTA_GAME_UI_DOTA_INGAME -> DOTA_GAME_UI_STATE_DASHBOARD
[  Client        ]: CL: disconnect clicked disconnect button
[  Client        ]: CL: Server disconnected: 2: #GameUI_Disconnect_User
[  Server        ]: SV: Disconnect client 'aizek' from server(1): NETWORK_DISCONNECT_SHUTDOWN
[  Client        ]: CL: Disconnecting from server: #GameUI_Disconnect_User
[  HostStateManager   ]: CHostStateMgr::QueueNewRequest( Idle (levelload), 3 )
[  EngineServiceManager ]: SwitchToLoop levelload requested: id [3] addons []
[  Client        ]: CL: IGameSystem::LoopDeactivateAllSystems
[  General       ]: WriteSteamRemoteStorageFileAsync( "scripts/control_groups.txt" ) -> at 185.077
[  Server        ]: SV: IGameSystem::LoopDeactivateAllSystems
[  Host         ]: HO: IGameSystem::LoopDeactivateAllSystems
[  General       ]: Unloading custom UI:
[  Client        ]: CL: CGameRulesGameSystem::GameShutdown uninstalled game rules
[  Client        ]: CL: CGameRules::CGameRules destructed
[  General       ]: WriteSteamRemoteStorageFileAsync( "voice_ban.dt" ) -> at 185.384
[  Server        ]: SV: CGameRulesGameSystem::GameShutdown uninstalled game rules
[  Server        ]: SV: CGameRules::CGameRules destructed
[ W EngineServiceManager ]: Can't CEngineServiceMgr::UpdateAddons to multiple addons in tools mode, tools restricting to fire_arena
[ W General       ]: Failed to load image for cursor from resource\cursor\valve\ti5\cursor_inivisible.bmp: Couldn't open resource\cursor\valve\ti5\cursor_inivisible.bmp
[  General       ]: **** Unable to localize '#addon_game_name' on panel 'GameModeName'
[  General       ]: ChangeGameUIState: DOTA_GAME_UI_STATE_DASHBOARD -> DOTA_GAME_UI_STATE_LOADING_SCREEN
[  Client        ]: LoadingDisplay changed from NONE to LOADING (map="")
[  HostStateManager   ]: Idle (levelload)
[ W Panorama       ]: DispatchAsyncEvent backlog, failed to dispatch all this frame. Queue depth: 15471 (15473 input number was)
[  General       ]: CAsyncWriteInProgress::OnComplete( "scripts/control_groups.txt" ) -> Success at 185.507
[  General       ]: CAsyncWriteInProgress::OnComplete( "voice_ban.dt" ) -> Success at 185.507
[  Client        ]: CL: CLoopModeLevelLoad::MaybeSwitchToGameLoop switching to "game" loopmode with addons ()
[  EngineServiceManager ]: SwitchToLoop game requested: id [3] addons []
[  Server        ]: SV: maxplayers set to 1
[  General       ]: Initializing script VM...
[  General       ]: ...done
[ W Panorama       ]: DispatchAsyncEvent backlog, failed to dispatch all this frame. Queue depth: 12075 (15534 input number was)
[ W General       ]: CSwapChainBase::QueuePresentAndWait() looped for 24 iterations without a present event.
[ W General       ]: CSwapChainBase::QueuePresentAndWait() looped for 24 iterations without a present event.
[ W Panorama       ]: DispatchAsyncEvent backlog, failed to dispatch all this frame. Queue depth: 9208 (12668 input number was)
[ W Panorama       ]: DispatchAsyncEvent backlog, failed to dispatch all this frame. Queue depth: 2391 (9497 input number was)
[ W General       ]: CSwapChainBase::QueuePresentAndWait() looped for 23 iterations without a present event.
[  Server        ]: SV: Spawn Server: <empty>
[  Client        ]: CL: CWaitForGameServerStartupPrerequisite done waiting for server
[  Client        ]: CL: CCreateGameClientJob creating client connection to 'loopback'
[  Client        ]: CL: Connected to 'loopback'
[  Server        ]: SV: Sending server info to client 'aizek' at loopback
[  Server        ]: SV: WriteInitialSpawnGroups sending 1 groups
[  Client        ]: Game: "Dota 2"
[  Client        ]: Map: "<empty>"
[  Client        ]: Players: 1 (0 bots) / 1 humans
[  Client        ]: Build: 7447 (revision 3891026)
[  Client        ]: Server Number: 3
[  SignonState     ]: CL: CNetworkGameClient::ProcessServerInfo
[  General       ]: Initializing script VM...
[  General       ]: ...done
[  General       ]: ReadSteamRemoteStorageFile( bufOut, "voice_ban.dt" ) -> 0.000322 seconds
[  Client        ]: CL: CGameClientConnectPrerequisite connection succeeded
[  General       ]: ChangeGameUIState: DOTA_GAME_UI_STATE_LOADING_SCREEN -> DOTA_GAME_UI_STATE_DASHBOARD
[  Client        ]: LoadingDisplay changed from LOADING to NONE (map="<empty>")
[  Server        ]: SV: IGameSystem::LoopActivateAllSystems
[  Host         ]: HO: IGameSystem::LoopActivateAllSystems
[  Server        ]: SV: Game started
[  Client        ]: CL: IGameSystem::LoopActivateAllSystems
[  General       ]: ReadSteamRemoteStorageFile( bufOut, "scripts/control_groups.txt" ) -> 0.000323 seconds
[  SignonState     ]: CL: CNetworkGameClient::OnSwitchLoopModeFinished( game : success )
[  Server        ]: SV: Sending full update to client aizek (reason: initial update)
[  Client        ]: CL: Receiving uncompressed update from server
[  Client        ]: CL: Signon traffic "client": incoming 35.149 KB [7 pkts], outgoing 1.078 KB [6 pkts]
[ W General       ]: Encountered entity that cannot be used in portrait maps - info_player_start_dota
[  Console       ]: Loading custom game "fire_arena" with map "fire_arena_1"
[  HostStateManager   ]: CHostStateMgr::QueueNewRequest( Loading (fire_arena_1), 4 )
[  EngineServiceManager ]: SwitchToLoop levelload requested: id [4] addons [fire_arena]
[  Client        ]: CL: IGameSystem::LoopDeactivateAllSystems
[  General       ]: WriteSteamRemoteStorageFileAsync( "scripts/control_groups.txt" ) -> at 239.243
[  Client        ]: CL: Disconnecting from server: #GameUI_Disconnect_LoopDeactivate
[  Server        ]: SV: IGameSystem::LoopDeactivateAllSystems
[  Host         ]: HO: IGameSystem::LoopDeactivateAllSystems
[  Server        ]: SV: Disconnect client 'aizek' from server(1): NETWORK_DISCONNECT_SHUTDOWN
[  General       ]: WriteSteamRemoteStorageFileAsync( "voice_ban.dt" ) -> at 239.256
[  EngineServiceManager ]: Unmounting addon 'fire_arena'
[  EngineServiceManager ]: Mounting addon 'fire_arena'
[ W General       ]: Failed to load image for cursor from resource\cursor\valve\ti5\cursor_inivisible.bmp: Couldn't open resource\cursor\valve\ti5\cursor_inivisible.bmp
[  General       ]: **** Unable to localize '#addon_game_name' on panel 'GameModeName'
[  General       ]: ChangeGameUIState: DOTA_GAME_UI_STATE_DASHBOARD -> DOTA_GAME_UI_STATE_LOADING_SCREEN
[  Client        ]: LoadingDisplay changed from NONE to LOADING (map="")
[ W Panorama       ]: DispatchAsyncEvent backlog, failed to dispatch all this frame. Queue depth: 99 (661 input number was)
[  General       ]: CAsyncWriteInProgress::OnComplete( "scripts/control_groups.txt" ) -> Success at 239.308
[  General       ]: CAsyncWriteInProgress::OnComplete( "voice_ban.dt" ) -> Success at 239.308
[  Client        ]: CL: CLoopModeLevelLoad::MaybeSwitchToGameLoop switching to "game" loopmode with addons (fire_arena)
[  EngineServiceManager ]: SwitchToLoop game requested: id [4] addons [fire_arena]
[  Networking      ]: Network socket 'server' opened on port 27015
[  Server        ]: SV: maxplayers set to 64
[ W General       ]: Unknown Ability Target Flag Value: DOTA_UNIT_TARGET_FLAG_NO_INVIS!
[ W General       ]: Unknown Ability Target Flag Value: DOTA_UNIT_TARGET_FLAG_NOT_ATTACK_IMMUNE!
[ W General       ]: ILocalize::AddFile() failed to load file "resource/addon_english.txt".
[ W General       ]: ILocalize::AddFile() failed to load file "resource/addon_russian.txt".
[  General       ]: Initializing script VM...
[  General       ]: ...done
[  Server        ]: SV: Executing listen server config file
[  General       ]: S:Gamerules: entering state 'DOTA_GAMERULES_STATE_INIT'
[  Server        ]: SV: CGameRulesGameSystem::GameInit installed game rules
[ W ResourceSystem    ]: Error loading resource file "particles/rain_fx/econ_weather_aurora_j.vpcf_c" (Error: ERROR_FILEOPEN)
[ W SchemaSystemUtils  ]: WARNING: Schema upconversion occuring for large data (14kb): models/creeps/neutral_creeps/n_creep_black_dragon/n_creep_black_dragon.vphys
[ W SchemaSystemUtils  ]: WARNING: Schema upconversion occuring for large data (9kb): models/creeps/roshan/roshan.vphys
[  Server        ]: SV: Spawn Server: fire_arena_1
[  Server        ]: SV: Connection to Steam servers successful.
[  Server        ]: SV: VAC secure mode is activated.
[ W VScript       ]: Script not found (scripts/vscripts/tp.lua) 
[  VScript       ]: [Timers] creating Timers
[  Developer      ]: ...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: module 'barebones' not found:
[  Developer      ]: 	no field package.preload['barebones']scripts/vscripts/barebones.lua:50: '=' expected near 'ðàóíäà'
[  Developer      ]: stack traceback:
[  Developer      ]: 	[C]: in function 'require'
[  Developer      ]: 	...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: in main chunk
[ W VScript       ]: Script Runtime Error: ...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: module 'barebones' not found:
[ W VScript       ]: 	no field package.preload['barebones']scripts/vscripts/barebones.lua:50: '=' expected near 'ðàóíäà'
[ W VScript       ]: stack traceback:
[ W VScript       ]: 	[C]: in function 'require'
[ W VScript       ]: 	...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: in main chunk
[ W VScript       ]: Error running script named addon_game_mode
[  Client        ]: CL: CWaitForGameServerStartupPrerequisite done waiting for server
[  Client        ]: CL: CCreateGameClientJob creating client connection to 'loopback'
[  Client        ]: CL: Connected to 'loopback'
[  Server        ]: SV: Sending server info to client 'aizek' at loopback
[  Server        ]: SV: WriteInitialSpawnGroups sending 1 groups
[  Client        ]: Game: "Dota 2"
[  Client        ]: Map: "fire_arena_1"
[  Client        ]: Players: 1 (0 bots) / 64 humans
[  Client        ]: Build: 7447 (revision 3891026)
[  Client        ]: Server Number: 4
[  SignonState     ]: CL: CNetworkGameClient::ProcessServerInfo
[ W General       ]: Unknown Ability Target Flag Value: DOTA_UNIT_TARGET_FLAG_NO_INVIS!
[ W General       ]: Unknown Ability Target Flag Value: DOTA_UNIT_TARGET_FLAG_NOT_ATTACK_IMMUNE!
[ W General       ]: ILocalize::AddFile() failed to load file "resource/addon_english.txt".
[ W General       ]: ILocalize::AddFile() failed to load file "resource/addon_russian.txt".
[  General       ]: Initializing script VM...
[  General       ]: ...done
[  General       ]: C:Gamerules: entering state 'DOTA_GAMERULES_STATE_INIT'
[  Client        ]: CDOTA_Hud_Main::EventGameRulesStateChanged DOTA_GAMERULES_STATE_INIT
[  Client        ]: CDOTA_Hud_Main::DeleteGameEndScreen deleted GameEndContainer
[  Client        ]: CL: CGameRulesGameSystem::GameInit installed game rules
[  General       ]: ReadSteamRemoteStorageFile( bufOut, "voice_ban.dt" ) -> 0.000492 seconds
[  GCClient       ]: Received server welcome from GC.
[  General       ]: GC Connection established for server version 2001
[  Server        ]: SV: "aizek<1><[U:1:179624947]><>" STEAM USERID validated
[  Client        ]: CL: CGameClientConnectPrerequisite connection succeeded
[  General       ]: ChangeGameUIState: DOTA_GAME_UI_STATE_LOADING_SCREEN -> DOTA_GAME_UI_DOTA_INGAME
[  Server        ]: SV: IGameSystem::LoopActivateAllSystems
[  Host         ]: HO: IGameSystem::LoopActivateAllSystems
[  Server        ]: SV: 64 player server started
[  Server        ]: SV: addon='fire_arena'
[  Client        ]: CL: IGameSystem::LoopActivateAllSystems
[  General       ]: ReadSteamRemoteStorageFile( bufOut, "scripts/control_groups.txt" ) -> 0.000338 seconds
[ W General       ]: Failed to load image for cursor from resource\cursor\valve\ti5\cursor_inivisible.bmp: Couldn't open resource\cursor\valve\ti5\cursor_inivisible.bmp
[  HostStateManager   ]: Loading (fire_arena_1)
[  SignonState     ]: CL: CNetworkGameClient::OnSwitchLoopModeFinished( game : success )
[ W General       ]: EntSelectSpawnPoint: no info_player_start on level
[  Developer      ]: GetUserSetting: cvar 'cl_interpolate' unknown.
[  Server        ]: SV: Sending full update to client aizek (reason: initial update)
[  Client        ]: CL: Receiving uncompressed update from server
[  Client        ]: CL: Signon traffic "client": incoming 80.410 KB [8 pkts], outgoing 1.278 KB [9 pkts]
[ W Panorama       ]: DispatchAsyncEvent backlog, failed to dispatch all this frame. Queue depth: 740 (3190 input number was)
[  General       ]: customgamesetup_select_team - can only change team during setup phase
[  Server        ]: CDOTA_PlayerResource: Adding player SteamID 76561198139890675 to slot 0 FakeClient=0 preferred slot = -1
[  Server        ]: PR:OnFullyJoinedServer 0:[U:1:179624947]
[  Server        ]: PR:SetLeaverStatus 0:[U:1:179624947] DOTA_LEAVER_NONE
[  Server        ]: PR:SetConnectionState 0:[U:1:179624947] DOTA_CONNECTION_STATE_CONNECTED NETWORK_DISCONNECT_INVALID
[  General       ]: S:Gamerules: entering state 'DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP'
[  General       ]: C:Gamerules: entering state 'DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP'
[  Client        ]: LoadingDisplay changed from LOADING to CUSTOM_GAME_SETUP (map="fire_arena_1")
[  General       ]: **** Unable to localize '#addon_game_name' on panel 'GameModeNameLabel'
[  Client        ]: CDOTA_Hud_Main::EventGameRulesStateChanged DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP
[  Client        ]:  187: 0.842249 msec change 'OnTeamChanged()' on field m_iPlayerTeam(path=1/0/2) for ent (C_DOTA_PlayerResource) name=''
[  VConComm       ]: ==============================================================
[  VConComm       ]: =============== End VConsole Buffered Messages ===============
[  VConComm       ]: ==============================================================
[  General       ]: S:Gamerules: entering state 'DOTA_GAMERULES_STATE_HERO_SELECTION'
[  General       ]: C:Gamerules: entering state 'DOTA_GAMERULES_STATE_HERO_SELECTION'
[  Client        ]: LoadingDisplay changed from CUSTOM_GAME_SETUP to NONE (map="fire_arena_1")
[  Client        ]: CDOTA_Hud_Main::EventGameRulesStateChanged DOTA_GAMERULES_STATE_HERO_SELECTION
[  General       ]: **** Unable to localize '#DOTA_GameMode_15' on panel 'PreGame'
[  Server        ]: PR:SetPossibleHeroSelection 0:[U:1:179624947] npc_dota_hero_antimage(1)
[  Server        ]: PR:SetSelectedHero 0:[U:1:179624947] npc_dota_hero_antimage(1)
[  General       ]: S:Gamerules: entering state 'DOTA_GAMERULES_STATE_STRATEGY_TIME'
[  General       ]: C:Gamerules: entering state 'DOTA_GAMERULES_STATE_STRATEGY_TIME'
[  Client        ]: CDOTA_Hud_Main::EventGameRulesStateChanged DOTA_GAMERULES_STATE_STRATEGY_TIME
[  Workshop       ]: Requesting page 1 of items
[  Workshop       ]: Requesting page 1 of items
[  Workshop       ]: Requesting page 1 of items
[  General       ]: S:Gamerules: entering state 'DOTA_GAMERULES_STATE_WAIT_FOR_MAP_TO_LOAD'
[  General       ]: S:Gamerules: entering state 'DOTA_GAMERULES_STATE_PRE_GAME'
[  General       ]: m_flPreGameStartTime set to 17.57
[  General       ]: m_flStateTransitionTime set to 107.57
[  General       ]: C:Gamerules: entering state 'DOTA_GAMERULES_STATE_PRE_GAME'
[  Client        ]: CDOTA_Hud_Main::EventGameRulesStateChanged DOTA_GAMERULES_STATE_PRE_GAME
 
Последнее редактирование модератором:
Во первых, тебе пишут, что не могут найти tp.lua: Script not found (scripts/vscripts/tp.lua)
Вообще убери все то, что ты там делал с tp, чтобы не мешало разбираться с волнами.

Во вторых: ты зачем трогал в barebones то, что не просили трогать? Я про этот блок.
У тебя он не такой:
Код:
for i=1,MAX_LEVEL do
  XP_PER_LEVEL_TABLE = i * 100
end
И тебе на это и жалуются, потому что ошибку ты тут нарисовал.


И чего ты скинул только лог? А как же скинуть по новой addon-game и barebones?
 
Я просто несколько без понятия где там ошибка, это консоль.

Ошибки с lua кодом пишут розовым цветом и они же в игре отображаются красным.
Находишь первую строчку про lua (не беря во внимание tp, про него уже сказал):

[ Developer ]: ...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: module 'barebones' not found:

Пишут, что в addon_game_mode.lua на третье позиции (строчке) 3 модуль 'barebones' не найден. Если не найден, то либо ты его бредово подключил, либо в нем ошибка. Тебе как раз через двоеточие и поясняют, что в нем ошибка:

[ Developer ]: no field package.preload['barebones']scripts/vscripts/barebones.lua:50: '=' expected near 'ðàóíäà'

Пишут, что в barebones.lua на 50 позиции ожидается оператор "=" возле какой-то белеберды 'ðàóíäà'. Лезешь туда и находишь тот блок, про который я тебе писал выше.
Код:
XP_PER_LEVEL_TABLE = {}
for i=1,MAX_LEVEL do
	XP_PER_LEVEL_TABLE = i * 100
end
В нем ты самостоятельно сделал ранее ошибку, ибо в оригинале её нет.
XP_PER_LEVEL_TABLE = {} - это объявление таблицы, а далее идет её наполнение.
for i=1,MAX_LEVEL do - от первого, до максимального уровня сделать следующее
XP_PER_LEVEL_TABLE = i * 100 - здесь именно у тебя целиком таблицу приравнивают к некоторому числу, это неверно, потому что таблицу нельзя к числу приравнять, должно быть так:
Код:
XP_PER_LEVEL_TABLE[i] = i * 100
- здесь каждый элемент таблицы приравнивают к некоему числу (100, 200 и т.д.)

Все последующие сообщения указывают на эту же ошибку.[/code]
 
Последнее редактирование модератором:
Так, возможно у тебя там другая ошибка, потому что из-за того, что ты не выделил в блок кода свой баребонес в прошлый раз, вот это вот [ i ] форум воспринял как ВВ код для перехода на курсив.

Скинь по новой свой баребонес и addongame, только обязательно в блоке кода.
 
addon_game_mod
Код:
-- Required files to be visible from anywhere
require( 'timers' )
require( 'barebones' )

function Precache( context )
  PrecacheUnitByNameSync("example_unit_1", context)
  --[[
  This function is used to precache resources/units/items/abilities that will be needed
  for sure in your game and that cannot or should not be precached asynchronously or 
  after the game loads.
  See GameMode:PostLoadPrecache() in barebones.lua for more information
  ]]

  print("[BAREBONES] Performing pre-load precache")
  
  -- Particles can be precached individually or by folder
  -- It it likely that precaching a single particle system will precache all of its children, but this may not be guaranteed
  PrecacheResource("particle", "particles/econ/generic/generic_aoe_explosion_sphere_1/generic_aoe_explosion_sphere_1.vpcf", context)
  PrecacheResource("particle_folder", "particles/test_particle", context)

  -- Models can also be precached by folder or individually
  -- PrecacheModel should generally used over PrecacheResource for individual models
  PrecacheResource("model_folder", "particles/heroes/antimage", context)
  PrecacheResource("model", "particles/heroes/viper/viper.vmdl", context)
  PrecacheModel("models/heroes/viper/viper.vmdl", context)

  -- Sounds can precached here like anything else
  PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_gyrocopter.vsndevts", context)

  -- Entire items can be precached by name
  -- Abilities can also be precached in this way despite the name
  PrecacheItemByNameSync("example_ability", context)
  PrecacheItemByNameSync("item_example_item", context)

  -- Entire heroes (sound effects/voice/models/particles) can be precached with PrecacheUnitByNameSync
  -- Custom units from npc_units_custom.txt can also have all of their abilities and precache{} blocks precached in this way
  PrecacheUnitByNameSync("npc_dota_hero_ancient_apparition", context)
  PrecacheUnitByNameSync("npc_dota_hero_enigma", context)
end

-- Create the game mode when we activate
function Activate()
  GameRules.GameMode = GameMode()
  GameRules.GameMode:InitGameMode()
end
барбон
Код:
print ('[BAREBONES] barebones.lua' )

-- GameRules Variables
ENABLE_HERO_RESPAWN = true       -- Should the heroes automatically respawn on a timer or stay dead until manually respawned
UNIVERSAL_SHOP_MODE = false       -- Should the main shop contain Secret Shop items as well as regular items
ALLOW_SAME_HERO_SELECTION = true    -- Should we let people select the same hero as each other

HERO_SELECTION_TIME = 1.0       -- How long should we let people select their hero?
PRE_GAME_TIME = 0.0          -- How long after people select their heroes should the horn blow and the game start?
POST_GAME_TIME = 60.0          -- How long should we let people look at the scoreboard before closing the server automatically?
TREE_REGROW_TIME = 60.0         -- How long should it take individual trees to respawn after being cut down/destroyed?

GOLD_PER_TICK = 100           -- How much gold should players get per tick?
GOLD_TICK_TIME = 5           -- How long should we wait in seconds between gold ticks?

RECOMMENDED_BUILDS_DISABLED = false   -- Should we disable the recommened builds for heroes (Note: this is not working currently I believe)
CAMERA_DISTANCE_OVERRIDE = 1134.0    -- How far out should we allow the camera to go? 1134 is the default in Dota

MINIMAP_ICON_SIZE = 1          -- What icon size should we use for our heroes?
MINIMAP_CREEP_ICON_SIZE = 1       -- What icon size should we use for creeps?
MINIMAP_RUNE_ICON_SIZE = 1       -- What icon size should we use for runes?

RUNE_SPAWN_TIME = 120          -- How long in seconds should we wait between rune spawns?
CUSTOM_BUYBACK_COST_ENABLED = true   -- Should we use a custom buyback cost setting?
CUSTOM_BUYBACK_COOLDOWN_ENABLED = true -- Should we use a custom buyback time?
BUYBACK_ENABLED = false         -- Should we allow people to buyback when they die?

DISABLE_FOG_OF_WAR_ENTIRELY = true   -- Should we disable fog of war entirely for both teams?
USE_STANDARD_HERO_GOLD_BOUNTY = true  -- Should we give gold for hero kills the same as in Dota, or allow those values to be changed?

USE_CUSTOM_TOP_BAR_VALUES = true    -- Should we do customized top bar values or use the default kill count per team?
TOP_BAR_VISIBLE = true         -- Should we display the top bar score/count at all?
SHOW_KILLS_ON_TOPBAR = true       -- Should we display kills only on the top bar? (No denies, suicides, kills by neutrals) Requires USE_CUSTOM_TOP_BAR_VALUES

ENABLE_TOWER_BACKDOOR_PROTECTION = false -- Should we enable backdoor protection for our towers?
REMOVE_ILLUSIONS_ON_DEATH = false    -- Should we remove all illusions if the main hero dies?
DISABLE_GOLD_SOUNDS = false       -- Should we disable the gold sound when players get gold?

END_GAME_ON_KILLS = true        -- Should the game end after a certain number of kills?
KILLS_TO_END_GAME_FOR_TEAM = 50     -- How many kills for a team should signify an end of game?

USE_CUSTOM_HERO_LEVELS = true      -- Should we allow heroes to have custom levels?
MAX_LEVEL = 50             -- What level should we let heroes get to?
USE_CUSTOM_XP_VALUES = true       -- Should we use custom XP values to level up heroes, or the default Dota numbers?

GAME_ROUND = 0 - номер текущего раунда
 MAX_ROUNDS = 5 - номер конечного раунда
 ROUND_UNITS = 5 - кол-во юнитов на 1 раунд

-- Fill this table up with the required XP per level if you want to change it
XP_PER_LEVEL_TABLE = {}
for i=1,MAX_LEVEL do
	XP_PER_LEVEL_TABLE[i] = i * 100
end

-- Generated from template
if GameMode == nil then
	print ( '[BAREBONES] creating barebones game mode' )
	GameMode = class({})
end

-- This function initializes the game mode and is called before anyone loads into the game
-- It can be used to pre-initialize any values/tables that will be needed later
function GameMode:InitGameMode()
	GameMode = self
	print('[BAREBONES] Starting to load Barebones gamemode...')

	-- Setup rules
	GameRules:SetHeroRespawnEnabled( ENABLE_HERO_RESPAWN )
	GameRules:SetUseUniversalShopMode( UNIVERSAL_SHOP_MODE )
	GameRules:SetSameHeroSelectionEnabled( ALLOW_SAME_HERO_SELECTION )
	GameRules:SetHeroSelectionTime( HERO_SELECTION_TIME )
	GameRules:SetPreGameTime( PRE_GAME_TIME)
	GameRules:SetPostGameTime( POST_GAME_TIME )
	GameRules:SetTreeRegrowTime( TREE_REGROW_TIME )
	GameRules:SetUseCustomHeroXPValues ( USE_CUSTOM_XP_VALUES )
	GameRules:SetGoldPerTick(GOLD_PER_TICK)
	GameRules:SetGoldTickTime(GOLD_TICK_TIME)
	GameRules:SetRuneSpawnTime(RUNE_SPAWN_TIME)
	GameRules:SetUseBaseGoldBountyOnHeroes(USE_STANDARD_HERO_GOLD_BOUNTY)
	GameRules:SetHeroMinimapIconScale( MINIMAP_ICON_SIZE )
	GameRules:SetCreepMinimapIconScale( MINIMAP_CREEP_ICON_SIZE )
	GameRules:SetRuneMinimapIconScale( MINIMAP_RUNE_ICON_SIZE )
	print('[BAREBONES] GameRules set')

	-- Listeners - Event Hooks
	-- All of these events can potentially be fired by the game, though only the uncommented ones have had
	-- Functions supplied for them.
	ListenToGameEvent('dota_player_gained_level', Dynamic_Wrap(GameMode, 'OnPlayerLevelUp'), self)
	ListenToGameEvent('dota_ability_channel_finished', Dynamic_Wrap(GameMode, 'OnAbilityChannelFinished'), self)
	ListenToGameEvent('dota_player_learned_ability', Dynamic_Wrap(GameMode, 'OnPlayerLearnedAbility'), self)
	ListenToGameEvent('entity_killed', Dynamic_Wrap(GameMode, 'OnEntityKilled'), self)
	ListenToGameEvent('player_connect_full', Dynamic_Wrap(GameMode, 'OnConnectFull'), self)
	ListenToGameEvent('player_disconnect', Dynamic_Wrap(GameMode, 'OnDisconnect'), self)
	ListenToGameEvent('dota_item_purchased', Dynamic_Wrap(GameMode, 'OnItemPurchased'), self)
	ListenToGameEvent('dota_item_picked_up', Dynamic_Wrap(GameMode, 'OnItemPickedUp'), self)
	ListenToGameEvent('last_hit', Dynamic_Wrap(GameMode, 'OnLastHit'), self)
	ListenToGameEvent('dota_non_player_used_ability', Dynamic_Wrap(GameMode, 'OnNonPlayerUsedAbility'), self)
	ListenToGameEvent('player_changename', Dynamic_Wrap(GameMode, 'OnPlayerChangedName'), self)
	ListenToGameEvent('dota_rune_activated_server', Dynamic_Wrap(GameMode, 'OnRuneActivated'), self)
	ListenToGameEvent('dota_player_take_tower_damage', Dynamic_Wrap(GameMode, 'OnPlayerTakeTowerDamage'), self)
	ListenToGameEvent('tree_cut', Dynamic_Wrap(GameMode, 'OnTreeCut'), self)
	ListenToGameEvent('entity_hurt', Dynamic_Wrap(GameMode, 'OnEntityHurt'), self)
	ListenToGameEvent('player_connect', Dynamic_Wrap(GameMode, 'PlayerConnect'), self)
	ListenToGameEvent('dota_player_used_ability', Dynamic_Wrap(GameMode, 'OnAbilityUsed'), self)
	ListenToGameEvent('game_rules_state_change', Dynamic_Wrap(GameMode, 'OnGameRulesStateChange'), self)
	ListenToGameEvent('npc_spawned', Dynamic_Wrap(GameMode, 'OnNPCSpawned'), self)
	ListenToGameEvent('dota_player_pick_hero', Dynamic_Wrap(GameMode, 'OnPlayerPickHero'), self)
	ListenToGameEvent('dota_team_kill_credit', Dynamic_Wrap(GameMode, 'OnTeamKillCredit'), self)
	ListenToGameEvent("player_reconnected", Dynamic_Wrap(GameMode, 'OnPlayerReconnect'), self)

	-- Change random seed
	local timeTxt = string.gsub(string.gsub(GetSystemTime(), ':', ''), '0','')
	math.randomseed(tonumber(timeTxt))

	-- Initialized tables for tracking state
	self.vUserIds = {}
	self.vSteamIds = {}
	self.vBots = {}
	self.vBroadcasters = {}

	self.vPlayers = {}
	self.vRadiant = {}
	self.vDire = {}

	self.nRadiantKills = 0
	self.nDireKills = 0

	self.bSeenWaitForPlayers = false

	-- Commands can be registered for debugging purposes or as functions that can be called by the custom Scaleform UI
	Convars:RegisterCommand( "command_example", Dynamic_Wrap(GameMode, 'ExampleConsoleCommand'), "A console command example", 0 )

	print('[BAREBONES] Done loading Barebones gamemode!\n\n')
end

mode = nil

-- This function is called 1 to 2 times as the player connects initially but before they
-- have completely connected
function GameMode:PlayerConnect(keys)
	print('[BAREBONES] PlayerConnect')
	DeepPrintTable(keys)

	if keys.bot == 1 then
		-- This user is a Bot, so add it to the bots table
		self.vBots[keys.userid] = 1
	end
end

-- This function is called once when the player fully connects and becomes "Ready" during Loading
function GameMode:OnConnectFull(keys)
	print ('[BAREBONES] OnConnectFull')
	DeepPrintTable(keys)
	GameMode:CaptureGameMode()

	local entIndex = keys.index+1
	-- The Player entity of the joining user
	local ply = EntIndexToHScript(entIndex)

	-- The Player ID of the joining player
	local playerID = ply:GetPlayerID()

	-- Update the user ID table with this user
	self.vUserIds[keys.userid] = ply

	-- Update the Steam ID table
	self.vSteamIds[PlayerResource:GetSteamAccountID(playerID)] = ply

	-- If the player is a broadcaster flag it in the Broadcasters table
	if PlayerResource:IsBroadcaster(playerID) then
		self.vBroadcasters[keys.userid] = 1
		return
	end
end

-- This function is called as the first player loads and sets up the GameMode parameters
function GameMode:CaptureGameMode()
	if mode == nil then
		-- Set GameMode parameters
		mode = GameRules:GetGameModeEntity()
		mode:SetRecommendedItemsDisabled( RECOMMENDED_BUILDS_DISABLED )
		mode:SetCameraDistanceOverride( CAMERA_DISTANCE_OVERRIDE )
		mode:SetCustomBuybackCostEnabled( CUSTOM_BUYBACK_COST_ENABLED )
		mode:SetCustomBuybackCooldownEnabled( CUSTOM_BUYBACK_COOLDOWN_ENABLED )
		mode:SetBuybackEnabled( BUYBACK_ENABLED )
		mode:SetTopBarTeamValuesOverride ( USE_CUSTOM_TOP_BAR_VALUES )
		mode:SetTopBarTeamValuesVisible( TOP_BAR_VISIBLE )
		mode:SetUseCustomHeroLevels ( USE_CUSTOM_HERO_LEVELS )
		mode:SetCustomHeroMaxLevel ( MAX_LEVEL )
		mode:SetCustomXPRequiredToReachNextLevel( XP_PER_LEVEL_TABLE )

		--mode:SetBotThinkingEnabled( USE_STANDARD_DOTA_BOT_THINKING )
		mode:SetTowerBackdoorProtectionEnabled( ENABLE_TOWER_BACKDOOR_PROTECTION )

		mode:SetFogOfWarDisabled(DISABLE_FOG_OF_WAR_ENTIRELY)
		mode:SetGoldSoundDisabled( DISABLE_GOLD_SOUNDS )
		mode:SetRemoveIllusionsOnDeath( REMOVE_ILLUSIONS_ON_DEATH )

		self:OnFirstPlayerLoaded()
	end
end

-- This is an example console command
function GameMode:ExampleConsoleCommand()
	print( '******* Example Console Command ***************' )
	local cmdPlayer = Convars:GetCommandClient()
	if cmdPlayer then
		local playerID = cmdPlayer:GetPlayerID()
		if playerID ~= nil and playerID ~= -1 then
			-- Do something here for the player who called this command
			PlayerResource:ReplaceHeroWith(playerID, "npc_dota_hero_viper", 1000, 1000)
		end
	end
	print( '*********************************************' )
end

--[[
 This function should be used to set up Async precache calls at the beginning of the game. The Precache() function 
 in addon_game_mode.lua used to and may still sometimes have issues with client's appropriately precaching stuff.
 If this occurs it causes the client to never precache things configured in that block.
 In this function, place all of your PrecacheItemByNameAsync and PrecacheUnitByNameAsync. These calls will be made
 after all players have loaded in, but before they have selected their heroes. PrecacheItemByNameAsync can also
 be used to precache dynamically-added datadriven abilities instead of items. PrecacheUnitByNameAsync will 
 precache the precache{} block statement of the unit and all precache{} block statements for every Ability# 
 defined on the unit.
 This function should only be called once. If you want to/need to precache more items/abilities/units at a later
 time, you can call the functions individually (for example if you want to precache units in a new wave of
 holdout).
]]
function GameMode:PostLoadPrecache()
	print("[BAREBONES] Performing Post-Load precache")

end

--[[
 This function is called once and only once as soon as the first player (almost certain to be the server in local lobbies) loads in.
 It can be used to initialize state that isn't initializeable in InitGameMode() but needs to be done before everyone loads in.
]]
function GameMode:OnFirstPlayerLoaded()
	print("[BAREBONES] First Player has loaded")
end

--[[
 This function is called once and only once after all players have loaded into the game, right as the hero selection time begins.
 It can be used to initialize non-hero player state or adjust the hero selection (i.e. force random etc)
]]
function GameMode:OnAllPlayersLoaded()
	print("[BAREBONES] All Players have loaded into the game")
end

--[[
 This function is called once and only once for every player when they spawn into the game for the first time. It is also called
 if the player's hero is replaced with a new hero for any reason. This function is useful for initializing heroes, such as adding
 levels, changing the starting gold, removing/adding abilities, adding physics, etc.
 The hero parameter is the hero entity that just spawned in.
]]
function GameMode:OnHeroInGame(hero)
	print("[BAREBONES] Hero spawned in game for first time -- " .. hero:GetUnitName())

	-- Store a reference to the player handle inside this hero handle.
	hero.player = PlayerResource:GetPlayer(hero:GetPlayerID())
	-- Store the player's name inside this hero handle.
	hero.playerName = PlayerResource:GetPlayerName(hero:GetPlayerID())
	-- Store this hero handle in this table.
	table.insert(self.vPlayers, hero)

	-- This line for example will set the starting gold of every hero to 500 unreliable gold
	hero:SetGold(500, false)

	-- These lines will create an item and add it to the player, effectively ensuring they start with the item
	local item = CreateItem("item_example_item", hero, hero)
	hero:AddItem(item)
end

--[[
	This function is called once and only once when the game completely begins (about 0:00 on the clock). At this point,
	gold will begin to go up in ticks if configured, creeps will spawn, towers will become damageable etc. This function
	is useful for starting any game logic timers/thinkers, beginning the first round, etc.
]]
function GameMode:OnGameInProgress()
	print("[BAREBONES] The game has officially begun")

local point = Entities:FindByName( nil, "spawnerino"):GetAbsOrigin() // Записываем в переменную 'point' координаты нашего спавнера 'spawnerino'
   local waypoint = Entities:FindByName( nil, "way1") // Записываем в переменную 'waypoint' координаты первого бокса way1.
   local return_time = 10 // Записываем в переменную значение '10'
   Timers:CreateTimer(15, function()  // Создаем таймер, который запустится через 15 секунд после начала матча и запустит следующую функцию. 
    GAME_ROUND = GAME_ROUND + 1 // Значение GAME_ROUND увеличивается на 1.
    if GAME_ROUND == MAX_ROUNDS // Если GAME_ROUND равно MAX_ROUNDS, THEN переменная return_time получит нулевое значение.
      return_time = nil
     end
     Say(nil,"Wave №" .. GAME_ROUND, false) // Выводим в чат сообщение 'Wave №', в конце к которому добавится значение GAME_ROUND.
     for i=1, ROUND_UNITS do // Произведет нижние действия столько раз, сколько указано в ROUND_UNITS. То есть в нашем случае создаст 5 юнита.
       local unit = CreateUnitByName( "example_unit_" .. GAME_ROUND, point + RandomVector( RandomFloat( 0, 200 ) ), true, nil, nil, DOTA_TEAM_GOODGUYS ) // Создаем юнита 'example_unit_', в конце к названию добавится 1,2,3,4 или 5, в зависимости от раунда, и в итоге получатся наши example_unit_1, example_unit_2 и т.д.. Юнит появится в векторе point + RandomVector( RandomFloat( 0, 200 ) ) - point - наша переменная, а рандомный вектор добавляется для того, чтобы мобы не появлялись в одной точке и не застревали. Мобы будут за силы света.
     unit:SetInitialGoalEntity( waypoint ) // Посылаем мобов на наш way1, координаты которого мы записали в переменную 'waypoint'
     end  
     return return_time // Возвращаем таймеру время, через которое
end

-- Cleanup a player when they leave
function GameMode:OnDisconnect(keys)
	print('[BAREBONES] Player Disconnected ' .. tostring(keys.userid))
	DeepPrintTable(keys)

	local name = keys.name
	local networkid = keys.networkid
	local reason = keys.reason
	local userid = keys.userid
end

-- The overall game state has changed
function GameMode:OnGameRulesStateChange(keys)
	print("[BAREBONES] GameRules State Changed")
	DeepPrintTable(keys)

	local newState = GameRules:State_Get()
	if newState == DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD then
		self.bSeenWaitForPlayers = true
	elseif newState == DOTA_GAMERULES_STATE_INIT then
		Timers:RemoveTimer("alljointimer")
	elseif newState == DOTA_GAMERULES_STATE_HERO_SELECTION then
		local et = 6
		if self.bSeenWaitForPlayers then
			et = .01
		end
		Timers:CreateTimer("alljointimer", {
			useGameTime = true,
			endTime = et,
			callback = function()
				if PlayerResource:HaveAllPlayersJoined() then
					GameMode:PostLoadPrecache()
					GameMode:OnAllPlayersLoaded()
					return
				end
				return 1
			end})
	elseif newState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
		GameMode:OnGameInProgress()
	end
end

-- An NPC has spawned somewhere in game. This includes heroes
function GameMode:OnNPCSpawned(keys)
	print("[BAREBONES] NPC Spawned")
	DeepPrintTable(keys)
	local npc = EntIndexToHScript(keys.entindex)

	if npc:IsRealHero() and npc.bFirstSpawned == nil then
		npc.bFirstSpawned = true
		GameMode:OnHeroInGame(npc)
	end
end

-- An entity somewhere has been hurt. This event fires very often with many units so don't do too many expensive
-- operations here
function GameMode:OnEntityHurt(keys)
	--print("[BAREBONES] Entity Hurt")
	--DeepPrintTable(keys)
	local entCause = EntIndexToHScript(keys.entindex_attacker)
	local entVictim = EntIndexToHScript(keys.entindex_killed)
end

-- An item was picked up off the ground
function GameMode:OnItemPickedUp(keys)
	print ( '[BAREBONES] OnItemPurchased' )
	DeepPrintTable(keys)

	local heroEntity = EntIndexToHScript(keys.HeroEntityIndex)
	local itemEntity = EntIndexToHScript(keys.ItemEntityIndex)
	local player = PlayerResource:GetPlayer(keys.PlayerID)
	local itemname = keys.itemname
end

-- A player has reconnected to the game. This function can be used to repaint Player-based particles or change
-- state as necessary
function GameMode:OnPlayerReconnect(keys)
	print ( '[BAREBONES] OnPlayerReconnect' )
	DeepPrintTable(keys)
end

-- An item was purchased by a player
function GameMode:OnItemPurchased( keys )
	print ( '[BAREBONES] OnItemPurchased' )
	DeepPrintTable(keys)

	-- The playerID of the hero who is buying something
	local plyID = keys.PlayerID
	if not plyID then return end

	-- The name of the item purchased
	local itemName = keys.itemname

	-- The cost of the item purchased
	local itemcost = keys.itemcost

end

-- An ability was used by a player
function GameMode:OnAbilityUsed(keys)
	print('[BAREBONES] AbilityUsed')
	DeepPrintTable(keys)

	local player = EntIndexToHScript(keys.PlayerID)
	local abilityname = keys.abilityname
end

-- A non-player entity (necro-book, chen creep, etc) used an ability
function GameMode:OnNonPlayerUsedAbility(keys)
	print('[BAREBONES] OnNonPlayerUsedAbility')
	DeepPrintTable(keys)

	local abilityname= keys.abilityname
end

-- A player changed their name
function GameMode:OnPlayerChangedName(keys)
	print('[BAREBONES] OnPlayerChangedName')
	DeepPrintTable(keys)

	local newName = keys.newname
	local oldName = keys.oldName
end

-- A player leveled up an ability
function GameMode:OnPlayerLearnedAbility( keys)
	print ('[BAREBONES] OnPlayerLearnedAbility')
	DeepPrintTable(keys)

	local player = EntIndexToHScript(keys.player)
	local abilityname = keys.abilityname
end

-- A channelled ability finished by either completing or being interrupted
function GameMode:OnAbilityChannelFinished(keys)
	print ('[BAREBONES] OnAbilityChannelFinished')
	DeepPrintTable(keys)

	local abilityname = keys.abilityname
	local interrupted = keys.interrupted == 1
end

-- A player leveled up
function GameMode:OnPlayerLevelUp(keys)
	print ('[BAREBONES] OnPlayerLevelUp')
	DeepPrintTable(keys)

	local player = EntIndexToHScript(keys.player)
	local level = keys.level
end

-- A player last hit a creep, a tower, or a hero
function GameMode:OnLastHit(keys)
	print ('[BAREBONES] OnLastHit')
	DeepPrintTable(keys)

	local isFirstBlood = keys.FirstBlood == 1
	local isHeroKill = keys.HeroKill == 1
	local isTowerKill = keys.TowerKill == 1
	local player = PlayerResource:GetPlayer(keys.PlayerID)
end

-- A tree was cut down by tango, quelling blade, etc
function GameMode:OnTreeCut(keys)
	print ('[BAREBONES] OnTreeCut')
	DeepPrintTable(keys)

	local treeX = keys.tree_x
	local treeY = keys.tree_y
end

-- A rune was activated by a player
function GameMode:OnRuneActivated (keys)
	print ('[BAREBONES] OnRuneActivated')
	DeepPrintTable(keys)

	local player = PlayerResource:GetPlayer(keys.PlayerID)
	local rune = keys.rune

end

-- A player took damage from a tower
function GameMode:OnPlayerTakeTowerDamage(keys)
	print ('[BAREBONES] OnPlayerTakeTowerDamage')
	DeepPrintTable(keys)

	local player = PlayerResource:GetPlayer(keys.PlayerID)
	local damage = keys.damage
end

-- A player picked a hero
function GameMode:OnPlayerPickHero(keys)
	print ('[BAREBONES] OnPlayerPickHero')
	DeepPrintTable(keys)

	local heroClass = keys.hero
	local heroEntity = EntIndexToHScript(keys.heroindex)
	local player = EntIndexToHScript(keys.player)
end

-- A player killed another player in a multi-team context
function GameMode:OnTeamKillCredit(keys)
	print ('[BAREBONES] OnTeamKillCredit')
	DeepPrintTable(keys)

	local killerPlayer = PlayerResource:GetPlayer(keys.killer_userid)
	local victimPlayer = PlayerResource:GetPlayer(keys.victim_userid)
	local numKills = keys.herokills
	local killerTeamNumber = keys.teamnumber
end

-- An entity died
function GameMode:OnEntityKilled( keys )
	print( '[BAREBONES] OnEntityKilled Called' )
	DeepPrintTable( keys )

	-- The Unit that was Killed
	local killedUnit = EntIndexToHScript( keys.entindex_killed )
	-- The Killing entity
	local killerEntity = nil

	if keys.entindex_attacker ~= nil then
		killerEntity = EntIndexToHScript( keys.entindex_attacker )
	end

	-- Put code here to handle when an entity gets killed
end
 
Последнее редактирование модератором:
Теперь замени "-" на "--", либо вообще удали эти комментарии (это у констант твоих новых). Потому что оператор комментария "--", а "-" выдаст ошибку.

То же самое и с "//" - убери там комментарии целиком, либо замени просто слэши на "--". И ты каким редактором пользуешься? Sublime, notepad++? В них для lua есть подсветка синтаксиса, сможешь понять, где ты "недоделал" комментарий (то есть где не закомментировал какие-нибудь пояснения)

Ну и скидывай по новой файлы и лог с ошибками, если таковые будут.
 
Последнее редактирование модератором:
Блокнотом пользуюсь))) Тогда сейчас нотпад скачаю
 
Лучше тогда сразу SublimeText, там больше функционал.
 
мне вот только очень интересно изза чего ошибка в консоли такая
Код:
[ W VScript       ]: Script Runtime Error: ...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: module 'barebones' not found:
файл этот у меня есть и в аддон моде он 3 строчкой как раз таки указан
 
консоль
Код:
[  VScript       ]: [Timers] creating Timers
[  Developer      ]: ...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: module 'barebones' not found:
[  Developer      ]: 	no field package.preload['barebones']scripts/vscripts/barebones.lua:46: '=' expected near 'ðàóíäà'
[  Developer      ]: stack traceback:
[  Developer      ]: 	[C]: in function 'require'
[  Developer      ]: 	...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: in main chunk
[ W VScript       ]: Script Runtime Error: ...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: module 'barebones' not found:
[ W VScript       ]: 	no field package.preload['barebones']scripts/vscripts/barebones.lua:46: '=' expected near 'ðàóíäà'
[ W VScript       ]: stack traceback:
[ W VScript       ]: 	[C]: in function 'require'
[ W VScript       ]: 	...a_addons\fire_arena\scripts\vscripts\addon_game_mode.lua:3: in main chunk
[ W VScript       ]: Error running script named addon_game_mode
[  Client        ]: CL: CWaitForGameServerStartupPrerequisite done waiting for server
[  Client        ]: CL: CCreateGameClientJob creating client connection to 'loopback'
[  Client        ]: CL: Connected to 'loopback'
[  Server        ]: SV: Sending server info to client 'aizek' at loopback
[  Server        ]: SV: WriteInitialSpawnGroups sending 1 groups
[  Client        ]: Game: "Dota 2"
[  Client        ]: Map: "fire_arena_1"
[  Client        ]: Players: 1 (0 bots) / 64 humans
[  Client        ]: Build: 7447 (revision 3892942)
[  Client        ]: Server Number: 2

мой аддон гейм мод
Код:
-- Required files to be visible from anywhere
require( 'timers' )
require( 'barebones' )

function Precache( context )
  --[[
  This function is used to precache resources/units/items/abilities that will be needed
  for sure in your game and that cannot or should not be precached asynchronously or 
  after the game loads.
  See GameMode:PostLoadPrecache() in barebones.lua for more information
  ]]

  print("[BAREBONES] Performing pre-load precache")
  
  -- Particles can be precached individually or by folder
  -- It it likely that precaching a single particle system will precache all of its children, but this may not be guaranteed
  PrecacheResource("particle", "particles/econ/generic/generic_aoe_explosion_sphere_1/generic_aoe_explosion_sphere_1.vpcf", context)
  PrecacheResource("particle_folder", "particles/test_particle", context)

  -- Models can also be precached by folder or individually
  -- PrecacheModel should generally used over PrecacheResource for individual models
  PrecacheResource("model_folder", "particles/heroes/antimage", context)
  PrecacheResource("model", "particles/heroes/viper/viper.vmdl", context)
  PrecacheModel("models/heroes/viper/viper.vmdl", context)

  -- Sounds can precached here like anything else
  PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_gyrocopter.vsndevts", context)

  -- Entire items can be precached by name
  -- Abilities can also be precached in this way despite the name
  PrecacheItemByNameSync("example_ability", context)
  PrecacheItemByNameSync("item_example_item", context)

  -- Entire heroes (sound effects/voice/models/particles) can be precached with PrecacheUnitByNameSync
  -- Custom units from npc_units_custom.txt can also have all of their abilities and precache{} blocks precached in this way
  PrecacheUnitByNameSync("npc_dota_hero_ancient_apparition", context)
  PrecacheUnitByNameSync("npc_dota_hero_enigma", context)
  PrecacheUnitByNameSync("example_unit_1", context)
end

-- Create the game mode when we activate
function Activate()
  GameRules.GameMode = GameMode()
  GameRules.GameMode:InitGameMode()
end

мой барбонс
Код:
print ('[BAREBONES] barebones.lua' )

-- GameRules Variables
ENABLE_HERO_RESPAWN = true       -- Should the heroes automatically respawn on a timer or stay dead until manually respawned
UNIVERSAL_SHOP_MODE = false       -- Should the main shop contain Secret Shop items as well as regular items
ALLOW_SAME_HERO_SELECTION = true    -- Should we let people select the same hero as each other

HERO_SELECTION_TIME = 1.0       -- How long should we let people select their hero?
PRE_GAME_TIME = 0.0          -- How long after people select their heroes should the horn blow and the game start?
POST_GAME_TIME = 60.0          -- How long should we let people look at the scoreboard before closing the server automatically?
TREE_REGROW_TIME = 60.0         -- How long should it take individual trees to respawn after being cut down/destroyed?

GOLD_PER_TICK = 100           -- How much gold should players get per tick?
GOLD_TICK_TIME = 5           -- How long should we wait in seconds between gold ticks?

RECOMMENDED_BUILDS_DISABLED = false   -- Should we disable the recommened builds for heroes (Note: this is not working currently I believe)
CAMERA_DISTANCE_OVERRIDE = 1134.0    -- How far out should we allow the camera to go? 1134 is the default in Dota

MINIMAP_ICON_SIZE = 1          -- What icon size should we use for our heroes?
MINIMAP_CREEP_ICON_SIZE = 1       -- What icon size should we use for creeps?
MINIMAP_RUNE_ICON_SIZE = 1       -- What icon size should we use for runes?

RUNE_SPAWN_TIME = 120          -- How long in seconds should we wait between rune spawns?
CUSTOM_BUYBACK_COST_ENABLED = true   -- Should we use a custom buyback cost setting?
CUSTOM_BUYBACK_COOLDOWN_ENABLED = true -- Should we use a custom buyback time?
BUYBACK_ENABLED = false         -- Should we allow people to buyback when they die?

DISABLE_FOG_OF_WAR_ENTIRELY = true   -- Should we disable fog of war entirely for both teams?
USE_STANDARD_HERO_GOLD_BOUNTY = true  -- Should we give gold for hero kills the same as in Dota, or allow those values to be changed?

USE_CUSTOM_TOP_BAR_VALUES = true    -- Should we do customized top bar values or use the default kill count per team?
TOP_BAR_VISIBLE = true         -- Should we display the top bar score/count at all?
SHOW_KILLS_ON_TOPBAR = true       -- Should we display kills only on the top bar? (No denies, suicides, kills by neutrals) Requires USE_CUSTOM_TOP_BAR_VALUES

ENABLE_TOWER_BACKDOOR_PROTECTION = false -- Should we enable backdoor protection for our towers?
REMOVE_ILLUSIONS_ON_DEATH = false    -- Should we remove all illusions if the main hero dies?
DISABLE_GOLD_SOUNDS = false       -- Should we disable the gold sound when players get gold?

END_GAME_ON_KILLS = true        -- Should the game end after a certain number of kills?
KILLS_TO_END_GAME_FOR_TEAM = 50     -- How many kills for a team should signify an end of game?

USE_CUSTOM_HERO_LEVELS = true      -- Should we allow heroes to have custom levels?
MAX_LEVEL = 50             -- What level should we let heroes get to?
USE_CUSTOM_XP_VALUES = true       -- Should we use custom XP values to level up heroes, or the default Dota numbers?

GAME_ROUND = 0 - номер текущего раунда
 MAX_ROUNDS = 5 - номер конечного раунда
 ROUND_UNITS = 5 - кол-во юнитов на 1 раунд

-- Fill this table up with the required XP per level if you want to change it
XP_PER_LEVEL_TABLE = {}
for i=1,MAX_LEVEL do
	XP_PER_LEVEL_TABLE[i] = i * 100
end

-- Generated from template
if GameMode == nil then
	print ( '[BAREBONES] creating barebones game mode' )
	GameMode = class({})
end

-- This function initializes the game mode and is called before anyone loads into the game
-- It can be used to pre-initialize any values/tables that will be needed later
function GameMode:InitGameMode()
	GameMode = self
	print('[BAREBONES] Starting to load Barebones gamemode...')

	-- Setup rules
	GameRules:SetHeroRespawnEnabled( ENABLE_HERO_RESPAWN )
	GameRules:SetUseUniversalShopMode( UNIVERSAL_SHOP_MODE )
	GameRules:SetSameHeroSelectionEnabled( ALLOW_SAME_HERO_SELECTION )
	GameRules:SetHeroSelectionTime( HERO_SELECTION_TIME )
	GameRules:SetPreGameTime( PRE_GAME_TIME)
	GameRules:SetPostGameTime( POST_GAME_TIME )
	GameRules:SetTreeRegrowTime( TREE_REGROW_TIME )
	GameRules:SetUseCustomHeroXPValues ( USE_CUSTOM_XP_VALUES )
	GameRules:SetGoldPerTick(GOLD_PER_TICK)
	GameRules:SetGoldTickTime(GOLD_TICK_TIME)
	GameRules:SetRuneSpawnTime(RUNE_SPAWN_TIME)
	GameRules:SetUseBaseGoldBountyOnHeroes(USE_STANDARD_HERO_GOLD_BOUNTY)
	GameRules:SetHeroMinimapIconScale( MINIMAP_ICON_SIZE )
	GameRules:SetCreepMinimapIconScale( MINIMAP_CREEP_ICON_SIZE )
	GameRules:SetRuneMinimapIconScale( MINIMAP_RUNE_ICON_SIZE )
	print('[BAREBONES] GameRules set')

	-- Listeners - Event Hooks
	-- All of these events can potentially be fired by the game, though only the uncommented ones have had
	-- Functions supplied for them.
	ListenToGameEvent('dota_player_gained_level', Dynamic_Wrap(GameMode, 'OnPlayerLevelUp'), self)
	ListenToGameEvent('dota_ability_channel_finished', Dynamic_Wrap(GameMode, 'OnAbilityChannelFinished'), self)
	ListenToGameEvent('dota_player_learned_ability', Dynamic_Wrap(GameMode, 'OnPlayerLearnedAbility'), self)
	ListenToGameEvent('entity_killed', Dynamic_Wrap(GameMode, 'OnEntityKilled'), self)
	ListenToGameEvent('player_connect_full', Dynamic_Wrap(GameMode, 'OnConnectFull'), self)
	ListenToGameEvent('player_disconnect', Dynamic_Wrap(GameMode, 'OnDisconnect'), self)
	ListenToGameEvent('dota_item_purchased', Dynamic_Wrap(GameMode, 'OnItemPurchased'), self)
	ListenToGameEvent('dota_item_picked_up', Dynamic_Wrap(GameMode, 'OnItemPickedUp'), self)
	ListenToGameEvent('last_hit', Dynamic_Wrap(GameMode, 'OnLastHit'), self)
	ListenToGameEvent('dota_non_player_used_ability', Dynamic_Wrap(GameMode, 'OnNonPlayerUsedAbility'), self)
	ListenToGameEvent('player_changename', Dynamic_Wrap(GameMode, 'OnPlayerChangedName'), self)
	ListenToGameEvent('dota_rune_activated_server', Dynamic_Wrap(GameMode, 'OnRuneActivated'), self)
	ListenToGameEvent('dota_player_take_tower_damage', Dynamic_Wrap(GameMode, 'OnPlayerTakeTowerDamage'), self)
	ListenToGameEvent('tree_cut', Dynamic_Wrap(GameMode, 'OnTreeCut'), self)
	ListenToGameEvent('entity_hurt', Dynamic_Wrap(GameMode, 'OnEntityHurt'), self)
	ListenToGameEvent('player_connect', Dynamic_Wrap(GameMode, 'PlayerConnect'), self)
	ListenToGameEvent('dota_player_used_ability', Dynamic_Wrap(GameMode, 'OnAbilityUsed'), self)
	ListenToGameEvent('game_rules_state_change', Dynamic_Wrap(GameMode, 'OnGameRulesStateChange'), self)
	ListenToGameEvent('npc_spawned', Dynamic_Wrap(GameMode, 'OnNPCSpawned'), self)
	ListenToGameEvent('dota_player_pick_hero', Dynamic_Wrap(GameMode, 'OnPlayerPickHero'), self)
	ListenToGameEvent('dota_team_kill_credit', Dynamic_Wrap(GameMode, 'OnTeamKillCredit'), self)
	ListenToGameEvent("player_reconnected", Dynamic_Wrap(GameMode, 'OnPlayerReconnect'), self)

	-- Change random seed
	local timeTxt = string.gsub(string.gsub(GetSystemTime(), ':', ''), '0','')
	math.randomseed(tonumber(timeTxt))

	-- Initialized tables for tracking state
	self.vUserIds = {}
	self.vSteamIds = {}
	self.vBots = {}
	self.vBroadcasters = {}

	self.vPlayers = {}
	self.vRadiant = {}
	self.vDire = {}

	self.nRadiantKills = 0
	self.nDireKills = 0

	self.bSeenWaitForPlayers = false

	-- Commands can be registered for debugging purposes or as functions that can be called by the custom Scaleform UI
	Convars:RegisterCommand( "command_example", Dynamic_Wrap(GameMode, 'ExampleConsoleCommand'), "A console command example", 0 )

	print('[BAREBONES] Done loading Barebones gamemode!\n\n')
end

mode = nil

-- This function is called 1 to 2 times as the player connects initially but before they
-- have completely connected
function GameMode:PlayerConnect(keys)
	print('[BAREBONES] PlayerConnect')
	DeepPrintTable(keys)

	if keys.bot == 1 then
		-- This user is a Bot, so add it to the bots table
		self.vBots[keys.userid] = 1
	end
end

-- This function is called once when the player fully connects and becomes "Ready" during Loading
function GameMode:OnConnectFull(keys)
	print ('[BAREBONES] OnConnectFull')
	DeepPrintTable(keys)
	GameMode:CaptureGameMode()

	local entIndex = keys.index+1
	-- The Player entity of the joining user
	local ply = EntIndexToHScript(entIndex)

	-- The Player ID of the joining player
	local playerID = ply:GetPlayerID()

	-- Update the user ID table with this user
	self.vUserIds[keys.userid] = ply

	-- Update the Steam ID table
	self.vSteamIds[PlayerResource:GetSteamAccountID(playerID)] = ply

	-- If the player is a broadcaster flag it in the Broadcasters table
	if PlayerResource:IsBroadcaster(playerID) then
		self.vBroadcasters[keys.userid] = 1
		return
	end
end

-- This function is called as the first player loads and sets up the GameMode parameters
function GameMode:CaptureGameMode()
	if mode == nil then
		-- Set GameMode parameters
		mode = GameRules:GetGameModeEntity()
		mode:SetRecommendedItemsDisabled( RECOMMENDED_BUILDS_DISABLED )
		mode:SetCameraDistanceOverride( CAMERA_DISTANCE_OVERRIDE )
		mode:SetCustomBuybackCostEnabled( CUSTOM_BUYBACK_COST_ENABLED )
		mode:SetCustomBuybackCooldownEnabled( CUSTOM_BUYBACK_COOLDOWN_ENABLED )
		mode:SetBuybackEnabled( BUYBACK_ENABLED )
		mode:SetTopBarTeamValuesOverride ( USE_CUSTOM_TOP_BAR_VALUES )
		mode:SetTopBarTeamValuesVisible( TOP_BAR_VISIBLE )
		mode:SetUseCustomHeroLevels ( USE_CUSTOM_HERO_LEVELS )
		mode:SetCustomHeroMaxLevel ( MAX_LEVEL )
		mode:SetCustomXPRequiredToReachNextLevel( XP_PER_LEVEL_TABLE )

		--mode:SetBotThinkingEnabled( USE_STANDARD_DOTA_BOT_THINKING )
		mode:SetTowerBackdoorProtectionEnabled( ENABLE_TOWER_BACKDOOR_PROTECTION )

		mode:SetFogOfWarDisabled(DISABLE_FOG_OF_WAR_ENTIRELY)
		mode:SetGoldSoundDisabled( DISABLE_GOLD_SOUNDS )
		mode:SetRemoveIllusionsOnDeath( REMOVE_ILLUSIONS_ON_DEATH )

		self:OnFirstPlayerLoaded()
	end
end

-- This is an example console command
function GameMode:ExampleConsoleCommand()
	print( '******* Example Console Command ***************' )
	local cmdPlayer = Convars:GetCommandClient()
	if cmdPlayer then
		local playerID = cmdPlayer:GetPlayerID()
		if playerID ~= nil and playerID ~= -1 then
			-- Do something here for the player who called this command
			PlayerResource:ReplaceHeroWith(playerID, "npc_dota_hero_viper", 1000, 1000)
		end
	end
	print( '*********************************************' )
end

--[[
 This function should be used to set up Async precache calls at the beginning of the game. The Precache() function 
 in addon_game_mode.lua used to and may still sometimes have issues with client's appropriately precaching stuff.
 If this occurs it causes the client to never precache things configured in that block.
 In this function, place all of your PrecacheItemByNameAsync and PrecacheUnitByNameAsync. These calls will be made
 after all players have loaded in, but before they have selected their heroes. PrecacheItemByNameAsync can also
 be used to precache dynamically-added datadriven abilities instead of items. PrecacheUnitByNameAsync will 
 precache the precache{} block statement of the unit and all precache{} block statements for every Ability# 
 defined on the unit.
 This function should only be called once. If you want to/need to precache more items/abilities/units at a later
 time, you can call the functions individually (for example if you want to precache units in a new wave of
 holdout).
]]
function GameMode:PostLoadPrecache()
	print("[BAREBONES] Performing Post-Load precache")

end

--[[
 This function is called once and only once as soon as the first player (almost certain to be the server in local lobbies) loads in.
 It can be used to initialize state that isn't initializeable in InitGameMode() but needs to be done before everyone loads in.
]]
function GameMode:OnFirstPlayerLoaded()
	print("[BAREBONES] First Player has loaded")
end

--[[
 This function is called once and only once after all players have loaded into the game, right as the hero selection time begins.
 It can be used to initialize non-hero player state or adjust the hero selection (i.e. force random etc)
]]
function GameMode:OnAllPlayersLoaded()
	print("[BAREBONES] All Players have loaded into the game")
end

--[[
 This function is called once and only once for every player when they spawn into the game for the first time. It is also called
 if the player's hero is replaced with a new hero for any reason. This function is useful for initializing heroes, such as adding
 levels, changing the starting gold, removing/adding abilities, adding physics, etc.
 The hero parameter is the hero entity that just spawned in.
]]
function GameMode:OnHeroInGame(hero)
	print("[BAREBONES] Hero spawned in game for first time -- " .. hero:GetUnitName())

	-- Store a reference to the player handle inside this hero handle.
	hero.player = PlayerResource:GetPlayer(hero:GetPlayerID())
	-- Store the player's name inside this hero handle.
	hero.playerName = PlayerResource:GetPlayerName(hero:GetPlayerID())
	-- Store this hero handle in this table.
	table.insert(self.vPlayers, hero)

	-- This line for example will set the starting gold of every hero to 500 unreliable gold
	hero:SetGold(500, false)

	-- These lines will create an item and add it to the player, effectively ensuring they start with the item
	local item = CreateItem("item_example_item", hero, hero)
	hero:AddItem(item)
end

--[[
	This function is called once and only once when the game completely begins (about 0:00 on the clock). At this point,
	gold will begin to go up in ticks if configured, creeps will spawn, towers will become damageable etc. This function
	is useful for starting any game logic timers/thinkers, beginning the first round, etc.
]]
function GameMode:OnGameInProgress()
	print("[BAREBONES] The game has officially begun")
 local point = Entities:FindByName( nil, "spawnerino"):GetAbsOrigin() -- Записываем в переменную 'point' координаты нашего спавнера 'spawnerino'
   local waypoint = Entities:FindByName( nil, "way1") -- Записываем в переменную 'waypoint' координаты первого бокса way1
   local return_time = 10 -- Записываем в переменную значение '10'
   Timers:CreateTimer(15, function() -- Создаем таймер, который запустится через 15 секунд после начала матча и запустит следующую функцию
    GAME_ROUND = GAME_ROUND + 1 -- Значение GAME_ROUND увеличивается на 1
    if GAME_ROUND == MAX_ROUNDS -- Если GAME_ROUND равно MAX_ROUNDS, переменная return_time получит нулевое значение
      return_time = nil
     end
     Say(nil,"Wave №" .. GAME_ROUND, false) -- Выводим в чат сообщение 'Wave №', в конце к которому добавится значение GAME_ROUND.
     for i=1, ROUND_UNITS do -- Произведет нижние действия столько раз, сколько указано в ROUND_UNITS. То есть в нашем случае создаст 2 юнита.
       local unit = CreateUnitByName( "example_unit_" .. GAME_ROUND, point + RandomVector( RandomFloat( 0, 200 ) ), true, nil, nil, DOTA_TEAM_GOODGUYS ) --[[ Создаем юнита 'example_unit_', в конце к названию добавится 1,2,3,4 или 5, в зависимости от раунда, и в итоге получатся наши example_unit_1, example_unit_2 и т.д. Юнит появится в векторе point + RandomVector (RandomFloat( 0, 200 ) ) - point - наша переменная, а рандомный вектор добавляется для того, чтобы мобы не появлялись в одной точке и не застревали. Мобы будут за силы света. ]]
     unit:SetInitialGoalEntity( waypoint ) -- Посылаем мобов на наш way1, координаты которого мы записали в переменную 'waypoint'
     end  
     return return_time -- Возвращаем таймеру время, через которое он должен снова сработать. Когда пройдет последний раунд таймер получит значение 'nil' и выключится.
   end)
end
local point = Entities:FindByName( nil, "spawnerino"):GetAbsOrigin() -- Записываем в переменную 'point' координаты нашего спавнера 'spawnerino'
   local waypoint = Entities:FindByName( nil, "way1") -- Записываем в переменную 'waypoint' координаты первого бокса way1.
   local return_time = 10 -- Записываем в переменную значение '10'
   Timers:CreateTimer(15, function()  -- Создаем таймер, который запустится через 15 секунд после начала матча и запустит следующую функцию. 
    GAME_ROUND = GAME_ROUND + 1 -- Значение GAME_ROUND увеличивается на 1.
    if GAME_ROUND == MAX_ROUNDS -- Если GAME_ROUND равно MAX_ROUNDS, THEN переменная return_time получит нулевое значение.
      return_time = nil
     end
     Say(nil,"Wave №" .. GAME_ROUND, false) -- Выводим в чат сообщение 'Wave №', в конце к которому добавится значение GAME_ROUND.
     for i=1, ROUND_UNITS do -- Произведет нижние действия столько раз, сколько указано в ROUND_UNITS. То есть в нашем случае создаст 5 юнита.
       local unit = CreateUnitByName( "example_unit_" .. GAME_ROUND, point + RandomVector( RandomFloat( 0, 200 ) ), true, nil, nil, DOTA_TEAM_GOODGUYS ) -- Создаем юнита 'example_unit_', в конце к названию добавится 1,2,3,4 или 5, в зависимости от раунда, и в итоге получатся наши example_unit_1, example_unit_2 и т.д.. Юнит появится в векторе point + RandomVector( RandomFloat( 0, 200 ) ) - point - наша переменная, а рандомный вектор добавляется для того, чтобы мобы не появлялись в одной точке и не застревали. Мобы будут за силы света.
     unit:SetInitialGoalEntity( waypoint ) -- Посылаем мобов на наш way1, координаты которого мы записали в переменную 'waypoint'
     end  
     return return_time -- Возвращаем таймеру время, через которое
end

-- Cleanup a player when they leave
function GameMode:OnDisconnect(keys)
	print('[BAREBONES] Player Disconnected ' .. tostring(keys.userid))
	DeepPrintTable(keys)

	local name = keys.name
	local networkid = keys.networkid
	local reason = keys.reason
	local userid = keys.userid
end

-- The overall game state has changed
function GameMode:OnGameRulesStateChange(keys)
	print("[BAREBONES] GameRules State Changed")
	DeepPrintTable(keys)

	local newState = GameRules:State_Get()
	if newState == DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD then
		self.bSeenWaitForPlayers = true
	elseif newState == DOTA_GAMERULES_STATE_INIT then
		Timers:RemoveTimer("alljointimer")
	elseif newState == DOTA_GAMERULES_STATE_HERO_SELECTION then
		local et = 6
		if self.bSeenWaitForPlayers then
			et = .01
		end
		Timers:CreateTimer("alljointimer", {
			useGameTime = true,
			endTime = et,
			callback = function()
				if PlayerResource:HaveAllPlayersJoined() then
					GameMode:PostLoadPrecache()
					GameMode:OnAllPlayersLoaded()
					return
				end
				return 1
			end})
	elseif newState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
		GameMode:OnGameInProgress()
	end
end

-- An NPC has spawned somewhere in game. This includes heroes
function GameMode:OnNPCSpawned(keys)
	print("[BAREBONES] NPC Spawned")
	DeepPrintTable(keys)
	local npc = EntIndexToHScript(keys.entindex)

	if npc:IsRealHero() and npc.bFirstSpawned == nil then
		npc.bFirstSpawned = true
		GameMode:OnHeroInGame(npc)
	end
end

-- An entity somewhere has been hurt. This event fires very often with many units so don't do too many expensive
-- operations here
function GameMode:OnEntityHurt(keys)
	--print("[BAREBONES] Entity Hurt")
	--DeepPrintTable(keys)
	local entCause = EntIndexToHScript(keys.entindex_attacker)
	local entVictim = EntIndexToHScript(keys.entindex_killed)
end

-- An item was picked up off the ground
function GameMode:OnItemPickedUp(keys)
	print ( '[BAREBONES] OnItemPurchased' )
	DeepPrintTable(keys)

	local heroEntity = EntIndexToHScript(keys.HeroEntityIndex)
	local itemEntity = EntIndexToHScript(keys.ItemEntityIndex)
	local player = PlayerResource:GetPlayer(keys.PlayerID)
	local itemname = keys.itemname
end

-- A player has reconnected to the game. This function can be used to repaint Player-based particles or change
-- state as necessary
function GameMode:OnPlayerReconnect(keys)
	print ( '[BAREBONES] OnPlayerReconnect' )
	DeepPrintTable(keys)
end

-- An item was purchased by a player
function GameMode:OnItemPurchased( keys )
	print ( '[BAREBONES] OnItemPurchased' )
	DeepPrintTable(keys)

	-- The playerID of the hero who is buying something
	local plyID = keys.PlayerID
	if not plyID then return end

	-- The name of the item purchased
	local itemName = keys.itemname

	-- The cost of the item purchased
	local itemcost = keys.itemcost

end

-- An ability was used by a player
function GameMode:OnAbilityUsed(keys)
	print('[BAREBONES] AbilityUsed')
	DeepPrintTable(keys)

	local player = EntIndexToHScript(keys.PlayerID)
	local abilityname = keys.abilityname
end

-- A non-player entity (necro-book, chen creep, etc) used an ability
function GameMode:OnNonPlayerUsedAbility(keys)
	print('[BAREBONES] OnNonPlayerUsedAbility')
	DeepPrintTable(keys)

	local abilityname= keys.abilityname
end

-- A player changed their name
function GameMode:OnPlayerChangedName(keys)
	print('[BAREBONES] OnPlayerChangedName')
	DeepPrintTable(keys)

	local newName = keys.newname
	local oldName = keys.oldName
end

-- A player leveled up an ability
function GameMode:OnPlayerLearnedAbility( keys)
	print ('[BAREBONES] OnPlayerLearnedAbility')
	DeepPrintTable(keys)

	local player = EntIndexToHScript(keys.player)
	local abilityname = keys.abilityname
end

-- A channelled ability finished by either completing or being interrupted
function GameMode:OnAbilityChannelFinished(keys)
	print ('[BAREBONES] OnAbilityChannelFinished')
	DeepPrintTable(keys)

	local abilityname = keys.abilityname
	local interrupted = keys.interrupted == 1
end

-- A player leveled up
function GameMode:OnPlayerLevelUp(keys)
	print ('[BAREBONES] OnPlayerLevelUp')
	DeepPrintTable(keys)

	local player = EntIndexToHScript(keys.player)
	local level = keys.level
end

-- A player last hit a creep, a tower, or a hero
function GameMode:OnLastHit(keys)
	print ('[BAREBONES] OnLastHit')
	DeepPrintTable(keys)

	local isFirstBlood = keys.FirstBlood == 1
	local isHeroKill = keys.HeroKill == 1
	local isTowerKill = keys.TowerKill == 1
	local player = PlayerResource:GetPlayer(keys.PlayerID)
end

-- A tree was cut down by tango, quelling blade, etc
function GameMode:OnTreeCut(keys)
	print ('[BAREBONES] OnTreeCut')
	DeepPrintTable(keys)

	local treeX = keys.tree_x
	local treeY = keys.tree_y
end

-- A rune was activated by a player
function GameMode:OnRuneActivated (keys)
	print ('[BAREBONES] OnRuneActivated')
	DeepPrintTable(keys)

	local player = PlayerResource:GetPlayer(keys.PlayerID)
	local rune = keys.rune

end

-- A player took damage from a tower
function GameMode:OnPlayerTakeTowerDamage(keys)
	print ('[BAREBONES] OnPlayerTakeTowerDamage')
	DeepPrintTable(keys)

	local player = PlayerResource:GetPlayer(keys.PlayerID)
	local damage = keys.damage
end

-- A player picked a hero
function GameMode:OnPlayerPickHero(keys)
	print ('[BAREBONES] OnPlayerPickHero')
	DeepPrintTable(keys)

	local heroClass = keys.hero
	local heroEntity = EntIndexToHScript(keys.heroindex)
	local player = EntIndexToHScript(keys.player)
end

-- A player killed another player in a multi-team context
function GameMode:OnTeamKillCredit(keys)
	print ('[BAREBONES] OnTeamKillCredit')
	DeepPrintTable(keys)

	local killerPlayer = PlayerResource:GetPlayer(keys.killer_userid)
	local victimPlayer = PlayerResource:GetPlayer(keys.victim_userid)
	local numKills = keys.herokills
	local killerTeamNumber = keys.teamnumber
end

-- An entity died
function GameMode:OnEntityKilled( keys )
	print( '[BAREBONES] OnEntityKilled Called' )
	DeepPrintTable( keys )

	-- The Unit that was Killed
	local killedUnit = EntIndexToHScript( keys.entindex_killed )
	-- The Killing entity
	local killerEntity = nil

	if keys.entindex_attacker ~= nil then
		killerEntity = EntIndexToHScript( keys.entindex_attacker )
	end

	-- Put code here to handle when an entity gets killed
end
вообще не понимаю просто, вроде поисправлял сам свои косяки, поиспровлял что ты советовал но все равно. Может есть какой то другой способ вызвать волны крипов ?
 
Последнее редактирование модератором:
Тебе консоль говорит: глянь 46 строку. Смотрим и видим, что ты у глобалок так и не исправил комменты:

Код:
GAME_ROUND = 0 - номер текущего раунда
 MAX_ROUNDS = 5 - номер конечного раунда
 ROUND_UNITS = 5 - кол-во юнитов на 1 раунд
 
И что непонятного то? Вроде бы же все объясняю.
Так программирование и выглядит: пишешь код, потом правишь косяки свои же.
Постепенно идешь к правильному варианту.
 
исправил то, теперь эта ошибка вылезает место предыдущей
Код:
[ W VScript       ]: 	no field package.preload['barebones']scripts/vscripts/barebones.lua:289: 'then' expected near 'return_time'
но мне интересно а с ней то что не так, вот барбонсы с 281 по 297
Код:
[quote]function GameMode:OnGameInProgress()
	print("[BAREBONES] The game has officially begun")
 local point = Entities:FindByName( nil, "spawnerino"):GetAbsOrigin() -- Записываем в переменную 'point' координаты нашего спавнера 'spawnerino'
   local waypoint = Entities:FindByName( nil, "way1") -- Записываем в переменную 'waypoint' координаты первого бокса way1
   local return_time = 10 -- Записываем в переменную значение '10'
   Timers:CreateTimer(15, function() -- Создаем таймер, который запустится через 15 секунд после начала матча и запустит следующую функцию
    GAME_ROUND = GAME_ROUND + 1 -- Значение GAME_ROUND увеличивается на 1
    if GAME_ROUND == MAX_ROUNDS -- Если GAME_ROUND равно MAX_ROUNDS, переменная return_time получит нулевое значение
      return_time = nil
     end
     Say(nil,"Wave №" .. GAME_ROUND, false) -- Выводим в чат сообщение 'Wave №', в конце к которому добавится значение GAME_ROUND.
     for i=1, ROUND_UNITS do -- Произведет нижние действия столько раз, сколько указано в ROUND_UNITS. То есть в нашем случае создаст 2 юнита.
       local unit = CreateUnitByName( "example_unit_" .. GAME_ROUND, point + RandomVector( RandomFloat( 0, 200 ) ), true, nil, nil, DOTA_TEAM_GOODGUYS ) --[[ Создаем юнита 'example_unit_', в конце к названию добавится 1,2,3,4 или 5, в зависимости от раунда, и в итоге получатся наши example_unit_1, example_unit_2 и т.д. Юнит появится в векторе point + RandomVector (RandomFloat( 0, 200 ) ) - point - наша переменная, а рандомный вектор добавляется для того, чтобы мобы не появлялись в одной точке и не застревали. Мобы будут за силы света. ]]
     unit:SetInitialGoalEntity( waypoint ) -- Посылаем мобов на наш way1, координаты которого мы записали в переменную 'waypoint'
     end  
     return return_time -- Возвращаем таймеру время, через которое он должен снова сработать. Когда пройдет последний раунд таймер получит значение 'nil' и выключится.
   end)[/quote]
не подскажешь как исправить ?
 
Последнее редактирование модератором:
Тебе пишут в логе, что в 289 строке отсутствует "then", который ожидается перед "return_time".
Смотришь и видишь:

Код:
if GAME_ROUND == MAX_ROUNDS -- комментарий
      return_time = nil

Тут оператор программирования if else. Можешь почитать о нем в будущем.
Его структура устроена так:
Если "выполняется условие" то
"сделать следующее"
иначе
"сделать другое"
конец.

Можно обходиться и без else (иначе), тогда будет так:
Если "выполняется условие" то
"сделать следующее"
конец.

if "выполняется условие" then
"сделать следующее"
end

У тебя есть "если" (if), но отсутствует "то" (then).


Ну и общие выводы по всем твоим вопросам сводятся к тому, что ты не воспользовался моим самым первым тебе советом. Ведь иначе бы ты прочел это и давно бы уже сделал все сам.
 
Последнее редактирование модератором:
Там просто ну очень много читать)))) а мне и так читать много ибо я курсач пишу). Но все равно спасибо за все, сегодня под вечер место сказки себе почитаю, если еще будет что то я напишу но впредь попробую сам все сделать) еще раз спасибо тебе
 
Спасибо большое, я понял свой косяк, исправил все и там почему то 2 раза была прописана команда с крипчиками. Все теперь ошибок нет вообще но... Как сделать крипов вражескими, ато они идут их бить нельзя. И как тогда увеличить волны и где взять коды других крипов, чтоб волны увеличить
 
Реклама: