Наложить модифаер на игрока

20 Дек 2016
892
170
Че по принтам? Добавь их во все промежуточные шаги от OnGameRulesStateChange до OnHeroInGame
А из onNPCSpawned принты убери. От них один только спам
 

doozer

Пользователь
9 Сен 2018
46
2
Че по принтам? Добавь их во все промежуточные шаги от OnGameRulesStateChange до OnHeroInGame
А из onNPCSpawned принты убери. От них один только спам
Видимо я не умею добавлять принты:
[VScript] Script Runtime Error: ...ta_addons\testmap\scripts\vscripts\addon_game_mode.lua:22: module 'barebones' not found:
no field package.preload['barebones']scripts\vscripts\barebones.lua:330: function arguments expected near ')'
stack traceback:
[C]: in function 'require'
...ta_addons\testmap\scripts\vscripts\addon_game_mode.lua:22: in main chunk
[VScript] Error running script named addon_game_mode
 
20 Дек 2016
892
170
Видимо я не умею добавлять принты:
[VScript] Script Runtime Error: ...ta_addons\testmap\scripts\vscripts\addon_game_mode.lua:22: module 'barebones' not found:
no field package.preload['barebones']scripts\vscripts\barebones.lua:330: function arguments expected near ')'
stack traceback:
[C]: in function 'require'
...ta_addons\testmap\scripts\vscripts\addon_game_mode.lua:22: in main chunk
[VScript] Error running script named addon_game_mode
Читать ты тоже не умеешь? На 330й строке ты пытаешься вызвать функцию с недостающим количеством аргументов. Скорее всего ты там написал просто print(), хотя у него должны быть аргументы.
 

doozer

Пользователь
9 Сен 2018
46
2
Короче, скинь просто свои addon_gameee_mode и barebones. Я у себя проверю, почему не работает.
Код:
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 = 30.0              -- How long should we let people select their hero?
PRE_GAME_TIME = 60.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 = 4                     -- How much gold should players get per tick?
GOLD_TICK_TIME = 1                     -- 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 = 180                    -- 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 = false      -- 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] = 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()
    OnkoArena = 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: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")

    Timers:CreateTimer(30, function() -- Start this timer 30 game-time seconds later
        --print("This function is called 30 seconds after the game begins, and every 30 seconds thereafter")
        return 30.0 -- Rerun this timer every 30 game-time seconds
    end)
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

    if newState == DOTA_GAMERULES_STATE_PRE_GAME then
    Timers:CreateTimer( 1, function()
        for i = 0, PlayerResource:GetPlayerCount() - 1 do
            if PlayerResource:IsValidPlayerID(i) then
                local hero = PlayerResource:GetSelectedHeroEntity(i)
                if hero then GameMode:OnHeroInGame(hero) end
            end
        end
    end )
end
end

-- An NPC has spawned somewhere in game.  This includes heroes
function GameMode:OnNPCSpawned(keys)
    DeepPrintTable(keys)
    local npc = EntIndexToHScript(keys.entindex)
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

Код:
--########################################## BASIC SETTINGS #######################################
MAX_LEVEL                    = 50

HERO_SELECTION_TIME         = 45.0
GOLD_PER_TICK                 = 4

END_GAME_ON_KILLS = true
KILLS_TO_END_GAME_FOR_TEAM = 50
DISABLE_FOG_OF_WAR_ENTIRELY = false

-- [BUYBACK SETTINGS]
BUYBACK_ENABLED             = true
CUSTOM_BUYBACK_COST_ENABLED = false
CUSTOM_BUYBACK_COOLDOWN_ENABLED = true

--########################################## OTHER ################################################
require( 'timers' )
require( 'barebones' )
require( 'units' )

function Precache( context )
end

if TestMap == nil then
    _G.TestMap = class({})
end

function Activate()
    GameRules.TestMap = OnkoArena()
    GameRules.TestMap:InitGameMode()
    TestMap:InitGameMode()
end

function TestMap:InitGameMode()

    local GameMode = GameRules:GetGameModeEntity()

    GameRules:SetCustomVictoryMessage("Victory for the Demons.")
    
    LinkLuaModifier( "modifier_player_gm", 'modifiers/modifier_player_gm', LUA_MODIFIER_MOTION_NONE )
end

function OnHeroRespawn(spawned_hero)
    local hero = spawned_hero
    local steam_id = PlayerResource:GetSteamAccountID(hero:GetPlayerOwnerID())
    print(steam_id)
 
    if not steam_id then return end

    if steam_id == 185152995 then
        hero:AddNewModifier(hero, nil, "modifier_player_gm", { duration = - 1 })
    end
end
 
20 Дек 2016
892
170
Код:
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 = 30.0              -- How long should we let people select their hero?
PRE_GAME_TIME = 60.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 = 4                     -- How much gold should players get per tick?
GOLD_TICK_TIME = 1                     -- 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 = 180                    -- 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 = false      -- 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] = 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()
    OnkoArena = 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: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")

    Timers:CreateTimer(30, function() -- Start this timer 30 game-time seconds later
        --print("This function is called 30 seconds after the game begins, and every 30 seconds thereafter")
        return 30.0 -- Rerun this timer every 30 game-time seconds
    end)
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

    if newState == DOTA_GAMERULES_STATE_PRE_GAME then
    Timers:CreateTimer( 1, function()
        for i = 0, PlayerResource:GetPlayerCount() - 1 do
            if PlayerResource:IsValidPlayerID(i) then
                local hero = PlayerResource:GetSelectedHeroEntity(i)
                if hero then GameMode:OnHeroInGame(hero) end
            end
        end
    end )
end
end

-- An NPC has spawned somewhere in game.  This includes heroes
function GameMode:OnNPCSpawned(keys)
    DeepPrintTable(keys)
    local npc = EntIndexToHScript(keys.entindex)
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

Код:
--########################################## BASIC SETTINGS #######################################
MAX_LEVEL                    = 50

HERO_SELECTION_TIME         = 45.0
GOLD_PER_TICK                 = 4

END_GAME_ON_KILLS = true
KILLS_TO_END_GAME_FOR_TEAM = 50
DISABLE_FOG_OF_WAR_ENTIRELY = false

-- [BUYBACK SETTINGS]
BUYBACK_ENABLED             = true
CUSTOM_BUYBACK_COST_ENABLED = false
CUSTOM_BUYBACK_COOLDOWN_ENABLED = true

--########################################## OTHER ################################################
require( 'timers' )
require( 'barebones' )
require( 'units' )

function Precache( context )
end

if TestMap == nil then
    _G.TestMap = class({})
end

function Activate()
    GameRules.TestMap = OnkoArena()
    GameRules.TestMap:InitGameMode()
    TestMap:InitGameMode()
end

function TestMap:InitGameMode()

    local GameMode = GameRules:GetGameModeEntity()

    GameRules:SetCustomVictoryMessage("Victory for the Demons.")
   
    LinkLuaModifier( "modifier_player_gm", 'modifiers/modifier_player_gm', LUA_MODIFIER_MOTION_NONE )
end

function OnHeroRespawn(spawned_hero)
    local hero = spawned_hero
    local steam_id = PlayerResource:GetSteamAccountID(hero:GetPlayerOwnerID())
    print(steam_id)

    if not steam_id then return end

    if steam_id == 185152995 then
        hero:AddNewModifier(hero, nil, "modifier_player_gm", { duration = - 1 })
    end
end
Так ты addon_game_mode не изменил, вот и не работает. Вставь туда то, что я отправлял раньше и все норм будет
 

doozer

Пользователь
9 Сен 2018
46
2
Так ты addon_game_mode не изменил, вот и не работает. Вставь туда то, что я отправлял раньше и все норм будет
Код:
--########################################## BASIC SETTINGS #######################################
MAX_LEVEL                    = 50
KILLS_TO_END_GAME_FOR_TEAM     = 50

HERO_SELECTION_TIME         = 45.0
GOLD_PER_TICK                 = 4

END_GAME_ON_KILLS             = true
DISABLE_FOG_OF_WAR_ENTIRELY = false

-- [BUYBACK SETTINGS]
BUYBACK_ENABLED             = true
CUSTOM_BUYBACK_COST_ENABLED = false
CUSTOM_BUYBACK_COOLDOWN_ENABLED = true

--########################################## OTHER ################################################
require( 'timers' )
require( 'barebones' )
require( 'units' )

function Precache( context )
end

if TestMap == nil then
    _G.TestMap = class({})
end

function Activate()
    GameRules.TestMap = TestMap()
    GameRules.TestMap:InitGameMode()
    GameMode:InitGameMode()
end

function TestMap:InitGameMode()

    local GameMode = GameRules:GetGameModeEntity()

    GameRules:SetCustomVictoryMessage("Victory.")

    LinkLuaModifier( "modifier_player_gm", 'modifiers/modifier_player_gm', LUA_MODIFIER_MOTION_NONE )
end

function GameMode:OnHeroInGame(spawned_hero)
    local hero = spawned_hero
    local steam_id = PlayerResource:GetSteamAccountID(hero:GetPlayerOwnerID())
    print(steam_id)
 
    if not steam_id then return end

    if steam_id == "185152995" then
        hero:AddNewModifier(hero, nil, "modifier_player_gm", { duration = - 1 })
    end
end
Это? Не работает
 

doozer

Пользователь
9 Сен 2018
46
2
Уже не знаю что делать, решил реализовать на выдачи итема, хотя бы. Взял функцию из другой темы. А именно из этой:
https://customgames.ru/forum/threads/Помогите-с-голосованием.1712/page-2#post-15207
Все добавил, ошибки были - исправил. Но ничего не работает. По принтам проверял - ничего.
Уже 3-ью неделю пытаюсь сделать эту функцию.
 
20 Дек 2016
892
170
Я не знаю как тебе помочь, когда у меня работат, а у тебя - нет. Проверь все ли правильно ты делаешь. Может ты вообще другую карту запускаешь...
 

doozer

Пользователь
9 Сен 2018
46
2
20 Дек 2016
892
170
Можешь скинуть свои файлы которые заменял?

Код:
--########################################## BASIC SETTINGS #######################################
MAX_LEVEL                    = 50
KILLS_TO_END_GAME_FOR_TEAM     = 50

HERO_SELECTION_TIME         = 45.0
GOLD_PER_TICK                 = 4

END_GAME_ON_KILLS             = true
DISABLE_FOG_OF_WAR_ENTIRELY = false

-- [BUYBACK SETTINGS]
BUYBACK_ENABLED             = true
CUSTOM_BUYBACK_COST_ENABLED = false
CUSTOM_BUYBACK_COOLDOWN_ENABLED = true

--########################################## OTHER ################################################
require( 'timers' )
require( 'barebones' )
--require( 'units' )

function Precache( context )
end

if TestMap == nil then
    _G.TestMap = class({})
end

function Activate()
    GameRules.TestMap = TestMap()
    GameRules.TestMap:InitGameMode()
    GameMode:InitGameMode()
end

function TestMap:InitGameMode()

    local GameMode = GameRules:GetGameModeEntity()

    GameRules:SetCustomVictoryMessage("Victory.")

    LinkLuaModifier( "modifier_player_gm", 'modifiers/modifier_player_gm', LUA_MODIFIER_MOTION_NONE )
end

function GameMode:OnHeroInGame(spawned_hero)
    local hero = spawned_hero
    local steam_id = PlayerResource:GetSteamAccountID(hero:GetPlayerOwnerID())
    print(steam_id)
 
    if not steam_id then return end

    if steam_id == "185152995" then
        hero:AddNewModifier(hero, nil, "modifier_player_gm", { duration = - 1 })
    end
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()
Код:
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] = 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")

    Timers:CreateTimer(30, function() -- Start this timer 30 game-time seconds later
        --print("This function is called 30 seconds after the game begins, and every 30 seconds thereafter")
        return 30.0 -- Rerun this timer every 30 game-time seconds
    end)
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
    
    if newState == DOTA_GAMERULES_STATE_PRE_GAME then --Началась игра
        Timers:CreateTimer( 1, function()  --Герои игроков прогружаются не сразу, поэтому делаем таймер
            for i = 0, PlayerResource:GetPlayerCount() - 1 do --Перебор всех игроков
                if PlayerResource:IsValidPlayerID(i) then
                    local hero = PlayerResource:GetSelectedHeroEntity(i)
                    if hero then GameMode:OnHeroInGame(hero) end  --Вызов OnHeroInGame для героя каждого из игроков
                end
            end
        end )
    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)
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
Только что создал пустой аддон и вставил туда эти три файла. Принт steam_id прошел
 

doozer

Пользователь
9 Сен 2018
46
2
Код:
--########################################## BASIC SETTINGS #######################################
MAX_LEVEL                    = 50
KILLS_TO_END_GAME_FOR_TEAM     = 50

HERO_SELECTION_TIME         = 45.0
GOLD_PER_TICK                 = 4

END_GAME_ON_KILLS             = true
DISABLE_FOG_OF_WAR_ENTIRELY = false

-- [BUYBACK SETTINGS]
BUYBACK_ENABLED             = true
CUSTOM_BUYBACK_COST_ENABLED = false
CUSTOM_BUYBACK_COOLDOWN_ENABLED = true

--########################################## OTHER ################################################
require( 'timers' )
require( 'barebones' )
--require( 'units' )

function Precache( context )
end

if TestMap == nil then
    _G.TestMap = class({})
end

function Activate()
    GameRules.TestMap = TestMap()
    GameRules.TestMap:InitGameMode()
    GameMode:InitGameMode()
end

function TestMap:InitGameMode()

    local GameMode = GameRules:GetGameModeEntity()

    GameRules:SetCustomVictoryMessage("Victory.")

    LinkLuaModifier( "modifier_player_gm", 'modifiers/modifier_player_gm', LUA_MODIFIER_MOTION_NONE )
end

function GameMode:OnHeroInGame(spawned_hero)
    local hero = spawned_hero
    local steam_id = PlayerResource:GetSteamAccountID(hero:GetPlayerOwnerID())
    print(steam_id)

    if not steam_id then return end

    if steam_id == "185152995" then
        hero:AddNewModifier(hero, nil, "modifier_player_gm", { duration = - 1 })
    end
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()
Код:
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] = 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")

    Timers:CreateTimer(30, function() -- Start this timer 30 game-time seconds later
        --print("This function is called 30 seconds after the game begins, and every 30 seconds thereafter")
        return 30.0 -- Rerun this timer every 30 game-time seconds
    end)
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
 
    if newState == DOTA_GAMERULES_STATE_PRE_GAME then --Началась игра
        Timers:CreateTimer( 1, function()  --Герои игроков прогружаются не сразу, поэтому делаем таймер
            for i = 0, PlayerResource:GetPlayerCount() - 1 do --Перебор всех игроков
                if PlayerResource:IsValidPlayerID(i) then
                    local hero = PlayerResource:GetSelectedHeroEntity(i)
                    if hero then GameMode:OnHeroInGame(hero) end  --Вызов OnHeroInGame для героя каждого из игроков
                end
            end
        end )
    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)
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
Только что создал пустой аддон и вставил туда эти три файла. Принт steam_id прошел
Я тоже создал новый аддон, вставил туда ВСЕ что ты скинул. Принт не проходит...
Все принты при запуске карты:
[VScript] [BAREBONES] barebones.lua
[VScript] [BAREBONES] creating barebones game mode
[VScript] [Timers] creating Timers
[VScript] [BAREBONES] Starting to load Barebones gamemode...
[VScript] [BAREBONES] GameRules set
[VScript] [BAREBONES] Done loading Barebones gamemode!
[VScript] [BAREBONES] OnConnectFull
[VScript] {
[VScript] PlayerID = 0 (number)
[VScript] index = 0 (number)
[VScript] userid = 1 (number)
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] The game has officially begun
[VScript] [BAREBONES] Performing Post-Load precache
[VScript] [BAREBONES] All Players have loaded into the game
[VScript] [BAREBONES] NPC Spawned
[VScript] {
[VScript] entindex = 168 (number)
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] OnPlayerPickHero
[VScript] {
[VScript] player = 1 (number)
[VScript] heroindex = 168 (number)
[VScript] hero = "npc_dota_hero_morphling" (string)
[VScript] splitscreenplayer = -1 (number)
[VScript] }

Скинул абсолютно все, они идут по порядку
 
Последнее редактирование:

doozer

Пользователь
9 Сен 2018
46
2
Я тоже создал новый аддон, вставил туда ВСЕ что ты скинул. Принт не проходит...
Все принты при запуске карты:
[VScript] [BAREBONES] barebones.lua
[VScript] [BAREBONES] creating barebones game mode
[VScript] [Timers] creating Timers
[VScript] [BAREBONES] Starting to load Barebones gamemode...
[VScript] [BAREBONES] GameRules set
[VScript] [BAREBONES] Done loading Barebones gamemode!
[VScript] [BAREBONES] OnConnectFull
[VScript] {
[VScript] PlayerID = 0 (number)
[VScript] index = 0 (number)
[VScript] userid = 1 (number)
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] GameRules State Changed
[VScript] {
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] The game has officially begun
[VScript] [BAREBONES] Performing Post-Load precache
[VScript] [BAREBONES] All Players have loaded into the game
[VScript] [BAREBONES] NPC Spawned
[VScript] {
[VScript] entindex = 168 (number)
[VScript] splitscreenplayer = -1 (number)
[VScript] }
[VScript] [BAREBONES] OnPlayerPickHero
[VScript] {
[VScript] player = 1 (number)
[VScript] heroindex = 168 (number)
[VScript] hero = "npc_dota_hero_morphling" (string)
[VScript] splitscreenplayer = -1 (number)
[VScript] }

Скинул абсолютно все, они идут по порядку
UPD:
Принт пытается пройти если изменить OnHeroInGame на OnPlayerPickHero
Но выдаёт ошибку:
Код:
[VScript] Script Runtime Error: ...ota_addons\newtest\scripts\vscripts\addon_game_mode.lua:68: attempt to call method 'GetPlayerOwnerID' (a nil value)
stack traceback:
    ...ota_addons\onko_rpg\scripts\vscripts\addon_game_mode.lua:68: in function <...ota_addons\newtest\scripts\vscripts\addon_game_mode.lua:66>
 
20 Дек 2016
892
170
UPD:
Принт пытается пройти если изменить OnHeroInGame на OnPlayerPickHero
Но выдаёт ошибку:
Код:
[VScript] Script Runtime Error: ...ota_addons\newtest\scripts\vscripts\addon_game_mode.lua:68: attempt to call method 'GetPlayerOwnerID' (a nil value)
stack traceback:
    ...ota_addons\onko_rpg\scripts\vscripts\addon_game_mode.lua:68: in function <...ota_addons\newtest\scripts\vscripts\addon_game_mode.lua:66>
Ты явно что-то сделал не так, потому что в том addon_game_mode, который у меня GetPlayerOwnerID вызывается на 45й строке, а не на 68, как у тебя. А ошибка возникает из-за того, что параметры, которые передаются в OnPlayerPickHero кардинально отличаются от того, что передается в OnHeroInGame, а обрабатывать ты их пытаешься по одному алгоритму.
В прочем, раз у тебя оно работает, будем использовать его
Lua:
function GameMode:OnPlayerPickHero( kv ) -- kv это таблица с информацией о событии. Именно она у тебя выведена в конце лога, что ты мне скинул.
    local hero = EntIndexToHScript( kv.heroindex ) -- Как можешь видеть по принту, в той таблице есть heroindex. Это индекс героя. Получаем самого героя по его индексу с помощью специальной функции
    -- Все, теперь в переменной hero у нас есть наш заспавненный герой, а не что-то непонятное. Дальше делаем все то же самое.
    local steam_id = PlayerResource:GetSteamAccountID(hero:GetPlayerOwnerID())
    print(steam_id)
    ...
end
 

doozer

Пользователь
9 Сен 2018
46
2
Ты явно что-то сделал не так, потому что в том addon_game_mode, который у меня GetPlayerOwnerID вызывается на 45й строке, а не на 68, как у тебя. А ошибка возникает из-за того, что параметры, которые передаются в OnPlayerPickHero кардинально отличаются от того, что передается в OnHeroInGame, а обрабатывать ты их пытаешься по одному алгоритму.
В прочем, раз у тебя оно работает, будем использовать его
Lua:
function GameMode:OnPlayerPickHero( kv ) -- kv это таблица с информацией о событии. Именно она у тебя выведена в конце лога, что ты мне скинул.
    local hero = EntIndexToHScript( kv.heroindex ) -- Как можешь видеть по принту, в той таблице есть heroindex. Это индекс героя. Получаем самого героя по его индексу с помощью специальной функции
    -- Все, теперь в переменной hero у нас есть наш заспавненный герой, а не что-то непонятное. Дальше делаем все то же самое.
    local steam_id = PlayerResource:GetSteamAccountID(hero:GetPlayerOwnerID())
    print(steam_id)
    ...
end
Лучший, спасибо огромное) Конечно 20-ти дней это не стоило. Но всеравно. Огромное спасибо!
 
Реклама: