content
stringlengths 5
1.05M
|
|---|
-- Copyright (C) by Hiroaki Nakamura (hnakamur)
local session_cookie = require "session.cookie"
local session_store = require "session.store"
local saml_sp_request = require "saml.service_provider.request"
local saml_sp_response = require "saml.service_provider.response"
local resty_random = require "resty.random"
local str = require "resty.string"
local setmetatable = setmetatable
local _M = { _VERSION = '0.1.0' }
local mt = { __index = _M }
function _M.new(self, config)
return setmetatable({
config = config
}, mt)
end
function _M.access(self)
local session_cookie = self:session_cookie()
local session_id, err = session_cookie:get()
if err ~= nil then
return false,
string.format("failed to get session cookie during access, err=%s", err)
end
local key_attr = nil
if session_id ~= nil then
local ss = self:session_store()
key_attr = ss:get(session_id)
if key_attr ~= nil and ss.expire_seconds ~= 0 then
local ok, err = ss:extend(session_id)
if err ~= nil then
return false,
string.format("failed to extend session during access, err=%s", err)
end
end
end
if session_id == nil or key_attr == nil then
local sp_req = self:request()
return sp_req:redirect_to_idp_to_login()
end
local key_attr_name = self.config.key_attribute_name
ngx.req.set_header(key_attr_name, key_attr)
return true, key_attr
end
function _M.finish_login(self)
local sp_resp = self:response()
local response_xml, err = sp_resp:read_and_base64decode_response()
if err ~= nil then
return false,
string.format("failed to read and decode response during finish_login, err=%s", err)
end
local ok, err = sp_resp:verify_response(response_xml)
if err ~= nil then
return false,
string.format("failed to verify response during finish_login, err=%s", err)
end
local attrs, err = sp_resp:take_attributes_from_response(response_xml)
if err ~= nil then
return false,
string.format("failed to take attributes from response during finish_login, err=%s", err)
end
local key_attr_name = self.config.key_attribute_name
local key_attr = attrs[key_attr_name]
if key_attr == nil then
return false,
string.format('failed to get key attribute "%s" from response during finish_login, err=%s', key_attr_name, err)
end
local ss = self:session_store()
local session_id, err = ss:add(key_attr)
if err ~= nil then
return false,
string.format("failed to create session dict entry during finish_login, err=%s", err)
end
local sc = self:session_cookie()
local ok, err = sc:set(session_id)
if err ~= nil then
return false,
string.format("failed to set session cookie during finish_login, err=%s", err)
end
local dict_name = self.config.request.urls_before_login.dict_name
local redirect_urls_dict = dict_name ~= nil and ngx.shared[dict_name] or nil
ngx.log(ngx.INFO, string.format("finish_login dict_name=%s, dict=%s", dict_name, redirect_urls_dict))
if redirect_urls_dict ~= nil then
local request_id, err = sp_resp:take_request_id_from_response(response_xml)
if err ~= nil then
return false,
string.format("failed to take request ID from response during finish_login, err=%s", err)
end
ngx.log(ngx.INFO, string.format("finish_login request_id=%s", request_id))
local redirect_url = redirect_urls_dict:get(request_id)
ngx.log(ngx.INFO, string.format("finish_login redirect_url=%s", redirect_url))
if redirect_url ~= nil then
redirect_urls_dict:delete(request_id)
return ngx.redirect(redirect_url)
end
end
return ngx.redirect(self.config.redirect.url_after_login)
end
function _M.logout(self)
local sc = self:session_cookie()
local session_id, err = sc:get()
if err ~= nil then
return false,
string.format("failed to get session cookie during logout, err=%s", err)
end
if session_id ~= nil then
local ss = self:session_store()
ss:delete(session_id)
end
local ok, err = sc:delete()
if err ~= nil then
return false,
string.format("failed to delete session cookie during logout, err=%s", err)
end
return ngx.redirect(self.config.redirect.url_after_logout)
end
function _M.request(self)
local request = self._request
if request ~= nil then
return request
end
local config = self.config.request
request = saml_sp_request:new{
idp_dest_url = config.idp_dest_url,
sp_entity_id = config.sp_entity_id,
sp_saml_finish_url = config.sp_saml_finish_url,
urls_before_login = config.urls_before_login,
request_id_generator = function()
return "_" .. str.to_hex(resty_random.bytes(config.request_id_byte_length or 16))
end
}
self._request = request
return request
end
function _M.response(self)
local response = self._response
if response ~= nil then
return response
end
local config = self.config.response
response = saml_sp_response:new{
xmlsec_command = config.xmlsec_command,
idp_cert_filename = config.idp_cert_filename,
key_attribute_name = config.key_attribute_name
}
self._response = response
return response
end
function _M.session_cookie(self)
local cookie = self._session_cookie
if cookie ~= nil then
return cookie
end
local config = self.config.session.cookie
cookie = session_cookie:new{
name = config.name,
path = config.path,
secure = config.secure
}
self._session_cookie = cookie
return cookie
end
function _M.session_store(self)
local store = self._session_store
if store ~= nil then
return store
end
local config = self.config.session.store
store = session_store:new{
dict_name = config.dict_name,
id_generator = function()
return str.to_hex(resty_random.bytes(config.id_byte_length or 16))
end
}
self._session_store = store
return store
end
return _M
|
--[[------------
Q U A K E
Heads Up Display
Version 1.3.3
19/01/22
By DyaMetR
]]--------------
-- Main framework table
Q1HUD = {};
Q1HUD.Version = "1. 33";
--[[
METHODS
]]
--[[
Correctly includes a file
@param {string} file
@void
]]--
function Q1HUD:IncludeFile(file)
if SERVER then
include(file);
AddCSLuaFile(file);
end
if CLIENT then
include(file);
end
end
--[[
INCLUDES
]]
Q1HUD:IncludeFile("q1hud/core.lua");
|
registerNpc(347, {
walk_speed = 210,
run_speed = 700,
scale = 150,
r_weapon = 1064,
l_weapon = 0,
level = 98,
hp = 27,
attack = 413,
hit = 219,
def = 313,
res = 359,
avoid = 148,
attack_spd = 95,
is_magic_damage = 1,
ai_type = 129,
give_exp = 79,
drop_type = 379,
drop_money = 0,
drop_item = 49,
union_number = 49,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 1500,
npc_type = 7,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
registerNpc(349, {
walk_speed = 210,
run_speed = 700,
scale = 150,
r_weapon = 1064,
l_weapon = 0,
level = 98,
hp = 27,
attack = 413,
hit = 219,
def = 313,
res = 359,
avoid = 148,
attack_spd = 100,
is_magic_damage = 1,
ai_type = 138,
give_exp = 79,
drop_type = 379,
drop_money = 0,
drop_item = 48,
union_number = 48,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 1500,
npc_type = 7,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end
|
local Const = require(ENV_RFF_PATH .. "constants")
local Firearm = require(ENV_RFF_PATH .. "firearm/init")
local Ammo = require(ENV_RFF_PATH .. "ammo/init")
local Magazine = require(ENV_RFF_PATH .. "magazine/init")
local TestData = { }
TestData.AmmoGroups = {
AmmoGroup_357Magnum = { },
AmmoGroup_556x45mm = { },
}
TestData.Ammo = {
Ammo_357Magnum_Type1 = {
case = "Case_357Magnum",
groups = { AmmoGroup_357Magnum = 1, },
case_mass = 1, bullet_mass = 1, powder_mass = 1, powder_type = "",
category = Ammo.Flags.PISTOL,
features = Ammo.Flags.JACKETED + Ammo.Flags.HOLLOWPOINT + Ammo.Flags.FLATPOINT,
},
Ammo_357Magnum_Type2 = {
case = "Case_357Magnum",
groups = { AmmoGroup_357Magnum = 1, },
case_mass = 1, bullet_mass = 1, powder_mass = 1, powder_type = "",
category = Ammo.Flags.PISTOL,
features = Ammo.Flags.JACKETED + Ammo.Flags.FLATPOINT,
},
Ammo_556x45mm_Type1 = {
case = "Case_556x45mm",
groups = { AmmoGroup_556x45mm = 1, },
case_mass = 1, bullet_mass = 1, powder_mass = 1, powder_type = "",
category = Ammo.Flags.RIFLE,
features = Ammo.Flags.JACKETED,
},
}
TestData.MagazineGroups = {
MagazineGroup_STANAG = { },
}
TestData.Magazines = {
STANAGx20 = {
weight = 0.2,
groups = { MagazineGroup_STANAG = 1 },
max_capacity = 20,
ammo_group = "AmmoGroup_556x45mm",
features = Magazine.Flags.BOX,
},
STANAGx30 = {
weight = 0.2,
groups = { MagazineGroup_STANAG = 1 },
max_capacity = 30,
ammo_group = "AmmoGroup_556x45mm",
features = Magazine.Flags.BOX,
}
}
TestData.Firearms = {
Revolver1 = {
weight = 1,
barrel_length = 6,
max_capacity = 6,
category = Const.REVOLVER,
feed_system = Firearm.Flags.ROTARY,
features = Firearm.Flags.SINGLEACTION + Firearm.Flags.DOUBLEACTION + Firearm.Flags.SAFETY,
ammo_group = "AmmoGroup_357Magnum",
},
SemiAutoRifle1 = {
weight = 3.3,
barrel_length = 20,
-- max_capacity = 6,
category = Const.RIFLE,
magazine_group = nil,
feed_system = Firearm.Flags.AUTO + Firearm.Flags.DIRECTGAS,
features = Firearm.Flags.DOUBLEACTION + Firearm.Flags.SAFETY,
ammo_group = "AmmoGroup_556x45mm",
}
}
return TestData
--[[
local Const = require(ENV_RFF_PATH .. "constants")
local Firearm = require(ENV_RFF_PATH .. "firearm/init")
local FirearmType = require(ENV_RFF_PATH .. "firearm/type")
local FirearmGroup = require(ENV_RFF_PATH .. "firearm/group")
local Flags = require(ENV_RFF_PATH .. "firearm/flags")
FirearmGroup:new("Group_Main")
FirearmGroup:new("Group_RareCollectables")
FirearmGroup:new("Group_Classifications", { Groups = { Group_Main = 1, } })
FirearmGroup:new("Group_Rifles", { Groups = { Group_Classifications = 20, } })
FirearmGroup:new("Group_Manufacturers", { Groups = { Group_Main = 1, } })
FirearmGroup:new("Group_Colt", { Groups = { Group_Manufacturers = 1, } })
FirearmGroup:new("Group_Colt_Rifles", { Groups = { Group_Rifles = 1, Group_Colt = 1 } })
FirearmGroup:new("Group_Colt_CAR15", { Groups = { Group_Colt_Rifles = 1, } })
FirearmType:newCollection("Colt_CAR15", {
category = Const.RIFLE,
ammo_group = "AmmoGroup_556x45mm",
magazine_group = "MagGroup_STANAG",
weight = 3.3,
barrel_length = 20,
max_capacity = 30,
classification = "IGUI_Firearm_AssaultRifle",
country = "IGUI_Firearm_Country_US",
manufacturer = "IGUI_Firearm_Manuf_Colt",
description = "IGUI_Firearm_Desc_M16",
feed_system = Flags.AUTO + Flags.DIRECTGAS,
features = Flags.DOUBLEACTION + Flags.SLIDELOCK + Flags.SAFETY + Flags.SELECTFIRE + Flags.SEMIAUTO,
}, {
M601 = { -- Colt AR-15 Model 601
year = 1959,
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.FULLAUTO,
},
M604 = { -- Colt M16 Model 604
year = 1964,
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.FULLAUTO,
},
M603 = { -- Colt M16A1 Model 603
year = 1967,
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.FULLAUTO,
},
M605A = { -- Colt CAR-15 Carbine Model 605A
year = 1962,
Groups = { Group_Colt_CAR15 = 1 },
barrelLength = 15,
additional_features = Flags.FULLAUTO,
},
M605B = { -- Colt CAR-15 Carbine Model 605B
year = 1966,
Groups = { Group_Colt_CAR15 = 1 },
barrelLength = 15,
additional_features = Flags.FULLAUTO + Flags.BURST3,
},
M607 = { -- Colt CAR-15 SMG Model 607
year = 1966,
barrelLength = 10,
additional_features = Flags.FULLAUTO,
Groups = { Group_Colt_CAR15 = 1, Group_RareCollectables = 50, }, -- 50 manufactured
},
M645 = { -- M16A2 Colt Model 645
year = 1982,
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.BURST3,
},
M646 = { -- M16A3 Colt Model 646
year = 1982,
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.FULLAUTO,
},
M945 = { -- M16A4 Colt Model 945
year = 1998,
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.BURST3,
},
M920 = { -- M4 Model 920
barrelLength = 14.5,
Icon = "Colt_CAR15_M4",
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.BURST3,
--classification = "IGUI_Firearm_AssaultCarbine",
year = 1984,
--country = "IGUI_Firearm_Country_US",
--manufacturer = "IGUI_Firearm_Manuf_Colt",
--description = "IGUI_Firearm_Desc_M4C",
},
M921 = { -- M4A1 Model 921
barrelLength = 14.5,
Icon = "Colt_CAR15_M4",
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.FULLAUTO,
},
M933 = { -- M4 Commando Model 933
barrelLength = 11.5,
Icon = "Colt_CAR15_M4",
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.FULLAUTO,
},
M935 = { -- M4 Commando Model 935
barrelLength = 11.5,
Icon = "Colt_CAR15_M4",
Groups = { Group_Colt_CAR15 = 1 },
additional_features = Flags.BURST3,
},
})
]]
|
return function()
local Modules = game:GetService("Players").LocalPlayer.PlayerGui.AvatarEditorInGame.Modules
local TryOnCharacterModelVersion = require(script.Parent.TryOnCharacterModelVersion)
local IncrementTryOnCharacterModelVersion = require(Modules.AvatarExperience.Catalog.Actions.IncrementTryOnCharacterModelVersion)
it("should be unchanged by other actions", function()
local oldState = TryOnCharacterModelVersion(nil, {})
local newState = TryOnCharacterModelVersion(oldState, { type = "some action" })
expect(oldState).to.equal(newState)
end)
it("should have the character model version be 0 on startup", function()
local state = TryOnCharacterModelVersion(nil, {})
expect(state).to.equal(0)
end)
it("should increment the character model version.", function()
local state = TryOnCharacterModelVersion(nil, IncrementTryOnCharacterModelVersion())
expect(state).to.equal(1)
end)
end
|
SetDiscordAppId(cfg.DiscordAppID)
Citizen.CreateThread(function()
while true do
SetDiscordRichPresenceAsset(cfg.discordImageName)
SetDiscordRichPresenceAssetText(cfg.hoverText)
SetDiscordRichPresenceAssetSmall(cfg.smallDiscordImageName)
SetRichPresence(cfg.richPresenceText)
SetDiscordRichPresenceAction(0, cfg.button1.text, cfg.button1.url)
Wait(5000)
end
end)
|
object_tangible_meatlump_event_meatlump_weapon_palette_01_10 = object_tangible_meatlump_event_shared_meatlump_weapon_palette_01_10:new {
}
ObjectTemplates:addTemplate(object_tangible_meatlump_event_meatlump_weapon_palette_01_10, "object/tangible/meatlump/event/meatlump_weapon_palette_01_10.iff")
|
local uv = vim.loop -- Alias for Neovim's event loop (libuv)
local run_hook -- to handle mutual recursion
-- nvim 0.4 compatibility
local cmd = vim.api.nvim_command
local vfn = vim.api.nvim_call_function
local compat = require('paq-nvim.compat')
----- Constants
local PATH = vfn('stdpath', {'data'}) .. '/site/pack/paqs/' --TODO: PATH is now configurable, rename!
local LOGFILE = vfn('stdpath', {'cache'}) .. '/paq.log'
local GITHUB = 'https://github.com/'
local REPO_RE = '^[%w-]+/([%w-_.]+)$'
local DATEFMT = '%F T %H:%M:%S%z'
----- Globals
local packages = {} -- Table of 'name':{options} pairs
local changes = {} -- Table of 'name':'change' pairs
local num_pkgs = 0
local num_to_rm = 0
local ops = {
clone = {ok=0, fail=0, past = 'cloned' },
pull = {ok=0, fail=0, past = 'pulled changes for'},
remove = {ok=0, fail=0, past = 'removed' },
}
local function output_result(op, name, ok, ishook)
local result, total, msg
local count = ''
local failstr = 'Failed to '
local c = ops[op]
if c then
result = ok and 'ok' or 'fail'
c[result] = c[result] + 1
total = (op == 'remove') and num_to_rm or num_pkgs -- FIXME
count = string.format('%d/%d', c[result], total)
msg = ok and c.past or failstr .. op
if c.ok + c.fail == total then --no more packages to update
c.ok, c.fail = 0, 0
cmd('packloadall! | helptags ALL')
end
elseif ishook then --hooks aren't counted
msg = (ok and 'ran' or failstr .. 'run') .. string.format(' `%s` for', op)
else
msg = failstr .. op
end
print(string.format('Paq [%s] %s %s', count, msg, name))
end
local function call_proc(process, pkg, args, cwd, ishook, cb)
local log, stderr, handle, op
log = uv.fs_open(LOGFILE, 'a+', 0x1A4) -- FIXME: Write in terms of uv.constants
stderr = uv.new_pipe(false)
stderr:open(log)
handle = uv.spawn(
process,
{args=args, cwd=cwd, stdio = {nil, nil, stderr}},
vim.schedule_wrap( function(code)
uv.fs_write(log, '\n', -1) --space out error messages
uv.fs_close(log)
stderr:close()
handle:close()
output_result(args[1] or process, pkg.name, code == 0, ishook)
if type(cb) == 'function' then cb(code) end
if not ishook then run_hook(pkg) end
end)
)
end
function run_hook(pkg) --(already defined as local)
local t, process, args, ok
t = type(pkg.run)
if t == 'function' then
cmd('packadd ' .. pkg.name)
local ok = pcall(pkg.run)
output_result(t, pkg.name, ok, true)
elseif t == 'string' then
args = {}
for word in pkg.run:gmatch('%S+') do
table.insert(args, word)
end
process = table.remove(args, 1)
call_proc(process, pkg, args, pkg.dir, true)
end
end
local function install(pkg)
local args = {'clone', pkg.url}
if pkg.exists then
ops['clone']['ok'] = ops['clone']['ok'] + 1
return
elseif pkg.branch then
compat.list_extend(args, {'-b', pkg.branch})
end
compat.list_extend(args, {pkg.dir})
local cb = function(code)
if code == 0 then
pkg.exists = true
changes[pkg.name] = 'installed'
end
end
call_proc('git', pkg, args, nil, nil, cb)
end
local function get_git_hash(dir)
local function first_line(path)
local file = uv.fs_open(path, 'r', 0x1A4)
if file then
local line = uv.fs_read(file, 41, -1) --FIXME: this might fail
uv.fs_close(file)
return line
end
end
local head_ref = first_line(dir .. "/.git/HEAD")
if head_ref then
return first_line(dir .. "/.git/" .. head_ref:gsub("ref: ", ""))
end
end
local function update(pkg)
if pkg.exists then
local hash = get_git_hash(pkg.dir)
local cb = function(code)
if code == 0 and get_git_hash(pkg.dir) ~= hash then
changes[pkg.name] = 'updated'
end
end
call_proc('git', pkg, {'pull'}, pkg.dir, nil, cb)
end
end
local function iter_dir(fn, dir, args)
local child, name, t, ok
local handle = uv.fs_scandir(dir)
while handle do
name, t = uv.fs_scandir_next(handle)
if not name then break end
child = dir .. '/' .. name
ok = fn(child, name, t, args)
if not ok then return end
end
return true
end
local function rm_dir(child, name, t)
if t == 'directory' then
return iter_dir(rm_dir, child) and uv.fs_rmdir(child)
else
return uv.fs_unlink(child)
end
end
local function mark_dir(dir, name, _, list)
local pkg = packages[name]
if not (pkg and pkg.dir == dir) then
table.insert(list, {name=name, dir=dir})
end
return true
end
local function clean_pkgs()
local rm_list = {}
iter_dir(mark_dir, PATH .. 'start', rm_list)
iter_dir(mark_dir, PATH .. 'opt', rm_list)
num_to_rm = #rm_list -- update count of plugins to be deleted
for _, i in ipairs(rm_list) do
ok = iter_dir(rm_dir, i.dir) and uv.fs_rmdir(i.dir)
output_result('remove', i.name, ok)
if ok then changes[i.name] = 'removed' end
end
end
local function paq(args)
local name, dir
if type(args) == 'string' then args = {args} end
name = args.as or args[1]:match(REPO_RE)
if not name then return output_result('parse', args[1]) end
dir = PATH .. (args.opt and 'opt/' or 'start/') .. name
if not packages[name] then
num_pkgs = num_pkgs + 1
end
packages[name] = {
name = name,
branch = args.branch,
dir = dir,
exists = (vfn('isdirectory', {dir}) ~= 0),
run = args.run or args.hook, --wait for paq 1.0 to deprecate
url = args.url or GITHUB .. args[1] .. '.git',
}
end
local function setup(args)
assert(type(args) == 'table')
if type(args.path) == 'string' then
PATH = args.path --FIXME: should probably rename PATH
end
end
local function list()
local is_installed = function(name) return packages[name].exists end
local was_removed = function(name) return changes[name] == 'removed' end
local installed = compat.tbl_filter(is_installed, compat.tbl_keys(packages))
local removed = compat.tbl_filter(was_removed, compat.tbl_keys(changes))
table.sort(installed)
table.sort(removed)
local indent = " "
local symb_tbl = {
installed = "+",
updated = "*",
removed = " ",
default = " ",
}
local function prefix(name)
return indent .. symb_tbl[changes[name] or 'default'] .. name
end
local function list_pkgs(header, pkgs)
if #pkgs ~= 0 then print(header) end
for _, v in ipairs(compat.tbl_map(prefix, pkgs)) do print(v) end
end
list_pkgs("Installed packages:", installed)
list_pkgs("Recently removed:", removed)
end
return {
install = function() compat.tbl_map(install, packages) end,
update = function() compat.tbl_map(update, packages) end,
clean = clean_pkgs,
list = list,
setup = setup,
paq = paq,
log_open = function() cmd('sp ' .. LOGFILE) end,
log_clean = function() uv.fs_unlink(LOGFILE); print('Paq log file deleted') end,
}
|
Rule("sig01", 1):
fields("request_uri"):
phase("REQUEST_HEADER"):
op('rx', [[f\x00?oo]]):
action("setRequestHeader:X-Foo=bar")
Rule("sig02", 1):
fields("request_uri"):
phase("REQUEST_HEADER"):
op('streq', [[f\x00?oo]]):
action("setRequestHeader:X-Bar=baz")
|
--[[
################################################################################
#
# Copyright (c) 2014-2020 Ultraschall (http://ultraschall.fm)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
################################################################################
]]
-- little helpers
dofile(reaper.GetResourcePath().."/UserPlugins/ultraschall_api.lua")
reaper.Undo_BeginBlock()
for i=0, reaper.CountTracks(0)-1 do
if ultraschall.IsTrackSoundboard(i+1) then
tr = reaper.GetTrack(0, i)
ok, vol, pan = reaper.GetTrackUIVolPan(tr, 0, 0)
-- print(vol)
if vol < 0.01 then vol = 0 end
reaper.SetMediaTrackInfo_Value(tr, "D_VOL", vol*0.8)
-- print("Soundboard: "..i)
-- else
-- print("track: "..i)
end
end
reaper.Undo_EndBlock("Ultraschall lower Soundboard volume", -1)
|
local data = {}
-- Read data
function readPassport()
local p = {}
local line = io.read("l")
while line and line ~= "" do
for k, v in line:gmatch("(%a+):([^%s]+)") do
p[k] = v
end
line = io.read("l")
end
table.insert(data, p)
return line
end
repeat
local l = readPassport()
until not l
function has(p, ...)
local keys = {...}
for i = 1, #keys do
if not p[keys[i]] then return false end
end
return true
end
function validateFields(p)
return has(p, "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
end
function validateByr(p)
local n = tonumber(p.byr)
return #p.byr == 4 and n and tonumber(p.byr) >= 1920 and tonumber(p.byr) <= 2002
end
function validateIyr(p)
local n = tonumber(p.iyr)
return #p.iyr == 4 and n and tonumber(p.iyr) >= 2010 and tonumber(p.iyr) <= 2020
end
function validateEyr(p)
local n = tonumber(p.eyr)
return #p.eyr == 4 and n and tonumber(p.eyr) >= 2020 and tonumber(p.eyr) <= 2030
end
function validateHgt(p)
local n_cm = p.hgt:match("(%d+)cm")
local n_in = p.hgt:match("(%d+)in")
if n_cm then
return tonumber(n_cm) >= 150 and tonumber(n_cm) <= 193
elseif n_in then
return tonumber(n_in) >= 59 and tonumber(n_in) <= 76
else
return false
end
end
function validateHcl(p)
return p.hcl:match("#%x%x%x%x%x%x")
end
function validateEcl(p)
return p.ecl == "amb" or p.ecl == "blu" or p.ecl == "brn" or p.ecl == "gry"
or p.ecl == "grn" or p.ecl == "hzl" or p.ecl == "oth"
end
function validatePid(p)
return #p.pid == 9 and not p.pid:match("[^%d]")
end
function validateAll(p)
if not validateFields(p) then return 0 end
if not validateByr(p) then return 0 end
if not validateIyr(p) then return 0 end
if not validateEyr(p) then return 0 end
if not validateHgt(p) then return 0 end
if not validateHcl(p) then return 0 end
if not validateEcl(p) then return 0 end
if not validatePid(p) then return 0 end
return 1
end
function f1()
local count = 0
for i = 1, #data do
if validateFields(data[i]) then count = count+1 end
end
return count
end
function f2()
local count = 0
for i = 1, #data do
count = count+validateAll(data[i])
end
return count
end
print(f2())
|
object_tangible_veteran_reward_frn_vet_holo_darth_vader = object_tangible_veteran_reward_shared_frn_vet_holo_darth_vader:new {
}
ObjectTemplates:addTemplate(object_tangible_veteran_reward_frn_vet_holo_darth_vader, "object/tangible/veteran_reward/frn_vet_holo_darth_vader.iff")
|
name = "aa[A]bcde"
i=name:find("%[")
print(i)
print(name:sub(i+1,i+1))
|
if enemy_1.hp_percentage > 10 then
character_1:WithWaitTime(1000):UseSkill(2)
character_1:UseSkill(3)
if enemy_1.hp_percentage > 50 then
character_1:UseSkill(4)
end
character_2:UseSkill(2)
character_2:UseSkill(3)
character_2:UseSkill(4)
character_4:UseSkill(1)
character_4:UseSkill(2)
if character_4.hp_percentage > 80 then
character_4:OnPartyMember(3):UseSkill(3)
end
character_3:UseSkill(1)
character_3:UseSkill(2)
end
if turn >= 2 then
character_1:UseSkill(1)
end
if turn > 2 then
character_3:UseSkill(3)
end
if turn > 3 and not character_1:HasStatusEffect("1241") then
if enemy_1.hp_percentage < 25 then
Summon(2)
end
if enemy_1.hp_percentage < 50 then
character_2:UseSkill(1)
end
end
if enemy_1.hp_percentage <= 50 and character_1.hp_percentage < 30 then
UseBluePotion()
end
if enemy_1.hp_percentage <= 50 and character_2.hp_percentage < 30 then
UseBluePotion()
end
|
--***********************************************************
--** THE INDIE STONE **
--***********************************************************
require "TimedActions/ISBaseTimedAction"
---@class ISInsertMagazine : ISBaseTimedAction
ISInsertMagazine = ISBaseTimedAction:derive("ISInsertMagazine")
function ISInsertMagazine:isValid()
if not self.loadFinished then
if self.gun:isContainsClip() then return false end
if not self.character:getInventory():contains(self.magazine) then return false end
end
return self.character:getPrimaryHandItem() == self.gun
end
function ISInsertMagazine:start()
self.character:setVariable("WeaponReloadType", self.gun:getWeaponReloadType())
self.character:setVariable("isLoading", true)
self:setOverrideHandModels(self.gun, nil)
self:setActionAnim(CharacterActionAnims.Reload)
self.character:reportEvent("EventReloading");
self:initVars()
end
function ISInsertMagazine:update()
-- FIXME: jobDelta is always zero since maxTime is -1
self.gun:setJobDelta(self:getJobDelta())
self.magazine:setJobDelta(self:getJobDelta())
end
function ISInsertMagazine:initVars()
ISReloadWeaponAction.setReloadSpeed(self.character, false)
end
function ISInsertMagazine:loadAmmo()
-- we insert a new clip only if we're in the motion of loading
self.character:getInventory():Remove(self.magazine)
self.gun:setCurrentAmmoCount(self.magazine:getCurrentAmmoCount())
self.gun:setContainsClip(true)
self.character:clearVariable("isLoading")
-- we rack only if no round is chambered
if not self.gun:isRoundChambered() and self.gun:getCurrentAmmoCount() >= self.gun:getAmmoPerShoot() then
ISTimedActionQueue.addAfter(self, ISRackFirearm:new(self.character, self.gun))
end
self:forceComplete()
end
function ISInsertMagazine:animEvent(event, parameter)
-- Loading clip is done, we're moving to racking if needed
if event == 'loadFinished' then
self.loadFinished = true
local chance = 3
local xp = 1
if self.character:getPerkLevel(Perks.Reloading) < 5 then
chance = 1
xp = 4
end
if ZombRand(chance) == 0 then
self.character:getXp():AddXP(Perks.Reloading, xp)
end
self:loadAmmo()
end
if event == 'playReloadSound' then
if parameter == 'load' then
if self.gun:getInsertAmmoSound() and self.gun:getCurrentAmmoCount() < self.gun:getMaxAmmo() then
self.character:playSound(self.gun:getInsertAmmoSound())
end
end
end
end
function ISInsertMagazine:stop()
self.gun:setJobDelta(0.0)
self.magazine:setJobDelta(0.0)
self.character:clearVariable("isLoading")
self.character:clearVariable("WeaponReloadType")
ISBaseTimedAction.stop(self)
end
function ISInsertMagazine:perform()
self.gun:setJobDelta(0.0)
self.magazine:setJobDelta(0.0)
self.character:clearVariable("isLoading")
self.character:clearVariable("WeaponReloadType")
-- needed to remove from queue / start next.
ISBaseTimedAction.perform(self)
end
function ISInsertMagazine:new(character, gun, magazine)
local o = ISBaseTimedAction.new(self, character)
o.stopOnWalk = false
o.stopOnRun = true
o.stopOnAim = false
o.maxTime = -1
o.useProgressBar = false
o.gun = gun
o.magazine = magazine
o.loadFinished = false
return o
end
|
local composer = require( "composer" )
local loadsave = require( "loadsave" )
local roleslib = require( "scenes.library.roles" )
local scene = composer.newScene()
local uiGroup = display.newGroup()
local settings = loadsave.loadTable( "settings.json" )
local ui = {
background,
frontbox, title, roles = {}, playericon,
helper, daytime, dayalert,
forward, forwardtext,
strat, strattext,
roleactionicon
}
local playerinfo = {}
local nightcount = 0
local lastkillerkill
local lastdocsave
local lastculted
local currentvisit
local lastdeaths = {}
local lastshrunk = {}
local lynchedvotes = {}
local lastlynched
local nightsound = audio.loadSound( "audio/howl.wav" )
local sunrisesound = audio.loadSound( "audio/rooster.wav" )
local townwinsound = audio.loadSound( "audio/townwin.wav" )
local killerwinsound = audio.loadSound( "audio/killerwin.wav" )
local cultwinsound = audio.loadSound( "audio/cultwin.wav" )
local seconds = 0
local minutes = 0
local stoppedtime = false
local discussLynch
local nightTime
local sunriseTime
local dayTime
local sunsetTime
local function changeBackground( daytime )
ui.background:removeSelf()
ui.background = display.newImageRect( uiGroup, "images/backgrounds/" .. daytime .. "background.png", display.contentWidth, display.contentHeight )
ui.background.x, ui.background.y = display.contentCenterX, display.contentCenterY
ui.background:toBack()
end
local function playDeathAudio( dead )
local deathsound
if settings.playerdeaths[dead] == "audio/deaths/death" .. dead .. ".wav" then
deathsound = audio.loadSound( settings.playerdeaths[dead] )
audio.play( deathsound )
else
deathsound = audio.loadSound( settings.playerdeaths[dead], system.DocumentsDirectory )
audio.play( deathsound )
end
end
local function enforceWinCondition( trigger )
local winchannel
local winchannel2
stoppedtime = true
local function gotoNarrator()
ui.background:removeSelf()
ui.background = nil
ui.strat:removeSelf()
ui.strat = nil
ui.strattext:removeSelf()
ui.strattext = nil
ui.forward:removeEventListener( "tap", gotoNarrator )
ui.forward:removeSelf()
ui.forward = nil
ui.forwardtext:removeSelf()
ui.forwardtext = nil
transition.cancel( ui.forward )
transition.cancel( ui.forwardtext )
ui.title:removeSelf()
ui.title= nil
for i=1, settings.setup.players do
ui.roles[i]:removeSelf()
ui.roles[i] = nil
end
ui.helper:removeSelf()
ui.helper = nil
ui.rolehandbook:removeSelf()
ui.rolehandbook = nil
audio.stop( winchannel )
audio.stop( winchannel2 )
composer.setVariable( "scenario", settings.setup.id )
composer.removeScene( "scenes.narrator" )
composer.gotoScene( "scenes.narrator" )
end
local function congratulate( alignment )
local congratulations = ""
for i=1, table.getn( playerinfo ) do
if playerinfo[i].alignment == alignment then
congratulations = congratulations .. playerinfo[i].name .. ", "
end
end
congratulations = congratulations:sub( 1, -3 )
return congratulations
end
local function endingScenario()
changeBackground( "win" )
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
ui.forwardtext.text = "Scenari"
ui.forward:addEventListener( "tap", gotoNarrator )
end
local function jointKillerCultWins()
winchannel = audio.play( killerwinsound )
winchannel2 = timer.performWithDelay( 1000, function() audio.play( cultwinsound ); end )
local congratulations1 = congratulate( 2 )
local congratulations2 = congratulate( 3 )
ui.helper.text = "Il Killer ha portato a termine una strage ed il Culto ha convertito il Villaggio.\n\nIl Killer ha vinto!\nComplimenti a " .. congratulations1 .. ".\n\nIl Culto ha vinto!\nComplimenti a " .. congratulations2 .. "."
endingScenario()
end
local function cultWins()
winchannel = audio.play( cultwinsound )
local congratulations = congratulate( 3 )
ui.helper.text = "Il Culto ha convertito il Villaggio. Il Culto ha vinto!\n\nComplimenti a " .. congratulations .. "."
endingScenario()
end
local function killerWins()
winchannel = audio.play( killerwinsound )
local congratulations = congratulate( 2 )
ui.helper.text = "Il Killer ha portato a termine una strage. Il Killer ha vinto!\n\nComplimenti a " .. congratulations .. "."
endingScenario()
end
local function townWins()
winchannel = audio.play( townwinsound )
local congratulations = congratulate( 0 )
ui.helper.text = "Il Villaggio ha eradicato il Culto ed eliminato il Killer. Il Villaggio ha vinto!\n\nComplimenti a " .. congratulations .. "."
endingScenario()
end
local function alignmentCount()
local towncount = 0
local killercount = 0
local cultcount = 0
for i=1, table.getn( playerinfo ) do
if playerinfo[i].alive == 1 and playerinfo[i].alignment == 0 then
towncount = towncount + 1
elseif playerinfo[i].alive == 1 and playerinfo[i].alignment == 2 then
killercount = killercount + 1
elseif playerinfo[i].alive == 1 and playerinfo[i].alignment == 3 then
cultcount = cultcount + 1
end
end
return towncount, killercount, cultcount
end
local towncount, killercount, cultcount = alignmentCount()
if trigger == "lynch" then
if killercount+cultcount == 0 then
townWins()
elseif killercount == 1 and towncount+killercount+cultcount <= 2 then
killerWins()
elseif cultcount > towncount+killercount then
cultWins()
else
nightTime()
end
elseif trigger == "kill" then
if killercount+cultcount == 0 then
townWins()
elseif killercount == 1 and towncount+killercount+cultcount <= 2 then
killerWins()
elseif cultcount > towncount+killercount then
cultWins()
else
seconds = 0
minutes = 0
dayTime()
end
end
end
sunsetTime = function()
local function endSunsetTime()
ui.forward:removeEventListener( "tap", endSunsetTime )
display.remove( ui.roleactionicon )
ui.roleactionicon = nil
if lastlynched ~= -1 and playerinfo[lastlynched].role == "Capocultista" then
local count = 0
local function suicideCultist()
count = count + 1
ui.helper.text = ""
display.remove( ui.roleactionicon )
if count > settings.setup.players then
ui.forward:removeEventListener( "tap", suicideCultist )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
enforceWinCondition( "lynch" )
elseif playerinfo[count].alive == 0 or playerinfo[count].role ~= "Cultista" then
suicideCultist()
elseif playerinfo[count].alive == 1 and playerinfo[count].role == "Cultista" then
ui.helper.text = playerinfo[count].name .. " beve da un calice avvelenato ed esala il suo ultimo respiro."
playDeathAudio( count )
playerinfo[count].alive = 0
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/" .. playerinfo[count].role .. ".png", display.contentWidth * 0.3, display.contentWidth * 0.3 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
end
end
ui.helper.text = "Il Capocultista è morto.\n\nIl Culto è stato eradicato. I Cultisti, presi dalla disperazione, si stanno suicidando in massa."
ui.forward:addEventListener( "tap", suicideCultist )
else
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
enforceWinCondition( "lynch" )
end
end
local function voteLynch()
local lynchvote = {}
local lynchvotationicon = {}
local function calculateAliveVoters()
local alivevoters = 0
local voteindicator = ""
for i=1, settings.setup.players do
if playerinfo[i].alive == 1 and lynchedvotes[i] == 0 then
alivevoters = alivevoters + 1
end
end
return alivevoters
end
local function calculateVoteIndicator()
local alivevoters = calculateAliveVoters()
if alivevoters == 1 then
voteindicator = "ANCORA " .. alivevoters .. " VOTO"
else
voteindicator = "ANCORA " .. alivevoters .. " VOTI"
end
return voteindicator
end
local function chooseVote( event )
local lynchedname = {}
local lynchaddvote = {}
local lyncher = event.target.id
local function addVote( event )
for i=1, table.getn( lynchedname ) do
lynchedname[i]:removeSelf()
lynchedname[i] = nil
end
for i=1, table.getn( lynchaddvote ) do
lynchaddvote[i]:removeSelf()
lynchaddvote[i] = nil
end
local voted = event.target.id
lynchedvotes[lyncher] = voted
if calculateAliveVoters() > 0 then
voteLynch()
else
local majority = {}
for i=1, table.getn( lynchedvotes ) do
majority[i] = 0
end
local mostvotes = 0
local mostvoted = 0
for i=1, table.getn( lynchedvotes ) - 1 do
if lynchedvotes[i] ~= 0 then
majority[ lynchedvotes[i] ] = majority[ lynchedvotes[i] ] + 1
if mostvotes < majority[ lynchedvotes[i] ] then
mostvotes = majority[ lynchedvotes[i] ]
mostvoted = lynchedvotes[i]
end
end
end
local absolutemajority = true
for i=1, table.getn( majority ) do
if mostvotes <= majority[i] and i ~= mostvoted then
absolutemajority = false
end
end
if absolutemajority == true and mostvoted ~= settings.setup.players+1 then
ui.helper.text = "Oggi il Villaggio ha decretato il Linciaggio di " .. playerinfo[mostvoted].name .. ".\n\nChe fine orrenda.\n\nAveva il Ruolo di " .. playerinfo[mostvoted].role .. "."
playDeathAudio( mostvoted )
lastlynched = mostvoted
playerinfo[mostvoted].alive = 0
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/" .. playerinfo[mostvoted].role .. ".png", display.contentWidth * 0.3, display.contentWidth * 0.3 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
else
lastlynched = -1
if mostvoted == settings.setup.players+1 then
ui.helper.text = "Oggi il Villaggio ha optato per evitare il Linciaggio."
else
ui.helper.text = "Oggi il Villaggio non ha trovato un accordo e nessun Linciaggio è avvenuto."
end
end
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
ui.forwardtext.text = "Avanti"
ui.forward:addEventListener( "tap", endSunsetTime )
end
end
for i=1, table.getn( lynchvote ) do
lynchvote[i]:removeSelf()
lynchvote[i] = nil
end
for i=1, table.getn( lynchvotationicon ) do
lynchvotationicon[i]:removeSelf()
lynchvotationicon[i] = nil
end
ui.helper.text = "VOTO DI " .. string.upper( playerinfo[lyncher].name .. ":" )
ui.rolehandbook.text = ""
local j = 1
for i=1, settings.setup.players do
if playerinfo[i].alive == 1 then
lynchedname[j] = display.newText( uiGroup, "Lincia " .. settings.playernames[i], display.contentWidth * 0.07, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.086, "GosmickSans.ttf", 18 )
lynchedname[j].anchorX = 0
lynchaddvote[j] = display.newImageRect( uiGroup, "images/interface/hang.png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
lynchaddvote[j].x, lynchaddvote[j].y = display.contentWidth * 0.85, lynchedname[j].y
lynchaddvote[j].id = i
lynchaddvote[j]:addEventListener( "tap", addVote )
j = j + 1
end
end
lynchedname[j] = display.newText( uiGroup, "**NON LINCIARE", display.contentWidth * 0.07, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.086, "GosmickSans.ttf", 18 )
lynchedname[j].anchorX = 0
lynchaddvote[j] = display.newImageRect( uiGroup, "images/interface/peace.png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
lynchaddvote[j].x, lynchaddvote[j].y = display.contentWidth * 0.85, lynchedname[j].y
lynchaddvote[j].id = settings.setup.players + 1
lynchaddvote[j]:addEventListener( "tap", addVote )
end
ui.strat.alpha = 0
ui.strattext.alpha = 0
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
ui.forward:removeEventListener( "tap", voteLynch )
local voteindicator = calculateVoteIndicator()
ui.helper.text = voteindicator.. " AL LINCIAGGIO.."
ui.rolehandbook.text = ""
local j = 1
local votedicon
for i=1, settings.setup.players do
if playerinfo[i].alive == 1 then
if lynchedvotes[i] == 0 then
lynchvote[j] = display.newText( uiGroup, settings.playernames[i] .. " non ha ancora votato", display.contentWidth * 0.07, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.086, "GosmickSans.ttf", 12 )
votedicon = "vote"
elseif lynchedvotes[i] == settings.setup.players+1 then
lynchvote[j] = display.newText( uiGroup, settings.playernames[i] .. " vota **Non Linciare", display.contentWidth * 0.07, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.086, "GosmickSans.ttf", 12 )
votedicon = "voted"
else
lynchvote[j] = display.newText( uiGroup, settings.playernames[i] .. " vota " .. settings.playernames[ lynchedvotes[i] ], display.contentWidth * 0.07, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.086, "GosmickSans.ttf", 12 )
votedicon = "voted"
end
lynchvote[j].anchorX = 0
lynchvotationicon[j] = display.newImageRect( uiGroup, "images/interface/" .. votedicon .. ".png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
lynchvotationicon[j].x, lynchvotationicon[j].y = display.contentWidth * 0.85, lynchvote[j].y
lynchvotationicon[j].id = i
lynchvotationicon[j]:addEventListener( "tap", chooseVote )
j = j + 1
end
end
end
local function clearBeforeVoteLynch()
ui.daytime:removeSelf()
ui.daytime = nil
ui.dayalert.text = ""
voteLynch()
end
changeBackground( "sunset" )
ui.dayalert.text = "GIUNGE IL TRAMONTO.."
ui.dayalert.alpha = 1
ui.helper.text = "\n\nDurante il Tramonto, i Giocatori vivi votano nel Linciaggio. Al termine della votazione, il più votato muore. In caso di pareggio, nessuno muore. Si può votare di evitare il Linciaggio."
ui.helper.alpha = 1
ui.daytime = display.newImageRect( uiGroup, "images/interface/sunset.png", display.contentWidth * 0.35, display.contentWidth * 0.35 )
ui.daytime.x, ui.daytime.y = display.contentWidth * 0.75, display.contentHeight * 0.84
ui.daytime:addEventListener( "tap", clearBeforeVoteLynch )
end
dayTime = function()
local function updateTime()
seconds = seconds + 1
if seconds > 59 then
seconds = 0
minutes = minutes + 1
end
if stoppedtime == false then
ui.helper.text = "Durata della Discussione: " .. minutes .. "m " .. seconds .. "s"
end
end
local discussionTimer = timer.performWithDelay( 1000, updateTime, 0 )
stoppedtime = true
local function endDayTime()
ui.strat.alpha = 0
ui.strattext.alpha = 0
sunsetTime()
end
local showDayStrat
discussLynch = function()
local discussalivenames = {}
local discussdeadnames = {}
local discussdeaths = {}
local discussroles = {}
stoppedtime = false
ui.dayalert.text = ""
local function clearDiscussLynch()
for i=1, table.getn( discussalivenames ) do
discussalivenames[i]:removeSelf()
discussalivenames[i] = nil
end
for i=1, table.getn( discussdeadnames ) do
discussdeadnames[i]:removeSelf()
discussdeadnames[i] = nil
end
for i=1, table.getn( discussdeaths ) do
discussdeaths[i]:removeSelf()
discussdeaths[i] = nil
end
for i=1, table.getn( discussroles ) do
discussroles[i]:removeSelf()
discussroles[i] = nil
end
end
local clearShowDayStrat
local function clearVoteLynch()
timer.cancel( discussionTimer )
clearDiscussLynch()
ui.forward:removeEventListener( "tap", clearVoteLynch )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
ui.strat:removeEventListener( "tap", clearShowDayStrat )
endDayTime()
end
clearShowDayStrat = function()
clearDiscussLynch()
ui.forward:removeEventListener( "tap", clearVoteLynch )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
ui.strat:removeEventListener( "tap", clearShowDayStrat )
showDayStrat()
end
display.remove( ui.daytime )
ui.daytime = nil
local alive
local role
local j = 1
local w = 1
for i=1, settings.setup.players do
if playerinfo[i].alive == 1 then
discussalivenames[w] = display.newText( uiGroup, settings.playernames[i], display.contentWidth * 0.24, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.06, "GosmickSans.ttf", 17 )
discussalivenames[w].anchorX = 0
if playerinfo[i].revealed == 1 then
discussroles[j] = display.newImageRect( uiGroup, "images/roles/" .. playerinfo[i].role .. ".png", display.contentWidth * 0.075, display.contentWidth * 0.075 )
else
discussroles[j] = display.newImageRect( uiGroup, "images/interface/unknown.png", display.contentWidth * 0.075, display.contentWidth * 0.075 )
end
discussroles[j].x, discussroles[j].y = display.contentWidth * 0.13, discussalivenames[w].y
j = j + 1
w = w + 1
end
end
w = 1
for i=1, settings.setup.players do
if playerinfo[i].alive == 0 then
discussdeadnames[w] = display.newText( uiGroup, settings.playernames[i], display.contentWidth * 0.24, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.06, "GosmickSans.ttf", 17 )
discussdeadnames[w].anchorX = 0
discussdeadnames[w]:setFillColor( 250/255, 30/255, 30/255, 1 )
discussdeaths[w] = display.newImageRect( uiGroup, "images/interface/dead.png", display.contentWidth * 0.075, display.contentWidth * 0.075 )
discussdeaths[w].x, discussdeaths[w].y = display.contentWidth * 0.1, discussdeadnames[w].y
discussroles[j] = display.newImageRect( uiGroup, "images/roles/" .. playerinfo[i].role .. ".png", display.contentWidth * 0.075, display.contentWidth * 0.075 )
discussroles[j].x, discussroles[j].y = display.contentWidth * 0.16, discussdeadnames[w].y
j = j + 1
w = w + 1
end
end
ui.helper.text = "Durata della Discussione: " .. minutes .. "m " .. seconds .. "s"
for i=1, settings.setup.players + 1 do
lynchedvotes[i] = 0
end
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
ui.forwardtext.text = "Linciaggio"
ui.forward:addEventListener( "tap", clearVoteLynch )
ui.strat.alpha = 1
ui.strattext.alpha = 1
ui.strat:addEventListener( "tap", clearShowDayStrat )
end
changeBackground( "day" )
ui.dayalert.text = "SOPRAVANZA IL GIORNO.."
ui.dayalert.alpha = 1
ui.helper.text = "\n\nDurante il Giorno, i Giocatori vivi possono discutere tra di loro su Ruoli, avvenimenti, accuse, comportamenti e quant'altro. Lo scopo della Discussione è decidere SE linciare al Tramonto, e CHI."
ui.helper.alpha = 1
ui.daytime = display.newImageRect( uiGroup, "images/interface/sun.png", display.contentWidth * 0.35, display.contentWidth * 0.35 )
ui.daytime.x, ui.daytime.y = display.contentWidth * 0.75, display.contentHeight * 0.84
ui.daytime:addEventListener( "tap", discussLynch )
showDayStrat = function()
local function backDiscussLynch()
ui.strattext.text = "Strategia"
ui.strat:removeEventListener( "tap", backDiscussLynch )
ui.rolehandbook.text = ""
stoppedtime = false
discussLynch()
end
stoppedtime = true
ui.helper.text = "STRATEGIA GENERALE (GIORNO)"
ui.rolehandbook.text = roleslib.getDayStrat( settings.setup.title, nightcount )
ui.rolehandbook.alpha = 1
ui.strattext.text = "Indietro"
ui.strat:addEventListener( "tap", backDiscussLynch )
end
end
sunriseTime = function()
local function endSunriseTime()
ui.forward:removeEventListener( "tap", endSunriseTime )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
display.remove( ui.roleactionicon )
ui.roleactionicon = nil
enforceWinCondition( "kill" )
end
local function checkDeaths()
local function announceDeaths()
display.remove( ui.roleactionicon )
ui.forward:removeEventListener( "tap", announceDeaths )
if table.getn( lastdeaths ) > 0 then
local dead = table.remove( lastdeaths )
playDeathAudio( dead )
playerinfo[dead].alive = 0
ui.helper.text = "Il cadavere di " .. playerinfo[dead].name .. " è stato rinvenuto. Era stato abbandonato in un cassonetto dell'immondizia.\n\nAveva il Ruolo di " .. playerinfo[dead].role .. "."
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/" .. playerinfo[dead].role .. ".png", display.contentWidth * 0.3, display.contentWidth * 0.3 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
ui.forward:addEventListener( "tap", announceDeaths )
if playerinfo[dead].role == "Capocultista" then
local count = 0
local function suicideCultist()
count = count + 1
ui.helper.text = ""
display.remove( ui.roleactionicon )
if count > settings.setup.players then
ui.forward:removeEventListener( "tap", suicideCultist )
announceDeaths()
elseif playerinfo[count].alive == 1 and playerinfo[count].role == "Cultista" then
ui.helper.text = playerinfo[count].name .. " beve da un calice avvelenato ed esala il suo ultimo respiro."
playDeathAudio( count )
playerinfo[count].alive = 0
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/" .. playerinfo[count].role .. ".png", display.contentWidth * 0.3, display.contentWidth * 0.3 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
else
suicideCultist()
end
end
ui.helper.text = "Il Capocultista è morto.\n\nIl Culto è stato eradicato. I Cultisti, presi dalla disperazione, si stanno suicidando in massa."
ui.forward:removeEventListener( "tap", announceDeaths )
ui.forward:addEventListener( "tap", suicideCultist )
end
elseif table.getn( lastdeaths ) == 0 then
ui.forward:removeEventListener( "tap", announceDeaths )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
endSunriseTime()
end
end
ui.dayalert.text = ""
ui.daytime:removeEventListener( "tap", checkDeaths )
ui.daytime:removeSelf()
ui.daytime = nil
if table.getn( lastdeaths ) > 0 then
announceDeaths()
else
ui.helper.text = "Nessun Giocatore è morto stanotte."
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
ui.forward:addEventListener( "tap", endSunriseTime )
end
end
audio.play( sunrisesound )
changeBackground( "sunrise" )
ui.dayalert.text = "SORGE L'ALBA.."
ui.dayalert.alpha = 1
ui.helper.text = "\n\nDurante l'Alba, i Giocatori riaprono gli occhi e vengono rivelate le vittime della Notte appena passata."
ui.helper.alpha = 1
ui.daytime = display.newImageRect( uiGroup, "images/interface/sunrise.png", display.contentWidth * 0.35, display.contentWidth * 0.35 )
ui.daytime.x, ui.daytime.y = display.contentWidth * 0.75, display.contentHeight * 0.84
ui.daytime:addEventListener( "tap", checkDeaths )
end
nightTime = function()
local function endNightTime()
ui.forward:removeEventListener( "tap", endNightTime )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
sunriseTime()
end
local function cultistConversionCheck()
local count = 0
local function cultistConversion()
count = count + 1
ui.helper.text = ""
ui.rolehandbook.text = ""
if count > settings.setup.players then
ui.forward:removeEventListener( "tap", cultistConversion )
endNightTime()
elseif playerinfo[count].alive == 0 then
cultistConversion()
elseif playerinfo[count].alive == 1 then
if playerinfo[count].role == "Cultista" then
ui.helper.text = playerinfo[count].name .. " apre gli occhi."
ui.rolehandbook.text = "\nIl Giocatore loda il Culto, oppure lo condanna.\n\n[Segno positivo, è un Cultista]\n\nPoi chiude gli occhi."
elseif playerinfo[count].role == "Capocultista" then
ui.helper.text = playerinfo[count].name .. " apre gli occhi."
ui.rolehandbook.text = "\nIl Giocatore loda il Culto, oppure lo condanna.\n\n[Segno positivo, è il Capocultista]\n\nPoi chiude gli occhi."
elseif count <= settings.setup.players then
ui.helper.text = playerinfo[count].name .. " apre gli occhi."
ui.rolehandbook.text = "\nIl Giocatore loda il Culto, oppure lo condanna.\n\n[Segno negativo, si oppone al Culto]\n\nPoi chiude gli occhi."
end
end
end
local cultleadercount = 0
for i=1, settings.setup.players do
if playerinfo[i].role == "Capocultista" and playerinfo[i].alive == 1 then
cultleadercount = cultleadercount + 1
end
end
if cultleadercount > 0 then
ui.helper.text = "Tenete ancora chiusi gli occhi."
ui.rolehandbook.text = "A turno, farò aprire gli occhi a ciascun Giocatore. Gli appartenenti al Culto riceveranno un segno positivo, tutti gli altri invece un segno negativo."
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
ui.forward:addEventListener( "tap", cultistConversion )
else
endNightTime()
end
end
local function evaluateNightVisits()
ui.forward:removeEventListener( "tap", evaluateNightVisits )
lastdeaths = {}
for i=1, table.getn( lastshrunk ) do
if playerinfo[ lastshrunk[i] ].role == "Killer" then --killerredeemed
playerinfo[ lastshrunk[i] ].role = "Paesano"
playerinfo[ lastshrunk[i] ].alignment = 0
end
if lastshrunk[i] == lastculted then
lastculted = -1 --conversionaverted
end
end
if lastculted ~= -1 then --convertedtocult
playerinfo[lastculted].role = "Cultista"
playerinfo[lastculted].alignment = 3
end
if lastkillerkill ~= -1 then --killeraliveandactive
if lastdocsave == -1 or lastdocsave ~= lastkillerkill then --nokillersave or wrongkillersave
table.insert( lastdeaths, lastkillerkill ) --killerkill happens
end
end
cultistConversionCheck()
end
local showNightStrat
local visitSomeone
local function activateNightStrat( role )
ui.strat.alpha = 1
ui.strattext.alpha = 1
ui.strattext.text = "Strategia"
ui.strat.role = role
ui.strat:addEventListener( "tap", showNightStrat )
end
local function visitVillager()
local function villagerLoafs()
local function clearVillager( event )
ui.forward:removeEventListener( "tap", clearVillager )
ui.helper.text = playerinfo[currentvisit].name .. " ha eseguito la sua Visita Notturna.\n\n[Come Paesano, non ha visitato nessuno]\n\nIl Giocatore chiude gli occhi."
ui.rolehandbook.text = ""
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
local function clearVillagerReminder()
ui.forward:removeEventListener( "tap", clearVillagerReminder )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
visitSomeone()
end
ui.forward:addEventListener( "tap", clearVillagerReminder )
end
ui.roleactionicon:removeSelf()
ui.roleactionicon = nil
ui.strat:removeEventListener( "tap", showNightStrat )
ui.strat.alpha = 0
ui.strattext.alpha = 0
ui.helper.text = "[Il Paesano non esegue alcuna Visita Notturna quindi non dovrà indicare nessuno]"
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
ui.forward:addEventListener( "tap", clearVillager )
end
ui.helper.text = playerinfo[currentvisit].name .. " apre gli occhi."
ui.rolehandbook.text = roleslib.getVisit( settings.setup.title, "Paesano" )
activateNightStrat( "Paesano" )
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/Paesano.png", display.contentWidth * 0.4, display.contentWidth * 0.4 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
ui.roleactionicon:addEventListener( "tap", villagerLoafs )
end
local function visitCultist()
local function cultistPraise()
local function clearCultist( event )
ui.forward:removeEventListener( "tap", clearCultist )
ui.helper.text = playerinfo[currentvisit].name .. " ha eseguito la sua Visita Notturna.\n\n[Come Cultista, ha lodato il Culto senza aver visitato nessuno]\n\nIl Giocatore chiude gli occhi."
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
local function clearCultistReminder()
ui.forward:removeEventListener( "tap", clearCultistReminder )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
visitSomeone()
end
ui.forward:addEventListener( "tap", clearCultistReminder )
end
ui.roleactionicon:removeSelf()
ui.roleactionicon = nil
ui.strat:removeEventListener( "tap", showNightStrat )
ui.strat.alpha = 0
ui.strattext.alpha = 0
ui.helper.text = "[Il Cultista non esegue alcuna Visita Notturna quindi non dovrà indicare nessuno]"
ui.rolehandbook.text = ""
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
ui.forward:addEventListener( "tap", clearCultist )
end
ui.helper.text = playerinfo[currentvisit].name .. " apre gli occhi."
ui.rolehandbook.text = roleslib.getVisit( settings.setup.title, "Cultista" )
activateNightStrat( "Cultista" )
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/Cultista.png", display.contentWidth * 0.4, display.contentWidth * 0.4 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
ui.roleactionicon:addEventListener( "tap", cultistPraise )
end
local function visitCultleader()
local function leaderCulted()
local cultedicons = {}
local cultednames = {}
local function clearCulted( event )
for i=1, table.getn( cultedicons ) do
cultedicons[i]:removeSelf()
cultedicons[i] = nil
end
for i=1, table.getn( cultednames ) do
cultednames[i]:removeSelf()
cultednames[i] = nil
end
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
ui.forward:removeEventListener( "tap", clearCulted )
lastculted = event.target.id
if lastculted ~= -1 then --save
ui.helper.text = playerinfo[currentvisit].name .. " ha eseguito la sua Visita Notturna.\n\n[Come Capocultista, ha visitato " .. playerinfo[lastculted].name .. "]\n\nIl Giocatore chiude gli occhi."
else --nosave
ui.helper.text = playerinfo[currentvisit].name .. " ha eseguito la sua Visita Notturna.\n\n[Come Capocultista, non ha visitato Nessuno]\n\nIl Giocatore chiude gli occhi."
end
ui.rolehandbook.text = ""
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
local function clearCultedReminder()
ui.forward:removeEventListener( "tap", clearCultedReminder )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
visitSomeone()
end
ui.forward:addEventListener( "tap", clearCultedReminder )
end
ui.roleactionicon:removeSelf()
ui.roleactionicon = nil
ui.strat:removeEventListener( "tap", showNightStrat )
ui.strat.alpha = 0
ui.strattext.alpha = 0
ui.helper.text = "POSSIBILI CONVERSIONI:"
ui.rolehandbook.text = ""
local j = 1
for i=1, settings.setup.players do
if playerinfo[i].alive == 1 and playerinfo[i].role ~= "Capocultista" then
cultedicons[j] = display.newImageRect( uiGroup, "images/interface/culted.png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
cultedicons[j].x, cultedicons[j].y = display.contentWidth * 0.74, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.09
cultedicons[j].id = i
cultedicons[j]:addEventListener( "tap", clearCulted )
cultednames[j] = display.newText( uiGroup, settings.playernames[i], display.contentWidth * 0.1, cultedicons[j].y, "GosmickSans.ttf", 18 )
cultednames[j].anchorX = 0
j = j + 1
end
end
cultedicons[j] = display.newImageRect( uiGroup, "images/interface/culted.png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
cultedicons[j].x, cultedicons[j].y = display.contentWidth * 0.74, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.09
cultedicons[j]:addEventListener( "tap", clearCulted )
cultedicons[j].id = -1
cultednames[j] = display.newText( uiGroup, "**Nessuno", display.contentWidth * 0.1, cultedicons[j].y, "GosmickSans.ttf", 18 )
cultednames[j].anchorX = 0
end
ui.helper.text = playerinfo[currentvisit].name .. " apre gli occhi."
ui.rolehandbook.text = roleslib.getVisit( settings.setup.title, "Capocultista" )
activateNightStrat( "Capocultista" )
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/Capocultista.png", display.contentWidth * 0.4, display.contentWidth * 0.4 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
ui.roleactionicon:addEventListener( "tap", leaderCulted )
end
local function visitDoctor()
local function docSave()
ui.roleactionicon:removeSelf()
ui.roleactionicon = nil
local saveicons = {}
local savenames = {}
local function clearSave( event )
for i=1, table.getn( saveicons ) do
saveicons[i]:removeSelf()
saveicons[i] = nil
end
for i=1, table.getn( savenames ) do
savenames[i]:removeSelf()
savenames[i] = nil
end
lastdocsave = event.target.id
if lastdocsave ~= -1 then --save
ui.helper.text = playerinfo[currentvisit].name .. " ha eseguito la sua Visita Notturna.\n\n[Come Dottore, ha visitato " .. playerinfo[event.target.id].name .. "]\n\nIl Giocatore chiude gli occhi."
else --nosave
ui.helper.text = playerinfo[currentvisit].name .. " ha eseguito la sua Visita Notturna.\n\n[Come Dottore, non ha visitato Nessuno]\n\nIl Giocatore chiude gli occhi."
end
ui.rolehandbook.text = ""
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
local function clearSaveReminder()
ui.forward:removeEventListener( "tap", clearSaveReminder )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
visitSomeone()
end
ui.forward:addEventListener( "tap", clearSaveReminder )
end
ui.strat:removeEventListener( "tap", showNightStrat )
ui.strat.alpha = 0
ui.strattext.alpha = 0
ui.helper.text = "POSSIBILI SALVATAGGI:"
ui.rolehandbook.text = ""
local j = 1
for i=1, settings.setup.players do
if playerinfo[i].alive == 1 and playerinfo[i].role ~= "Dottore" then
saveicons[j] = display.newImageRect( uiGroup, "images/interface/save.png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
saveicons[j].x, saveicons[j].y = display.contentWidth * 0.74, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.09
saveicons[j].id = i
saveicons[j]:addEventListener( "tap", clearSave )
savenames[j] = display.newText( uiGroup, settings.playernames[i], display.contentWidth * 0.1, saveicons[j].y, "GosmickSans.ttf", 18 )
savenames[j].anchorX = 0
j = j + 1
end
end
saveicons[j] = display.newImageRect( uiGroup, "images/interface/save.png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
saveicons[j].x, saveicons[j].y = display.contentWidth * 0.74, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.09
saveicons[j]:addEventListener( "tap", clearSave )
saveicons[j].id = -1
savenames[j] = display.newText( uiGroup, "**Nessuno", display.contentWidth * 0.1, saveicons[j].y, "GosmickSans.ttf", 18 )
savenames[j].anchorX = 0
end
ui.helper.text = playerinfo[currentvisit].name .. " apre gli occhi."
ui.rolehandbook.text = roleslib.getVisit( settings.setup.title, "Dottore" )
activateNightStrat( "Dottore" )
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/Dottore.png", display.contentWidth * 0.4, display.contentWidth * 0.4 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
ui.roleactionicon:addEventListener( "tap", docSave )
end
local function visitKiller()
local function killerKill()
ui.roleactionicon:removeSelf()
ui.roleactionicon = nil
local killicons = {}
local killnames = {}
local function clearKill( event )
for i=1, table.getn( killicons ) do
killicons[i]:removeSelf()
killicons[i] = nil
end
for i=1, table.getn( killnames ) do
killnames[i]:removeSelf()
killnames[i] = nil
end
lastkillerkill = event.target.id
ui.helper.text = playerinfo[currentvisit].name .. " ha eseguito la sua Visita Notturna.\n\n[Come Killer, ha visitato " .. playerinfo[lastkillerkill].name .. "]\n\nIl Giocatore chiude gli occhi."
ui.rolehandbook.text = ""
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
local function clearKillReminder()
ui.forward:removeEventListener( "tap", clearKillReminder )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
visitSomeone()
end
ui.forward:addEventListener( "tap", clearKillReminder )
end
ui.strat:removeEventListener( "tap", showNightStrat )
ui.strat.alpha = 0
ui.strattext.alpha = 0
ui.helper.text = "POSSIBILI VITTIME:"
ui.rolehandbook.text = ""
local j = 1
for i=1, settings.setup.players do
if playerinfo[i].alive == 1 and playerinfo[i].alignment ~= 2 then
killicons[j] = display.newImageRect( uiGroup, "images/interface/stab.png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
killicons[j].x, killicons[j].y = display.contentWidth * 0.74, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.09
killicons[j].id = i
killicons[j]:addEventListener( "tap", clearKill )
killnames[j] = display.newText( uiGroup, settings.playernames[i], display.contentWidth * 0.1, killicons[j].y, "GosmickSans.ttf", 18 )
killnames[j].anchorX = 0
j = j + 1
end
end
end
ui.helper.text = playerinfo[currentvisit].name .. " apre gli occhi."
ui.rolehandbook.text = roleslib.getVisit( settings.setup.title, "Killer" )
activateNightStrat( "Killer" )
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/Killer.png", display.contentWidth * 0.4, display.contentWidth * 0.4 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
ui.roleactionicon:addEventListener( "tap", killerKill )
end
local function visitShrink()
local function shrinkShrunk()
local shrunkicons = {}
local shrunknames = {}
local function clearShrunk( event )
for i=1, table.getn( shrunkicons ) do
shrunkicons[i]:removeSelf()
shrunkicons[i] = nil
end
for i=1, table.getn( shrunknames ) do
shrunknames[i]:removeSelf()
shrunknames[i] = nil
end
ui.forward:removeEventListener( "tap", clearShrunk )
local shrunktarget = event.target.id
if shrunktarget ~= -1 then --shrunk
table.insert( lastshrunk, shrunktarget )
ui.helper.text = playerinfo[currentvisit].name .. " ha eseguito la sua Visita Notturna.\n\n[Come Strizzacervelli, ha visitato " .. playerinfo[shrunktarget].name .. "]\n\nIl Giocatore chiude gli occhi."
else --noshrunk
ui.helper.text = playerinfo[currentvisit].name .. " ha eseguito la sua Visita Notturna.\n\n[Come Strizzacervelli, non ha visitato Nessuno]\n\nIl Giocatore chiude gli occhi."
end
ui.rolehandbook.text = ""
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
local function clearShrunkReminder()
ui.forward:removeEventListener( "tap", clearShrunkReminder )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
visitSomeone()
end
ui.forward:addEventListener( "tap", clearShrunkReminder )
end
ui.roleactionicon:removeSelf()
ui.roleactionicon = nil
ui.strat:removeEventListener( "tap", showNightStrat )
ui.strat.alpha = 0
ui.strattext.alpha = 0
ui.helper.text = "POSSIBILI PSICANALISI:"
ui.rolehandbook.text = ""
local j = 1
for i=1, settings.setup.players do
if playerinfo[i].alive == 1 then
shrunkicons[j] = display.newImageRect( uiGroup, "images/interface/shrunk.png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
shrunkicons[j].x, shrunkicons[j].y = display.contentWidth * 0.74, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.09
shrunkicons[j].id = i
shrunkicons[j]:addEventListener( "tap", clearShrunk )
shrunknames[j] = display.newText( uiGroup, settings.playernames[i], display.contentWidth * 0.1, shrunkicons[j].y, "GosmickSans.ttf", 18 )
shrunknames[j].anchorX = 0
j = j + 1
end
end
shrunkicons[j] = display.newImageRect( uiGroup, "images/interface/shrunk.png", display.contentWidth * 0.1, display.contentWidth * 0.1 )
shrunkicons[j].x, shrunkicons[j].y = display.contentWidth * 0.74, display.contentHeight * 0.36 + (j-1) * display.contentHeight * 0.09
shrunkicons[j]:addEventListener( "tap", clearShrunk )
shrunkicons[j].id = -1
shrunknames[j] = display.newText( uiGroup, "**Nessuno", display.contentWidth * 0.1, shrunkicons[j].y, "GosmickSans.ttf", 18 )
shrunknames[j].anchorX = 0
end
ui.helper.text = playerinfo[currentvisit].name .. " apre gli occhi."
ui.rolehandbook.text = roleslib.getVisit( settings.setup.title, "Strizzacervelli" )
activateNightStrat( "Strizzacervelli" )
ui.roleactionicon = display.newImageRect( uiGroup, "images/roles/Strizzacervelli.png", display.contentWidth * 0.4, display.contentWidth * 0.4 )
ui.roleactionicon.x, ui.roleactionicon.y = display.contentWidth * 0.5, display.contentHeight * 0.68
ui.roleactionicon:addEventListener( "tap", shrinkShrunk )
end
visitSomeone = function()
currentvisit = currentvisit + 1
if currentvisit <= settings.setup.players then
if playerinfo[currentvisit].alive == 1 then
if playerinfo[currentvisit].role == "Strizzacervelli" then
visitShrink()
elseif playerinfo[currentvisit].role == "Killer" then
visitKiller()
elseif playerinfo[currentvisit].role == "Capocultista" then
visitCultleader()
elseif playerinfo[currentvisit].role == "Dottore" then
visitDoctor()
elseif playerinfo[currentvisit].role == "Cultista" then
visitCultist()
elseif playerinfo[currentvisit].role == "Paesano" then
visitVillager()
end
else
visitSomeone()
end
else
evaluateNightVisits()
end
end
showNightStrat = function()
local function backVisitShrink()
ui.strat:removeEventListener( "tap", backVisitShrink )
visitShrink()
end
local function backVisitKiller()
ui.strat:removeEventListener( "tap", backVisitKiller )
visitKiller()
end
local function backVisitCultleader()
ui.strat:removeEventListener( "tap", backVisitCultleader )
visitCultleader()
end
local function backVisitDoctor()
ui.strat:removeEventListener( "tap", backVisitDoctor )
visitDoctor()
end
local function backVisitCultist()
ui.strat:removeEventListener( "tap", backVisitCultist )
visitCultist()
end
local function backVisitVillager()
ui.strat:removeEventListener( "tap", backVisitVillager )
visitVillager()
end
ui.roleactionicon:removeSelf()
ui.roleactionicon = nil
ui.helper.text = "STRATEGIA GENERALE (NOTTE)"
ui.rolehandbook.text = roleslib.getNightStrat( settings.setup.title, "Lode al Culto", nightcount-1 )
ui.strat:removeEventListener( "tap", showNightStrat )
ui.strattext.text = "Indietro"
if ui.strat.role == "Strizzacervelli" then
ui.strat:addEventListener( "tap", backVisitShrink )
elseif ui.strat.role == "Killer" then
ui.strat:addEventListener( "tap", backVisitKiller )
elseif ui.strat.role == "Capocultista" then
ui.strat:addEventListener( "tap", backVisitCultleader )
elseif ui.strat.role == "Dottore" then
ui.strat:addEventListener( "tap", backVisitDoctor )
elseif ui.strat.role == "Cultista" then
ui.strat:addEventListener( "tap", backVisitCultist )
elseif ui.strat.role == "Cultista" then
ui.strat:addEventListener( "tap", backVisitCultist )
elseif ui.strat.role == "Paesano" then
ui.strat:addEventListener( "tap", backVisitVillager )
end
end
local function visitHandler()
ui.dayalert.text = ""
ui.daytime:removeSelf()
ui.daytime = nil
currentvisit = 0
lastshrunk = {}
lastkillerkill = -1
lastdocsave = -1
lastculted = -1
visitSomeone()
end
audio.play( nightsound )
changeBackground( "night" )
nightcount = nightcount + 1
ui.dayalert.text = "CALA LA NOTTE.."
ui.dayalert.alpha = 1
ui.helper.text = "\n\nDurante la Notte, tutti i Giocatori tengono gli occhi chiusi. A turno, chiamerò i Giocatori e li guiderò. Se il loro Ruolo non prevede Visite Notturne, non dovranno fare nulla."
ui.helper.alpha = 1
ui.daytime = display.newImageRect( uiGroup, "images/interface/moon.png", display.contentWidth * 0.35, display.contentWidth * 0.35 )
ui.daytime.x, ui.daytime.y = display.contentWidth * 0.75, display.contentHeight * 0.84
ui.daytime:addEventListener( "tap", visitHandler )
end
local function narratorHints()
local function stepForward()
ui.forward:removeEventListener( "tap", stepForward )
ui.forward.alpha = 0
ui.forwardtext.alpha = 0
nightTime()
end
ui.forward.alpha = 1
ui.forwardtext.alpha = 1
ui.forward:addEventListener( "tap", stepForward )
ui.helper.text = settings.playernames[10] .. ", finalmente siamo tornati a noi due.\n\nConto su di te per moderare le Discussioni ed esporre le Strategie, così da condurre correttamente lo Scenario.\n\n[E ricordati di non leggere ad alta voce le frasi tra parentesi quadrate!]"
ui.helper.alpha = 1
end
local function computePlayerinfo()
for i=1, settings.setup.players do
table.insert( playerinfo,
{
id = i,
name = settings.playernames[i],
role = settings.playerroles[i],
alignment = -1,
alive = 1, --alive
}
)
if settings.playerroles[i] == "Dottore" then
playerinfo[i].alignment = 0
elseif settings.playerroles[i] == "Strizzacervelli" then
playerinfo[i].alignment = 0
elseif settings.playerroles[i] == "Capocultista" then
playerinfo[i].alignment = 3
elseif settings.playerroles[i] == "Killer" then
playerinfo[i].alignment = 2
end
print( "Giocatore " .. i .. ": " .. settings.playerroles[i] )
end
end
-- create()
function scene:create( event )
-- background
ui.background = display.newImageRect( uiGroup, "images/backgrounds/neutralbackground.png", display.contentWidth, display.contentHeight )
ui.background.x, ui.background.y = display.contentCenterX, display.contentCenterY
-- frontbox
ui.frontbox = display.newRect( uiGroup, display.contentWidth * 0.5, display.contentHeight * 0.11, display.contentWidth * 0.94, display.contentHeight * 0.18 )
ui.frontbox:setFillColor( 20/255, 50/255, 10/255, 1 )
ui.frontbox.strokeWidth = 2
ui.frontbox:setStrokeColor( 1, 1, 1, 1 )
-- title
ui.title = display.newText( uiGroup, settings.setup.title, display.contentWidth * 0.06, display.contentHeight * 0.06, "GosmickSans.ttf", 28 )
ui.title:setFillColor( 1, 1, 1, 1 )
ui.title.anchorX = 0
-- role icons
for i=settings.setup.players, 1, -1 do
ui.roles[i] = display.newImageRect( uiGroup, "images/roles/" .. settings.setup.roles[i] .. ".png", display.contentWidth * 0.12, display.contentWidth * 0.12 )
ui.roles[i].x, ui.roles[i].y = display.contentWidth * 0.06 + (i-1)*25, display.contentWidth * 0.21
ui.roles[i].anchorX = 0
end
-- player number icon
ui.playericon = display.newImageRect( uiGroup, "images/numbers/" .. settings.setup.players .. ".png", display.contentWidth * 0.13, display.contentWidth * 0.13 )
ui.playericon.x, ui.playericon.y = display.contentWidth * 0.88, display.contentWidth * 0.21
-- description
local helper = ""
local options = {
text = helper,
x = display.contentCenterX,
y = display.contentHeight * 0.54,
width = display.contentWidth * 0.9,
height = display.contentHeight * 0.6,
font = "GosmickSans.ttf",
fontSize = 20,
align = "left"
}
ui.helper = display.newText( options )
ui.helper:setFillColor( 1, 1, 1, 1 )
ui.helper.alpha = 0
-- rolehandbook
options = {
text = "",
x = display.contentCenterX,
y = display.contentHeight * 0.61,
width = display.contentWidth * 0.9,
height = display.contentHeight * 0.6,
font = "GosmickSans.ttf",
fontSize = 16,
align = "left"
}
ui.rolehandbook = display.newText( options )
ui.rolehandbook:setFillColor( 1, 1, 1, 1 )
-- forwardtext
ui.forward = display.newRect( uiGroup, display.contentWidth * 0.72, display.contentHeight * 0.9, display.contentWidth * 0.45, display.contentHeight * 0.12 )
ui.forward:setFillColor( 0, 0, 0, 1 )
ui.forward.strokeWidth = 2
ui.forward:setStrokeColor( 1, 1, 1, 1 )
ui.forward.alpha = 0
ui.forwardtext = display.newText( uiGroup, "Avanti", ui.forward.x, ui.forward.y, "GosmickSans.ttf", 28 )
ui.forwardtext:setFillColor( 1, 1, 1, 1 )
ui.forwardtext.alpha = 0
-- strat
ui.strat = display.newRect( uiGroup, display.contentWidth * 0.24, display.contentHeight * 0.9, display.contentWidth * 0.36, display.contentHeight * 0.08 )
ui.strat:setFillColor( 0, 0, 0, 1 )
ui.strat.strokeWidth = 2
ui.strat:setStrokeColor( 1, 1, 1, 1 )
ui.strat.alpha = 0
ui.strattext = display.newText( uiGroup, "Strategia", ui.strat.x, ui.strat.y, "GosmickSans.ttf", 18 )
ui.strattext:setFillColor( 1, 1, 1, 1 )
ui.strattext.alpha = 0
-- dayalert
ui.dayalert = display.newText( uiGroup, "", display.contentWidth * 0.055, display.contentHeight * 0.28, "GosmickSans.ttf", 25 )
ui.dayalert:setFillColor( 1, 1, 1, 1 )
ui.dayalert.anchorX = 0
ui.dayalert.alpha = 0
-- compute players info
computePlayerinfo()
-- narrator hints
narratorHints()
end
-- scene event listener
scene:addEventListener( "create", scene )
return scene
|
-- create node Arctangent2
require "moon.sg"
local node = moon.sg.new_node("sg_arctangent2")
if node then
node:set_pos(moon.mouse.get_position())
end
|
local builder = ll.class(ll.ContainerNodeBuilder)
function builder.newDescriptor()
ll.logd('ImagePyramid', 'newDescriptor')
local desc = ll.ContainerNodeDescriptor.new()
desc.builderName = 'ImagePyramid'
desc:addPort(ll.PortDescriptor.new(0, 'in_RGBA', ll.PortDirection.In, ll.PortType.ImageView))
desc:addPort(ll.PortDescriptor.new(1, 'out_RGBA', ll.PortDirection.Out, ll.PortType.ImageView))
-- parameter with default value
desc:setParameter('levels', 5)
return desc
end
function builder.onNodeInit(node)
levels = node.descriptor:getParameter('levels')
ll.logd('ImagePyramid', 'onNodeInit: levels:', levels)
-- in_RGBA should have been bound before calling init()
in_RGBA = node:getPort('in_RGBA')
node:bind(string.format('out_RGBA_downY_0', i), in_RGBA)
for i = 1, levels -1 do
ll.logd('ImagePyramid', 'onNodeInit: level:', i)
downX = ll.createComputeNode('ImageDownsampleX')
downY = ll.createComputeNode('ImageDownsampleY')
downX:bind('in_RGBA', in_RGBA)
downX:init()
downY:bind('in_RGBA', downX:getPort('out_RGBA'))
downY:init()
in_RGBA = downY:getPort('out_RGBA')
-- bind the output
if i == levels -1 then
node:bind('out_RGBA', downY:getPort('out_RGBA'))
end
node:bindNode(string.format('downX_%d', i), downX)
node:bindNode(string.format('downY_%d', i), downY)
node:bind(string.format('out_RGBA_downX_%d', i), downX:getPort('out_RGBA'))
node:bind(string.format('out_RGBA_downY_%d', i), downY:getPort('out_RGBA'))
end
end
function builder.onNodeRecord(node, cmdBuffer)
levels = node.descriptor:getParameter('levels')
for i = 1, levels -1 do
ll.logd('ImagePyramid', 'onNodeRecord: level:', i)
downX = node:getNode(string.format('downX_%d', i))
downY = node:getNode(string.format('downY_%d', i))
downX:record(cmdBuffer)
cmdBuffer:memoryBarrier()
downY:record(cmdBuffer)
cmdBuffer:memoryBarrier()
end
end
ll.registerNodeBuilder('ImagePyramid', builder)
|
local luaunit = require("luaunit")
require("imports_abs_abs")
TestImportsAbsAbs = {}
function TestImportsAbsAbs:test_imports_abs_abs()
local r = ImportsAbsAbs:from_file("src/fixed_struct.bin")
luaunit.assertEquals(r.one, 0x50)
luaunit.assertEquals(r.two.one, 0x41)
luaunit.assertEquals(r.two.two.one, 0x43)
end
|
BigWigs:AddColors("Vizier Jin'bak", {
[-5960] = "blue",
[-5959] = "red",
[-5958] = "yellow",
})
BigWigs:AddColors("Commander Vo'jak", {
[-6287] = {"blue","red"},
[120778] = "blue",
[120789] = {"blue","yellow"},
})
BigWigs:AddColors("General Pa'valak", {
[-5946] = "yellow",
[119875] = "red",
[124283] = "orange",
})
BigWigs:AddColors("Wing Leader Ner'onok", {
[-6205] = {"blue","green"},
[121284] = {"green","orange"},
[121443] = "blue",
["stages"] = "yellow",
})
|
--[[/*
* (C) 2012-2013 Marmalade.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/--]]
--------------------------------------------------------------------------------
-- Nodes
-- NOTE: This file must have no dependencies on the ones loaded after it by
-- openquick_init.lua. For example, it must have no dependencies on QDirector.lua
--------------------------------------------------------------------------------
QNode = {}
QNode.__index = QNode
-- Explicit override when setting color property, to allow for assignment
prop_setColor = function(prop, value)
if value.r then
-- Assume value is an existing QColor object: copy r,g,b,a
prop.r = value.r or 0xff
prop.g = value.g or 0xff
prop.b = value.b or 0xff
prop.a = value.a or 0xff
else
-- Assume value is a tuple, copy 1,2,3,4
prop.r = value[1] or 0xff
prop.g = value[2] or 0xff
prop.b = value[3] or 0xff
prop.a = value[4] or 0xff
end
end
-- Explicit override when setting rect property, to allow for assignment
prop_setRect = function(prop, value)
if value.w then
-- Assume value is an existing rect object: copy x,y,w,h
prop.x = value.x or 0
prop.y = value.y or 0
prop.w = value.w or 0
prop.h = value.h or 0
else
-- Assume value is a tuple, copy 1,2,3,4
prop.x = value[1] or 0
prop.y = value[2] or 0
prop.w = value[3] or 0
prop.h = value[4] or 0
end
end
-- Explicit override when setting vec2 property, to allow for assignment
prop_setVec2 = function(prop, value)
if value.x then
-- Assume value is an existing QVec2 object: copy x,y
prop.x = value.x or 0
prop.y = value.y or 0
else
-- Assume value is a tuple, copy 1,2
prop.x = value[1] or 0
prop.y = value[2] or 0
end
end
local oldNodeMTNI = getmetatable(quick.QNode).__newindex
QNode_set = function(t, name, value)
if name == "color" then
prop_setColor(t.color, value)
elseif name == "strokeColor" then -- Handle fillColor here also, even though it's a property of QVector
prop_setColor(t.strokeColor, value)
elseif name == "debugDrawColor" then
prop_setColor(t.debugDrawColor, value)
elseif name == "uvRect" then -- Handle uvRect, even though it's a property of QSprite
prop_setRect(t.uvRect, value)
else
oldNodeMTNI(t, name, value)
end
end
--------------------------------------------------------------------------------
-- Private API
--------------------------------------------------------------------------------
QNode.serialize = function(o)
local obj = serializeTLMT(getmetatable(o), o)
return obj
end
--[[
/*
Initialise the peer table for the C++ class QNode.
This must be called immediately after the QNode() constructor.
*/
--]]
-- Override QNode GC function (still call old one at the end)
QNode.oldGC = getmetatable(quick.QNode).__gc
QNode.newGC = function(n)
if config.debug.traceGC == true then
-- local s = "GC on node (" .. n:_getToLuaClassName() .. "): "
local s = "GC on node: "
if n.name then
s = s .. n.name
else
s = s.. "(unnamed)"
end
dbg.print(s)
end
-- Remove from physics?
if n.physics then
physics:removeNode(n)
end
QNode.oldGC(n)
end
function QNode:initNode(n)
-- Allow explicit control over assignment... see above
getmetatable(n).__newindex = QNode_set
-- ALWAYS set this, because it does stuff even in non-debug mode, e.g. remove node from physics
getmetatable(n).__gc = QNode.newGC
local np
np = {}
setmetatable(np, QNode)
tolua.setpeer(n, np)
local mt = getmetatable(n)
mt.__serialize = QNode.serialize
np.parent = nil
np.children = {}
np.tweens = {}
np.eventListeners = {}
np.timers = {}
end
--[[
/*
Handle events sent to this node. If there are any children, we work down the hierarchy.
@param event The event to handle.
@return True only if the event was caught.
*/
--]]
function QNode:handleEvent(event)
dbg.assertFuncVarType("table", event)
dbg.assert(event.name ~= "touch")
local result = false
-- Handle the event
result = handleEventWithListeners(event, self.eventListeners)
-- Propagate the event to our children
if result == false and not event.nopropagation then
for i = 1,#self.children do
result = self.children[i]:handleEvent(event)
if result == true then
break
end
end
end
return result
end
--[[
/*
Update any tweens attached to this node.
@param dt The delta time to apply
*/
--]]
function QNode:updateTweens(dt)
dbg.assertFuncVarType("number", dt)
-- Update tweens list
for i,v in ipairs(self.tweens) do
if v.isComplete == false then
local remove = v:update(dt)
if remove == true then
v.target = nil
table.remove(self.tweens, i)
end
end
end
end
--------------------------------------------------------------------------------
-- Public API
--------------------------------------------------------------------------------
--[[
/*
Create a node (base class object), specifying arbitrary input values.
@return The created node.
*/
--]]
function director:createNode(v)
dbg.assertFuncVarTypes({"table", "nil"}, v)
local n = quick.QNode()
n:_createCCNode()
QNode:initNode(n)
self:addNodeToLists(n)
table.setValuesFromTable(n, v)
return n
end
--[[
/**
Get the number of children of this node.
@return The number of children.
*/
--]]
function QNode:getNumChildren()
return table.getn(self.children)
end
--[[
/**
Determine if the specified node is a child of this node.
@param nc The node to test against.
@return True only if the specified node is a child of this node.
*/
--]]
function QNode:isChild(nc)
dbg.assertFuncVarType("userdata", nc)
return table.hasValue(self.children, nc)
end
--[[
/**
Set this node's parent to be the specified node.
If this node already has a parent, it is cleanly detached from that node first,
before being added as a child to the specified node.
@param np The node to set as the new parent.
*/
--]]
function QNode:setParent(np)
if np == nil and self.parent then
self:removeFromParent()
else
dbg.assertFuncVarType("userdata", np)
if self.parent then
self.parent:removeChild(self)
end
self.parent = np
self:_setParent(np)
end
end
--[[
/**
Get this node's parent.
@return The node's parent.
*/
--]]
function QNode:getParent()
return self.parent
end
--[[
/**
Add the specified node to this node as a child.
If the specified node already has a parent, it is cleanly detached from its parent first,
before being added as a child to this node.
@param nc The node to add as a child.
*/
--]]
function QNode:addChild(nc)
dbg.assertFuncVarType("userdata", nc)
if nc.parent then
nc.parent:removeChild(nc)
end
table.insert(self.children, nc)
nc.parent = self
nc:refreshTweens(false)
self:_addChild(nc)
end
--[[
/**
This function with 'drop = true' will break back link of all tweens
with 'drop = false' this will restore them
Needed to GC to destroy this node end tweens linked with it
@param drop boolean parameter
*/
--]]
function QNode:refreshTweens(drop)
for i,v in ipairs(self.tweens) do
if drop then
v.target = nil
else
v.target = self
end
end
for i,v in ipairs(self.children) do
v:refreshTweens(drop)
end
end
--[[
/**
Remove the specified child node from this node.
If the node is not a child of this node, a failure message is displayed.
@param nc The child node to remove from this node.
*/
--]]
function QNode:removeChild(nc)
dbg.assertFuncVarType("userdata", nc)
dbg.assert(table.hasValue(self.children, nc), "Specified node is not a child of this node")
nc.parent = nil
for i,v in ipairs(self.children) do
if v == nc then
table.remove(self.children, i)
break
end
end
nc:refreshTweens(true)
self:_removeChild(nc)
end
--[[
/**
Remove a node from its parent, and therefore from any scene it belongs to.
If the node has no parent, we assert.
*/
--]]
function QNode:removeFromParent()
dbg.assert(self.parent, "Node has no parent")
self.parent:removeChild(self)
end
--[[
/**
Add an event listener to the node.
@param name The name of the event or a table of event names to listen for.
@param funcortable The listener: either a listener function, or a Lua table with an index named <name> that is a listener function.
*/
--]]
function QNode:addEventListener(name, funcortable)
dbg.assertFuncVarTypes({"string", "table"}, name)
dbg.assertFuncVarTypes({"function", "table", "userdata"}, funcortable)
-- Use the QSystem global function
_addEventListener(self, name, funcortable)
end
--[[
/**
Remove an event listener from this node.
@param name The name of the event or a table of event names associated with the listener(s) to remove.
@param funcortable The listener to remove: either a listener function, or a Lua table with an index named <name> that is a listener function.
*/
--]]
function QNode:removeEventListener(name, funcortable)
dbg.assertFuncVarTypes({"string", "table"}, name)
dbg.assertFuncVarTypes({"function", "table", "userdata"}, funcortable)
-- Use the QSystem global function
_removeEventListener(self, name, funcortable)
end
--[[
/**
Add a timed event to this node.
@param funcortable The listener: either a listener function, or a Lua table with an index named <name> that is a listener function.
@param period The period of the timer, in seconds.
@param iterations The maximum number of times the listener will be called, or 0 to call it indefinitely. Default value is 0.
@param delay An initial delay which must elapse before we start counting down the first period. Default value is 0.
@return The timer object. This can be used to pause, resume or cancel the timer.
*/
--]]
function QNode:addTimer(funcortable, period, iterations, delay)
period = period or 1
iterations = iterations or 0
delay = delay or 0
dbg.assertFuncVarTypes({"function", "table", "userdata"}, funcortable)
dbg.assertFuncVarType("number", period)
dbg.assertFuncVarType("number", iterations)
dbg.assertFuncVarType("number", delay)
local el = quick.QEventListener:new()
QEventListener:initEventListener(el, "timer", funcortable)
local timer = quick.QTimer:new()
QTimer:initTimer(timer, el, period, iterations, delay)
timer.target = self
table.insert(self.timers, timer)
return timer
end
--[[
/**
Rotate a node by a specified angle.
@param a The angle to rotate by, in degrees, anticlockwise.
*/
--]]
function QNode:rotate(a)
dbg.assertFuncVarType("number", a)
self.rotation = self.rotation + a
end
--[[
/**
Scale a node by a specified amount, specifying the x and y scales to multiply by.
@param sx The multiplier for the scale along the x axis.
@param sy The multiplier for the scale along the y axis.
*/
--]]
function QNode:scale(sx, sy)
dbg.assertFuncVarType("number", sx)
dbg.assertFuncVarTypes({"number", "nil"}, sy)
sy = sy or sx -- if sy not passed in, we set it to the same as sx
self.xScale = self.xScale * sx
self.yScale = self.yScale * sy
end
--[[
/**
Translate a node by a specified amount.
@param dx The delta to move along the x axis.
@param dy The delta to move along the y axis.
*/
--]]
function QNode:translate(dx, dy)
dbg.assertFuncVarTypes({"number", "number"}, dx, dy)
self.x = self.x + dx
self.y = self.y + dy
end
--------------------------------------------------------------------------------
-- Utility functions to allow operating on trees of nodes at once
-- and performing useful operations in onComplete callbacks with
-- tweens and timers.
--[[
/**
Cancel all timers on a node.
myNode.cancelTimers can be passed as an onComplete callback since
onComplete is automatically passed the owning node as its first and
only parameter (i.e. self).
*/
--]]
function QNode:cancelTimers()
for k,v in pairs(self.timers) do
v:cancel()
end
end
--[[
/**
Cancel all timers on a node plus it's children and any descendants.
myNode.cancelTimersInTree can be passed as an onComplete callback.
*/
--]]
function QNode:cancelTimersInTree()
self:cancelTimers()
for k,child in pairs(self.children) do
child:cancelTimersInTree()
end
end
--[[
/**
Cancel all tweens on a node.
myNode.cancelTweens can be passed as an onComplete callback.
*/
--]]
function QNode:cancelTweens()
--tween:cancel() causes tween to be removed from node.tweens in an ipairs loop
--This relyies on that being true - using another pairs loop here would break.
--FIXME: Prob should also update tween:cancel in SDK to call break once it removes a tween
--for a tiny bit of performance (or replace cancel()'s loop with index by id or somesuch).
while self.tweens[1] do
tween:cancel(self.tweens[1])
end
end
--[[
/**
Cancel all tweens on a node plus it's children and any descendants.
myNode.cancelTweensInTree can be passed as an onComplete callback.
*/
--]]
function QNode:cancelTweensInTree()
self:cancelTweens()
for k,child in pairs(self.children) do
child:cancelTweensInTree()
end
end
--[[
/**
Pauses timers for a node and all its descendants in the
scene-graph.
*/
--]]
function QNode:pauseTimersInTree()
self:pauseTimers()
for k,child in pairs(self.children) do
child:pauseTimersInTree()
end
end
--[[
/**
Resumes paused timers for a node and all its descendants in the
scene-graph.
*/
--]]
function QNode:resumeTimersInTree()
self:resumeTimers()
for k,child in pairs(self.children) do
child:resumeTimersInTree()
end
end
--[[
/**
Pauses tweens for a node and all its descendants in the
scene-graph.
*/
--]]
function QNode:pauseTweensInTree()
self:pauseTweens()
for k,child in pairs(self.children) do
child:pauseTweensInTree()
end
end
--[[
/**
Resumes paused timers and tweens for a node and all its descendants in the
scene-graph.
*/
--]]
function QNode:resumeTweensInTree()
self:resumeTweens()
for k,child in pairs(self.children) do
child:resumeTweensInTree()
end
end
--[[
/**
Pauses timers and tweens for a node and all its descendants in the
scene-graph.
*/
--]]
function QNode:pauseTree()
self:pauseTimers()
self:pauseTweens()
for k,child in pairs(self.children) do
child:pauseTree()
end
end
--[[
/**
Resumes paused timers and tweens for a node and all its descendants in the
scene-graph.
*/
--]]
function QNode:resumeTree()
self:resumeTimers()
self:resumeTweens()
for k,child in pairs(self.children) do
child:resumeTree()
end
end
--[[
/**
-- Remove the nodes from its parent, and therefore the current scene,
-- cancelling all its timers and tweens and removing from the physics
-- simulation if using physics.
-- myNode.destroy can be passed as an onComplete callback
-- You still need to manually nil any explicit handles to the node
-- before it will be garbage collected.
-- Timers are cancelled becuase otherwise they can keep running until
-- the node is garbage collected.
-- Always returns nil to match node:removeFromParent() behaviour.
-- Call myNode = myNode:destroy() to destroy and nil local references
-- in one call.
*/
--]]
function QNode:destroy()
self:cancelTimers()
self:cancelTweens()
if self.physics then
physics:removeNode(self)
end
return self:removeFromParent()
end
--[[
/**
-- Remove the nodes from its parent, and therefore the current scene,
-- cancelling all its timers and tweens and removing from the physics
-- simulation if using physics. Also recursively performs the same
-- operations on all children of the node.
-- myNode.destroyTree can be passed as an onComplete callback
-- You still need to manually nil any explicit handles to the node
-- before it will be garbage collected.
-- Timers are cancelled because otherwise they can keep running until
-- the node is garbage collected.
-- Returns nil to match node:removeFromParent() behaviour.
-- Call myNode = myNode:destroyTree() to destroy and nil local
-- references to myNode in one call.
-- @param preseveRoot Set this true to just remove children and
-- keep root node. Equivalent to calling myNode:destroyChildren(),
-- however, destroyChildren can be passed as onComplete callbacks.
*/
--]]
function QNode:destroyTree(preserveRoot)
--Note: Each eventual call to node:destroy() calls removeFromParent(), which finds
--the node in parent's .children array and uses table.remove.
--Here, we can't use pairs() as order is not guaranteed. Can't use
--ipairs as behaviour is undefined after table.remove during ipairs loop.
--So, we use a manual loop, knowing that the SDK's .remove call will collapse
--the tree meaning we don't need to increment the index.
local i = 1
while self.children[i] do
--workaround to support VirtualResolution: don't delete the scalar node
local preserveThisNode = (self.children[i] == self.scalerRootNode)
self.children[i]:destroyTree(preserveThisNode)
if preserveThisNode then
i = i + 1 --but we do increment if we didn't delete the node
end
end
if not preserveRoot then
return self:destroy()
end
--FIXME: we could probably make this more efficient by traversing the other
--way and calling removeChild instead of node:destroy -> removeFromParent...
end
--[[
/**
-- Remove all child nodes and decendents from this one, and therefore
-- the current scene, cancelling timers and tweens and removing from the
-- physics simulation if using physics.
-- The node itself is not affected.
-- myNode.destroyChildren can be passed as an onComplete callback,
-- which is not possible if using myNode:destroyTree(true) (otherwise
-- equivalent bahaviour).
-- You still need to manually nil any explicit handles to the children
-- before they will be garbage collected.
-- Timers are cancelled because otherwise they can keep running until
-- nodes are garbage collected.
*/
--]]
function QNode:destroyChildren()
self:destroyTree(true)
end
--[[
/**
-- Get nodes position in world/screen coordinates
*/
--]]
function QNode:getWorldPosition()
if not self.parent then
return 0,0
end
return self.parent:getPointInWorldSpace(self.x, self.y)
end
--[[
/**
-- Returns the position of a decendent node in this nodes coordinate
-- space. Returns nil if the node beign queried is not actually a
-- decendent of this node.
-- @param descendant The node to serach for in this nodes tree and
-- return the position of in this nodes coordinate space.
*/
--]]
function QNode:getLocalPositionOfDescendant(descendant)
local x = descendant.x
local y = descendant.y
descendant = descendant.parent
local gotSelf = false
while descendant do
x = x * descendant.xScale + descendant.x
y = y * descendant.yScale + descendant.y
if descendant == self then
gotSelf = true
break
end
descendant = descendant.parent
end
if gotSelf then
return worldX, worldY
else
return nil
end
end
|
--
require "/lib/stardust/power.lua"
shared.energyReceptor = { }
function init()
rate = config.getParameter("conversionRate")
end
function shared.energyReceptor:receive(socket, amount, testOnly)
local fuel = world.getProperty("ship.fuel")
local maxFuel = world.getProperty("ship.maxFuel")
if type(fuel) ~= "number" or type(maxFuel) ~= "number" then return 0 end -- inactive on non-ship worlds
local result = math.min(amount, (maxFuel - fuel) * rate)
if not testOnly then -- commit
world.setProperty("ship.fuel", math.min(fuel + (result / rate), maxFuel))
end
return result
end
--
|
-- Log
--
local bret = require "behavior3.behavior_ret"
local M = {
name = "Log",
type = "Action",
desc = "打印日志",
args = {
{"str", "string", "日志"}
},
}
function M.run(node, env)
print(node.args.str)
return bret.SUCCESS
end
return M
|
local modname = ...
local M = {}
_G[modname] = M
local RPIN = 7
local GPIN = 6
local BPIN = 5
local REV = false
function M.init(r_pin, g_pin, b_pin, rev)
if rev then
REV = true
else
REV = false
end
RPIN = r_pin
GPIN = g_pin
BPIN = b_pin
pwm.setup(RPIN, 1000, 1023)
pwm.setup(GPIN, 1000, 1023)
pwm.setup(BPIN, 1000, 1023)
pwm.start(RPIN)
pwm.start(GPIN)
pwm.start(BPIN)
end
function M.r(r)
if r > 1023 then r = 1023 end
pwm.setduty(RPIN, REV and 1023-r or r)
end
function M.g(g)
if g > 1023 then g = 1023 end
pwm.setduty(GPIN, REV and 1023-g or g)
end
function M.b(b)
if b > 1023 then b = 1023 end
pwm.setduty(BPIN, REV and 1023-b or b)
end
function M.color(r, g, b)
M.r(r)
M.g(g)
M.b(b)
end
function M.freq(freq)
pwm.setclock(RPIN, freq)
end
return M
|
---
--- ColaFramework
--- Copyright © 2018-2049 ColaFramework 马三小伙儿
--- Common NotifyId 处理没有模块的通用类型事件
---
local NotifyId = {
CREATE_PANEL = 0, -- 创建UIPanel
DESTROY_PANEL = 1, -- 销毁UIPanel
ALLUI_SHOWSTATE_CHANGED = 2, --所有的UI显隐状态变化
}
return NotifyId
|
bloodbagstore = 0
-- if multiple but not all were used, the rest should stay in the tent. if you cant use the item, it needs to go back in the tent. Make using ground items not give space back.Making items not store when wanting to drop. make items you already have give the option to replace or store.Make items you dont have space for give you options.
tentstore = "n"
---------------------------(1)-------------------------------------------------------------------------------(2)----------------------------------------(3)----------------------------------------------(4)--------------------------------------------------(5)---------------------------------------------(6)
meatstore = 0
bandaidstore = 0
grenadestore = 0
radiostore = "n"
smokestore = 0
canstore = "n"
cfilledstore = "n"
epipenstore = 0
filledstore = "n"
bottlestore = "n"
knifestore = "n"
antibioticstore = 0
gunstoreone = "no weapon"
gunstoretwo = "no weapon"
gunstorethree = "no weapon"
gunspacestoreone = 0
gunspacestoretwo = 0
gunspacestorethree = 0
damagestoreone = 0
damagestoretwo = 0
damagestorethree = 0
accuracystoreone = 0
accuracystoretwo = 0
accuracystorethree = 0
fullaccuracystoreone = 0
fullaccuracystoretwo = 0
fullaccuracystorethree = 0
ammostoreone = 0
ammostoretwo = 0
ammostorethree = 0
painkillerstore = 0
morphinestore = 0
heatpackstore = 0
storedcolor = ""
storedwriting = ""
woodstore = "n"
gogglestore = "n"
matchstore = 0
beartrapstore = "n"
steakstore = 0
beanstore = 0
bookstore = "n"
popstore = 0
superbeanstore = "n"
roadflarestore = 0
tentplaced = "n"
gilliestore = "n"
watchstore = "n"
storedwcolor = ""
statsearch = "n"
statA = "y"
statB = "y"
statC = "y"
statD = "y"
statE = "y"
statF = "y"
statG = "y"
autostat = "n"
turns = 0
repeat
skinningdog = "n"
storinggun = "n"
alreadybook = "n"
symbol = "{@}"
bloodbags = 0
watch = "n"
watchcolor = ""
math.randomseed(os.time())
pack = "n"
bleeding = "n"
storingbook = "n"
tent = "n"
meat = 0
bandaids = 0
turn = 0
grenade = 0
radio = "n"
dogfeed = 3
days = 1
starve = "n"
gillie = "n"
wild = "n"
vision = "n"
can = "n"
gang = "n"
gangamount = 0
dogs = 0
smoke = 0
cfilled = "n"
attackchoice = "n"
doghealth = 0
dogfood = 0
hour = 8
period = "am"
dogwater = 0
droppedbook = "n"
droppedcolor = ""
trapcow = "n"
droppedwriting = ""
text = ""
thirst = "n"
request = "n"
filled = "n"
morphine = 0
----epi-pen
food = 300
invincible = "n"
bottle = "n"
findbook = "n"
objective = 50
dogcow = "n"
clothedrop = "y"
light = "light"
cpack = "n"
knife = "n"
infection = "n"
antibiotics = 0
tired = 0
------------------------------------------
mygun = "Test"
myguntwo = "no weapon"
mygunthree = "no weapon"
gunspace = 8
gunspacetwo = 0
gunspacethree = 0
damage = 0
damagetwo = 0
damagethree = 0
accuracy = 0
accuracythree = 0
accuracytwo = 0
fullaccuracy = 0
fullaccuracytwo = 0
fullaccuracythree = 0
myammo = 0
myammotwo = 0
myammothree = 0
------------------------------------------
moral = 50
water = 300
allsections = "n"
fullhealth = 12000
set = "n"
health = 12000
space = 10
pain = 0
epipen = 0
-----pain killers
creator = "n"
events = 0
painkillers = 0
---morphine
broken = "n"
temperature = 42
cold = "n"
store = "n"
heatpacks = 0
wood = "n"
goggles = "n"
matches = 0
beartrap = "n"
vpack = "n"
steak = 0
beans = 0
pop = 0
book = "n"
superbean = "n"
tenttravel = 0
roadflare = 0
amount = math.random(1, 2)
spawn = math.random(1, 3)
function dropgun()
if storinggun == "n" then
print("Which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
gunspacethree = gunspacetwo
myammothree = myammotwo
damagethree = damagetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
mygunthree = mygun
gunspacethree = gunspace
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
end
if mygunthree ~= "no weapon" then
if store == "y" then
if gunstoreone == "no weapon" then
gunstoreone = mygunthree
ammostoreone = myammothree
damagestoreone = damagethree
accuracystoreone = accuracythree
fullaccuracystoreone = fullaccuracythree
gunspacestoreone = gunspacethree
if storinggun == "n" then
space = space + gunspacethree
end
mygunthree = "no weapon"
myammothree = 0
gunspacethree = 0
damagethree = 0
accuracythree = 0
fullaccuracythree = 0
if storinggun == "n" then
takegun()
end
print("Stored.")
io.read()
elseif gunstoretwo == "no weapon" then
gunstoretwo = mygunthree
ammostoretwo = myammothree
damagestoretwo = damagethree
accuracystoretwo = accuracythree
fullaccuracystoretwo = fullaccuracythree
gunspacestoretwo = gunspacethree
mygunthree = "no weapon"
if storinggun == "n" then
space = space + gunspacethree
end
myammothree = 0
gunspacethree = 0
damagethree = 0
accuracythree = 0
fullaccuracythree = 0
if storinggun == "n" then
takegun()
end
print("Stored.")
io.read()
elseif gunstorethree == "no weapon" then
gunstorethree = mygunthree
ammostorethree = myammothree
damagestorethree = damagethree
accuracystorethree = accuracythree
fullaccuracystorethree = fullaccuracythree
gunspacestorethree = gunspacethree
mygunthree = "no weapon"
if storinggun == "n" then
space = space + gunspacethree
end
myammothree = 0
gunspacethree = 0
damagethree = 0
accuracythree = 0
fullaccuracythree = 0
if storinggun == "n" then
takegun()
end
print("Stored.")
io.read()
else
print("All weapon slots are full.")
print("Do you want to remove a slot?")
want = io.read()
if want == "y" then
print(
"Slot 1 = " ..
gunstoreone ..
", slot 2 = " ..
gunstoretwo .. ", slot 3 = " .. gunstorethree .. ', or "4" for cancel.'
)
print("Which do you want to remove?")
want = io.read()
if want == "1" then
gunstoreone = mygunthree
ammostoreone = myammothree
print("The gun was replaced.")
io.read()
mygunthree = "no weapon"
space = space + gunspacethree
myammothree = 0
gunspacethree = 0
damagethree = 0
accuracythree = 0
fullaccuracythree = 0
takegun()
elseif want == "2" then
gunstoretwo = mygunthree
ammostoretwo = myammothree
print("The gun was replaced.")
io.read()
mygunthree = "no weapon"
space = space + gunspacethree
myammothree = 0
gunspacethree = 0
damagethree = 0
accuracythree = 0
fullaccuracythree = 0
takegun()
elseif want == "3" then
gunstorethree = mygunthree
ammostorethree = myammothree
print("The gun was replaced.")
io.read()
mygunthree = "no weapon"
space = space + gunspacethree
myammothree = 0
gunspacethree = 0
damagethree = 0
accuracythree = 0
fullaccuracythree = 0
takegun()
else
print("No changes were made.")
io.read()
end
else
print("No changes were made.")
io.read()
end
end
else
print("Dropped.")
io.read()
mygunthree = "no weapon"
space = space + gunspacethree
myammothree = 0
gunspacethree = 0
damagethree = 0
accuracythree = 0
fullaccuracythree = 0
takegun()
end
elseif mygunthree == "no weapon" then
print("You have no weapon in slot " .. slot .. ".")
io.read()
end
end
function meatitem() --(1)--(2)--(3)--(4)--(x)--(6)--(X)
print("You found some meat.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = math.random(1, 3)
if meat < 1 then
if space >= 1 then
if skinningdog == "y" then
if wild == "n" then
meat = meat + math.random(1, dogfeed)
else
meat = meat + math.random(1, 3)
end
else
if store == "y" then
meat = meat + meatstore
meatstore = 0
else
meat = meat + math.random(1, 3)
end
end
space = space - 1
print("You picked it up.")
io.read()
break
elseif space < 1 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Meat")
if store == "y" then
sstore = "y"
store = "n"
end
dropped()
if sstore == "y" then
store = "y"
sstore = "n"
end
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Meat")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the meat(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
print("Stored")
io.read()
meatstore = meatstore + math.random(1, 3)
break
else
repeat
print("Meat")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
if store == "y" then
useamount = meatstore
else
useamount = math.random(1, 3)
end
repeat
if food < 500 then
meat = 100
--as long as its not less than 2
usemeat()
meat = 0
useamount = useamount - 1
if useamount ~= 0 then
print("Use more meat?")
print("You have " .. useamount .. " left.")
want = io.read()
if want ~= "y" then
break
end
end
else
print("You are not hungery.")
--Fixed
io.read()
break
end
until useamount == 0
if store == "y" then
meatstore = useamount
--------------Already done
end
useamount = 0
print("You leave.")
io.read()
meat = 0
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif meat >= 1 then
if skinningdog == "y" then
if wild == "n" then
meat = meat + math.random(1, dogfeed)
else
meat = meat + math.random(1, 3)
end
else
if store == "y" then
meat = meat + meatstore
meatstore = 0
else
meat = meat + math.random(1, 3)
end
end
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
end
until pickup ~= "y"
end
function gillieitem() --(x)--(x)--(x)--(x)--(5)--(X)--(X)
print("You found a gillie suit.")
print("pickup?")
pickup = io.read()
if pickup == "y" then
if gillie == "n" then
print("You took the gillie suit.")
io.read()
if store == "y" then
gilliestore = "n"
end
gillie = "y"
else
print("You already have a gillie suit.")
print("Store it(1), or leave it(2)?")
pickup = io.read()
if pickup == "1" then
print("You took the gillie.")
io.read()
if store == "y" then
gilliestore = "n"
end
gillie = "y"
else
if tentplaced == "y" then
print("You traveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
print("Stored.")
io.read()
watchstore = "y"
storedwcolor = ccolor
else
print("You don't have a placed tent.")
io.read()
end
end
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
end
function playerfight()
if myammo >= zhealth / damage - (accuracy - 10) then --win?
print("The player shot you but you killed them.")
io.read()
if attackchoice == "n" then
moral = moral + math.random(5, 20)
bandit = "n"
if moral > 100 then
moral = 100
hero = "y"
end
end
attackchoice = "n"
health = health - math.random(0, 5000)
doghealth = doghealth - math.random(0, 4000)
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 10)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
if mygun == "Hatchet" then
myammo = 99999
health = health - math.random(0, 2000)
end
myammo = myammo - zhealth / damage + (accuracy - 10)
print("You search his pockets.")
io.read()
dropamount = math.random(1, 5)
clothedrop = "y"
repeat
enemydrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
print("You leave the player.")
io.read()
elseif myammotwo >= zhealth / damagetwo - (accuracytwo - 10) then
print("The player shot you but you killed them with your secondary.")
io.read()
moral = moral + math.random(20, 50)
bandit = "n"
if moral > 100 then
moral = 100
hero = "y"
end
health = health - math.random(0, 5000)
doghealth = doghealth - math.random(0, 4000)
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 10)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
if myguntwo == "Hatchet" then
myammotwo = 99999
health = health - math.random(0, 2000)
end
myammotwo = myammotwo - zhealth / damagetwo + (accuracytwo - 10)
print("You search their pockets.")
io.read()
dropamount = math.random(1, 5)
clothedrop = "y"
repeat
enemydrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
print("You leave the player.")
io.read()
elseif dogs >= 1 then
print("The player shot you but your dog killed them.")
io.read()
moral = moral + math.random(20, 50)
bandit = "n"
if moral > 100 then
moral = 100
hero = "y"
end
health = health - math.random(0, 5000)
doghealth = doghealth - math.random(0, 7000)
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 10)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
print("You search their pockets.")
io.read()
dropamount = math.random(1, 5)
clothedrop = "y"
repeat
enemydrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
print("You leave the player.")
io.read()
elseif dogs < 1 then
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
bleeding = "y"
end
brake = math.random(1, 7)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(2000, 5000)
print("The player killed you.")
health = 0
health = health - math.random(1000, 8000)
end
--myammo
end
function skindog() --(X)--(X)--(X)--(X)--(X)--(X)--(X)
print("Skin it?")
pickup = io.read()
if pickup == "y" then
print("The dog has died.")
io.read()
dogs = dogs - 1
doghealth = 10000
damage = damage - 1000
if dogs < 1 then
dogname = ""
end
if knife == "y" then
skinningdog = "y"
meatitem()
if dogs < 1 then
dogfeed = 3
end
skinningdog = "n"
elseif knife == "n" then
print("You have no knife.")
io.read()
end
else
print("You leave your dog(s) alone.")
io.read()
end
end
function watchitem() --(x)--(x)--(x)--(x)--(5)--(X)--(X)
color = math.random(1, 19)
if store == "n" then
coloring()
if ccolor == "dress" then
ccolor = "leather"
end
print("You found a " .. ccolor .. " watch.")
else
print("You found a " .. storedwcolor .. " watch.")
end
print("pickup?")
pickup = io.read()
if pickup == "y" then
if watch == "n" then
print("You took the watch.")
io.read()
if store == "y" then
watchstore = "n"
watchcolor = storedwcolor
soredwcolor = ""
watchstore = "n"
else
watchcolor = ccolor
end
watch = "y"
else
print("You already have a " .. watchcolor .. " watch.")
----Already Done
print("Replace it(1), or store it(2)?")
pickup = io.read()
if pickup == "1" then
print("You took the watch.")
io.read()
if store == "y" then
watchstore = "n"
watchcolor = storedwcolor
soredwcolor = ""
watchstore = "n"
else
watchcolor = ccolor
end
watch = "y"
elseif pickup == "2" then
if tentplaced == "y" then
print("You traveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
print("Stored.")
io.read()
watchstore = "y"
storedwcolor = ccolor
else
print("You don't have a placed tent.")
io.read()
end
else
print("You leave the watch.")
io.read()
end
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
end
function resting()
if light == "light" then
if tentplaced == " y" then
print("You slept throught the day in your tent.")
else
print("You slept through the day.")
end
io.read()
if vision == "n" then
accuracy = fullaccuracy
accuracy = accuracy - 4
accuracytwo = fullaccuracytwo
accuracytwo = accuracytwo - 4
elseif vision == "y" then
accuracytwo = fullaccuracytwo
accuracy = fullaccuracy
end
light = "dark"
hour = 8
period = "pm"
elseif light == "dark" then
if tentplaced == " y" then
print("You slept throught the night in your tent.")
else
print("You slept through the night.")
end
io.read()
if vision == "n" then
accuracy = fullaccuracy
accuracytwo = fullaccuracytwo
elseif vision == "y" then
accuracy = fullaccuracy
accuracy = accuracy - 4
accuracytwo = fullaccuracytwo
accuracytwo = accuracytwo - 4
end
light = "light"
hour = 8
period = "am"
end
days = days + 1
if tentplaced == "n" then
tired = tired - math.random(200, 300)
food = food - math.random(30, 100)
water = water - math.random(50, 150)
temperature = temperature - math.random(0, 3)
if tired < 0 then
tired = 0
end
-- end of less than 0
rain = math.random(1, 5)
if rain == 1 then
print("It rained.")
io.read()
temperature = temperature - math.random(3, 5)
end
elseif tentplaced == "y" then
tired = 0
food = food - math.random(30, 100)
water = water - math.random(50, 150)
temperature = temperature - math.random(0, 1)
if tired < 0 then
tired = 0
end
-- end of less than 0
rain = math.random(1, 5)
if rain == 1 then
print("It rained.")
io.read()
temperature = temperature - math.random(1, 2)
end
end
end
function optionline()
print("___________________________")
---------------------------------------Write stats
repeat
use = io.read()
if use == "d" then
dropped()
elseif use == "u" then
used()
elseif use == "r" then
print("You have rested.")
io.read()
resting()
elseif use == "s" then
stats()
io.read()
elseif use == "h" then
help()
elseif use == "j" then
print("You go for a jog.")
io.read()
tired = tired + math.random(100, 300)
temperature = temperature + math.random(1, 3)
food = food - math.random(10, 30)
water = water - math.random(20, 50)
if temperature > 50 then
temperature = 50
end
if temperature >= 33 then
if cold == "y" then
print("You lost your cold.")
io.read()
cold = "n"
end
end
elseif use == "o" then
print("OPTIONS")
print("Press 1 for autostats, 2 for Stat Search, 3 for Stat Sections, or 4 for Name.")
want = io.read()
if want == "1" then
print("After how many turns do you want to view your stats automatically? 0 = off")
amount = io.read("*n")
turns = amount
if turns ~= 0 then
turn = turns
autostat = "y"
print("You will now view your stats after every " .. turns .. " turns.")
io.read()
else
print("You turned off autostats.")
io.read()
autostat = "n"
end
elseif want == "2" then
print("Do you want to have to search your stats? (Stats won't run out of screen using search.)")
want = io.read()
if want == "y" then
print("You will now have to search your stats.")
io.read()
statsearch = "y"
elseif want ~= "y" then
print("All your stats will be displayed at once.")
io.read()
statsearch = "n"
end
elseif want == "3" then
repeat
print("Please choose which sections to view, enter one number at a time.")
print(
"Section 1:INFORMATION, Section 2:STATS, Section 3:WEAPON, Section 4:DOGS, Section 5:ITEMS, Section 6:INJURIES, Section 7:OUTFIT, all:All Sections."
)
choose = io.read()
if choose == "1" then
if statA == "n" then
statA = "y"
print("You have chosen Section 1 to view.")
io.read()
else
statA = "n"
print("You have chosen not to view Section 1.")
io.read()
end
elseif choose == "2" then
if statB == "n" then
statB = "y"
print("You have chosen Section 2 to view.")
io.read()
else
statB = "n"
print("You have chosen not to view Section 2.")
io.read()
end
elseif choose == "3" then
if statC == "n" then
statC = "y"
print("You have chosen Section 3 to view.")
io.read()
else
statC = "n"
print("You have chosen not to view Section 3.")
io.read()
end
elseif choose == "4" then
if statD == "n" then
statD = "y"
print("You have chosen Section 4 to view.")
io.read()
else
statD = "n"
print("You have chosen not to view Section 4.")
io.read()
end
elseif choose == "5" then
if statE == "n" then
statE = "y"
print("You have chosen Section 5 to view.")
io.read()
else
statE = "n"
print("You have chosen not to view Section 5.")
io.read()
end
elseif choose == "6" then
if statF == "n" then
statF = "y"
print("You have chosen Section 6 to view.")
io.read()
else
statF = "n"
print("You have chosen not to view Section 6.")
io.read()
end
elseif choose == "7" then
if statG == "n" then
statG = "y"
print("You have chosen Section 7 to view.")
io.read()
else
statG = "n"
print("You have chosen not to view Section 7.")
io.read()
end
elseif choose == "all" then
if allsections == "n" then
print("All sections will be viewed.")
io.read()
allsections = "y"
statA = "y"
statB = "y"
statC = "y"
statD = "y"
statE = "y"
statF = "y"
statG = "y"
else
print("You have chosen not to view any sections.")
io.read()
allsections = "n"
statA = "n"
statB = "n"
statC = "n"
statD = "n"
statE = "n"
statF = "n"
statG = "n"
end
else
choose = "0"
end
until choose == "0"
elseif want == "4" then
print("Your name is currently " .. name .. ", what do you want to change it to?")
name = io.read()
print("You have successfully changed your name to " .. name .. ".")
io.read()
end
elseif use == "q" then
print("Are you sure you want to quit?")
want = io.read()
if want == "y" then
starve = "y"
health = 0
break
elseif want ~= "y" then
print("Continue playing.")
io.read()
end
elseif use == "w" then
print("You switched your primary and secondary.")
io.read()
if mygun ~= myguntwo then
mygunthree = mygun
mygun = myguntwo
myguntwo = mygunthree
damagethree = damage
damage = damagetwo
damagetwo = damagethree
accuracythree = accuracy
accuracy = accuracytwo
accuracytwo = accuracythree
fullaccuracythree = fullaccuracy
fullaccuracy = fullaccuracytwo
fullaccuracytwo = fullaccuracythree
myammothree = myammo
myammo = myammotwo
myammotwo = myammothree
elseif mygun == myguntwo then
print("You compiled the ammo.")
io.read()
myguntwo = "no weapon"
myammo = myammo + myammotwo
myammotwo = 0
damagetwo = 0
accuracytwo = 0
fullaccuracytwo = 0
space = space + gunspace
end
else
use = "none"
end
-----------------------------------------bandaids
if use ~= "none" then
print("Any other actions?")
end
until use == "none"
end
function stats7()
print("OUTFIT")
print(shirt .. " shirt")
print(pants .. " pants")
if cpack == "y" then
print("Coyote pack")
end
if pack == "y" then
print("Alice pack")
end
if vpack == "y" then
print("Vest Pouch")
end
if vision == "y" then
print("Goggles on")
end
if hero == "y" then
print("Cape")
elseif bandit == "y" then
print("Bandana")
end
if gillie == "y" then
print("Gillie suit")
end
if watch == "y" then
print(watchcolor .. " watch")
end
print("-----------------------")
end
function stats6()
print("INJURIES")
if cold == "y" then
print("Cold")
end
if bleeding == "y" then
print("Bleeding")
end
if broken == "y" then
print("Broken leg")
end
if infection == "y" then
print("Infection")
end
print("-----------------------")
end
function stats5()
print("ITEMS")
print(space .. " space(s)")
print(". . . . . . . . . . . .")
print("<food>")
if bottle == "y" then
if filled == "y" then
print("Water bottle")
else
print("empty bottle")
end
end
if beans >= 1 then
print(beans .. " can(s) of beans")
end
if pop >= 1 then
print(pop .. " pop")
end
if meat >= 1 then
print(meat .. " meat")
end
if steak >= 1 then
print(steak .. " steak(s)")
end
if superbean == "y" then
print("Super Bean?")
end
print(". . . . . . . . . . . .")
print("<medical>")
if bloodbags >= 1 then
print(bloodbags .. " blood bag(s)")
end
if bandaids >= 1 then
print(bandaids .. " bandaid(s)")
end
if morphine >= 1 then
print(morphine .. " epi-pen(s)")
end
if epipen >= 1 then
print(epipen .. " pain killer(s)")
end
if antibiotics >= 1 then
print(antibiotics .. " antibiotic(s)")
end
if painkillers >= 1 then
print(painkillers .. " morphine")
end
if heatpacks >= 1 then
print(heatpacks .. " heatpack(s)")
end
print(". . . . . . . . . . . .")
print("<tools>")
if knife == "y" then
print("Knife")
end
if matches >= 1 then
print(matches .. " match(es)")
end
if wood == "y" then
print("Wood")
end
if beartrap == "y" then
print("Bear Trap")
end
if goggles == "y" then
print("NV Goggles")
end
if roadflare >= 1 then
print(roadflare .. " road flare(s)")
end
if smoke >= 1 then
print(smoke .. " smoke grenade(s)")
end
if tent == "y" then
print("Tent")
end
if can == "y" then
if cfilled == "y" then
print("Filled Jerry can")
elseif cfilled ~= "y" then
print("Jerry can")
end
end
print(". . . . . . . . . . . .")
print("<other>")
if book == "y" then
if storingbook == "y" then
print(ccolor .. " book")
else
print(cover .. " book")
end
end
if radio == "y" then
print("Radio")
end
if tentplaced == "y" then
print("Set tent")
end
print("-----------------------")
end
function stats4()
print("DOGS")
if dogs >= 1 then
print(dogs .. " Dog(s)")
print(dogname)
print(doghealth .. " health")
print(dogfood .. " food")
print(dogwater .. " water")
end
print("-----------------------")
end
function stats3()
print("WEAPON")
print(". . . . . . . . . . . .")
print("<Primary weapon>")
if mygun ~= "no weapon" then
print(mygun)
if mygun ~= "Hatchet" then
print(myammo .. " ammo")
end
if mygun ~= "Hatchet" then
print(accuracy .. " accuracy")
end
print(damage .. " damage")
end
print(". . . . . . . . . . . .")
print("<Secondary weapon>")
if myguntwo ~= "no weapon" then
print(myguntwo)
if myguntwo ~= "Hatchet" then
print(myammotwo .. " ammo")
end
if myguntwo ~= "Hatchet" then
print(accuracytwo .. " accuracy")
end
print(damagetwo .. " damage")
end
print(". . . . . . . . . . . .")
print("<Other>")
if set == "y" then
print("Set Bear Trap")
end
if grenade >= 1 then
print(grenade .. " grenade(s)")
end
print("-----------------------")
end
function stats2()
print("STATS")
print(health .. " blood")
print(pain .. " pain")
print(temperature .. " degrees")
print(food .. " food")
print(water .. " water")
print(tired .. " exhaustion")
print("-----------------------")
end
function stats1()
if creator == "y" then
print(name .. symbol)
else
print(name)
end
if hero == "y" then
print("Hero " .. gamemode)
elseif bandit == "y" then
print("Bandit " .. gamemode)
else
print("Survivor " .. gamemode)
end
if watch == "y" then
if light == "light" then
print(light .. " " .. hour .. " " .. period)
else
print(light .. " " .. hour .. " " .. period)
end
else
print(light)
end
if spawn == 1 then
print("City Day " .. days)
elseif spawn == 2 then
print("Shore Day " .. days)
elseif spawn == 3 then
print("Forest Day " .. days)
end
-- end of spaw
print("-----------------------")
end
function DBshotgunitem() --(X)--(X)--(X)--(4)--(X)--(6)--(7)
print("You found a Doulble Barrel Shotgun.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "DB Shotgun" then
if space >= 7 - gunspacethree then
print("You have picked it up")
io.read()
space = space - (7 - gunspacethree)
gunspacethree = 7
myammothree = math.random(10, 50)
damagethree = 5000 + (1000 * dogs)
mygunthree = "DB Shotgun"
accuracythree = 6
fullaccuracythree = 6
takegun()
break
elseif space < 7 - gunspacethree then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("DB Shotgun")
if store == "y" then
sstore = "y"
store = "n"
end
dropped()
if sstore == "y" then
store = "y"
sstore = "n"
end
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("DB Shotgun")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the DB Shotgun(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
store = "y"
storinggun = "y"
gunspacethree = 7
myammothree = math.random(10, 50)
damagethree = 5000
mygunthree = "DB Shotgun"
accuracythree = 6
fullaccuracythree = 6
dropgun()
storinggun = "n"
store = "n"
break
else
repeat
print("DB Shotgun")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
print("You can't use this item.")
io.read()
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif mygunthree == "DB Shotgun" then
print("You already have this gun, store it(1) or take the ammo(2)?")
want = io.read()
if want == "2" then
print("You took the ammo.")
io.read()
myammothree = myammothree + math.random(10, 50)
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
else
if tentplaced == "y" then
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
store = "y"
storinggun = "y"
gunspacethree = 7
myammothree = math.random(10, 50)
damagethree = 5000
mygunthree = "DB Shotgun"
accuracythree = 6
fullaccuracythree = 6
dropgun()
storinggun = "n"
store = "n"
break
else
print("You don't have a placed tent.")
io.read()
end
end
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function M4A1item() --(X)--(X)--(X)--(!)--(X)--(!)--(!)--(!)
print("You found a M4A1.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "M4A1" then
if space >= 6 - gunspacethree then
print("You have picked it up")
io.read()
space = space - (6 - gunspacethree)
gunspacethree = 6
myammothree = math.random(10, 50)
damagethree = 4000 + (1000 * dogs)
mygunthree = "M4A1"
accuracythree = 8
fullaccuracythree = 8
takegun()
break
elseif space < 6 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == "M4A1" then
print("You took the ammo.")
io.read()
myammothree = myammothree + math.random(10, 50)
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function AK47item() --(X)--(X)--(X)--(!)--(X)--(!)--(!)--(!)
print("You found an AK47.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "AK47" then
if space >= 6 - gunspacethree then
print("You have picked it up")
io.read()
space = space - (6 - gunspacethree)
gunspacethree = 6
myammothree = math.random(30, 70)
damagethree = 3500 + (1000 * dogs)
mygunthree = "AK47"
accuracythree = 7
fullaccuracythree = 7
takegun()
break
elseif space < 6 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == "AK47" then
print("You took the ammo.")
io.read()
myammothree = myammothree + math.random(10, 50)
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function g36citem() --(X)--(X)--(X)--(!)--(X)--(!)--(!)--(!)
print("You found a G36C.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "G36C" then
if space >= 6 - gunspacethree then
print("You have picked it up")
io.read()
space = space - (6 - gunspacethree)
gunspacethree = 6
myammothree = math.random(30, 70)
damagethree = 3700 + (1000 * dogs)
mygunthree = "G36C"
accuracythree = 7
fullaccuracythree = 7
takegun()
break
elseif space < 6 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == "G36C" then
print("You took the ammo.")
io.read()
myammothree = myammothree + math.random(10, 50)
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function radioitem() --(X)--(X)--(X)--(!)--(!)--(6)--(X)
print("You found a radio.")
repeat
print("pickup?")
pickup = io.read()
if pickup == "y" then
if radio ~= "y" then
if space >= 1 then
print("You took the radio.")
io.read()
if store == "y" then
radiostore = "n"
end
radio = "y"
space = space - 1
break
elseif space < 1 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Radio")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Radio")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the radio(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if radiostore == "n" then
print("Stored")
io.read()
radiostore = "y"
break
else
print("You already have a stored radio.")
io.read()
end
else
repeat
print("Radio")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
radio = "y"
useradio()
radio = "n"
print("You leave.")
io.read()
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif radio == "y" then
print("Already owned.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
break
end
until pickup ~= "y"
end
function gasstation()
print("You found a gas station, approach?.")
approach = io.read()
if approach == "y" then
print("You prepare to approach.")
io.read()
amount = math.random(1, 7)
if amount == 1 then
playerevent()
if health <= 0 then
else
print("The player already cleared out the place.")
io.read()
end
else
print("You don't see anyone.")
io.read()
amount = math.random(1, 2)
if amount == 1 then
filledjerrycanitem()
else
print("You found a fuel tank.")
print("Use?")
pickup = io.read()
if pickup == "y" then
if can == "y" then
if cfilled == "n" then
print("You filled your jerry can.")
io.read()
cfilled = "y"
elseif cfilled == "y" then
print("Already filled.")
io.read()
end
elseif can ~= "y" then
print("You have no can.")
io.read()
end
elseif pickup ~= "y" then
print("You leave.")
io.read()
end
end
print("You leave the building.")
io.read()
end
elseif approach ~= "y" then
print("You leave.")
io.read()
end
end
function wooditem() --(X)--(X)--(X)--(!)--(!)--(6)--(X)
print("You found wood.")
repeat
print("pickup?")
pickup = io.read()
if pickup == "y" then
if wood ~= "y" then
if space >= 2 then
print("You took the wood.")
io.read()
if store == "y" then
woodstore = "n"
end
wood = "y"
space = space - 2
break
elseif space < 2 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Wood")
store = "n"
dropped()
store = "y"
print("drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Wood")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the wood(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if woodstore == "n" then
print("Stored")
io.read()
woodstore = "y"
break
else
print("You already have a stored wood.")
io.read()
end
else
repeat
print("Wood")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
print("Wood can not be used.")
io.read()
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif wood == "y" then
print("Already owned.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function ammoitem() --(X)--(X)--(X)--(X)--(X)--(X)--(!)
if mygun ~= "no weapon" then
print("You found some ammo.")
io.read()
myammo = myammo + math.random(5, 20)
if myguntwo ~= "no weapon" then
myammotwo = myammotwo + math.random(5, 20)
end
elseif myguntwo ~= "no weapon" then
print("You took the ammo.")
io.read()
myammotwo = myammotwo + math.random(5, 20)
else
beansitem()
end
end
function gogglesitem() --(X)--(X)--(X)--(!)--(!)--(6)--(X)
print("You found Night Vision Goggles.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
if goggles == "n" then
if space >= 2 then
goggles = "y"
space = space - 2
print("You picked it up.")
if store == "y" then
gogglestore = "n"
end
io.read()
break
elseif space < 2 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("NV Goggles")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("NV Goggles")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the goggles(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if gogglestore == "n" then
print("Stored")
io.read()
gogglestore = "y"
break
else
print("You already have a stored goggles.")
io.read()
end
else
repeat
print("NV Goggles")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
goggles = "y"
usegoggles()
space = space - 2
print("You leave.")
io.read()
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif goggles == "y" then
print("Already owned.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function coyotepackitem() --(x)--(x)--(x)--(x)--(!)--(x)--(x)
print("You found a Coyote pack, pickup?")
pickup = io.read()
if pickup == "y" then
if cpack == "y" then
print("Already owned.")
io.read()
elseif vpack == "y" then
space = space + 14
print("You picked it up.")
io.read()
cpack = "y"
vpack = "n"
elseif pack == "y" then
space = space + 10
print("You picked it up.")
io.read()
pack = "y"
pack = "n"
else
space = space + 20
print("You picked it up.")
io.read()
cpack = "y"
end
elseif pickup ~= "y" then
print("You left it there.")
end
end
function AS50item() --(X)--(X)--(X)--(!)--(X)--(!)--(!)
print("You found an AS50.")
repeat
print("Pickup?")
pickup = io.read()
print("Put in which slot?")
slot = io.read()
if pickup == "y" then
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "AS50" then
if space >= 8 - gunspacethree then
print("You have picked it up")
io.read()
myammothree = math.random(10, 50)
damagethree = 200000 + (1000 * dogs)
mygunthree = "AS50"
accuracythree = 10
fullaccuracythree = 10
space = space - (8 - gunspacethree)
gunspacethree = 8
takegun()
break
elseif space < 8 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == "AS50" then
print("You took the ammo.")
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
io.read()
myammothree = myammothree + math.random(10, 50)
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function filledjerrycanitem() --(x)--(x)--(x)--(!)--(!)--(6)--(x)
print("You have found a filled jerry can.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
if can == "n" then
if space >= 5 then -------------------------------------------------WIP
space = space - 5
can = "y"
cfilled = "y"
print("You picked it up.")
io.read()
if store == "y" then
canstore = "n"
cfilledstore = "n"
end
break
elseif space < 5 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Filled Jerry can")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Filled Jerry can")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the jerry can(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if canstore == "n" then
print("Stored")
io.read()
canstore = "y"
cfilledstore = "y"
break
else
if cfilledstore == "n" then
cfilledstore = "y"
print("You filled the jerry can in your tent.")
io.read()
break
else
print("You already have a stored jerry can.")
io.read()
end
end
else
repeat
print("Filled Jerry can")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
print("You can't use the Jerry can.")
io.read()
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif can == "y" then
if cfilled == "n" then
print("You filled your jerry can.")
io.read()
cfilled = "y"
if store == "y" then
print("You left the empty can in the tent.")
io.read()
cfilledstore = "n"
end
break
elseif cfilled == "y" then
print("Already owned.")
io.read()
break
end
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function beartrapitem() --(x)--(!)--(x)--(!)--(!)--(6)--(x)
print("You found a bear trap.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
if beartrap == "n" then
if space >= 2 then
beartrap = "y"
space = space - 2
print("You picked it up.")
io.read()
if store == "y" then
beartrapstore = "n"
end
break
elseif space < 2 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Bear Trap")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Bear Trap")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the bear trap(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if beartrapstore == "n" then
print("Stored")
io.read()
beartrapstore = "y"
break
else
print("You already have a stored bear trap.")
io.read()
end
else
repeat
print("Bear Trap")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
beartrap = "y"
usebeartrap()
beartrap = "n"
print("You leave.")
io.read()
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif beartrap == "y" then
print("Already owned.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function M16item() --(X)--(X)--(X)--(!)--(X)--(!)--(!)
print("You found a M16.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "M16" then
if space >= 6 - gunspacethree then
print("You have picked it up")
io.read()
space = space - (6 - gunspacethree)
gunspacethree = 6
myammothree = math.random(10, 50)
damagethree = 3400 + (1000 * dogs)
mygunthree = "M16"
accuracythree = 6
fullaccuracythree = 6
takegun()
break
elseif space < 6 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == "M16" then
print("You took the ammo.")
io.read()
myammothree = myammothree + math.random(10, 50)
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function matchitem() --(!)--(!)--(!)--(!)--(!)--(6)--(X)
print("You found matches.")
repeat
print("Pick up?")
pickup = io.read()
if pickup == "y" then
if matches < 1 then
if space >= 1 then
amount = math.random(1, 5)
print("You picked them up.")
io.read()
space = space - 1
if store ~= "y" then
matches = matches + amount
else
matches = matches + matchstore
matchstore = 0
end
break
elseif space < 1 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Match")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Match")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the match(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
print("Stored.")
io.read()
matchstore = matchstore + math.random(1, 5)
break
else
repeat
print("Match")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
useamount = math.random(1, 5)
repeat
matches = useamount
usematch()
matches = 0
useamount = useamount - 1
if useamount ~= 0 then
print("Use more matches?")
print("You have " .. useamount .. " left.")
want = io.read()
if want ~= "y" then
useamount = 0
end
end
until useamount == 0
print("You leave.")
io.read()
matches = 0
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif matches >= 1 then
print("You picked it up.")
io.read()
amount = math.random(1, 5)
if store ~= "y" then
matches = matches + amount
else
matches = matches + matchstore
matchstore = 0
end
break
end
elseif pickup ~= "y" then
print("You left them there.")
io.read()
end
until pickup ~= "y"
end
function jerrycanitem() --(X)--(X)--(X)--(!)--(!)--(6)--(X)
print("You have found a jerry can.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
if can == "n" then
if space >= 5 then
space = space - 5
can = "y"
print("You picked it up.")
io.read()
if store == "y" then
canstore = "n"
cfilledstore = "n"
end
break
elseif space < 5 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Jerry can")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Jerry can")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the jerry can(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if canstore == "n" then
print("Stored")
io.read()
canstore = "y"
break
else
print("You already have a stored jerry can.")
io.read()
end
else
repeat
print("Jerry can")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
print("You can't use the Jerry can.")
io.read()
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif can == "y" then
print("Already owned.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function watersourceitem()
print("You found a water source.")
print("Use it?")
pickup = io.read()
if pickup == "y" then --water
if bottle == "y" then
if filled == "n" then
print("You filled your bottle.")
io.read()
filled = "y"
if water < 700 then
print("You drank the water.")
io.read()
water = water + math.random(300, 500)
elseif water >= 700 then
print("You are not thirsty.")
io.read()
end
if dogs > 0 then
if dogwater < 500 then
print("Your dog(s) drank the water.")
io.read()
dogwater = dogwater + math.random(300, 500)
elseif dogwater >= 500 then
print("Your dog(s) are not thirsty.")
io.read()
end
end
elseif filled == "y" then
print("Already filled.")
io.read()
if water < 700 then
print("You drank the water.")
io.read()
water = water + math.random(300, 500)
elseif water >= 700 then
print("You are not thirsty.")
io.read()
end
if dogs > 0 then
if dogwater < 500 then
print("Your dog(s) drank the water.")
io.read()
dogwater = dogwater + math.random(300, 500)
elseif dogwater >= 500 then
print("Your dog(s) are not thirsty.")
io.read()
end
end
end
elseif bottle == "n" then
if water < 700 then
print("You drank the water.")
io.read()
water = water + math.random(300, 500)
elseif water >= 700 then
print("You are not thirsty.")
io.read()
end
if dogs > 0 then
if dogwater < 500 then
print("Your dog(s) drank the water.")
io.read()
dogwater = dogwater + math.random(300, 500)
elseif dogwater >= 500 then
print("Your dog(s) are not thirsty.")
io.read()
end
end
end
elseif pickup ~= "y" then
print("You left the water.")
io.read()
end
--end of water
end
function bottleitem() --(X)--(x)--(X)--(!)--(!)--(6)--(X)
print("You have found a water bottle.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
if bottle == "n" then
if space >= 1 then
space = space - 1
bottle = "y"
print("You picked it up.")
io.read()
if store == "y" then
bottlestore = "n"
filledstore = "n"
end
break
elseif space < 1 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Bottle")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Bottle")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the bottle(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if bottlestore == "n" then
print("Stored")
io.read()
bottlestore = "y"
break
else
print("You already have a stored bottle.")
io.read()
end
else
repeat
print("Bottle")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
print("You can't use a bottle.")
io.read()
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif bottle == "y" then
print("Already owned.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function tentitem() --(X)--(!)--(X)--(!)--(!)--(6)--(X)
print("You found a tent.")
repeat
print("pickup?")
pickup = io.read()
if pickup == "y" then
if tent == "n" then
if space >= 4 then
print("You took the tent.")
io.read()
if store == "y" then
tentstore = "n"
end
space = space - 4
tent = "y"
break
elseif space < 4 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Tent")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Tent")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the tent(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if tentstore == "n" then
print("Stored")
io.read()
tentstore = "y"
break
else
print("You already have a stored tent.")
io.read()
end
else
repeat
print("Tent")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
tent = "y"
usetent()
tent = "n"
print("You leave.")
io.read()
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif tent == "y" then
print("Already owned.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function knifeitem() --(X)--(X)--(x)--(!)--(!)--(6)--(x)
print("You found a hunting knife.")
repeat
print("Pick up?")
pickup = io.read()
if pickup == "y" then
if knife ~= "y" then
if space >= 2 then
knife = "y"
print("You picked it up.")
io.read()
if store == "y" then
knifestore = "n"
end
space = space - 2
break
elseif space < 2 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Knife")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Knife")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the knife(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if knifestore == "n" then
print("Stored")
io.read()
knifestore = "y"
break
else
print("You already have a stored knife.")
io.read()
end
else
repeat
print("Knife")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
print("You can't use a knife.")
io.read()
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif knife == "y" then
print("Already owned")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
--end of pickup
until pickup ~= "y"
end
function cowitem()
if dogcow == "n" then
if trapcow == "n" then
print("You found a cow.")
elseif trapcow == "y" then
print("You caught a cow in your bear trap.")
end
elseif dogcow == "y" then
print("Your dog caught a cow.")
end
print("Skin it?")
pickup = io.read()
if pickup == "y" then --meat
if knife == "y" then
meatitem()
else
print("You don't have a knife.")
io.read()
end
else
print("You leave.")
io.read()
end
end
function antibioticsitem() --(!)--(!)--(!)--(!)--(x)--(6)--(x)
print("You found some some antibiotics.")
repeat
print("accept?")
pickup = io.read()
if pickup == "y" then
if antibiotics < 1 then
if space >= 1 then
amount = math.random(1, 5)
print("You took them.")
io.read()
space = space - 1
if store ~= "y" then
antibiotics = antibiotics + amount
else
antibiotics = antibiotics + antibioticstore
antibioticstore = 0
end
break
elseif space < 1 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Antibiotics")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Antibiotics")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the antibiotics(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
print("Stored")
io.read()
antibioticstore = antibioticstore + math.random(1, 5)
break
else
repeat
print("Antibiotics")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
useamount = math.random(1, 5)
repeat
antibiotics = useamount
useantibiotics()
antibiotics = 0
useamount = useamount - 1
if useamount ~= 0 then
print("Use more antibiotics?")
print("You have " .. useamount .. " left.")
want = io.read()
if want ~= "y" then
useamount = 0
end
end
until useamount == 0
print("You leave.")
io.read()
antibiotics = 0
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif antibiotics >= 1 then
print("You picked it up.")
io.read()
amount = 1
if store ~= "y" then
antibiotics = antibiotics + amount
else
antibiotics = antibiotics + antibioticstore
antibioticstore = 0
end
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function filledbottleitem() --(x)--(2)--(x)--(!)--(!)--(6)--(x)
print("You found a bottle of water.")
repeat
print("Accept?")
pickup = io.read()
if pickup == "y" then
if bottle == "n" then
if filled == "n" then
if space >= 2 then
print("You took the bottle.")
io.read()
filled = "y"
bottle = "y"
space = space - 2
if store == "y" then
bottlestore = "n"
filledstore = "n"
end
break
elseif space < 2 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Water Bottle")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Water Bottle")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the Water Bottle(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if bottlestore == "n" then
print("Stored")
io.read()
bottlestore = "y"
filledstore = "y"
break
else
if filledstore == "n" then
filledstore = "y"
print("You filled the bottle in your tent.")
io.read()
break
else
print("You already have a stored water bottle.")
io.read()
end
end
else
repeat
print("water Bottle")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
if water < 700 then
usewater()
if store == "y" then
filledstore = "n"
print("You leave the empty bottle in your tent.")
io.read()
end
break
else
print("You are not thirsty.")
--Fixed
io.read()
break
end
print("You leave.")
io.read()
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif filled == "y" then
print("Already filled.")
io.read()
break
end
elseif bottle == "y" then
if filled == "n" then
if store == "y" then
print("You left the empty bottle in your tent.")
io.read()
filledstore = "n"
end
print("You filled your bottle.")
io.read()
filled = "y"
break
elseif filled == "y" then
print("Already filled.")
io.read()
break
end
end
elseif pickup ~= "y" then
print("You left it.")
end
until pickup ~= "y"
end
function morphineitem() --(!)--(!)--(!)--(!)--(x)--(6)--(x)
print("You found some morphine.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = math.random(1, 2)
if painkillers < 1 then
if space >= 1 then
if store ~= "y" then
painkillers = painkillers + amount
else
painkillers = painkillers + painkillerstore
morphinestore = 0
end
space = space - 1
print("You picked them up.")
io.read()
break
elseif space < 1 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Morphine")
store = "n"
dropped()
store = "y"
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Morphine")
--------------------
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the morphine(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
print("Stored")
io.read()
morphinestore = morphinestore + math.random(1, 2)
break
else
repeat
print("Morphine")
store = "y"
dropped()
store = "n"
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
useamount = math.random(1, 2)
repeat
painkillers = useamount
usemorphine()
painkillers = 0
useamount = useamount - 1
if useamount ~= 0 then
print("Use more morphine?")
print("You have " .. useamount .. " left.")
want = io.read()
if want ~= "y" then
useamount = 0
end
end
until useamount == 0
print("You leave.")
io.read()
painkillers = 0
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif painkillers >= 1 then
if store ~= "y" then
painkillers = painkillers + amount
else
painkillers = painkillers + painkillerstore
morphinestore = 0
end
print("You picked them up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function booksitem() --(x)--(x)--(x)--(!)--(!)--(6)--(x)
color = math.random(1, 19)
coloring()
if ccolor == "dress" then
ccolor = "leather"
end
if store == "n" then
if findbook == "y" then
print("You found a " .. droppedcolor .. " book.")
ccolor = droppedcolor
else
print("You found a " .. ccolor .. " book.")
end
else
print("You found a " .. storedcolor .. " book.")
ccolor = storedcolor
end
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
if space >= 2 then
if store == "n" then
if findbook == "n" then
word()
text = writing
else
text = droppedwriting
end
else
text = storedwriting
bookstore = "n"
storedcolor = ""
storedwriting = ""
end
book = "y"
cover = ccolor
space = space - 2
print("You picked it up.")
io.read()
break
elseif space < 2 then
print("Not enough space.")
io.read()
print("Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?")
want = io.read()
if want == "d" then
repeat
print("Book")
if store == "y" then
sstore = "y"
store = "n"
end
dropped()
if sstore == "y" then
store = "y"
sstore = "n"
end
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Book")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the book(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
if bookstore == "n" then
if store == "n" then
if findbook == "n" then
word()
storedwriting = writing
else
storedwriting = droppedwriting
end
end
bookstore = "y"
storedcolor = ccolor
print("Stored.")
io.read()
break
else
print("You already have a stored book.")
io.read()
end
else
repeat
print("Book")
if store == "n" then
sstore = "n"
store = "y"
end
dropped()
if sstore == "n" then
store = "n"
end
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
word()
booknow = "y"
if book == "y" then
alreadybook = "y"
end
book = "y"
usebook()
if store == "n" then
droppedwriting = text
droppedbook = "y"
droppedcolor = cover
print("You dropped the book.")
io.read()
end
if alreadybook == "n" then
book = "n"
end
alreadybook = "n"
booknow = "n"
print("You leave.")
io.read()
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function heatpackitem() --(!)--(!)--(!)--(!)--(x)--(6)--(x)
print("You found a heat pack.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = math.random(1, 3)
if heatpacks < 1 then
if space >= 1 then
if store ~= "y" then
heatpacks = heatpacks + amount
else
heatpacks = heatpacks + heatpackstore
heatpackstore = 0
end
space = space - 1
print("You picked it up.")
io.read()
break
elseif space < 1 then
print("Not enough space.")
io.read()
print(
"Do you want to drop(d) or use(u) something, try again(t), use now(n), or store(s) the item?"
)
want = io.read()
if want == "d" then
repeat
print("Heat Pack")
if store == "y" then
sstore = "y"
store = "n"
end
dropped()
if sstore == "y" then
store = "y"
sstore = "n"
end
print("Drop more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "u" then
repeat
print("Heat Pack")
used()
print("Use more?")
dropmore = io.read()
until dropmore ~= "y"
elseif want == "s" then
if tentplaced == "y" then
print("Store the heat pack(1) or something else(2)?")
want = io.read()
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
if want == "1" then
print("Stored")
io.read()
heatpackstore = heatpackstore + math.random(1, 3)
break
else
repeat
print("Heat Pack")
if store == "n" then
sstore = "n"
store = "y"
end
dropped()
if sstore == "n" then
store = "n"
end
print("Store more?")
dropmore = io.read()
until dropmore ~= "y"
end
else
print("You don't have set tent.")
io.read()
end
elseif want == "n" then
useamount = math.random(1, 3)
repeat
heatpacks = useamount
useheatpack()
heatpacks = 0
useamount = useamount - 1
if useamount ~= 0 then
print("Use more heatpacks?")
print("You have " .. useamount .. " left.")
want = io.read()
if want ~= "y" then
useamount = 0
end
end
until useamount == 0
print("You leave.")
io.read()
heatpacks = 0
break
elseif want ~= "t" then
print("You leave.")
io.read()
break
end
end
elseif heatpacks >= 1 then
if store ~= "y" then
heatpacks = heatpacks + amount
else
heatpacks = heatpacks + heatpackstore
heatpackstore = 0
end
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function painkilleritem() --(!)--(!)--(!)--(!)--(x)--(6)--(x)
print("You found some pain killers.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = math.random(1, 7)
if epipen < 1 then
if space >= 1 then
if store ~= "y" then
epipen = epipen + amount
else
epipen = epipen + painkillerstore
painkillerstore = 0
end
space = space - 1
print("You picked it up.")
io.read()
break
elseif space < 1 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif epipen >= 1 then
if store ~= "y" then
epipen = epipen + amount
else
epipen = epipen + painkillerstore
painkillerstore = 0
end
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
end
until pickup ~= "y"
end
function leeenfielditem() --(X)--(X)--(X)--(!)--(X)--(!)--(!)
print("You found a Lee Enfield.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "Lee Enfield" then
if space >= 7 - gunspacethree then
print("You have picked it up")
io.read()
myammothree = math.random(10, 50)
damagethree = 4000 + (1000 * dogs)
mygunthree = "Lee Enfield"
accuracythree = 7
space = space - (7 - gunspacethree)
gunspacethree = 7
fullaccuracythree = 7
takegun()
break
elseif space < 7 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == "Lee Enfield" then
print("You took the ammo.")
io.read()
myammothree = myammothree + math.random(10, 50)
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function alicepackitem() --(x)--(!)--(x)--(!)--(!)--(x)--(x)
print("You found an Alice pack, pickup?")
pickup = io.read()
if pickup == "y" then
if pack == "y" then
print("Already have.")
io.read()
elseif vpack == "y" then
space = space + 4
print("You picked it up.")
io.read()
pack = "y"
vpack = "n"
elseif cpack == "y" then
print("You already have a Coyote pack.")
io.read()
else
space = space + 10
print("You picked it up.")
io.read()
pack = "y"
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
end
function vestpouchitem() --(x)--(!)--(x)--(!)--(!)--(x)--(x)
print("You found a vest pouch, pickup?")
pickup = io.read()
if pickup == "y" then
if vpack == "y" then
print("Already have.")
io.read()
elseif pack == "y" then
print("You have an Alice pack.")
io.read()
elseif cpack == "y" then
print("You have a Coyote pack.")
io.read()
else
space = space + 6
print("You picked it up.")
io.read()
vpack = "y"
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
end
function penitem() --(!)--(!)--(!)--(!)--(x)--(!)--(x)
print("You found an epi-pen.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
if morphine < 1 then
if space >= 1 then
if store ~= "y" then
morphine = morphine + 1
else
morphine = morphine + epipenstore
epipenstore = 0
end
space = space - 1
print("You picked it up.")
io.read()
break
elseif space < 1 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif morphine >= 1 then
if store ~= "y" then
morphine = morphine + 1
else
morphine = morphine + epipenstore
epipenstore = 0
end
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
end
until pickup ~= "y"
end
function roadflareitem() --(!)--(x)--(!)--(!)--(x)--(!)--(x)
print("You found a roadflare.")
repeat
print("Pick up?")
pickup = io.read()
if pickup == "y" then
if roadflare < 1 then
if space >= 1 then
amount = 1
print("You picked it up.")
io.read()
space = space - 1
if store ~= "y" then
roadflare = roadflare + 1
else
roadflare = roadflare + roadflarestore
roadflarestore = 0
end
break
elseif space < 1 then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif roadflare >= 1 then
print("You picked it up.")
io.read()
amount = 1
if store ~= "y" then
roadflare = roadflare + 1
else
roadflare = roadflare + roadflarestore
roadflarestore = 0
end
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function bloodbagitem() --(!)--(!)--(!)--(!)--(x)--(!)--(x)
print("You found a bloodbag.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = 1
if bloodbags < 1 then
if space >= 1 then
if store ~= "y" then
bloodbags = bloodbags + amount
else
bloodbags = bloodbags + bloodbagstore
bloodbagstore = 0
end
space = space - 1
print("You picked it up.")
io.read()
break
elseif space < 1 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif bloodbags >= 1 then
if store ~= "y" then
bloodbags = bloodbags + amount
else
bloodbags = bloodbags + bloodbagstore
bloodbagstore = 0
end
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
end
until pickup ~= "y"
end
function popitem() --(!)--(!)--(!)--(!)--(x)--(!)--(x)
print("You found some pop.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = 1
if pop < 1 then
if space >= 1 then
if store ~= "y" then
pop = pop + amount
else
pop = pop + popstore
popstore = 0
end
space = space - 1
print("You picked it up.")
io.read()
break
elseif space < 2 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif pop >= 1 then
if store ~= "y" then
pop = pop + amount
else
pop = pop + popstore
popstore = 0
end
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function beansitem() --(!)--(!)--(!)--(!)--(x)--(!)--(x)
print("You found some beans.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = math.random(1, 2)
if beans < 1 then
if space >= 1 then
if store ~= "y" then
beans = beans + amount
else
beans = beans + beanstore
beanstore = 0
end
space = space - 1
print("You picked them up.")
io.read()
break
elseif space < 1 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif beans >= 1 then
if store ~= "y" then
beans = beans + amount
else
beans = beans + beanstore
beanstore = 0
end
print("You picked them up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function steakitem() --(!)--(!)--(!)--(!)--(x)--(!)--(x)
print("You found some steak.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = 1
if steak < 1 then
if space >= 1 then
if store ~= "y" then
steak = steak + amount
else
steak = steak + steakstore
steakstore = 0
end
space = space - 1
print("You picked it up.")
io.read()
break
elseif space < 1 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif steak >= 1 then
if store ~= "y" then
steak = steak + amount
else
steak = steak + steakstore
steakstore = 0
end
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
end
until pickup ~= "y"
end
function bandaiditem() --(!)--(!)--(!)--(!)--(x)--(!)--(x)
print("You found some bandaids.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = math.random(1, 5)
if bandaids < 1 then
if space >= 1 then
if store ~= "y" then
bandaids = bandaids + amount
else
bandaids = bandaids + bandaidstore
bandaidstore = 0
end
space = space - 1
print("You picked them up.")
io.read()
break
elseif space < 1 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif bandaids >= 1 then
if store ~= "y" then
bandaids = bandaids + amount
else
bandaids = bandaids + bandaidstore
bandaidstore = 0
end
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left them there.")
io.read()
end
until pickup ~= "y"
end
function grenadeitem() --(!)--(x)--(!)--(!)--(x)--(!)--(x)
print("You found grenades.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = math.random(1, 4)
if grenade < 1 then
if space >= 1 then
grenade = grenade + amount
space = space - 1
print("You picked them up.")
io.read()
break
elseif space < 1 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif grenade >= 1 then
grenade = grenade + amount
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
end
until pickup ~= "y"
end
function smokegrenadeitem() --(!)--(x)--(!)--(!)--(x)--(!)--(x)
print("You found a smoke grenade.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
amount = 1
if smoke < 1 then
if space >= 1 then
if store ~= "y" then
smoke = smoke + amount
else
smoke = smoke + smokestore
smokestore = 0
end
space = space - 1
print("You picked it up.")
io.read()
break
elseif space < 1 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif smoke >= 1 then
if store ~= "y" then
smoke = smoke + amount
else
smoke = smoke + smokestore
smokestore = 0
end
print("You picked it up.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
end
until pickup ~= "y"
end
function FNFALitem() --(x)--(x)--(x)--(x)--(!)--(x)--(!)
print("You found a FN FAL.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "FN FAL" then
if space >= 7 - gunspacethree then
print("You have picked it up")
io.read()
myammothree = math.random(10, 50)
damagethree = 8000 + (1000 * dogs)
mygunthree = "FN FAL"
accuracythree = 9
fullaccuracythree = 9
space = space - (7 - gunspacethree)
gunspacethree = 7
takegun()
break
elseif space < 7 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == "FN FAL" then
print("You took the ammo.")
io.read()
myammothree = myammothree + math.random(10, 50)
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
function crossbowitem() --(X)--(X)--(X)--(!)--(X)--(!)--(!)
print("You found a crossbow.")
ammo = math.random(10, 20)
--Ammo
print("It has " .. ammo .. " bolts.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "Crossbow" then
if space >= 5 - gunspacethree then
damagethree = 3000 + (1000 * dogs)
mygunthree = "Crossbow"
accuracythree = 6
fullaccuracythree = 6
space = space - (5 - gunspacethree)
gunspacethree = 5
myammothree = ammo
takegun()
print("You picked it up.")
io.read()
break
elseif space < 5 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
-- end of space
elseif mygunthree == "Crossbow" then
print("You took the ammo.")
io.read()
myammothree = myammothree + ammo
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
end
elseif pickup ~= "y" then --No
print("You left it there")
io.read()
end
--end of already owned
until pickup ~= "y"
end
function hatchetitem() --(X)--(X)--(X)--(!)--(X)--(!)--(!)
print("You found a Hatchet.")
ammo = math.random(99999)
--Ammo
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then -- Pick up Hatchet
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "Hatchet" then
if space >= 5 - gunspacethree then
space = space - (5 - gunspacethree)
gunspacethree = 5
damagethree = 3000 + (1000 * dogs)
mygunthree = "Hatchet"
accuracythree = 10
fullaccuracythree = 10
myammothree = ammo
takegun()
print("You picked it up.")
io.read()
break
elseif space < 5 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
-- end of space
elseif mygunthree == "Hatchet" then
print("Already owned.")
io.read()
break
end
elseif pickup ~= "y" then --No
print("You left it there")
io.read()
end
--end of already owned
until pickup ~= "y"
end
function makarovitem() --(X)--(X)--(X)--(!)--(X)--(!)--(!)
print("You found a Makarov.")
ammo = math.random(10, 25)
--Ammo
print("It has " .. ammo .. " bullets.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then -- Pick up Makarov
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "Makarov" then
if space >= 3 - gunspacethree then
space = space - (3 - gunspacethree)
gunspacethree = 3
damagethree = 1500 + (1000 * dogs)
mygunthree = "Makarov"
accuracythree = 4
fullaccuracythree = 4
myammothree = ammo
takegun()
print("You picked it up.")
io.read()
break
elseif space < 3 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
-- end of space
elseif mygunthree == "Makarov" then
print("You took the ammo.")
io.read()
myammothree = myammothree + ammo
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
end
elseif pickup ~= "y" then --No
print("You left it there")
io.read()
end
--end of already owned
until pickup ~= "y"
end
function revolveritem() --(X)--(X)--(X)--(!)--(X)--(!)--(!)
print("You found a revolver.")
ammo = math.random(1, 15)
--Ammo
print("It has " .. ammo .. " bullets.")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= "Revolver" then
if space >= 3 - gunspacethree then
space = space - (3 - gunspacethree)
gunspacethree = 3
damagethree = 2500 + (1000 * dogs)
mygunthree = "Revolver"
accuracythree = 5
fullaccuracythree = 5
myammothree = ammo
takegun()
print("You picked it up.")
io.read()
break
elseif space < 5 - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
-- end of space
elseif mygunthree == "Revolver" then
print("You took the ammo.")
io.read()
myammothree = myammothree + ammo
if slot == "2" then
myammotwo = myammothree
else
myammo = myammothree
end
break
end
elseif pickup ~= "y" then --No
print("You left it there")
io.read()
end
until pickup ~= "y"
--No
end
function takegun()
if slot == "2" then
gunspacetwo = gunspacethree
myguntwo = mygunthree
myammotwo = myammothree
damagetwo = damagethree
accuracytwo = accuracythree
fullaccuracytwo = fullaccuracythree
elseif slot == "1" then
gunspace = gunspacethree
mygun = mygunthree
myammo = myammothree
damage = damagethree
accuracy = accuracythree
fullaccuracy = fullaccuracythree
end
fullaccuracythree = 0
accuracythree = 0
damagethree = 0
myammothree = 0
mygunthree = "no weapon"
gunspacethree = 0
end
function guarddrop() --(X)--(X)--(X)--(X)--(!)--(X)--(X)
drop = math.random(1, 6)
if drop == 1 then
FNFALitem()
elseif drop == 6 then
gillieitem()
elseif drop == 2 then
smokegrenadeitem()
elseif drop == 3 then
grenadeitem()
elseif drop == 4 then
AK47item()
elseif drop == 5 then
g36citem()
end
end
function help()
repeat
print(
"Section 1:GAME HELP, Section 2:QUESTION HELP, Section 3:STAT HELP, Section 4:INFORMATION HELP, Section 5:WEAPON HELP"
)
print(
"Section 6:ITEM HELP, Section 7:INJURY HELP, Section 8:OUTFIT HELP, Section 9:SPAWN HELP, Section 10:EVENT HELP"
)
print("Section 11:ACTION HELP, Section 12:OPTION HELP, Section 13:GAMEMODE HELP")
print(
"Please type the number of the section you want to view and hit ENTER or RETURN. Or just hit ENTER or RETURN to leave the help section."
)
section = io.read()
if section == "1" then
print("GAME HELP")
print(
"This game randomly chooses from a list of different events to occur, after each event, it will show a line."
)
print('To view your stats type "s" after you see the line.')
print(
"After an event or message, press ENTER or RETURN to continue. Or if you just need to enter a word."
)
print('From now on, type "h" after the line to view help.')
print("Enter now to continue.")
io.read()
elseif section == "2" then
print("QUESTION HELP")
print("After typing an answer hit ENTER or RETURN to enter it.")
print('For a yes or no question, type "y" for yes or anything else for no.')
print("For items, type out the word in singular form and lower case.")
print("For actions, type the first letter of the word in lower case.")
print("See ITEM HELP for items or ACTION HELP for actions.")
io.read()
elseif section == "3" then
print("STAT HELP")
print("Your name is displayed at the top of your stats.")
print("Below your name is your gamemode and your moral level.")
print("Below that is your spawn and the number of days you have survived.")
print("Below that is the time of day and the time itself, if you have a watch.")
print(
"In options, you can choose to have your stats automaticly displayed, to search your stats, and what sections of stats to view."
)
print(
"See GAMEMODE HELP for gamemodes, INFORMATION HELP for accuracy (time of day), ITEM HELP for watches, or OPTION HELP for options."
)
io.read()
print("Your moral goes up by killing bandits and zombies.")
print("It goes down by attacking players.")
print("When it gets high enough, you become a Hero and get a cape.")
print("Players attack less often when you are a Hero.")
print("If your moral gets too low, you become a Bandit.")
print("Players attack more if you are a Bandit.")
print("See OUTFIT HELP for bandanas/capes")
io.read()
elseif section == "4" then
print("INFORMATION HELP")
print("Your blood lowers after being attacked.")
print("To raise it, find a bloodbag and hope a player will use it on you, or eat food.")
print("See ITEM HELP for bloodbags and food or INFORMATION HELP for food.")
io.read()
print("The more pain you have, the more ammo it takes to kill someone.")
print("Lower your pain by using a pain killer.")
print("See ITEM HELP for pain killers.")
io.read()
print("Your temperature drops when you sleep.")
print("If it gets below 33 then you catch a cold which rises your pain.")
print("To lower it, don't sleep as much or use a heat pack.")
print("See ITEM HELP for heat packs.")
io.read()
print("If your food gets to 0, you die.")
print("If you have food and you need to eat, you will automaticly do so.")
print("Otherwise, just use some beans or a steak.")
print("See ITEM HELP for beans and steak.")
io.read()
print("If your water gets to 0, you die.")
print("If you have water and you need to drink, you will again automaticly do so.")
print("Otherwise, just use some water or some pop.")
print("See ITEM HELP for bottles and pop.")
io.read()
print('If you are tired, type "r" after the line to rest.')
print("Too much exhaustion can get you caught by players and zombies if you try to run. ")
print("Fighting and fleeing brings up your exhaustion.")
print("Resting brings your food and water down. But it also brings down exhaustion.")
print("If you have a tent, resting brings down exhaustion faster.")
print("See ITEM HELP for tents.")
io.read()
elseif section == "5" then
print("WEAPON HELP")
print("You can find weapons all over.")
print("You have to have one to win a fight.")
print("You also have to have enough ammo.")
io.read()
print("You can have up to 2 guns at a time, a primary, and a secondary.")
print('When taking a gun, you can choose which slot to put it in, slot "1" or slot "2".')
print("If you don't have enought ammo in your primary gun, then it uses your secondary gun.")
print("If you still don't have enough, you die.")
print('To switch your primary and secondary guns, type "w" (weapon switch) after the line.')
print("If you have the same secondary and primary guns, it will compile your ammo when you do this.")
io.read()
print('The Makarov ("gun") can be found on the ground.')
print("It takes up 3 spaces and has 4 accuracy.")
print("It does 1500 damage and can be found with up to 50 bullets.")
io.read()
print('The Revolver ("gun") can be found on the ground and does 2500 damage.')
print("It takes up 3 spaces and has 5 accuracy.")
print("It can be found with up to 10 bullets.")
io.read()
print('The Crossbow ("gun") can be rarely found on the ground with up to 20 bullets. ')
print("It takes up 5 spaces and has 6 accuracy.")
print("The Crossbow does 3000 damage.")
io.read()
print('The M16 ("gun") can be found in campsites with up to 50 bullets.')
print("It takes up 6 spaces and has 6 accuracy.")
print("It does 3400 damage.")
print("See EVENT HELP for campsites")
io.read()
print('The Hatchet ("gun") can be found on the ground and does not need ammo.')
print("It takes up 5 spaces and has 10 accuracy.")
print("It does 3000 damage but takes alot more blood to use.")
print('Use the "hatchet" in a forest to chop wood.')
print("See ITEM HELP for wood.")
io.read()
print('The G36C ("gun") can be found in police stations and on guards.')
print("It does 3700 damage and takes up 6 spaces.")
print("It can be found with up to 70 bullets and has 7 accuracy.")
print("See EVENT HELP for campsites and buildings")
io.read()
print('The AK47 ("gun") can be found in police stations and on guards.')
print("It does 3500 damage takes up 6 spaces.")
print("It can be found with up to 70 bullets and has 7 accuracy.")
print("See EVENT HELP for campsites and buildings")
io.read()
print('The M4A1 ("gun") can be found in police stations.')
print("It does 4000 damage takes up 6 spaces.")
print("It can be found with up to 70 bullets and has 8 accuracy.")
print("See EVENT HELP for buildings")
io.read()
print('The Doulble Barrel Shotgun ("gun") can be found in police stations and on guards.')
print("It does 5000 damage takes up 7 spaces.")
print("It can be found with up to 50 bullets and has 6 accuracy.")
print("See EVENT HELP for buildings")
io.read()
print("The Lee Enfield does 4000 damage and can be found on players.")
print("It takes up 7 spaces and has 7 accuracy.")
print("It can be found with up to 50 bullets.")
print("See EVENT HELP for players")
io.read()
print('The FN FAL ("gun") can be found on gaurds and does 8000 damage.')
print("It takes up 7 spaces and is found with up to 50 bullets.")
print("It has 9 accuracy.")
print("See EVENT HELP for guards")
io.read()
print('The AS50 ("gun") can be found in Millitary camps and does 200000 damage.')
print("It takes up 8 spaces and is found with up to 50 bullets.")
print("It has 10 accuracy.")
print("See EVENT HELP for Millitary campsites")
io.read()
print("Ammo can be taken from a gun you find on the ground that you already have or from players.")
print("You need ammo to win a fight.")
print("Ammo does not take up space.")
io.read()
print("The more damage your weapon has, the less ammo it needs.")
io.read()
print("The more accuracy your gun has, the less ammo it needs.")
print("During the night, your accuracy goes down by 4.")
print("During the day, it goes back up 4.")
print("Use NV goggles to bring your accuracy up at night.")
print("See ITEM HELP for NV goggles")
io.read()
elseif section == "6" then
print("ITEM HELP")
print("Each item takes up space depending on the size.")
print(
"If you don't have room for an item, you will automaticly be asked to drop something and then use something, just hit enter to cancel."
)
print(
'To drop an item, type "d" after you see the line. Then type the item\'s name with all lower case in singular form.'
)
print(
'To use an item, type "u" after you see the line. Then type the item\'s name with all lower case in singular form.'
)
io.read()
print('The "jerry can" can be filled by players and is needed to use a vehicle.')
print("It takes up 5 spaces.")
print("The vehicle will then take you to a random spawn.")
print("See SPAWN HELP for the spawns.")
io.read()
print('A "bloodbag" can be found in campsites, on zombies, or on the ground.')
print("A player will use a blood bag on you to restore your health.")
print("You need one first though.")
print("They take up 1 space.")
print("See INFORMATION HELP for more on health.")
io.read()
print('Bandaids ("bandaid") can be found on the ground, on zombies, in campsites, or from players.')
print("They take up 1 space.")
print("They are used to stop bleeding.")
print("See INJURY HELP for bleeding.")
io.read()
print('A "bottle" can be found on the ground.')
print("You can fill it at water sources or with players.")
print("It takes up 1 space and restores up to 500 water when filled.")
print("See INFORMATION HELP for water.")
io.read()
print('Some "pop" can be found on the ground, in campsites, on zombies, on players, or from players.')
print("It takes up 1 space and restores up to 200 water.")
print("See INFORMATION HELP for water.")
io.read()
print('Some "steak" can be made by cooking meat with wood and matches.')
print("Use a match to cook.")
print("Restores up to 500 food.")
print("Takes 1 space.")
print("See INFORMATION HELP for food or ITEM HELP for wood, meat, and matches.")
io.read()
print('Some "beans" can be found on the ground, in campsites, on zombies, on players, or from players.')
print("Beans take up 1 space and restores up to 200 food.")
print("See INFORMATION HELP for food.")
io.read()
print('Some "morphine" can be found on players, on the ground, or from players.')
print("Morphine is used to heal broken bones.")
print("It takes up 1 space.")
print("See INJURY HELP for broken bones.")
io.read()
print('You can find a hunting "knife" on the ground.')
print("You use it to skin cows for meat.")
print("It takes up 2 spaces.")
print("See EVENT HELP for cows or ITEM HELP for meat.")
io.read()
print('An "epi-pen" can be found on players.')
print("It takes up 1 space.")
print(
"When you die of blood, you have 1/3 of a chance a player will use an epi-pen on you if you have one."
)
print("You will then be revived and continue playing.")
print("See INJURY HELP for death.")
io.read()
print('Use a "pain killer" to reduce pain.')
print("They can be found on the ground or on players.")
print("They take up 1 space.")
print("See INFORMATION HELP for pain.")
io.read()
print('A "heat pack" can be found on the ground, or on a player.')
print("The heat pack takes up 1 space and is used to raise temperature.")
print("See INFORMATION HELP for temperature.")
io.read()
print('A "match" can be found on the ground.')
print("The match takes up 1 space and is used to cook meat with wood.")
print("You can also warm yourself with fires.")
print("See ITEM HELP for wood and meat and INFORMATION HELP for temperature.")
io.read()
print('Some "wood" can be chopped down by using a hatchet in a forest.')
print("The wood is used to cook meat by using a match.")
print("You can also warm yourself with fires.")
print("Wood takes up 2 spaces.")
print("See ITEM HELP for meat and matches or SPAWN HELP for forest")
io.read()
print('A "bear trap" can be found in campsites.')
print("It is used to catch a player, zombie, or cow after a few turns.")
print("When used, it will say you have a set trap in the weapons section.")
print("You can only set one trap at a time.")
print("It takes up 2 space.")
print("See EVENT HELP for cows, players, and zombies")
io.read()
print('A "road flare" is used to attract eigther a player or a zombie.')
print("It takes up 1 space and can be found on the ground, from players, or on zombies. ")
print("See EVENT HELP for players and zombies.")
io.read()
print('Night vision "goggles", or NV goggles can be found in Millitary campsites.')
print("They rais your accuracy during the night and lower it during the day (if they are on)")
print("Use them to turn them on or off.")
print("They take up 2 spaces.")
print("See EVENT HELP for Millitary camps")
io.read()
print('A "grenade" can be found on guards or in Millitary campsites.')
print("It can be used to kill a person and take his stuff.")
print("It takes up 1 space.")
print("See EVENT HELP for Millitary camps and guards")
io.read()
print('A "smoke grenade" can be found on guards or in Millitary campsites.')
print("It is automaticly used when trying to escape a person when your too tired.")
print("When used, it lets you escape no matter what.")
print("It takes up 1 space.")
print("See EVENT HELP for Millitary camps and guards")
io.read()
print('A "tent" can be found in the city on the ground.')
print("It takes up 4 spaces and reduces more exhaustion when you sleep then without one.")
print("You can also use the tent to store items in.")
print(
"It takes exhaustion every time you travel to your teent but you can put anything in and take anything out of it."
)
print("Use the tent to place it, then use it again to travel to it.")
print("See INFORMATION HELP for exhaustion.")
io.read()
print('A "book" can be found in buildings in a variety of colors.')
print("It takes up 2 spaces.")
print('When used, type "w" to write in it, "r" to read it, or "e" to erase it.')
print("The book will have a random sentence automaticly written in it.")
print("If you write in a book and then drop it, players can find it.")
print('If a player finds it and it says "Help: Food" the player will give you food.')
print('Or, if it says "Help: Ammo" then the player will give you ammo.')
print('"Help: Water" gives water or pop and "Help: Bandaid" gives you bandaids.')
print("See ITEM HELP for items")
io.read()
print("Watches can be found in buildings or on the ground.")
print("They don't take up space and go in the outfit section.")
print("The watch tells you the time and cannot be dropped.")
print("See OUTFIT HELP for outfits or STAT HELP for time")
io.read()
print('A "radio" can be found in buildings.')
print("You can use the radio to talk to a chat bot.")
print("Radios are really just for fun as they don't help you at all.")
print("Radios take up 1 space.")
print("See EVENT HELP for buildings")
io.read()
print('A "antibiotic" can be obtained from players or in a campsite.')
print("They remove infection and take up 1 space.")
print("See INJURY HELP for infection.")
io.read()
print('Some "meat" can be found by skinning cows or dogs.')
print("Meat takes up 1 space and is used to cook into steak.")
print("Eating it will heal very little and fill just a bit.")
print("If eaten, you have a high chance of it infecting you.")
print("See ITEM HELP for wood and meat")
io.read()
print("The Medbox can be found in Hospitals in the City.")
print("They contain every type of Medical supply with random amounts for each.")
print("See EVENT HELP for Hospitals, SPAWN HELP for the City, and ITEM HELP for medical supplies")
io.read()
print("An Alice pack can be found on players or in campsites.")
print("They can hold up to 10 items.")
print("They can not be dropped and are found in the outfit section.")
print("See OUTFIT HELP for outfits.")
io.read()
print("A Vest Pouch can be found on zombies.")
print("They can hold up to 6 items.")
print("They can not be dropped and are found in the outfit section.")
print("See OUTFIT HELP for outfits")
io.read()
print("A Coyote pack can be found in Millitary camps.")
print("They can hold up to 20 items.")
print("They can not be dropped and are found in the outfit section.")
print("See OUTFIT HELP for outfits.")
io.read()
elseif section == "7" then
print("INJURY HELP")
print("When bleeding, you lose bloos after each event.")
print("You stop losing blood at 2000 blood left.")
print("To stop bleeding, use a bandaid.")
print("See ITEM HELP for bandaids.")
io.read()
print("If you have a broken bone, your exhaustion goes up each turn.")
print("If it gets above 1000, you could black out for a couple days.")
print("Use morphine to heal broken bones.")
print("See ITEM HELP for morphine.")
io.read()
print("Colds raise your pain and are cured with heat packs.")
print("You can also cure it by raising your temperature by jogging or waiting around.")
print("See ITEM HELP for heat packs or ACTION HELP for jogging.")
io.read()
print("When you die, a player might revive you if you have an epi-pen.")
print(
"If you still don't have enough blood but have a blood bag, he will then give you a blood tranfusion."
)
print("See ITEM HELP for epi-pens and bloodbags or INFORMATION HELP for blood.")
io.read()
print("You can get infections from standing near players or bleeding on a zombie.")
print("Cure the infection with antibiotics.")
print("You lose blood until you you only have 6000 left with an infection.")
print("See ITEM HELP for antibiotics.")
io.read()
elseif section == "8" then
print("OUTFIT HELP")
print("Your outfit is randomly made at the start of the game.")
print("It has no effect on the gameplay itself.")
print("Clothes take no space and can be found on bodies.")
print("There are several different colors of clothing.")
print("The back packs, gillie's, watches, and bandanas/capes can also be found in this section.")
print("See ITEM HELP for back packs and watches and STAT HELP for bandanas/capes.")
io.read()
print("Gillie suits can be found on players and in military camps.")
print("They don't take up space and make it easier to escape people.")
io.read()
elseif section == "9" then
print("SPAWN HELP")
print("You start in one of three spawns.")
io.read()
print("Spawn 1 is the city, you find tents and buildings here.")
print("See INFORMATION HELP or ITEM HELP for tents and EVENT HELP for buildings.")
io.read()
print("Spawn 2 is the shore, you find water sources here.")
print("See ITEM HELP or EVENT HELP for water.")
io.read()
print("Spawn 3 is the forest, you find cows, trees, and Farms here.")
print("See ITEM HELP for trees or EVENT HELP for cows and farms")
io.read()
elseif section == "10" then
print("EVENT HELP")
print("Zombies drop 4 items and have up to 3000 health.")
print("They can cut you or brake your leg if you attack.")
print("If you are too exhausted to escape they will kill you.")
print("They drop bandaids, beans, pop, and road flares.")
print("See ITEM HELP for items, INJURY HELP for injuries, or INFORMATION HELP for exhaustion.")
io.read()
print("Players drop everything and have up to 12000 health.")
print("When you approach a player, you have a 1/2 chance they will be nice.")
print("If they are nice, they will give you something.")
print("Otherwise they will attack you.")
print("They can cut you or brake your leg if they attack.")
print("If you are too exhausted to escape they can either kill you or release you.")
print("Players give ammo, beans, water, fuel, bandaids, morphine, pop, antibiotics, and road flares.")
print("See ITEM HELP for items, INJURY HELP for injuries, or INFORMATION HELP for exhaustion.")
io.read()
print("Gangs can rarely be found with 2-5 players in them.")
print("Gangs always attack.")
io.read()
print("On the ground, you can find 13 items.")
print(
"You can find bloodbags, knives, tents, bottles, jerry cans, bandaids, painkillers, morphine, heat packs, matches, beans, pop, and road flares."
)
print("See ITEM HELP for items.")
io.read()
print("Campsites can have every item.")
print("But be careful, sometimes you could step on a bear trap and brake a leg.")
print("Players can also find you here.")
print("Campsites can also have fires to cook or warm.")
print("See ITEM HELP for items and WEAPON HELP for M16.")
io.read()
print("Campsites have a 30th of a chance to be a Millitary camp.")
print("Millitary camps drop rare items.")
print(
"You can find an AS50 in the tent, NV goggles, smoke grenades, grenades, gillie suits, and the Coyote pack."
)
print("The Millitary campsite will sometimes have a guard, which is really hard to kill.")
print(
"The guard can drop 6 items which are smoke grenades, grenades, G36C, gillie suits, AK47, and an FN FAL."
)
print("See ITEM HELP for items, OUTFIT HELP for gillie suit, and WEAPON HELP for weapons")
io.read()
print("You can find cows in the forest.")
print('Using a "knife", you can skin them for up to 8 meat.')
print("You can then cook meat with wood and matches.")
print("See ITEM HELP for wood and matches.")
io.read()
print("You can find water sources on the shore.")
print("You can drink it with your hands or fill your bottle.")
print("Drinking gives up to 500 water.")
print("See INFORMATION HELP for water and ITEM HELP for bottles.")
io.read()
print("You can find dogs on the ground.")
print("You can tame with steak, otherwise they will attack.")
print("Each dog can be named and does 1000 extra damage.")
print("Dogs will also catch things from time to time.")
print(
"When your dogs run out of health, only one dies. When they run out of food or water, they all die."
)
print("When a dog dies, his name will stay on the list until they all die.")
print('Feed them by using "dog" and selecting to either feed ("f") or water ("w").')
print("You can also skin them for meat.")
print("See ACTION HELP for feeding/watering/skinning")
io.read()
print("Buildings can be found in the City and the Farm can be found in the Forest.")
print("Buildings can have many different items depending on what kind of building it is.")
print("Police Stations have guns and ammo and are found in the City.")
print("Gas Stations have fuel and Jerry cans and are also found in the City.")
print("Hospitals can also be found in the City and have medical supplies.")
print("Hospitals can also have the Medbox which contains every medical supplie.")
print("Buildings can be found in the City and have every day stuff like food and tools.")
print("Farms are found in the Forest with stuff like tools.")
print("See WEAPON HELP for weapons, ITEM HELP for items and Medbox, and SPAWN HELP for spawns")
io.read()
elseif section == "11" then
print("ACTION HELP")
print("Type actions after the line to use.")
io.read()
print(
'To view stats type "s", to use type "u", to drop type "d", to jog type "j", type "o" for options, and to rest type "r".'
)
print(
"Jogging raises your temperature and resting lowers your exhaustion and switches between night and day."
)
print("See INFORMATION HELP for exhaustion and temperature.")
io.read()
print('When using a book, type "w" to write, "e" to erase, and "r" to read.')
print("See ITEM HELP for books.")
io.read()
print('When feeding dogs, use "f" for feed and "w" for water.')
print('To skin a dog, use the dog, then type "s".')
print("The more you feed him, the more meat you get from skinning him.")
print("See EVENT HELP for dogs")
io.read()
print('To quit, type "q" after the line.')
io.read()
elseif section == "12" then
print("OPTION HELP")
print('Type "o" after the line to change options.')
print("Autostats will automatically dispay your stats after a said amount of turns.")
print(
"Stat Seach lets you look at sections of your stats individually. (Useful if stats are running out of your screen.)"
)
print("Stat Sections lets you choose which sections of stats to view when your stats are shown.")
print("You can change your name using options.")
io.read()
elseif section == "13" then
print("GAMEMODE HELP")
print(
"The recruit gamemode gives you all the medical supplies, a road flare, a bottle of water, a revolver, a Vest Pouch, and 5 steak. You have 22,000 health."
)
print("The easy gamemode gives you 5 bandaids, 7 pop, and 5 beans. You have 20,000 health.")
print("The medium gamemode gives you 2 beans and a 3 pop. You have 15,000 health.")
print("The hard gamemode gives you nothing with 12,000 health.")
print("See ITEM HELP for items or INFORMATION HELP for health.")
io.read()
else
section = "0"
end
until section == "0"
end
function zombiedrop() --(X)--(X)--(X)--(X)--(!)--(X)--(X)
if clothedrop == "y" then
clothes = math.random(1, 10)
if clothes == 1 then
print("It had a bloody shirt.")
print("Take?")
pickup = io.read()
if pickup == "y" then
print("You now have a bloody shirt.")
io.read()
shirt = "bloody"
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
else
print("It had a ripped shirt.")
print("Take?")
pickup = io.read()
if pickup == "y" then
print("You now have a ripped shirt.")
io.read()
shirt = "ripped"
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
end
print("It had ripped pants.")
print("Take?")
pickup = io.read()
if pickup == "y" then
print("You now have ripped pants.")
io.read()
pants = "ripped"
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
end
drop = math.random(1, 7)
if drop == 3 then
bandaiditem()
elseif drop == 4 then
beansitem()
elseif drop == 5 then
popitem()
elseif drop == 6 then
roadflareitem()
elseif drop == 7 then
vestpouchitem()
end
end
function enemydrop() --(X)--(X)--(X)--(X)--(!)--(X)--(X)
if clothedrop == "y" then
color = math.random(1, 28)
coloring()
print("They had a " .. ccolor .. " shirt.")
print("Take?")
pickup = io.read()
if pickup == "y" then
print("You now have a " .. ccolor .. " shirt.")
io.read()
shirt = ccolor
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
color = math.random(1, 7)
coloring()
print("They had " .. ccolor .. " pants.")
print("Take?")
pickup = io.read()
if pickup == "y" then
print("You now have " .. ccolor .. " pants.")
io.read()
pants = ccolor
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
end
drop = math.random(1, 37)
if drop == 1 then
makarovitem()
elseif drop == 2 then
revolveritem()
elseif drop == 3 then
amount = math.random(1, 7)
if amount == 1 then
M16item()
else
beansitem()
end
elseif drop == 37 then
gillieitem()
elseif drop == 4 then
amount = math.random(1, 2)
if amount == 1 then
crossbowitem()
else
popitem()
end
elseif drop == 5 then
amount = math.random(1, 2)
if amount == 1 then
hatchetitem()
else
beansitem()
end
elseif drop == 6 then
amount = math.random(1, 10)
if amount == 1 then
leeenfielditem()
else
popitem()
end
elseif drop == 7 then
amount = math.random(1, 40)
if amount == 1 then
FNFALitem()
else
beansitem()
end
elseif drop == 8 then
amount = math.random(1, 100)
if amount == 1 then
AS50item()
else
popitem()
end
elseif drop == 9 then
amount = math.random(1, 5)
if amount == 1 then
gogglesitem()
else
beansitem()
end
elseif drop == 10 then
amount = math.random(1, 30)
if amount == 1 then
coyotepackitem()
else
popitem()
end
elseif drop == 11 then
amount = math.random(1, 5)
if amount == 1 then
filledjerrycanitem()
else
jerrycanitem()
end
elseif drop == 12 then
beartrapitem()
elseif drop == 13 then
matchitem()
elseif drop == 14 then
amount = math.random(1, 3)
if amount == 1 then
filledbottleitem()
else
bottleitem()
end
elseif drop == 15 then
tentitem()
elseif drop == 16 then
knifeitem()
elseif drop == 17 then
amount = math.random(1, 3)
if amount == 1 then
antibioticsitem()
else
beansitem()
end
elseif drop == 18 then
morphineitem()
elseif drop == 19 then
if droppedbook == "y" then
amount = math.random(1, 10)
if amount == 1 then
findbook = "y"
booksitem()
findbook = "n"
droppedbook = "n"
else
booksitem()
end
else
booksitem()
end
elseif drop == 20 then
heatpackitem()
elseif drop == 21 then
painkilleritem()
elseif drop == 22 then
amount = math.random(1, 15)
if amount == 1 then
alicepackitem()
else
popitem()
end
elseif drop == 23 then
vestpouchitem()
elseif drop == 24 then
penitem()
elseif drop == 25 then
roadflareitem()
elseif drop == 26 then
bloodbagitem()
elseif drop == 27 then
bandaiditem()
elseif drop == 28 then
amount = math.random(1, 40)
if amount == 1 then
grenadeitem()
else
beansitem()
end
elseif drop == 29 then
amount = math.random(1, 35)
if amount == 1 then
smokegrenadeitem()
else
popitem()
end
elseif drop == 30 then
ammoitem()
elseif drop == 31 then
radioitem()
elseif drop == 32 then
amount = math.random(1, 15)
if amount == 1 then
g36citem()
else
beansitem()
end
elseif drop == 33 then
amount = math.random(1, 7)
if amount == 1 then
AK47item()
else
popitem()
end
elseif drop == 34 then
amount = math.random(1, 7)
if amount == 1 then
M4A1item()
else
beansitem()
end
elseif drop == 35 then
amount = math.random(1, 4)
if amount == 1 then
DBshotgunitem()
else
popitem()
end
elseif drop == 36 then
watchitem()
end
end
function word()
words = math.random(1, 19)
if words == 1 then
writing = "You shouldn't have killed me..."
elseif words == 2 then
amount = math.random(20, 100)
amounts = math.random(2, 5)
writing = "Day " .. amount .. ", I began work on a house. Killed " .. amounts .. " cows."
elseif words == 3 then
writing = "Find meat, set up camp, fill bottle"
elseif words == 4 then
writing =
"If my family finds this, I'm already dead. I attached my will to the following page...I wish you the best."
elseif words == 5 then
writing = "I'll kill dat boy!"
elseif words == 6 then
writing = "I want halp, food. English my not firsts langwage"
elseif words == 7 then
writing = "TIC TAC TOE #"
elseif words == 8 then
writing = "SURVIVE"
elseif words == 9 then
writing = "I AM SUPERBEAN!"
elseif words == 10 then
writing = "Another failed attempt at a cure."
elseif words == 11 then
writing = "You found me! 1-18-89"
elseif words == 12 then
writing = "The end is near"
elseif words == 13 then
writing = "What you are about to read is an account following the multiple deaths of 205 AD."
elseif words == 14 then
writing = "The Journal of Jonson Brown"
elseif words == 15 then
writing = "The Adventures of Sherlock Holmes by Sir Aurthor Connan Doyle"
elseif words == 16 then
writing = " "
elseif words == 17 then
writing = "LOL "
elseif words == 18 then
writing = "Beans to you Sir. "
elseif words == 19 then
writing = "Died by a Zombie while witnessing paint dry. "
end
end
function giving()
drop = math.random(1, 41)
if request == "y" then
if droppedwriting == "Help: Food" then
drop = 39
elseif droppedwriting == "Help: Water" then
if bottle == "y" then
filledbottleitem()
elseif bottle == "n" then
drop = 40
end
elseif droppedwriting == "Help: Ammo" then
drop = 30
elseif droppedwriting == "Help: Bandaid" then
drop = 27
end
end
giveamount = math.random(0, 4)
repeat
if giveamount > 0 then
if drop == 1 then
amount = math.random(1, 4)
if amount == 1 then
makarovitem()
else
popitem()
end
elseif drop == 38 then
steakitem()
elseif drop == 39 then
beansitem()
elseif drop == 40 then
popitem()
elseif drop == 41 then
amount = math.random(1, 45)
if amount == 1 then
gillieitem()
else
beansitem()
end
elseif drop == 37 then
print("The player wants to give you fuel.")
print("Accept?")
pickup = io.read()
if pickup == "y" then
if can == "y" then
if cfilled == "n" then
print("They filled your jerry can.")
io.read()
cfilled = "y"
elseif cfilled == "y" then
print("Already filled.")
io.read()
end
elseif can ~= "y" then
print("You have no can.")
io.read()
end
elseif pickup ~= "y" then
print("You declined.")
io.read()
end
elseif drop == 2 then
amount = math.random(1, 4)
if amount == 1 then
revolveritem()
else
beansitem()
end
elseif drop == 3 then
amount = math.random(1, 10)
if amount == 1 then
M16item()
else
beansitem()
end
elseif drop == 4 then
amount = math.random(1, 5)
if amount == 1 then
crossbowitem()
else
popitem()
end
elseif drop == 5 then
amount = math.random(1, 4)
if amount == 1 then
hatchetitem()
else
beansitem()
end
elseif drop == 6 then
amount = math.random(1, 20)
if amount == 1 then
leeenfielditem()
else
popitem()
end
elseif drop == 7 then
amount = math.random(1, 70)
if amount == 1 then
FNFALitem()
else
beansitem()
end
elseif drop == 8 then
amount = math.random(1, 200)
if amount == 1 then
AS50item()
else
popitem()
end
elseif drop == 9 then
amount = math.random(1, 10)
if amount == 1 then
gogglesitem()
else
beansitem()
end
elseif drop == 10 then
amount = math.random(1, 50)
if amount == 1 then
coyotepackitem()
else
popitem()
end
elseif drop == 11 then
amount = math.random(1, 10)
if amount == 1 then
filledjerrycanitem()
else
jerrycanitem()
end
elseif drop == 12 then
beartrapitem()
elseif drop == 13 then
matchitem()
elseif drop == 14 then
amount = math.random(1, 2)
if amount == 1 then
filledbottleitem()
else
bottleitem()
end
elseif drop == 15 then
amount = math.random(1, 4)
if amount == 1 then
tentitem()
else
popitem()
end
elseif drop == 16 then
knifeitem()
elseif drop == 17 then
amount = math.random(1, 5)
if amount == 1 then
antibioticsitem()
else
beansitem()
end
elseif drop == 18 then
morphineitem()
elseif drop == 19 then
booksitem()
elseif drop == 20 then
heatpackitem()
elseif drop == 21 then
painkilleritem()
elseif drop == 22 then
amount = math.random(1, 30)
if amount == 1 then
alicepackitem()
else
popitem()
end
elseif drop == 23 then
amount = math.random(1, 10)
if amount == 1 then
vestpouchitem()
else
popitem()
end
elseif drop == 24 then
penitem()
elseif drop == 25 then
roadflareitem()
elseif drop == 26 then
bloodbagitem()
elseif drop == 27 then
bandaiditem()
elseif drop == 28 then
amount = math.random(1, 70)
if amount == 1 then
grenadeitem()
else
beansitem()
end
elseif drop == 29 then
amount = math.random(1, 50)
if amount == 1 then
smokegrenadeitem()
else
popitem()
end
elseif drop == 30 then
ammoitem()
elseif drop == 31 then
radioitem()
elseif drop == 32 then
amount = math.random(1, 30)
if amount == 1 then
g36citem()
else
beansitem()
end
elseif drop == 33 then
amount = math.random(1, 30)
if amount == 1 then
AK47item()
else
popitem()
end
elseif drop == 34 then
amount = math.random(1, 30)
if amount == 1 then
M4A1item()
else
beansitem()
end
elseif drop == 35 then
amount = math.random(1, 15)
if amount == 1 then
DBshotgunitem()
else
popitem()
end
elseif drop == 36 then
watchitem()
end
drop = math.random(1, 40)
giveamount = giveamount - 1
elseif giveamount < 1 then
print("You leave the player.")
io.read()
end
until giveamount < 1
end
-- end of give
cheatkey = "@cheat"
password = "cheatcodecentral"
function used()
stats()
print("What do you want to use?")
drop = io.read()
if drop == "bandaid" then
usebandaid()
elseif drop == "antibiotic" then
useantibiotic()
elseif drop == "goggles" then
usegoggles()
elseif drop == "tent" then
usetent()
elseif drop == "bear trap" then
usebeartrap()
elseif drop == "radio" then
useradio()
elseif drop == "dog" then
usedog()
elseif drop == "water" then
usewater()
elseif drop == "grenade" then
usegrenade()
elseif drop == "steak" then
usesteak()
elseif drop == "meat" then
usemeat()
elseif drop == "pain killer" then
usepainkiller()
elseif drop == "morphine" then
usemorphine()
elseif drop == "road flare" then
useroadflare()
elseif drop == "super bean" then
usesuperbean()
elseif drop == "heat pack" then
useheatpack()
elseif drop == "hatchet" then
usehatchet()
elseif drop == "match" then
usematch()
elseif drop == "beans" then ----------------------Change into functions then make using items on the spot-- radio: already started
usebeans()
elseif drop == "pop" then
usepop()
elseif drop == "book" then
usebook()
end
end
function coloring()
if color == 1 then
ccolor = "blue"
elseif color == 2 then
ccolor = "black"
elseif color == 3 then
ccolor = "grey"
elseif color == 4 then
ccolor = "brown"
elseif color == 5 then
ccolor = "camo"
elseif color == 6 then
ccolor = "ripped"
elseif color == 7 then
ccolor = "dress"
elseif color == 23 then
ccolor = "yellow"
elseif color == 8 then
ccolor = "green"
elseif color == 9 then
ccolor = "orange"
elseif color == 10 then
ccolor = "purple"
elseif color == 11 then
ccolor = "red"
elseif color == 12 then
ccolor = "pink"
elseif color == 13 then
ccolor = "polka-dot"
elseif color == 14 then
ccolor = "striped"
elseif color == 15 then
ccolor = "plaid"
elseif color == 16 then
ccolor = "magenta"
elseif color == 17 then
ccolor = "rainbow"
elseif color == 18 then
ccolor = "turquoise"
elseif color == 19 then
ccolor = "white"
elseif color == 20 then
ccolor = "T"
elseif color == 21 then
ccolor = "long-sleeved"
elseif color == 24 then
ccolor = "Science"
elseif color == 22 then
ccolor = "ripped"
elseif color == 28 then
ccolor = "turtle neck"
elseif color == 25 then
ccolor = "Got BeanZ?"
elseif color == 26 then
ccolor = "Zombie Survival"
elseif color == 27 then
ccolor = "Mountain Dew"
end
end
function stats() -------------------------------------Stats
if statsearch == "y" then
repeat
print("Choose a section to view.")
print(
'Section 1:INFORMATION, Section 2:STATS, Section 3:WEAPON, Section 4:DOGS, Section 5:ITEMS, Section 6:INJURIES, Section 7:OUTFIT, or "all" for all.'
)
want = io.read()
if want == "1" then
stats1()
elseif want == "2" then
stats2()
elseif want == "3" then
stats3()
elseif want == "4" then
stats4()
elseif want == "5" then
stats5()
elseif want == "6" then
stats6()
elseif want == "7" then
stats7()
elseif want == "all" then
stats1()
stats2()
stats3()
stats4()
stats5()
stats6()
stats7()
else
want = "0"
end
until want == "0"
elseif statsearch ~= "y" then
if statA == "y" then
stats1()
end
if statB == "y" then
stats2()
end
if statC == "y" then
stats3()
end
if statD == "y" then
stats4()
end
if statE == "y" then
stats5()
end
if statF == "y" then
stats6()
end
if statG == "y" then
stats7()
end
end
end
function dropped() -----------------------------------------Drop
stats()
if store == "n" then
print("What do you want to drop?")
else
print("What do you want to store?")
end
dropping = io.read()
if dropping == "bloodbag" then
if bloodbags >= 1 then
if store == "y" then
print("Stored.")
io.read()
bloodbagstore = bloodbagstore + bloodbags
else
print("Dropped.")
io.read()
end
bloodbags = 0
space = space + 1
elseif bloodbags < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "super bean" then
if superbean == "y" then
superbean = "n"
if store == "y" then
print("Stored.")
io.read()
superbeanstore = "y"
else
print("Dropped.")
io.read()
end
space = space + .5
elseif superbean == "n" then
print("...")
io.read()
end
elseif dropping == "meat" then
if meat >= 1 then
if store == "y" then
print("Stored.")
io.read()
meatstore = meatstore + meat
else
print("Dropped.")
io.read()
end
meat = 0
space = space + 1
elseif meat < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "steak" then
if steak >= 1 then
if store == "y" then
print("Stored.")
io.read()
steakstore = steakstore + steak
else
print("Dropped.")
io.read()
end
steak = 0
space = space + 1
elseif steak < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "book" then
if book == "y" then
if store == "y" then
print("Stored.")
io.read()
bookstore = "y"
storedwriting = text
storedcolor = ccolor
book = "n"
space = space + 2
else
print("Dropped.")
io.read()
book = "n"
space = space + 2
droppedwriting = text
droppedbook = "y"
droppedcolor = cover
end
elseif book == "n" then
print("Unowned.")
io.read()
end
elseif dropping == "road flare" then
if roadflare >= 1 then
if store == "y" then
print("Stored.")
io.read()
roadflarestore = roadflarestore + roadflare
else
print("Dropped.")
io.read()
end
roadflare = 0
space = space + 1
elseif roadflare < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "smoke grenade" then
if smoke >= 1 then
if store == "y" then
print("Stored.")
io.read()
smokestore = smokestore + smoke
else
print("Dropped.")
io.read()
end
smoke = 0
space = space + 1
elseif smoke < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "grenade" then
if grenade >= 1 then
if store == "y" then
print("Stored.")
io.read()
grenadestore = grenadestore + grenade
else
print("Dropped.")
io.read()
end
grenade = 0
space = space + 1
elseif grenade < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "antibiotic" then
if antibiotics >= 1 then
if store == "y" then
print("Stored.")
io.read()
antibioticstore = antibioticstore + antibiotics
else
print("Dropped.")
io.read()
end
antibiotics = 0
space = space + 1
elseif antibiotics < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "tent" then
if tent == "y" then
if store == "y" then
print("Stored.")
io.read()
tentstore = "y"
else
print("Dropped.")
io.read()
end
tent = "n"
space = space + 7
elseif tent ~= "y" then
print("Unowned.")
io.read()
end
elseif dropping == "bear trap" then
if beartrap == "y" then
if store == "y" then
print("Stored.")
io.read()
beartrapstore = "y"
else
print("Dropped.")
io.read()
end
beartrap = "n"
space = space + 2
elseif beartrap ~= "y" then
print("Unowned.")
io.read()
end
elseif dropping == "goggles" then
if goggles == "y" then
if store == "y" then
print("Stored.")
io.read()
gogglestore = "y"
else
print("Dropped.")
io.read()
end
goggles = "n"
if vision ~= "y" then
space = space + 2
end
vision = "n"
elseif goggles ~= "y" then
print("Unowned.")
io.read()
end
elseif dropping == "bandaid" then
if bandaids >= 1 then
if store == "y" then
print("Stored.")
io.read()
bandaidstore = bandaidstore + bandaids
else
print("Dropped.")
io.read()
end
bandaids = 0
space = space + 1
elseif bandaids < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "jerry can" then
if can == "y" then
if store == "y" then
print("Stored.")
io.read()
canstore = "y"
if cfilled == "y" then
cfilledstore = "y"
else
cfilledstore = "n"
end
else
print("Dropped.")
io.read()
end
can = "n"
cfilled = "n"
space = space + 5
elseif can ~= "y" then
print("Unowned.")
io.read()
end
elseif dropping == "bottle" then
if bottle == "y" then
if store == "y" then
print("Stored.")
io.read()
bottlestore = "y"
if filled == "y" then
filledstore = "y"
else
filledstore = "n"
end
else
print("Dropped.")
io.read()
end
bottle = "n"
filled = "n"
space = space + 1
elseif bottle ~= "y" then
print("Unowned.")
io.read()
end
elseif dropping == "gillie suit" then
if gillie == "y" then
if store == "y" then
print("stored.")
io.read()
gillie = "n"
gilliestore = "y"
else
print("Dropped.")
io.read()
gillie = "n"
end
else
print("Unowned.")
io.read()
end
elseif dropping == "watch" then
if watch == "y" then
if store == "y" then
print("stored.")
io.read()
watch = "n"
watchstore = "y"
storedwcolor = watchcolor
else
print("Dropped.")
io.read()
watch = "n"
end
else
print("Unowned.")
io.read()
end
elseif dropping == "epi-pen" then
if morphine >= 1 then
if store == "y" then
print("Stored.")
io.read()
epipenstore = epipenstore + morphine
else
print("Dropped.")
io.read()
end
morphine = 0
space = space + 1
elseif morphine < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "knife" then
if knife == "y" then
if store == "y" then
print("Stored.")
io.read()
knifestore = "y"
else
print("Dropped.")
io.read()
end
knife = "n"
space = space + 2
elseif knife ~= "y" then
print("Unowned.")
io.read()
end
elseif dropping == "gun" then
dropgun()
elseif dropping == "pain killer" then
if epipen >= 1 then
if store == "y" then
print("Stored.")
io.read()
painkillerstore = painkillerstore + epipen
else
print("Dropped.")
io.read()
end
epipen = 0
space = space + 1
elseif epipen < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "morphine" then
if painkillers >= 1 then
if store == "y" then
print("Stored.")
io.read()
morphinestore = morphinestore + painkillers
else
print("Dropped.")
io.read()
end
painkillers = 0
space = space + 1
elseif painkillers < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "heat pack" then
if heatpacks >= 1 then
if store == "y" then
print("Stored.")
io.read()
heatpackstore = heatpackstore + heatpacks
else
print("Dropped.")
io.read()
end
heatpacks = 0
space = space + 1
elseif heatpacks < 1 then
print("You have no heat packs.")
io.read()
end
elseif dropping == "match" then
if matches >= 1 then
if store == "y" then
print("Stored.")
io.read()
matchstore = matchstore + matches
else
print("Dropped.")
io.read()
end
matches = 0
space = space + 1
elseif matches < 1 then
print("You have no matches.")
io.read()
end
elseif dropping == "wood" then
if wood == "y" then
if store == "y" then
print("Stored.")
io.read()
woodstore = "y"
else
print("Dropped.")
io.read()
end
wood = "n"
space = space + 2
elseif wood == "n" then
print("You have no wood.")
io.read()
end
elseif dropping == "radio" then
if radio == "y" then
if store == "y" then
print("Stored.")
io.read()
radiostore = "y"
else
print("Dropped.")
io.read()
end
radio = "n"
space = space + 1
elseif radio == "n" then
print("You don't have a radio.")
io.read()
end
elseif dropping == "beans" then
if beans >= 1 then
if store == "y" then
print("Stored.")
io.read()
beanstore = beanstore + beans
else
print("Dropped.")
io.read()
end
beans = 0
space = space + 1
elseif beans < 1 then
print("Unowned.")
io.read()
end
elseif dropping == "pop" then
if pop >= 1 then
if store == "y" then
print("Stored.")
io.read()
popstore = popstore + pop
else
print("Dropped.")
io.read()
end
pop = 0
space = space + 1
elseif pop < 1 then
print("Unowned.")
io.read()
end
end
end
function niceplayer()
if health < fullhealth - 3000 then
if bloodbags >= 1 then --bloodbags
print("The player has given you a blood transfusion using your bag.")
io.read()
bloodbags = bloodbags - 1
if bloodbags < 1 then
space = space + 1
end
health = fullhealth
elseif bloodbags < 1 then
amount = math.random(1, 5)
if amount == 1 then
print("The player has given you a blood transfusion.")
io.read()
health = fullhealth
end
end
end
if broken == "y" then
if painkillers >= 1 then
print("The player healed your broken bone with your morphine.")
broken = "n"
painkillers = painkillers - 1
if painkillers < 1 then
space = space + 1
end
io.read()
else
amount = math.random(1, 6)
if amount == 1 then
print("The player healed your broken bone.")
broken = "n"
io.read()
end
end
end
if bleeding == "y" then
if bandaids >= 1 then
print("The player used one of your bandaids on you.")
io.read()
bleeding = "n"
bandaids = bandaids - 1
if bandaids < 1 then
space = space + 1
end
else
amount = math.random(1, 3)
if amount == 1 then
print("The player used a bandaid on you.")
bleeding = "n"
io.read()
end
end
end
if infection == "y" then
if antibiotics >= 1 then
print("The player used one of your antibiotics on you.")
io.read()
infection = "n"
antibiotics = antibiotics - 1
if antibiotics < 1 then
space = space + 1
end
else
amount = math.random(1, 5)
if amount == 1 then
print("The player used an antibiotic on you.")
infection = "n"
io.read()
end
end
end
if cold == "y" then
if heatpacks >= 1 then
print("The player used one of your heatpacks on you.")
io.read()
heatpacks = heatpacks - 1
if heatpacks < 1 then
space = space + 1
end
temperature = temperature + math.random(5, 7)
if temperature >= 33 then
if cold == "y" then
print("You lost your cold.")
io.read()
cold = "n"
end
end
else
amount = math.random(1, 5)
if amount == 1 then
print("The player used a heat pack on you.")
temperature = temperature + math.random(5, 7)
if temperature >= 33 then
if cold == "y" then
print("You lost your cold.")
io.read()
cold = "n"
end
end
io.read()
end
end
end
if gender == 1 then
print("The player lets you look through his stuff.")
else
print("The player lets you look through her stuff.")
end
io.read()
giving()
end
-- end of health
function playerevent()
gender = math.random(1, 2)
if gender == 1 then
print("You found a survivor, approach him?")
else
print("You found a survivor, approach her?")
end
zhealth = math.random(5000, 12000)
zhealth = zhealth + pain
approach = io.read()
if approach == "y" then
sick = math.random(1, 20)
if sick == 1 then
print("You got an infection from the player.")
io.read()
infection = "y"
end
if gang == "y" then
player = 2
else
if bandit == "y" then
amount = math.random(1, 3)
if amount == 1 then
player = 1
else
player = 2
end
elseif hero == "y" then
amount = math.random(1, 3)
if amount == 1 then
player = 2
else
player = 1
end
else
player = math.random(1, 2)
end
end
print("Attack?")
approach = io.read()
if approach == "y" then
attackchoice = "y"
player = 2
print("You prepare to attack.")
io.read()
moral = moral - math.random(5, 30)
hero = "n"
if moral < 0 then
moral = 0
bandit = "y"
end
elseif approach ~= "y" then
print("You prepare to approach.")
io.read()
end
if player == 1 then
print("The player is friendly.")
io.read()
if droppedbook == "y" then
find = math.random(1, 10)
if find == 1 then
print("I found your " .. droppedcolor .. ' book, the one that said "' .. droppedwriting .. '".')
io.read()
print("Here it is.")
io.read()
findbook = "y"
booksitem()
droppedbook = "n"
findbook = "n"
if droppedwriting == "Help: Food" then
giving()
request = "y"
elseif droppedwriting == "Help: Water" then
giving()
request = "y"
elseif droppedwriting == "Help: Ammo" then
giving()
request = "y"
elseif droppedwriting == "Help: Bandaid" then
giving()
request = "y"
end
elseif find ~= 1 then
niceplayer()
end
else
niceplayer()
end
elseif player == 2 then -----------------------------Evil player
amount = math.random(1, 7)
if amount == 1 then
if mygun ~= "no weapon" then
holdup = "y"
elseif myguntwo ~= "no weapon" then
holdup = "y"
else
holdup = "n"
end
if holdup == "y" then
print("The player wants you to drop your weapons.")
print("Drop them(1), or fight(2)?")
want = io.read()
if want == "1" then
slot = "1"
if slot == "2" then
mygunthree = myguntwo
gunspacethree = gunspacetwo
else
mygunthree = mygun
gunspacethree = gunspace
slot = "1"
end
if mygunthree ~= "no weapon" then
mygunthree = "no weapon"
space = space + gunspacethree
myammothree = 0
gunspacethree = 0
damagethree = 0
accuracythree = 0
fullaccuracythree = 0
takegun()
end
slot = "2"
if slot == "2" then
mygunthree = myguntwo
gunspacethree = gunspacetwo
else
mygunthree = mygun
gunspacethree = gunspace
slot = "1"
end
if mygunthree ~= "no weapon" then
mygunthree = "no weapon"
space = space + gunspacethree
myammothree = 0
gunspacethree = 0
damagethree = 0
accuracythree = 0
fullaccuracythree = 0
takegun()
end
print("Dropped.")
io.read()
amount = math.random(1, 5)
if amount == 1 then
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 7)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(2000, 5000)
print("The player killed you.")
health = 0
health = health - math.random(1000, 8000)
else
print("The player takes your weapons and leaves.")
io.read()
end
--myammo
else
playerfight()
end
------------------------------------------------------------------------------------------------------------------------WIP
elseif holdup == "n" then
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
bleeding = "y"
end
brake = math.random(1, 7)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(2000, 5000)
print("The player killed you because you had no weapons for them.")
health = 0
health = health - math.random(1000, 8000)
end
else
playerfight()
end
end
--end of fight
elseif approach ~= "y" then
if gillie == "n" then
amount = math.random(70, 150)
else
amount = math.random(200, 400)
end
if tired < amount then
print("You have escaped.")
io.read()
tired = tired + math.random(20, 70)
else
if smoke >= 1 then
print("You used a smoke grenade.")
io.read()
smoke = smoke - 1
if smoke < 1 then
space = space + 1
end
elseif smoke < 1 then
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
bleeding = "y"
end
brake = math.random(1, 7)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(2000, 5000)
print("The player caught you.")
if gang ~= "y" then
if bandit == "y" then
amount = math.random(1, 3)
if amount == 1 then
escape = 1
else
escape = 2
end
elseif hero == "y" then
amount = math.random(1, 3)
if amount == 1 then
escape = 2
else
escape = 1
end
else
escape = math.random(1, 2)
end
else
escape = 2
end
if escape == 2 then
print("They killed you.")
health = 0
health = health - math.random(1000, 8000)
elseif escape == 1 then
print("The player let you go.")
io.read()
end
end
end
--end of fle
end
end -- end of player
--uses
function usebandaid()
if bleeding == "y" then
if bandaids >= 1 then
print("You used a bandaid.")
io.read()
bleeding = "n"
bandaids = bandaids - 1
if bandaids < 1 then
space = space + 1
end
elseif bandaids < 1 then
print("You have no bandaids.")
io.read()
end
elseif bleeding == "n" then
print("You are not bleeding.")
io.read()
end
end
function useantibiotic()
if infection == "y" then
if antibiotics >= 1 then
print("You used an antibiotic.")
io.read()
infection = "n"
antibiotics = antibiotics - 1
if antibiotics < 1 then
space = space + 1
end
elseif antibiotics < 1 then
print("You have no antibiotics.")
io.read()
end
elseif infection == "n" then
print("You are not infected.")
io.read()
end
end
function usegoggles() --(X)--(!)--(!)--(!)--(!)--(!)--(X)
if goggles == "y" then
if vision == "y" then
repeat
if space >= 2 then
print("You took off your goggles.")
io.read()
vision = "n"
space = space - 2
if light == "light" then
accuracy = fullaccuracy
accuracytwo = fullaccuracytwo
elseif light == "dark" then
accuracy = fullaccuracy
accuracy = accuracy - 4
accuracytwo = fullaccuracytwo
accuracytwo = accuracytwo - 4
end
break
elseif space < 2 then
print("Not enough space to put away.")
io.read()
dropped()
used()
print("Take off?")
pickup = io.read()
end
until pickup ~= "y"
elseif vision == "n" then
print("You put on your goggles.")
io.read()
vision = "y"
space = space + 2
if light == "dark" then
accuracy = fullaccuracy
accuracytwo = fullaccuracytwo
elseif light == "light" then
accuracy = fullaccuracy
accuracy = accuracy - 4
accuracytwo = fullaccuracytwo
accuracytwo = accuracytwo - 4
end
end
elseif goggles == "n" then
print("You have no goggles.")
io.read()
end
end
function usetent() --(X)--(X)--(X)--(!)--(X)--(!)--(!)
if tentplaced == "y" then
print("You taveled to your tent.")
io.read()
tired = tired + tenttravel
tenttravel = 0
repeat
print("Do you want to store(1), or take out(2)?")
want = io.read()
if want == "1" then
store = "y"
dropped()
store = "n"
elseif want == "2" then
print("")
print("TENT INVENTORY")
print("_______________")
print("ITEMS")
print("<food>")
if bottlestore == "y" then
if filledstore == "y" then
print("Water bottle")
else
print("empty bottle")
end
end
if beanstore >= 1 then
print(beanstore .. " can(s) of beans")
end
if popstore >= 1 then
print(popstore .. " pop")
end
if meatstore >= 1 then
print(meatstore .. " meat")
end
if steakstore >= 1 then
print(steakstore .. " steak(s)")
end
if superbeanstore == "y" then
print("Super Bean?")
end
print(". . . . . . . . . . . .")
print("<medical>")
if bloodbagstore >= 1 then
print(bloodbagstore .. " blood bag(s)")
end
if bandaidstore >= 1 then
print(bandaidstore .. " bandaid(s)")
end
if epipenstore >= 1 then
print(epipenstore .. " epi-pen(s)")
end
if painkillerstore >= 1 then
print(painkillerstore .. " pain killer(s)")
end
if antibioticstore >= 1 then
print(antibioticstore .. " antibiotic(s)")
end
if morphinestore >= 1 then
print(morphinestore .. " morphine")
end
if heatpackstore >= 1 then
print(heatpackstore .. " heatpack(s)")
end
print(". . . . . . . . . . . .")
print("<tools>")
if knifestore == "y" then
print("Knife")
end
if matchstore >= 1 then
print(matchstore .. " match(es)")
end
if woodstore == "y" then
print("Wood")
end
if beartrapstore == "y" then
print("Bear Trap")
end
if gogglesstore == "y" then
print("NV Goggles")
end
if roadflarestore >= 1 then
print(roadflarestore .. " road flare(s)")
end
if smokestore >= 1 then
print(smokestore .. " smoke grenade(s)")
end
if tentstore == "y" then
print("Tent")
end
if canstore == "y" then
if cfilledstore == "y" then
print("Filled Jerry can")
elseif cfilledstore ~= "y" then
print("Jerry can")
end
end
print(". . . . . . . . . . . .")
print("<other>")
if bookstore == "y" then
print(storedcolor .. " book")
end
if radiostore == "y" then
print("radio")
end
print("------------------------")
print("WEAPONS")
print(". . . . . . . . . . . .")
print("<slot 1>")
if gunstoreone ~= "no weapon" then
print(gunstoreone)
if gunstoreone ~= "Hatchet" then
print(ammostoreone .. " ammo")
end
end
print(". . . . . . . . . . . .")
print("<slot 2>")
if gunstoretwo ~= "no weapon" then
print(gunstoretwo)
if gunstoretwo ~= "Hatchet" then
print(ammostoretwo .. " ammo")
end
end
print(". . . . . . . . . . . .")
print("<slot 3>")
if gunstorethree ~= "no weapon" then
print(gunstorethree)
if gunstorethree ~= "Hatchet" then
print(ammostorethree .. " ammo")
end
end
print(". . . . . . . . . . . .")
print("<other>")
if grenadestore >= 1 then
print(grenadestore .. " grenade(s)")
end
print("------------------------")
print("OUTFIT")
if gilliestore == "y" then
print("Gillie Suit")
end
if watchstore == "y" then
print(storedwcolor .. " watch")
end
print("")
print("What do you want to take out?")
want = io.read()
store = "y"
if want == "pop" then
if popstore >= 1 then
popitem()
else
print("Unowned.")
io.read()
end
elseif want == "bottle" then
if bottlestore == "y" then
if filledstore == "y" then
filledbottleitem()
else
bottleitem()
end
else
print("Unowned.")
io.read()
end
elseif want == "gillie suit" then
if gilliestore == "y" then
gillieitem()
else
print("Unowned.")
io.read()
end
elseif want == "watch" then
if watchstore == "y" then
watchitem()
else
print("Unowned.")
io.read()
end
elseif want == "beans" then
if beanstore >= 1 then
beansitem()
else
print("Unowned.")
io.read()
end
elseif want == "meat" then
if meatstore >= 1 then
meatitem()
else
print("Unowned.")
io.read()
end
elseif want == "steak" then
if steakstore >= 1 then
steakitem()
else
print("Unowned.")
io.read()
end
elseif want == "super bean" then
if superbeanstore == "y" then
print("You took the super bean.")
io.read()
superbean = "y"
superbeanstore = "n"
if space >= .5 then
space = space - .5
else
print("...You don't have enough space.")
print("Here, just take it.")
io.read()
end
else
print("Unowned.")
io.read()
end
elseif want == "blood bag" then
if bloodbagstore >= 1 then
bloodbagitem()
else
print("Unowned.")
io.read()
end
elseif want == "bandaid" then
if bandaidstore >= 1 then
bandaiditem()
else
print("Unowned.")
io.read()
end
elseif want == "epi-pen" then
if epipenstore >= 1 then
penitem()
else
print("Unowned.")
io.read()
end
elseif want == "pain killer" then
if painkillerstore >= 1 then
painkilleritem()
else
print("Unowned.")
io.read()
end
elseif want == "antibiotic" then
if antibioticstore >= 1 then
antibioticsitem()
else
print("Unowned.")
io.read()
end
elseif want == "morphine" then
if morphinestore >= 1 then
morphineitem()
else
print("Unowned.")
io.read()
end
elseif want == "heatpack" then
if heatpackstore >= 1 then
heatpackitem()
else
print("Unowned.")
io.read()
end
elseif want == "knife" then
if knifestore == "y" then
knifeitem()
else
print("Unowned.")
io.read()
end
elseif want == "match" then
if matchstore == "y" then
matchitem()
else
print("Unowned.")
io.read()
end
elseif want == "wood" then
if woodstore == "y" then
wooditem()
else
print("Unowned.")
io.read()
end
elseif want == "beartrap" then
if beartrapstore == "y" then
beartrapitem()
else
print("Unowned.")
io.read()
end
elseif want == "goggles" then
if gogglestore == "y" then
gogglesitem()
else
print("Unowned.")
io.read()
end
elseif want == "road flare" then
if roadflarestore >= 0 then
roadflareitem()
else
print("Unowned.")
io.read()
end
elseif want == "smoke grenade" then
if smokestore == "y" then
smokegrenadeitem()
else
print("Unowned.")
io.read()
end
elseif want == "tent" then
if tentstore == "y" then
tentitem()
else
print("Unowned.")
io.read()
end
elseif want == "jerry can" then
if canstore == "y" then
if cfilledstore == "y" then
filledjerrycanitem()
else
jerrycanitem()
end
else
print("Unowned.")
io.read()
end
elseif want == "book" then
if bookstore == "y" then
booksitem()
else
print("Unowned.")
io.read()
end
elseif want == "radio" then
if radiostore == "y" then
radioitem()
else
print("Unowned.")
io.read()
end
elseif want == "gun" then
print("Which tent slot?")
want = io.read()
if want == "1" then
if gunstoreone ~= "no weapon" then
repeat
print("Pickup?")
pickup = io.read()
print("Put in which slot?")
slot = io.read()
if pickup == "y" then
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= gunstoreone then
if space >= gunspacestoreone - gunspacethree then
print("You have picked it up")
io.read()
myammothree = ammostoreone
damagethree = damagestoreone + (1000 * dogs)
mygunthree = gunstoreone
accuracythree = accuracystoreone
fullaccuracythree = fullaccuracystoreone
space = space - (gunspacestoreone - gunspacethree)
gunspacethree = gunspacestoreone
gunstoreone = "no weapon"
gunspacestoreone = 0
damagestoreone = 0
ammostoreone = 0
accuracystoreone = 0
fullaccuracystoreone = 0
takegun()
break
elseif space < gunspacestoreone - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == gunstoreone then
print("You took the ammo.")
if slot == "2" then
myammotwo = myammotwo + myammothree
else
myammo = myammo + myammothree
end
io.read()
myammothree = myammothree + ammostoreone
gunstoreone = "no weapon"
gunspacestoreone = 0
damagestoreone = 0
ammostoreone = 0
accuracystoreone = 0
fullaccuracystoreone = 0
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
else
print("There is no weapon in slot one.")
io.read()
end
elseif want == "2" then
if gunstoretwo ~= "no weapon" then
repeat
print("Pickup?")
pickup = io.read()
print("Put in which slot?")
slot = io.read()
if pickup == "y" then
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= gunstoretwo then
if space >= gunspacestoretwo - gunspacethree then
print("You have picked it up")
io.read()
myammothree = ammostoretwo
damagethree = damagestoretwo + (1000 * dogs)
mygunthree = gunstoretwo
accuracythree = accuracystoretwo
fullaccuracythree = fullaccuracystoretwo
space = space - (gunspacestoretwo - gunspacethree)
gunspacethree = gunspacestoretwo
gunstoretwo = "no weapon"
gunspacestoretwo = 0
damagestoretwo = 0
ammostoretwo = 0
accuracystoretwo = 0
fullaccuracystoretwo = 0
takegun()
break
elseif space < gunspacestoretwo - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == gunstoretwo then
print("You took the ammo.")
if slot == "2" then
myammotwo = myammotwo + myammothree
else
myammo = myammo + myammothree
end
io.read()
myammothree = myammothree + ammostoretwo
-------------------------------------------------------------
gunstoretwo = "no weapon"
gunspacestoretwo = 0
damagestoretwo = 0
ammostoretwo = 0
accuracystoretwo = 0
fullaccuracystoretwo = 0
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
else
print("There is no weapon in slot two.")
io.read()
end
elseif want == "3" then
if gunstorethree ~= "no weapon" then
repeat
want = "4"
print("Pickup?")
pickup = io.read()
print("Put in which slot?")
slot = io.read()
if pickup == "y" then
if slot == "2" then
mygunthree = myguntwo
myammothree = myammotwo
damagethree = damagetwo
gunspacethree = gunspacetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
gunspacethree = gunspace
mygunthree = mygun
myammothree = myammo
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
if mygunthree ~= gunstorethree then
if space >= gunspacestorethree - gunspacethree then
print("You have picked it up")
io.read()
myammothree = ammostorethree
damagethree = damagestorethree + (1000 * dogs)
mygunthree = gunstorethree
accuracythree = accuracystorethree
fullaccuracythree = fullaccuracystorethree
space = space - (gunspacestorethree - gunspacethree)
gunspacethree = gunspacestorethree
gunstorethree = "no weapon"
gunspacestorethree = 0
damagestorethree = 0
ammostorethree = 0
accuracystorethree = 0
fullaccuracystorethree = 0
takegun()
break
elseif space < gunspacestorethree - gunspacethree then
print("Not enough space.")
io.read()
dropped()
used()
end
elseif mygunthree == gunstorethree then
print("You took the ammo.")
if slot == "2" then
myammotwo = myammotwo + myammothree
else
myammo = myammo + myammothree
end
io.read()
myammothree = myammothree + ammostorethree
gunstorethree = "no weapon"
gunspacestorethree = 0
damagestorethree = 0
ammostorethree = 0
accuracystorethree = 0
fullaccuracystorethree = 0
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
else
print("There is no weapon in slot three.")
io.read()
end
else
print("Invalid.")
io.read()
end
else
print("Invalid.")
io.read()
end
else
want = "3"
end
store = "n"
until want == "3"
store = "n"
elseif tentplaced == "n" then
if tent == "y" then
tentplaced = "y"
tent = "n"
space = space + 4
print("You placed your tent.")
io.read()
elseif tent == "n" then
print("You have no tent.")
io.read()
end
end
end
function usebeartrap()
if beartrap == "y" then
if set == "n" then
print("Trap set.")
io.read()
set = "y"
beartrap = "n"
space = space + 2
elseif set == "y" then
print("Already one set.")
io.read()
end
elseif beartrap == "n" then
print("You have no a trap.")
io.read()
end
end
function useradio()
if radio == "y" then
rname = math.random(1, 5)
if rname == 1 then
radioname = "Nikolai"
elseif rname == 2 then
radioname = "Rick"
elseif rname == 3 then
radioname = "Frankie"
elseif rname == 4 then
radioname = "Columbus"
elseif rname == 5 then
radioname = "R"
end
print("Hello, this is " .. radioname .. ", over.")
repeat
say = io.read()
if say == "Hello, I'm " .. name .. "." then
print("Hello, " .. name .. ", over.")
elseif say == "Help!" then
print("Sorry, can't, over.")
elseif say == "I'm going to die!" then
print("I can't do anything for you, sorry, over.")
elseif say == "You are an idiot!" then
print("Look who's talking, over.")
elseif say == "Hello?" then
print("Didn't you hear me the first time? I'm " .. radioname .. ", over.")
elseif say == "Hello." then
print("How are you doing? Over.")
elseif say == "Hello, " .. radioname .. "." then
print("Hello, " .. name .. ", over.")
elseif say == "How are you?" then
print("I'm fine, over.")
elseif say == "Super Bean?" then
print("It is just a legend, over.")
elseif say == "You suck!" then
print("You will be the first to die, over.")
elseif say == "I'm going to kill you!" then
print("Prove it, over.")
elseif say == "Good bye." then
print("Bye, over.")
io.read()
break
elseif say == "I'm fine." then
print("Good to here, over.")
elseif say == "Not so well." then
print("Sorry to hear, over.")
elseif say == "Awesomely!" then
print("Great, over.")
elseif say == "What started all this?" then
print("Some dude named Reece Mathews, he got a new computer program and went to work, over.")
elseif say == "" then
print("See you later, over.")
io.read()
else
amount = math.random(1, 10)
if amount == 1 then
print("What? Over.")
elseif amount == 2 then
print("I don't understand, over.")
elseif amount == 3 then
print(say .. " to you too, over.")
elseif amount == 4 then
print("Oh really? Over.")
elseif amount == 5 then
print("...")
elseif amount == 6 then
print("Haha")
elseif amount == 7 then
print("Be more specific, over.")
elseif amount == 8 then
print("I have no clue what the heck you just said, over.")
elseif amount == 9 then
print("Speak up, over.")
elseif amount == 10 then
print("Could you repeat that? Over.")
end
end
until say == ""
elseif radio ~= "y" then
print("You don't own a radio.")
io.read()
end
end
function usedog()
if dogs >= 1 then
print("Feed, water, or skin?")
want = io.read()
if want == "w" then
if dogwater < 500 then
if filled == "y" then
filled = "n"
dogwater = dogwater + math.random(300, 500)
print("Your dog(s) drank some water.")
io.read()
elseif filled == "n" then
print("You have no water.")
io.read()
end
--end of eat
elseif dogwater > 500 then
print("They are not thirsty.")
end
elseif want == "f" then
if dogfood < 500 then
if steak >= dogs then
steak = steak - dogs
dogfood = dogfood + math.random(300, 500)
doghealth = doghealth + 800
print("Your dog(s) ate some food")
io.read()
dogfeed = dogfeed + 2
if steak < 1 then
space = space + 1
end
elseif beans >= dogs then
beans = beans - dogs
dogfood = 0
dogfood = dogfood + math.random(100, 200)
health = health + 200
print("Your dog(s) ate some food")
io.read()
dogfeed = dogfeed + 1
if beans < 1 then
space = space + 1
end
else
print("You have no food.")
io.read()
end
--end of eat
elseif dogfood > 500 then
print("They are not hungry.")
io.read()
end
elseif want == "s" then
skindog()
end
elseif dogs < 1 then
print("You have no dogs.")
io.read()
end
end
function usewater()
if water < 700 then
if filled == "y" then
filled = "n"
water = water + math.random(300, 500)
print("You drank some water.")
io.read()
elseif filled == "n" then
print("You have no water.")
io.read()
end
elseif water >= 700 then
print("You are not thirsty.")
io.read()
end
end
function usegrenade()
if grenade >= 1 then
print("You threw a grenade at someone.")
io.read()
grenade = grenade - 1
if grenade < 1 then
space = space + 1
end
dropamount = math.random(1, 5)
clothedrop = "y"
repeat
enemydrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
enemydrop()
elseif grenade < 1 then
print("You have no grenades.")
io.read()
end
end
function usesteak()
if food < 500 then
if steak >= 1 then
steak = steak - 1
food = food + math.random(300, 500)
health = health + 800
print("You ate some food")
io.read()
if steak < 1 then
space = space + 1
end
elseif steak < 1 then
print("You have no steak.")
io.read()
end
elseif food >= 500 then
print("You are not hungry.")
io.read()
end
end
function usemeat()
if food < 500 then
if meat >= 1 then
meat = meat - 1
food = food + math.random(50, 150)
health = health + 100
print("You ate some food")
io.read()
amount = math.random(1, 2)
if amount == 1 then
print("You got an infection from the meat.")
infection = "y"
end
if meat < 1 then
space = space + 1
end
elseif meat < 1 then
print("You have no meat.")
io.read()
end
elseif food >= 500 then
print("You are not hungry.")
io.read()
end
end
function usepainkiller()
if epipen >= 1 then
if pain >= 700 then
print("You used a pain killer.")
io.read()
epipen = epipen - 1
if epipen < 1 then
space = space + 1
end
pain = pain - math.random(3000, 7000)
if pain < 0 then
pain = 0
end
elseif pain < 700 then
print("You are not badly hurt.")
io.read()
end
elseif epipen < 1 then
print("You have no pain killers.")
io.read()
end
end
function usemorphine()
if painkillers >= 1 then
print("You used a morphine.")
io.read()
broken = "n"
painkillers = painkillers - 1
if painkillers < 1 then
space = space + 1
end
elseif painkillers < 1 then
print("You have no morpine.")
io.read()
end
end
function useroadflare()
if roadflare >= 1 then
roadflare = roadflare - 1
if roadflare < 1 then
space = space + 1
end
flare = "y"
print("Flare used.")
io.read()
elseif roadflare < 1 then
print("You have no flare.")
io.read()
end
end
function usesuperbean()
if superbean == "y" then
print("You ate a scrumptious Super Bean... Yum.")
io.read()
superbean = "n"
shirt = "Super"
pants = "Super"
symbol = ":P"
invincible = "y"
space = space + .5
elseif superbean == "n" then
print("You can has no haxs for you.")
io.read()
name = "I R Stupid."
end
end
function useheatpack()
if heatpacks >= 1 then
print("You used a heat pack.")
io.read()
heatpacks = heatpacks - 1
if heatpacks < 1 then
space = space + 1
end
temperature = temperature + math.random(5, 7)
if temperature >= 33 then
if cold == "y" then
print("You lost your cold.")
io.read()
cold = "n"
end
end
elseif heatpacks < 1 then
print("You have no heat packs.")
io.read()
end
end
function usehatchet() --(X)--(!)--(X)--(!)--(!)--(!)--(X)
if mygun == "Hatchet" then
if spawn == 3 then
repeat
if space >= 2 then
if wood ~= "y" then
print("You cut down a tree.")
io.read()
wood = "y"
space = space - 2
break
elseif wood == "y" then
print("Already owned.")
io.read()
break
end
elseif space < 2 then
print("Not enough space.")
io.read()
dropped()
used()
print("Chop down?")
pickup = io.read()
end
until pickup ~= "y"
elseif spawn ~= 3 then
print("You are not in a forest.")
io.read()
end
elseif myguntwo == "Hatchet" then
if spawn == 3 then
repeat
if space >= 2 then
if wood ~= "y" then
print("You cut down a tree.")
io.read()
wood = "y"
space = space - 2
break
elseif wood == "y" then
print("Already owned.")
io.read()
break
end
elseif space < 2 then
print("Not enough space.")
io.read()
dropped()
used()
print("Chop down?")
pickup = io.read()
end
until pickup ~= "y"
elseif spawn ~= 3 then
print("You are not in a forest.")
io.read()
end
elseif myguntwo ~= "Hatchet" then
print("You have no hatchet.")
io.read()
end
end
function usematch()
if matches >= 1 then
if wood == "y" then
repeat
print("Light a fire?")
approach = io.read()
if approach == "y" then
if meat >= 1 then
print("You cooked some meat and warm yourself.")
io.read()
temperature = temperature + math.random(1, 3)
if temperature > 50 then
temperature = 50
end
if temperature >= 33 then
if cold == "y" then
print("You lost your cold.")
io.read()
cold = "n"
end
end
steak = steak + meat
meat = 0
matches = matches - 1
if matches < 1 then
space = space + 1
end
break
elseif meat < 1 then
print("You have no meat but warm yourself.")
io.read()
temperature = temperature + math.random(1, 3)
if temperature > 50 then
temperature = 50
end
if temperature >= 33 then
if cold == "y" then
print("You lost your cold.")
io.read()
cold = "n"
end
end
break
end
elseif approach ~= "y" then
print("You left.")
io.read()
break
end
until pickup ~= "y"
elseif wood == "n" then
print("You have no wood.")
io.read()
end
elseif matches < 1 then
print("You have no matches.")
io.read()
end
end
function usebeans()
if food < 500 then
if beans >= 1 then
beans = beans - 1
food = food + math.random(100, 200)
health = health + 200
print("You ate some food")
io.read()
if beans < 1 then
space = space + 1
end
elseif beans < 1 then
print("You have no beans.")
io.read()
end
elseif food >= 500 then
print("You are not hungry.")
io.read()
end
end
function usepop()
if water < 700 then
if pop >= 1 then
pop = pop - 1
if pop < 1 then
space = space + 1
end
water = water + math.random(100, 200)
print("You drank some pop.")
io.read()
elseif pop < 1 then
print("You have no pop.")
io.read()
end
elseif water >= 700 then
print("You are not thirsty.")
io.read()
end
end
function usebook()
if book == "y" then
repeat
print("What do you want to do?")
print('"r" for read, "w" for write, "e" for erase, and "q" for quit.')
choice = io.read()
if choice == "r" then
if booknow == "n" then
print(text)
io.read()
else
if store == "n" then
print(writing)
io.read()
else
print(storedwriting)
io.read()
end
end
elseif choice == "w" then
if booknow == "n" then
print("The book says: " .. text)
print("Please write what you want to add.")
add = io.read()
text = text .. add
print("The book now reads: " .. text)
io.read()
else
if store == "n" then
print("The book says: " .. writing)
print("Please write what you want to add.")
add = io.read()
writing = writing .. add
print("The book now reads: " .. writing)
io.read()
else
print("The book says: " .. storedwriting)
print("Please write what you want to add.")
add = io.read()
storedwriting = storedwriting .. add
print("The book now reads: " .. storedwriting)
io.read()
end
end
elseif choice == "e" then
if booknow == "n" then
text = ""
else
writing = ""
end
print("Erased.")
io.read()
else
choice = "q"
break
end
until choice == "q"
elseif book == "n" then
print("Unowned.")
io.read()
end
end
color = math.random(1, 23)
coloring()
shirt = ccolor
color = math.random(1, 7)
coloring()
pants = ccolor
print("Welcome to Zombie Survival Lua Edition V. 1.6")
print('Press ENTER to continue or type "help" and hit ENTER or RETURN for help.')
reece = io.read()
if reece == cheatkey then -----------------------------------------Cheats
print("Please enter the code.")
code = io.read()
if code == password then
print("Welcome.")
creator = "y"
repeat
cheat = io.read()
if cheat == "health" then
print("How much health?")
amount = io.read("*n")
health = amount
print("updated")
io.read()
elseif cheat == "damage" then
print("How much damage?")
amount = io.read("*n")
damage = amount
print("Updated")
io.read()
elseif cheat == "space" then
print("How much space?")
amount = io.read("*n")
space = amount
print("Updated")
io.read()
elseif cheat == "day" then
print("What is the day?")
amount = io.read("*n")
day = amount
print("Updated")
io.read()
elseif cheat == "spawn" then
print("Which spawn?")
spawn = io.read("*n")
print("You have spawned at spawn " .. spawn .. ".")
io.read()
elseif cheat == "godmode" then
print("activated")
io.read()
invincible = "y"
health = 1000000
water = 1000000
food = 1000000
myammo = 1000000
damage = 1000000
tired = 0
elseif cheat == "symbol" then
print("Please make a symbol for your name.")
symbol = io.read()
print("Your symbol is " .. symbol .. ".")
elseif cheat == "item" then
print("What do you want?")
want = io.read()
if want == "bloodbag" then
print("How many?")
amount = io.read("*n")
bloodbags = amount
print("Obtained.")
io.read()
elseif want == "pack" then
print("Which one?")
want = io.read()
if want == "Coyote" then
print("Obtained.")
io.read()
cpack = "y"
space = space + 20
elseif want == "Alice" then
print("Obtained.")
io.read()
pack = "y"
space = space + 10
elseif want == "Vest Pouch" then
print("Obtained.")
io.read()
vpack = "y"
space = space + 6
end
elseif want == "meat" then
print("How much?")
amount = io.read("*n")
meat = amount
print("Obtained.")
io.read()
elseif want == "road flare" then
print("How many?")
amount = io.read("*n")
roadflare = amount
print("Obtained.")
io.read()
elseif want == "smoke grenade" then
print("How many?")
amount = io.read("*n")
smoke = amount
print("Obtained.")
io.read()
elseif want == "grenade" then
print("How many?")
amount = io.read("*n")
grenade = amount
print("Obtained.")
io.read()
elseif want == "antibiotic" then
print("How many?")
amount = io.read("*n")
antibiotics = amount
print("Obtained.")
io.read()
elseif want == "radio" then
print("Obtained.")
io.read()
radio = "y"
elseif want == "tent" then
print("Obtained.")
io.read()
tent = "y"
elseif want == "book" then
print("what color?")
ccolor = io.read()
cover = ccolor
book = "y"
word()
print("Obtained.")
io.read()
elseif want == "watch" then
print("what color?")
ccolor = io.read()
watchcolor = ccolor
watch = "y"
print("Obtained.")
io.read()
elseif want == "jerry can" then
can = "y"
print("Filled?")
fill = io.read()
if fill == "y" then
print("Obtained.")
io.read()
cfilled = "y"
elseif fill ~= "y" then
print("Obtained.")
io.read()
end
elseif want == "bottle" then
bottle = "y"
print("Filled?")
fill = io.read()
if fill == "y" then
print("Obtained.")
filled = "y"
elseif fill ~= "y" then
print("Obtained.")
io.read()
end
elseif want == "epi-pen" then
print("How much?")
amount = io.read("*n")
morphine = amount
print("obtained")
io.read()
elseif want == "knife" then
knife = "y"
print("obtained")
io.read()
elseif want == "bear trap" then
beartrap = "y"
print("obtained")
io.read()
elseif want == "goggles" then
goggles = "y"
print("obtained")
io.read()
elseif want == "bandaid" then
print("How many?")
amount = io.read("*n")
bandaids = amount
print("Obtained.")
io.read()
elseif want == "pop" then
print("How much?")
amount = io.read("*n")
pop = amount
print("Obtained.")
io.read()
elseif want == "pain killer" then
print("How many?")
amount = io.read("*n")
epipen = amount
print("Obtained.")
io.read()
elseif want == "gillie" then
print("You now have a gillie suit.")
io.read()
gillie = "y"
elseif want == "morphine" then
print("How many?")
amount = io.read("*n")
painkillers = amount
print("Obtained.")
io.read()
elseif want == "heatpack" then
print("How many?")
amount = io.read("*n")
heatpacks = amount
print("Obtained.")
io.read()
elseif want == "match" then
print("How many?")
amount = io.read("*n")
matches = amount
print("Obtained.")
io.read()
elseif want == "super bean" then
superbean = "y"
print("Obtained.")
io.read()
elseif want == "wood" then
wood = "y"
print("Obtained.")
io.read()
elseif want == "steak" then
print("How much?")
amount = io.read("*n")
steak = amount
print("Obtained.")
io.read()
elseif want == "beans" then
print("How much?")
amount = io.read("*n")
beans = amount
print("Obtained.")
io.read()
end
elseif cheat == "gun" then
print("Put in which slot?")
slot = io.read()
if slot == "2" then
mygunthree = myguntwo
gunspacethree = gunspacetwo
myammothree = myammotwo
damagethree = damagetwo
accuracythree = accuracytwo
fullaccuracythree = fullaccuracytwo
else
mygunthree = mygun
myammothree = myammo
gunspacethree = gunspace
damagethree = damage
accuracythree = accuracy
fullaccuracythree = fullaccuracy
slot = "1"
end
print("Which one?")
want = io.read()
if want == "Revolver" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "Revolver"
myammothree = amount
gunspacethree = 3
damagethree = 1839
accuracythree = 4
fullaccuracythree = 4
takegun()
print("obtained")
io.read()
elseif want == "Makarov" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "Makarov"
accuracythree = 4
fullaccuracythree = 4
gunspacethree = 3
damagethree = 889
myammothree = amount
takegun()
print("obtained")
io.read()
elseif want == "Crossbow" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "Crossbow"
accuracythree = 6
fullaccuracythree = 6
gunspacethree = 6
damagethree = 3555
myammothree = amount
takegun()
print("obtained")
io.read()
elseif want == "Create" then
print("What do you want to name it?")
gunname = io.read()
mygunthree = gunname
print("How much ammo?")
amount = io.read("*n")
myammothree = amount
print("How much accuracy?")
amount = io.read("*n")
if amount > 10 then
amount = 10
elseif amount < 0 then
amount = 0
end
accuracythree = amount
fullaccuracythree = amount
print("How much space?")
amount = io.read("*n")
gunspacethree = amount
print("How much damage?")
amount = io.read("*n")
damagethree = amount
takegun()
print("Obtained")
io.read()
elseif want == "Lee Enfield" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "Lee Enfield"
accuracythree = 7
fullaccuracythree = 7
gunspacethree = 7
damagethree = 6722
myammothree = amount
takegun()
print("Obtained")
io.read()
elseif want == "M16" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "M16"
accuracythree = 6
fullaccuracythree = 6
gunspacethree = 7
damagethree = 3555
myammothree = amount
takegun()
print("Obtained")
io.read()
elseif want == "AS50" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "AS50"
accuracythree = 10
fullaccuracythree = 10
gunspacethree = 8
damagethree = 174205
myammothree = amount
takegun()
print("Obtained")
io.read()
elseif want == "FN FAL" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "FN FAL"
accuracythree = 8
fullaccuracythree = 8
gunspacethree = 7
damagethree = 8000
myammothree = amount
takegun()
print("Obtained")
io.read()
elseif want == "G36C" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "G36C"
accuracythree = 7
fullaccuracythree = 7
gunspacethree = 6
damagethree = 3555
myammothree = amount
takegun()
print("Obtained")
io.read()
elseif want == "M4A1" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "M4A1"
accuracythree = 8
fullaccuracythree = 8
gunspacethree = 7
damagethree = 3555
myammothree = amount
takegun()
print("Obtained")
io.read()
elseif want == "AK47" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "AK47"
accuracythree = 8
fullaccuracythree = 8
gunspacethree = 7
damagethree = 2722
myammothree = amount
takegun()
print("Obtained")
io.read()
elseif want == "DB Shotgun" then
print("How much ammo?")
amount = io.read("*n")
mygunthree = "DB Shotgun"
accuracythree = 3
fullaccuracythree = 3
gunspacethree = 6
damagethree = 4500
myammothree = amount
takegun()
print("Obtained")
io.read()
elseif want == "Hatchet" then
mygunthree = "Hatchet"
accuracythree = 10
fullaccuracythree = 10
gunspacethree = 6
damagethree = 4500
myammothree = 99999
takegun()
print("Obtained")
io.read()
end
elseif cheat == "moral" then
print("How much?")
amount = io.read("*n")
moral = amount
if moral > 99 then
hero = "y"
bandit = "n"
moral = 100
elseif moral < 1 then
moral = 0
bandit = "y"
hero = "n"
end
print("Updated")
io.read()
elseif cheat == "dog" then
print("What do you want to call your dog?")
dognameadd = io.read()
if dogs >= 1 then
dogname = dogname .. " and " .. dognameadd
else
dogname = dognameadd
end
print("You now have " .. dogname .. ".")
io.read()
dogs = dogs + 1
doghealth = 10000
dogfood = 500
dogwater = 500
elseif cheat == "water" then
print("How much?")
amount = io.read("*n")
water = amount
print("Updated")
io.read()
elseif cheat == "food" then
print("How much?")
amount = io.read("*n")
food = amount
print("Updated")
io.read()
elseif cheat == "exhaustion" then
print("How much?")
amount = io.read("*n")
tired = amount
print("Updated")
io.read()
elseif cheat == "accuracy" then
print("How much?")
amount = io.read("*n")
accuracy = amount
print("Updated")
io.read()
elseif cheat == "pain" then
print("How much?")
amount = io.read("*n")
pain = amount
print("Updated")
io.read()
elseif cheat == "temperature" then
print("What temperature?")
temperature = io.read("*n")
print("Updated.")
io.read()
elseif cheat == "clothes" then
print("Which one?")
want = io.read()
if want == "shirt" then
print("What color?")
ccolor = io.read()
shirt = ccolor
print("You now have a " .. ccolor .. " shirt.")
io.read()
elseif want == "pants" then
print("What color?")
ccolor = io.read()
pants = ccolor
print("You now have " .. ccolor .. " pants.")
io.read()
end
end
until cheat == "Leave"
elseif code ~= password then
print("HAAAAAAAAAAAAAAAAAAAAAX!")
health = 0
print("You died from hax.") --------------------------------------Help
end
elseif reece == "help" then
help()
end
--------------------------------------------------------Gamemode
print(" Choose a game mode.")
print("Recruit Easy Medium Hard")
mode = io.read()
if mode == "e" then
print("Easy.")
io.read()
gamemode = "Easy"
bandaids = 5
beans = 5
pop = 7
tent = "y"
health = 20000
fullhealth = 20000
space = 2
elseif mode == "r" then
print("Recruit.")
io.read()
gamemode = "Recruit"
myguntwo = "Revolver"
myammotwo = 10
damagetwo = 1839
accuracytwo = 5
fullaccuracytwo = 5
bandaids = 5
epipen = 1
morphine = 2
antibiotics = 2
heatpacks = 2
bloodbags = 1
painkillers = 4
steak = 5
bottle = "y"
filled = "y"
health = 22000
fullhealth = 22000
vpack = "y"
tent = "y"
space = 0
elseif mode == "m" then
print("Medium.")
io.read()
gamemode = "Medium"
beans = 2
pop = 3
health = 15000
fullhealth = 15000
space = 7
elseif mode == "h" then
print("Hard.")
io.read()
gamemode = "Hard"
else
print("Medium.")
io.read()
gamemode = "Medium"
beans = 2
pop = 3
health = 15000
fullhealth = 15000
space = 7
end
--------------------------------------------------Name
print("What is your name?")
name = io.read()
if name == "" then
name = "Player"
end
print("Hello " .. name .. ".")
io.read()
if spawn == 1 then
print("You have spawned in the city.")
elseif spawn == 2 then
print("You have spawned on the shore.")
elseif spawn == 3 then
print("You have spawned in the forest.")
end
-- end of spawn
io.read()
stats()
io.read()
optionline()
repeat ------------------------------------------------------Events
repeat
if flare ~= "y" then
event = math.random(1, 7)
elseif flare == "y" then
attract = math.random(1, 5)
if attract == 1 then
event = 4
print("Your flare atracted something.")
io.read()
else
event = 2
print("Your flare atracted something.")
io.read()
end
flare = "n"
end
if event == 1 then ----------------------------------------------------------------------------------------------------------------------------------------------------------------------Event 1
gun = math.random(1, 4)
if gun == 1 then --------------------Revolver
revolveritem()
elseif gun == 2 then -------------------------------Makarov
makarovitem()
elseif gun == 3 then
hatchetitem()
elseif gun == 4 then -------------------------------crossbow
find = math.random(1, 5)
if find == 1 then
crossbowitem()
elseif find ~= 1 then
print("Nothing happened.")
io.read()
end
end
elseif event == 2 then --------------------------------EVent 2
print("You found a zombie, attack it?")
move = io.read()
if move == "y" then --attack
zhealth = math.random(2000, 3000) + pain
if myammo >= zhealth / damage - (accuracy - 10) then
myammo = myammo - zhealth / damage + (accuracy - 10)
health = health - math.random(0, 3000)
doghealth = doghealth - math.random(0, 2000)
tired = tired + math.random(1, 10)
if bleeding == "y" then
sick = math.random(1, 5)
if sick == 1 then
print("You got an infection.")
io.read()
infection = "y"
end
end
bleed = math.random(1, 7)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 15)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(500, 2000)
if myguntwo == "Hatchet" then
myammotwo = 99999
health = health - math.random(0, 1000)
end
print("You killed it.")
io.read()
moral = moral + math.random(5, 10)
bandit = "n"
if moral > 100 then
moral = 100
hero = "y"
end
print("You search its pockets.")
io.read()
dropamount = math.random(1, 4)
clothedrop = "y"
repeat
zombiedrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
elseif myammotwo >= zhealth / damagetwo - (accuracytwo - 10) then
print("You killed it with your secondary.")
io.read()
myammotwo = myammotwo - zhealth / damagetwo + (accuracytwo - 10)
health = health - math.random(0, 3000)
doghealth = doghealth - math.random(0, 2000)
tired = tired + math.random(1, 10)
if bleeding == "y" then
sick = math.random(1, 2)
if sick == 1 then
print("You got an infection.")
io.read()
infection = "y"
end
end
bleed = math.random(1, 7)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 15)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(500, 2000)
if myguntwo == "Hatchet" then
myammotwo = 99999
health = health - math.random(0, 1000)
end
moral = moral + math.random(5, 10)
bandit = "n"
if moral > 100 then
moral = 100
hero = "y"
end
print("You search its pockets.")
io.read()
dropamount = math.random(1, 3)
clothedrop = "y"
repeat
zombiedrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
elseif dogs >= 1 then
print("Your dog killed it.")
io.read()
health = health - math.random(0, 3000)
doghealth = doghealth - math.random(0, 4000)
tired = tired + math.random(1, 10)
if bleeding == "y" then
sick = math.random(1, 2)
if sick == 1 then
print("You got an infection.")
io.read()
infection = "y"
end
end
bleed = math.random(1, 7)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 15)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(500, 2000)
moral = moral + math.random(5, 10)
bandit = "n"
if moral > 100 then
moral = 100
hero = "y"
end
print("You search its pockets.")
io.read()
dropamount = math.random(1, 3)
clothedrop = "y"
repeat
zombiedrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
elseif dogs < 1 then
if bleeding == "y" then
sick = math.random(1, 2)
if sick == 1 then
print("You got an infection.")
io.read()
infection = "y"
end
end
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 12)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
print("The zombie killed you.")
health = 0
health = health - math.random(1000, 6000)
break
end
--end of attack
elseif move ~= "y" then --flee
if gillie == "y" then
amount = math.random(500, 800)
else
amount = math.random(250, 500)
end
if tired >= amount then
if smoke >= 1 then
print("You used a smoke grenade.")
io.read()
smoke = smoke - 1
if smoke < 1 then
space = space + 1
end
elseif smoke < 1 then
bleed = math.random(1, 5)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 12)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
print("The zombie caught you.")
health = 0
health = health - math.random(1000, 6000)
break
end
elseif tired < amount then
print("You ran away")
io.read()
tired = tired + math.random(10, 50)
end
--end if escape
end --end of y/n attack
elseif event == 3 then --------------------------------------Event 4
print("You look around.")
io.read()
item = math.random(1, 17)
if item == 2 then
if spawn == 3 then
cowitem()
else
popitem()
end
elseif item == 3 then
knifeitem()
elseif item == 4 then
if spawn == 1 then
tentitem()
elseif spawn ~= 1 then
beansitem()
end
elseif item == 5 then
bottleitem()
elseif item == 6 then -- water
if spawn == 2 then
watersourceitem()
else
popitem()
end
elseif item == 7 then
jerrycanitem()
elseif item == 8 then
bandaiditem()
elseif item == 9 then
painkilleritem()
elseif item == 10 then
morphineitem()
elseif item == 11 then
heatpackitem()
elseif item == 12 then
matchitem()
elseif item == 13 then
beansitem()
elseif item == 14 then
popitem()
elseif item == 15 then
roadflareitem()
elseif item == 16 then
vestpouchitem()
elseif item == 17 then
watchitem()
elseif item == 1 then
print("You found a dog, approach?")
approach = io.read()
if approach == "y" then
if steak >= 1 then
print("You fed the dog a steak.")
io.read()
steak = steak - 1
if steak == 0 then
space = space + 1
end
damage = damage + 1000
if dogs < 1 then
doghealth = 10000
dogfood = 500
dogwater = 500
end
print("What do you want to call your dog?")
dognameadd = io.read()
if dogs >= 1 then
dogname = dogname .. " and " .. dognameadd
else
dogname = dognameadd
end
print("You now have " .. dogname .. ".")
io.read()
dogs = dogs + 1
elseif steak < 1 then
zhealth = math.random(7000, 12000)
if myammo >= zhealth / damage - (accuracy - 10) then
print("The dog attacked you but you killed it.")
io.read()
health = health - math.random(0, 3000)
doghealth = doghealth - math.random(0, 2000)
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 10)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
if mygun == "Hatchet" then
myammo = 99999
health = health - math.random(0, 2000)
end
myammo = myammo - zhealth / damage + (accuracy - 10)
wild = "y"
skindog()
wild = "n"
elseif myammotwo >= zhealth / damagetwo - (accuracytwo - 10) then
print("The dog attacked you but you killed it with your secondary.")
io.read()
health = health - math.random(0, 3000)
doghealth = doghealth - math.random(0, 2000)
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 10)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
if myguntwo == "Hatchet" then
myammotwo = 99999
health = health - math.random(0, 2000)
end
myammotwo = myammotwo - zhealth / damagetwo + (accuracytwo - 10)
wild = "y"
skindog()
wild = "n"
elseif dogs >= 1 then
print("The dog attacked you but your dog killed it.")
io.read()
health = health - math.random(0, 3000)
doghealth = doghealth - math.random(0, 5000)
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 10)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
wild = "y"
skindog()
wild = "n"
elseif dogs < 1 then
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
bleeding = "y"
end
brake = math.random(1, 7)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(2000, 5000)
print("The dog killed you.")
health = 0
health = health - math.random(1000, 8000)
break
end
end
elseif approach ~= "y" then
if gillie == "n" then
amount = math.random(20, 100)
else
amount = math.random(100, 200)
end
if tired >= amount then
if smoke >= 1 then
print("You used a smoke grenade.")
io.read()
smoke = smoke - 1
if smoke < 1 then
space = space + 1
end
elseif smoke < 1 then
bleed = math.random(1, 5)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 12)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
print("The dog caught you.")
health = 0
health = health - math.random(1000, 6000)
break
end
elseif tired < amount then
print("You ran away")
io.read()
tired = tired + math.random(10, 50)
end
--end if escape
end
--end of fight
end
--end of item
elseif event == 4 then -------------------------------------Event 5
amount = math.random(1, 10)
if amount == 1 then
gangamount = math.random(2, 5)
print("You see a gang of " .. gangamount .. " people in a small house.")
print("Enter?")
approach = io.read()
if approach == "y" then
gang = "y"
repeat
gangamount = gangamount - 1
playerevent()
if gangamount ~= 0 then
optionline()
end
until gangamount == 0
gang = "n"
elseif approach ~= "y" then
if tired < math.random(50, 100) then
print("You have escaped.")
io.read()
tired = tired + math.random(50, 150)
else
if smoke >= 1 then
print("You used a smoke grenade.")
io.read()
smoke = smoke - 1
if smoke < 1 then
space = space + 1
end
elseif smoke < 1 then
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
bleeding = "y"
end
brake = math.random(1, 7)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(2000, 5000)
print("The gang caught you.")
print("They killed you.")
health = 0
health = health - math.random(1000, 8000)
end
end
--end of fle
end
else
playerevent()
end
elseif event == 5 then ------------------------------------Event 6
amount = math.random(1, 6)
if amount == 1 then
vehiclename = "GAZ"
elseif amount == 2 then
vehiclename = "Tractor"
elseif amount == 3 then
vehiclename = "Helix"
elseif amount == 4 then
vehiclename = "UAZ"
elseif amount == 5 then
vehiclename = "MotorCycle"
elseif amount == 6 then
vehiclename = "ATV"
end
print("You found a " .. vehiclename .. ", use it?.")
----------Vehicle
fix = io.read()
if fix == "y" then
if cfilled == "y" then
print("You have used your fuel.")
io.read()
cfilled = "n"
if spawn == 1 then
spawning = math.random(2, 3)
elseif spawn == 2 then
spawning = math.random(1, 2)
if spawning == 2 then
spawning = 3
end
elseif spawn == 3 then
spawning = math.random(1, 2)
end
if spawning == 1 then
print("You have traveled to the city.")
spawn = 1
elseif spawning == 2 then
print("You have traveled to the shore.")
spawn = 2
elseif spawning == 3 then
print("You have traveled to the forest.")
spawn = 3
end
-- end of vehicle
io.read()
elseif cfilled == "n" then
print("You have no fuel.")
io.read()
end
elseif fix ~= "y" then
print("You left the vehicle.")
io.read()
end
elseif event == 6 then ------------------Event 7!
site = math.random(1, 30)
if site ~= 1 then
print("You found a campsite.")
print("Approach?")
approach = io.read()
if approach == "y" then -----------camp
print("You prepare to approach.")
io.read()
trap = math.random(1, 6)
if trap == 1 then
print("You broke your leg on a bear trap.")
io.read()
broken = "y"
bleeding = "y"
elseif trap == 2 then
playerevent()
if health >= 1 then
print("The place is empty.")
io.read()
else
break
end
else
trap = math.random(1, 3)
if trap == 1 then
print("You found a fire at the camp.")
repeat
print("Use it?")
approach = io.read()
if approach == "y" then
if meat >= 1 then
print("You cooked some meat and warm yourself.")
io.read()
temperature = temperature + math.random(1, 3)
if temperature > 50 then
temperature = 50
end
if temperature >= 33 then
if cold == "y" then
print("You lost your cold.")
io.read()
cold = "n"
end
end
steak = steak + meat
meat = 0
break
elseif meat < 1 then
print("You have no meat but warm yourself.")
io.read()
temperature = temperature + math.random(1, 3)
if temperature > 50 then
temperature = 50
end
if temperature >= 33 then
if cold == "y" then
print("You lost your cold.")
io.read()
cold = "n"
end
end
break
end
elseif approach ~= "y" then
print("You left.")
io.read()
break
end
until pickup ~= "y"
elseif trap ~= 1 then
print("You search The camp.")
io.read()
dropamount = math.random(1, 7)
repeat
drop = math.random(1, 37)
dropamount = dropamount - 1
if drop == 1 then
makarovitem()
elseif drop == 37 then
gillieitem()
elseif drop == 2 then
revolveritem()
elseif drop == 3 then
amount = math.random(1, 3)
if amount == 1 then
M16item()
else
beansitem()
end
elseif drop == 4 then
amount = 1
if amount == 1 then
crossbowitem()
else
popitem()
end
elseif drop == 5 then
amount = 1
if amount == 1 then
hatchetitem()
else
beansitem()
end
elseif drop == 6 then
amount = math.random(1, 4)
if amount == 1 then
leeenfielditem()
else
popitem()
end
elseif drop == 7 then
amount = math.random(1, 30)
if amount == 1 then
FNFALitem()
else
beansitem()
end
elseif drop == 8 then
amount = math.random(1, 70)
if amount == 1 then
AS50item()
else
popitem()
end
elseif drop == 9 then
amount = math.random(1, 2)
if amount == 1 then
gogglesitem()
else
beansitem()
end
elseif drop == 10 then
amount = math.random(1, 20)
if amount == 1 then
coyotepackitem()
else
popitem()
end
elseif drop == 11 then
amount = math.random(1, 2)
if amount == 1 then
filledjerrycanitem()
else
jerrycanitem()
end
elseif drop == 12 then
beartrapitem()
elseif drop == 13 then
matchitem()
elseif drop == 14 then
amount = math.random(1, 2)
if amount == 1 then
filledbottleitem()
else
bottleitem()
end
elseif drop == 15 then
tentitem()
elseif drop == 16 then
knifeitem()
elseif drop == 17 then
amount = 1
if amount == 1 then
antibioticsitem()
else
beansitem()
end
elseif drop == 18 then
morphineitem()
elseif drop == 19 then
if droppedbook == "y" then
amount = math.random(1, 10)
if amount == 1 then
findbook = "y"
booksitem()
findbook = "n"
droppedbook = "n"
else
booksitem()
end
else
booksitem()
end
elseif drop == 20 then
heatpackitem()
elseif drop == 21 then
painkilleritem()
elseif drop == 22 then
amount = math.random(1, 5)
if amount == 1 then
alicepackitem()
else
popitem()
end
elseif drop == 23 then
vestpouchitem()
elseif drop == 24 then
penitem()
elseif drop == 25 then
roadflareitem()
elseif drop == 26 then
bloodbagitem()
elseif drop == 27 then
bandaiditem()
elseif drop == 28 then
amount = math.random(1, 20)
if amount == 1 then
grenadeitem()
else
beansitem()
end
elseif drop == 29 then
amount = math.random(1, 15)
if amount == 1 then
smokegrenadeitem()
else
popitem()
end
elseif drop == 30 then
ammoitem()
elseif drop == 31 then
radioitem()
elseif drop == 32 then
amount = math.random(1, 3)
if amount == 1 then
g36citem()
else
beansitem()
end
elseif drop == 33 then
amount = math.random(1, 2)
if amount == 1 then
AK47item()
else
popitem()
end
elseif drop == 34 then
amount = math.random(1, 3)
if amount == 1 then
M4A1item()
else
beansitem()
end
elseif drop == 35 then
DBshotgunitem()
elseif drop == 36 then
watchitem()
end
until dropamount == 0
print("You leave the camp.")
io.read()
elseif approach ~= "y" then
print("You left.")
io.read()
end
end
end
elseif site == 1 then --------------------------------Millitary
print("You found a Military Camp.")
print("Approach?")
approach = io.read()
if approach == "y" then
trap = math.random(1, 7)
if trap == 1 then
print("You sneak past the guards.")
io.read()
print("You search the Military camp.")
io.read()
dropamount = math.random(1, 3)
repeat
drop = math.random(1, 6)
dropamount = dropamount - 1
if drop == 1 then
smokegrenade()
elseif drop == 2 then
AS50item()
elseif drop == 3 then
grenadeitem()
elseif drop == 4 then
coyotepackitem()
elseif drop == 5 then
gogglesitem()
elseif drop == 6 then
gillieitem()
end
until dropamount == 0
elseif trap ~= 1 then ------------------------------------------------Guard
zhealth = math.random(12000, 22000)
if myammo >= zhealth / damage - (accuracy - 10) then --win?
print("The player guard shot you but you killed them.")
io.read()
health = health - math.random(0, 10000)
doghealth = doghealth - math.random(0, 7000)
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 10)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
if mygun == "Hatchet" then
myammo = 99999
health = health - math.random(0, 2000)
end
myammo = myammo - zhealth / damage + (accuracy - 10)
print("They had a Soldier Shirt.")
print("Take?")
pickup = io.read()
if pickup == "y" then
print("You now have a Soldier Shirt.")
io.read()
shirt = "Soldier"
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
print("They had Soldier Pants.")
print("Take?")
pickup = io.read()
if pickup == "y" then
print("You now have Soldier Pants.")
io.read()
pants = "Soldier"
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
print("You search his pockets.")
io.read()
dropamount = math.random(1, 4)
repeat
guarddrop()
dropamount = dropamount - 1
until dropamount == 0
guarddrop()
elseif myammotwo >= zhealth / damagetwo - (accuracytwo - 10) then
print("The player guard shot you but you killed them with your secondary.")
io.read()
health = health - math.random(0, 10000)
doghealth = doghealth - math.random(0, 7000)
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 10)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
if myguntwo == "Hatchet" then
myammotwo = 99999
health = health - math.random(0, 2000)
end
myammotwo = myammotwo - zhealth / damagetwo + (accuracytwo - 10)
drop = math.random(1, 3)
print("They had a Soldier Shirt.")
print("Take?")
pickup = io.read()
if pickup == "y" then
print("You now have a Soldier Shirt.")
io.read()
shirt = "Soldier"
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
print("You search his pockets.")
io.read()
dropamount = math.random(1, 4)
repeat
guarddrop()
dropamount = dropamount - 1
until dropamount == 0
guarddrop()
elseif dogs >= 1 then
print("The player guard shot you but your dog killed them.")
io.read()
health = health - math.random(0, 10000)
doghealth = doghealth - math.random(0, 10000)
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
io.read()
bleeding = "y"
end
brake = math.random(1, 10)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(1000, 3000)
drop = math.random(1, 3)
print("They had a Soldier Shirt.")
print("Take?")
pickup = io.read()
if pickup == "y" then
print("You now have a Soldier Shirt.")
io.read()
shirt = "Soldier"
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
print("You search his pockets.")
io.read()
dropamount = math.random(1, 4)
repeat
guarddrop()
dropamount = dropamount - 1
until dropamount == 0
guarddrop()
elseif dogs < 1 then
bleed = math.random(1, 2)
if bleed == 1 then
print("You are bleeding.")
bleeding = "y"
end
brake = math.random(1, 7)
if brake == 1 then
print("You broke your leg.")
io.read()
broken = "y"
bleeding = "y"
end
pain = pain + math.random(2000, 5000)
print("The player guard killed you.")
--------------------------Die
health = 0
health = health - math.random(1000, 8000)
break
end
--myammo
end
--end of fight
end
elseif approach ~= "y" then
print("You left.")
io.read()
end
elseif event == 7 then --------------------------------------------------------------------------EVENT 8
if spawn == 1 then
site = math.random(1, 5)
if site == 1 then
print("You found a hospital, approach?.")
approach = io.read()
if approach == "y" then
print("You prepare to approach.")
io.read()
amount = math.random(1, 3)
if amount == 1 then
playerevent()
if health <= 0 then
break
else
print("The player already cleared out the place.")
io.read()
end
else
print("You don't see anyone.")
io.read()
dropamount = math.random(1, 4)
repeat
drop = math.random(1, 8)
dropamount = dropamount - 1
if drop == 1 then
penitem()
elseif drop == 2 then
morphineitem()
elseif drop == 3 then
bandaiditem()
elseif drop == 4 then
bloodbagitem()
elseif drop == 5 then
antibioticsitem()
elseif drop == 6 then
heatpackitem()
elseif drop == 7 then
roadflareitem()
elseif drop == 8 then
print("You find a medbox and look inside.")
io.read()
penitem()
morphineitem()
bandaiditem()
bloodbagitem()
antibioticsitem()
heatpackitem()
painkilleritem()
print("You left the box.")
io.read()
end
until dropamount == 0
print("You leave the building.")
io.read()
end
elseif approach ~= "y" then
print("You leave.")
io.read()
end
elseif site == 2 then
print("You found a police station, approach?.")
approach = io.read()
if approach == "y" then
print("You prepare to approach.")
io.read()
amount = math.random(1, 2)
if amount == 1 then
playerevent()
if health <= 0 then
break
else
print("The player already cleared out the place.")
io.read()
end
else
print("You don't see anyone.")
io.read()
dropamount = math.random(1, 3)
repeat
drop = math.random(1, 13)
dropamount = dropamount - 1
if drop == 1 then
makarovitem()
elseif drop == 2 then
revolveritem()
elseif drop == 3 then
amount = 1
if amount == 1 then
M16item()
else
ammoitem()
end
elseif drop == 4 then
amount = 1
if amount == 1 then
crossbowitem()
else
ammoitem()
end
elseif drop == 5 then
amount = 1
if amount == 1 then
hatchetitem()
else
ammoitem()
end
elseif drop == 6 then
amount = math.random(1, 3)
if amount == 1 then
leeenfielditem()
else
ammoitem()
end
elseif drop == 7 then
amount = math.random(1, 25)
if amount == 1 then
FNFALitem()
else
ammoitem()
end
elseif drop == 8 then
amount = math.random(1, 40)
if amount == 1 then
AS50item()
else
ammoitem()
end
elseif drop == 9 then
radioitem()
elseif drop == 10 then
g36citem()
elseif drop == 11 then
AK47item()
elseif drop == 12 then
M4A1item()
elseif drop == 13 then
DBshotgunitem()
end
until dropamount == 0
print("You leave the building.")
io.read()
end
elseif approach ~= "y" then
print("You leave.")
io.read()
end
elseif site == 3 then
gasstation()
else
print("You found a building, approach?.")
approach = io.read()
if approach == "y" then
print("You prepare to approach.")
io.read()
amount = math.random(1, 5)
if amount == 1 then
playerevent()
if health <= 0 then
break
else
print("The player already cleared out the place.")
io.read()
end
else
print("You don't see anyone.")
io.read()
dropamount = math.random(1, 5)
repeat
drop = math.random(1, 16)
dropamount = dropamount - 1
if drop == 1 then
makarovitem()
elseif drop == 2 then
revolveritem()
elseif drop == 3 then
steakitem()
elseif drop == 4 then
popitem()
elseif drop == 5 then
beansitem()
elseif drop == 6 then
knifeitem()
elseif drop == 7 then
matchitem()
elseif drop == 8 then
bandaiditem()
elseif drop == 9 then
amount = math.random(1, 3)
if amount == 1 then
hatchetitem()
else
beansitem()
end
elseif drop == 10 then
roadflareitem()
elseif drop == 11 then
alicepackitem()
elseif drop == 12 then
watersourceitem()
elseif drop == 13 then
vestpouchitem()
elseif drop == 14 then
booksitem()
elseif drop == 15 then
radioitem()
elseif drop == 16 then
watchitem()
end
until dropamount == 0
print("You leave the building.")
io.read()
end
elseif approach ~= "y" then
print("You leave.")
io.read()
end
end
elseif spawn == 3 then
print("You found a farm, approach?.")
approach = io.read()
if approach == "y" then
print("You prepare to approach.")
io.read()
amount = math.random(1, 2)
if amount == 1 then
playerevent()
if health <= 0 then
break
else
print("The player already cleared out the place.")
io.read()
end
else
print("You don't see anyone.")
io.read()
dropamount = math.random(1, 7)
repeat
drop = math.random(1, 17)
dropamount = dropamount - 1
if drop == 1 then
makarovitem()
elseif drop == 2 then
revolveritem()
elseif drop == 3 then
beartrapitem()
elseif drop == 4 then
wooditem()
elseif drop == 5 then
beansitem()
elseif drop == 6 then
knifeitem()
elseif drop == 7 then
matchitem()
elseif drop == 8 then
bandaiditem()
elseif drop == 9 then
hatchetitem()
elseif drop == 10 then
roadflareitem()
elseif drop == 11 then
alicepackitem()
elseif drop == 12 then
watersourceitem()
elseif drop == 13 then
vestpouchitem()
elseif drop == 14 then
booksitem()
elseif drop == 15 then
steakitem()
elseif drop == 16 then
popitem()
elseif drop == 16 then
radioitem()
elseif drop == 17 then
DBshotgunitem()
end
until dropamount == 0
print("You left the farm.")
io.read()
end
elseif approach ~= "y" then
print("You left the farm.")
io.read()
end
else
gasstation()
end
end
if tired < 0 then
tired = 0
end
------------------------------------- stats
if hour == 12 then
hour = 1
else
hour = hour + 1
end
if hour == 12 then
if period == "pm" then
period = "am"
else
period = "pm"
end
end
if hour == 8 then
if period == "pm" then
light = "dark"
print("It's dark out.")
io.read()
if vision == "n" then
accuracy = fullaccuracy
accuracy = accuracy - 4
accuracytwo = fullaccuracytwo
accuracytwo = accuracytwo - 4
elseif vision == "y" then
accuracytwo = fullaccuracytwo
accuracy = fullaccuracy
end
elseif period == "am" then
print("It's light out.")
io.read()
light = "light"
if vision == "n" then
accuracy = fullaccuracy
accuracytwo = fullaccuracytwo
elseif vision == "y" then
accuracy = fullaccuracy
accuracy = accuracy - 4
accuracytwo = fullaccuracytwo
accuracytwo = accuracytwo - 4
end
end
end
if cold == "y" then
amount = math.random(1, 10)
if amount == 10 then
print("You got an infection from your cold.")
io.read()
cold = "y"
end
end
if dogs >= 1 then
catch = math.random(1, 10)
if catch == 1 then
catch = math.random(1, 3)
if catch == 1 then
print("Your dog caught someone.")
print("You search his pockets.")
io.read()
dropamount = math.random(1, 5)
clothedrop = "y"
repeat
enemydrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
elseif catch == 2 then
print("Your dog caught a zombie.")
print("You search its pockets.")
io.read()
dropamount = math.random(1, 4)
clothedrop = "y"
repeat
zombiedrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
elseif catch == 3 then
if spawn == 3 then
dogcow = "y"
cowitem()
dogcow = "n"
end
end
end
end
if set == "y" then
catch = math.random(1, 10)
if catch == 1 then
catch = math.random(1, 3)
if catch == 1 then
print("You caught someone in your trap.")
io.read()
dropamount = math.random(1, 3)
clothedrop = "y"
repeat
enemydrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
set = "n"
elseif catch == 2 then
print("You caught a zombie in your trap.")
io.read()
dropamount = math.random(1, 3)
clothedrop = "y"
repeat
zombiedrop()
dropamount = dropamount - 1
clothedrop = "n"
until dropamount == 0
set = "n"
elseif catch == 3 then
if spawn == 3 then
trapcow = "y"
cowitem()
trapcow = "n"
set = "n"
elseif spawn ~= 3 then
set = "y"
end
end
if set == "n" then
print("Do you want back your bear trap?")
repeat
print("Pickup?")
pickup = io.read()
if pickup == "y" then
if beartrap == "n" then
if space >= 2 then
beartrap = "y"
space = space - 2
print("You picked it up.")
io.read()
break
elseif space < 2 then
print("Not enough room.")
io.read()
dropped()
used()
end
elseif beartrap == "y" then
print("Already owned.")
io.read()
break
end
elseif pickup ~= "y" then
print("You left it there.")
io.read()
end
until pickup ~= "y"
end
end
end
if tired > 1000 then
tired = 1000
end
water = water - math.random(10)
food = food - math.random(5)
if pain > 10000 then
pain = 10000
end
if mygun == "Hatchet" then
myammo = 99999
end
temp = math.random(1, 15)
if temp == 1 then
temperature = temperature + math.random(1, 2)
if temperature > 50 then
temperature = 50
end
if temperature >= 33 then
if cold == "y" then
print("You lost your cold.")
io.read()
cold = "n"
end
end
end
if temperature < 33 then
if cold == "n" then
cold = "y"
print("You caught a cold.")
io.read()
pain = pain + math.random(1000, 2000)
elseif cold == "y" then
pain = pain + math.random(200, 700)
end
end
if broken == "y" then
tired = tired + math.random(50, 100)
end
events = events + 1
if events == objective then
print("Congrats! You have survived " .. objective .. " events!")
io.read()
objective = objective + 50
end
if events == 50 then
print("For reaching 50 events, you will now be rewarded with a cheatcode.")
print("You will be rewarded more codes the further you get.")
print('At the welcome screen, type "@cheat" to open the cheat input screen.')
print('Once there, type "' .. password .. '" to open the cheat screen.')
print("Be warned, some cheats will be changed when you choose any gamemode but hard.")
io.read()
elseif events == 60 then
print('While on the cheat screen (after the "Welcome",) type "clothes".')
print('You can then type "shirt" or "pants" to change their color.')
io.read()
elseif events == 65 then
print('While on the cheat screen, type "pain".')
print("You can then change the amount of pain you have to start with.")
io.read()
elseif events == 70 then
print('While on the cheat screen, type "temperature".')
print("You can then change the temperature of your body.")
print("This is in celcius with 42 being the normal body temperature.")
io.read()
elseif events == 75 then
print('While on the cheat screen, type "symbol".')
print("You can then change the symbol by your name that comes after using cheats.")
io.read()
elseif events == 80 then
print('While on the cheat screen, type "exhaustion".')
print("You can then change your exhaustion.")
io.read()
end
---------------------------------------------------------------------------------------------------------------
if infection == "y" then
if health > 6000 then
health = health - math.random(300, 1000)
end
end
if doghealth < 10000 then
doghealth = doghealth + math.random(0, 300)
if doghealth > 10000 then
doghealth = 10000
end
end
if health < fullhealth then
health = health + math.random(0, 500)
if health > fullhealth then
health = fullhealth
end
end
optionline()
if autostat == "y" then
turn = turn - 1
if turn < 1 then
stats()
io.read()
turn = turns
end
end
if bleeding == "y" then
if health > 2000 then
health = health - math.random(100, 1000)
end
end
------------------------------------------------godmode
if tentplaced == "y" then
tenttravel = tenttravel + math.random(5, 10)
end
if bleeding == "y" then
amount = math.random(1, 20)
if amount == 1 then
bleeding = "n"
print("You have stopped bleeding.")
io.read()
end
end
if light == "dark" then
if vision == "n" then
accuracy = fullaccuracy
accuracy = accuracy - 4
elseif vision == "y" then
accuracy = fullaccuracy
end
elseif light == "light" then
if vision == "n" then
accuracy = fullaccuracy
elseif vision == "y" then
accuracy = fullaccuracy
accuracy = accuracy - 4
end
end
if tired > math.random(1000, 1400) then
print("You blacked out.")
io.read()
days = days + math.random(1, 3)
tired = 0
food = food - math.random(50, 100)
water = water - math.random(100, 200)
temperature = temperature - math.random(0, 5)
rain = math.random(1, 3)
if rain == 1 then
print("It rained.")
io.read()
temperature = temperature - math.random(3, 5)
end
end
if invincible == "y" then
health = 1000000
water = 1000000
food = 1000000
myammo = 1000000
damage = 1000000
tired = 0
end
----------------------------------eating
if dogs >= 1 then
if doghealth < 1 then
print("Your dog has died.")
io.read()
dogs = dogs - 1
doghealth = 10000
damage = damage - 1000
if dogs < 1 then
dogname = ""
dogfeed = 3
end
skindog()
end
end
if dogs >= 1 then
dogfood = dogfood - math.random(20, 50)
dogwater = dogwater - math.random(20, 50)
if dogfood < 1 then
if steak >= dogs then
steak = steak - dogs
dogfood = 0
dogfood = dogfood + math.random(300, 500)
doghealth = doghealth + 800
print("Your dog(s) ate some food")
io.read()
dogfeed = dogfeed + 2
if steak < 1 then
space = space + 1
end
elseif beans >= dogs then
beans = beans - dogs
dogfood = 0
dogfood = dogfood + math.random(100, 200)
doghealth = doghealth + 200
print("Your dog(s) ate some food")
io.read()
dogfeed = dogfeed + 1
if beans < 1 then
space = space + 1
end
else
print("Your dog(s) starved to death.")
io.read()
damage = damage - (1000 * dogs)
dogs = 0
dogfeed = 3
doghealth = 0
dogfood = 0
dogwater = 0
skindog()
end
--end of eat
end
--end of food
if dogwater < 1 then
if filled == "y" then
filled = "n"
dogwater = 0
dogwater = dogwater + math.random(300, 500)
print("Your dog(s) drank some water.")
io.read()
elseif filled == "n" then
print("Your dog(s) died of thirst.")
io.read()
damage = damage - (1000 * dogs)
dogs = 0
doghealth = 0
dogfood = 0
dogfeed = 3
dogwater = 0
skindog()
end
--end of eat
end
--end of food
end
if food < 1 then
if steak >= 1 then
steak = steak - 1
food = 0
food = food + math.random(300, 500)
health = health + 800
print("You ate some food")
io.read()
if steak < 1 then
space = space + 1
end
elseif beans >= 1 then
beans = beans - 1
food = 0
food = food + math.random(100, 200)
health = health + 200
print("You ate some food")
io.read()
if beans < 1 then
space = space + 1
end
else
print("You starved to death.")
health = 0
starve = "y"
break
end
--end of eat
end
--end of food
if water < 1 then
if filled == "y" then
filled = "n"
water = 0
water = water + math.random(300, 500)
print("You drank some water.")
io.read()
elseif filled == "n" then
if pop >= 1 then
print("You drank some pop.")
io.read()
water = 0
water = water + math.random(100, 200)
pop = pop - 1
if pop < 1 then
space = space + 1
end
elseif pop < 1 then
print("You died of thirst.")
health = 0
thirst = "y"
break
end
end
--end of eat
end
--end of food
until health <= 0
--repeat event
if thirst ~= "y" then -----------------------------epi-pen
if starve ~= "y" then
if health <= 0 then
if morphine >= 1 then
revive = math.random(1, 3)
if revive == 1 then
morphine = morphine - 1
health = health + math.random(500, 5000)
print("A player used an epi-pen on you.")
print("You have " .. health .. " health.")
io.read()
if morphine < 1 then
space = space + 1
end
if health < fullhealth - 3000 then
if bloodbags >= 1 then --bloodbags
print("The player has given you a blood transfusion.")
io.read()
bloodbags = bloodbags - 1
if bloodbags < 1 then
space = space + 1
end
health = fullhealth
end
end
end
end
end
end
end
if health <= 0 then
print("You are dead.")
io.read()
break
end
forever = "forever"
until forever == "never"
print("You survived " .. events .. " events.")
io.read()
stats()
io.read()
print("Play again?")
playagain = io.read()
until playagain ~= "y"
print("CREDITS")
print("Zombie Survival, Lua Edition by Reece Mathews.")
io.read()
print("Programming by Reece Mathews.")
io.read()
print("Co-Creator: Graham Mathews")
io.read()
print("Made and Developed in the U.S.A")
io.read()
print("Made using the game programming software: Lua")
io.read()
print("THE END")
io.read()
|
---@meta
---@class network.Tskill
---@field dataID integer
---@field level integer
--* network.TGameSkill
---@class TGameSkill:System.Object
---@field actionName string
---@field animationID integer
---@field consumeHP integer
---@field consumeMP integer
---@field coolTime number
---@field criticalPercent number
---@field damageFormula string
---@field damageType integer
---@field desc integer
---@field hasCritical boolean
---@field iconID string
---@field memo string
---@field name string
---@field l_desc string
---@field l_name string
---@field oldTraits TGameTrait[]
---@field sturnEnable boolean
---@field sturnTarget integer
---@field sturnTime number
---@field traits TGameMapEventCommand[]
---@field type integer 0: 물리공격, 1: 마법공격
|
------------------------------
-- library
------------------------------
require 'xlua'
require 'csvigo'
require 'optim'
require 'cutorch'
require 'read_data'
require 'save_feature'
require 'lib/orderedPairs'
require 'lib/fill_na'
require 'lib/log_transform'
require 'lib/normalize_col'
require 'lib/normalize_row'
torch.setdefaulttensortype('torch.FloatTensor')
------------------------------
-- function
------------------------------
function sim_cos(cmat, vec)
local cvec = vec:cuda()
local dist = torch.mv(cmat, cvec)
-- dist:add(1e-100)
-- local sim = dist:pow(-1)
return -dist:float()
end
function knn(data, label, pred_data, istrain)
local pred = torch.Tensor(pred_data:size(1), 4):fill(0)
local shift
if istrain then
shift = 1
else
shift = 0
end
local pred_size = pred_data:size(1)
ctrain_data = data:cuda()
ctrain_data2 = ctrain_data:clone()
for i = 1,pred_size do
local nn_value, nn_index = torch.sort(sim_cos(ctrain_data, pred_data[i]), false)
pred[{{i},{1}}] = label:index(1,nn_index[{{1+shift}}])
pred[{{i},{2}}] = label:index(1,nn_index[{{1+shift,1+shift+4}}]):float():mean()
pred[{{i},{3}}] = label:index(1,nn_index[{{1+shift,1+shift+8}}]):float():mean()
pred[{{i},{4}}] = label:index(1,nn_index[{{1+shift,1+shift+26}}]):float():mean()
if i % 100 == 0 then
xlua.progress(i, pred_size)
collectgarbage();
end
end
xlua.progress(pred_size, pred_size)
return pred
end
------------------------------
-- main
------------------------------
-- load data: ----------
print('==> Load data')
train_unique_data, train_unique_label, train_unique_id = read_data("../../input/train_unique.csv", true)
collectgarbage();
train_data, train_label, train_id = read_data("../../input/train.csv", true)
collectgarbage();
test_data, _, test_id = read_data("../../input/test.csv", false)
collectgarbage();
-- preprocess (fill na): ----------
print('==> Fill NA')
mean_ = get_mean_(train_data)
train_unique_data = fill_na(train_unique_data, mean_)
train_data = fill_na(train_data, mean_)
test_data = fill_na(test_data, mean_)
collectgarbage();
-- preprocess (log transform): ----------
print('==> Log transform')
mins = get_mins(train_data)
train_unique_data = log_transform(train_unique_data, mins)
train_data = log_transform(train_data, mins)
test_data = log_transform(test_data, mins)
collectgarbage();
-- preprocess (normalze columns): ----------
print('==> Normalize columns')
mean_, std_ = get_mean_std(train_data)
train_unique_data = normalize_col(train_unique_data, mean_, std_)
train_data = normalize_col(train_data, mean_, std_)
test_data = normalize_col(test_data, mean_, std_)
collectgarbage();
-- preprocess (normalzie rows): ----------
print('==> Normalize rows')
train_unique_data = normalize_row(train_unique_data)
train_data = normalize_row(train_data)
test_data = normalize_row(test_data)
collectgarbage();
-- KNN: ----------
print('==> KNN')
train_pred = knn(train_unique_data, train_unique_label, train_data, true)
test_pred = knn(train_unique_data, train_unique_label, test_data, false)
-- Save result: ----------
print('==> Save Result')
feature_names = {"ID", "KNN_cos1", "KNN_cos5", "KNN_cos9", "KNN_cos27"}
save_feature(train_id, train_pred, "../../add_features/KNN_cos_train.csv", feature_names)
save_feature(test_id, test_pred, "../../add_features/KNN_cos_test.csv", feature_names)
|
----------------------------------<
-- Bluebird GUI
-- elements/dxImage.lua
----------------------------------<
-- Element variables
--[[------------------------------<
dxElement -> dxImage
-------------------
[Includes Basic Indicators]
x : X position
y : Y position
sx : SX position
sy : SY position
pathOrImage : The path to the image or just the texture
rotation : Rotation of the image in degrees
rotationOffX : X Offset from the image center to rotation point
rotationOffY : Y Offset ...
color : The color of the images (includes alpha)
parent : Parent table
--]]------------------------------<
-- Creator
----------------------------------<
function dxCreateImage(x,y,sx,sy,pathOrImage,parent,relativeX, relativeY,rotation, rotationOffX, rotationOffY, color)
if (x == nil) or (y == nil) or (sx == nil) or (sy == nil) or (pathOrImage == nil) then pushError(1, 'dxCreateImage') return false end
if type(x) ~= 'number' then pushError(2, 'dxCreateImage', 'X Position', 'number') return false end
if type(y) ~= 'number' then pushError(2, 'dxCreateImage', 'Y Position', 'number') return false end
if type(sx) ~= 'number' then pushError(2, 'dxCreateImage', 'Width', 'number') return false end
if type(sy) ~= 'number' then pushError(2, 'dxCreateImage', 'Height', 'number') return false end
if (type(pathOrImage) ~= 'string') and (type(pathOrImage) ~= 'userdata') then pushError(2, 'dxCreateImage', 'Path or Image', 'path/material') return false end
if (parent == nil) or (parent == false) then
parent = dxContainer
else
if (not isElement(parent)) then
pushError(2, 'dxCreateImage', 'Parent', 'dxElement')
return false
end
local elementType = dxElementsList[parent]["type"]
if (elementType ~= "dxTile") and (elementType ~= "dxScrollPane") and (elementType ~= "dxContainer") then
pushError(4, 'dxCreateImage', 'Parent')
return false
end
parent = dxElementsList[parent]
end
if type(pathOrImage) == "string" then
if string.sub(pathOrImage, 1,1) ~= ":" then
pathOrImage = ":"..getResourceName(sourceResource or getThisResource()).."/"..pathOrImage
end
else
if (not isElement(pathOrImage)) then
pushError(2, 'dxCreateImage', 'Path or Image', 'path/material')
return false
end
if (getElementType(pathOrImage) ~= "texture") then
pushError(2, 'dxCreateImage', 'Path or Image', 'path/material')
return false
end
end
if (relativeX == nil) then
relativeX = false
else
if type(relativeX) ~= "boolean" then
pushError(3, 'dxCreateImage', 'X Relativity', 'boolean')
relativeX = false
end
if (relativeX == true) then
x = parent.sx*x
sx = parent.sx*sx
end
end
if (relativeY == nil) then
relativeY = false
else
if type(relativeY) ~= "boolean" then
pushError(3, 'dxCreateImage', 'Y Relativity', 'boolean')
relativeY = false
end
if (relativeY == true) then
y = parent.sy*y
sy = parent.sy*sy
end
end
if (color == nil) then
color = -1
else
if type(color) ~= "number" then
pushError(3, 'dxCreateTile', 'Color', 'number')
color = -1
end
if (color < -2147483648) or (color > 2147483647) then
pushError(6, 'dxCreateTile', 'Color')
return false
end
end
if (rotation == nil) then
rotation = 0
else
if type(rotation) ~= "number" then
pushError(3, 'dxCreateTile', 'Rotation', 'number')
rotation = 0
end
end
if (rotationOffX == nil) then
rotationOffX = 0
else
if type(rotationOffX) ~= "number" then
pushError(3, 'dxCreateTile', 'Rotation X Offset', 'number')
rotationOffX = 0
end
end
if (rotationOffY == nil) then
rotationOffY = 0
else
if type(rotationOffY) ~= "number" then
pushError(3, 'dxCreateTile', 'Rotation Y Offset', 'number')
rotationOffY = 0
end
end
local ElementTable = {
["type"] = "dxImage",
["element"] = createElement("dxGUI", "dxImage"),
["creator"] = getResourceName(sourceResource or getThisResource()),
["x"] = x,
["y"] = y,
["sx"] = sx,
["sy"] = sy,
["Image"] = pathOrImage,
["rotation"] = rotation,
["rotationOffX"] = rotationOffX,
["rotationOffY"] = rotationOffY,
["Enabled"] = true,
["Color"] = color,
["parent"] = parent,
}
table.insert(parent["children"], ElementTable)
dxElementsList[ElementTable["element"]] = ElementTable
triggerEvent("onDXElementCreation", root)
return ElementTable["element"]
end
fileDelete("elements/dxImage.lua")
|
Locales['en'] = {
['not_enough_nitrous'] = 'Not enough nitrous.',
['nitrous_activated'] = 'Nitrous activated.',
['nitrous_ready'] = 'Nitrous ready. Press ~INPUT_PICKUP~ to use.'
}
|
--[[
-- Copyright(c) 2019, 武汉舜立软件 All Rights Reserved
-- Created: 2019/4/23
--
-- @file upgrade.lua
-- @brief 升级模块
-- @version 0.1
-- @author 李绍良
-- @history 修改历史
-- \n 2019/4/23 0.1 创建文件
-- @warning 没有警告
--]]
local string = require("string")
local io = require("io")
local os = require("os")
local l_sys = require("l_sys")
--local l_net_a = require("l_net_a")
local l_nsm_a = require("l_nsm_a")
local util = require("base.util")
local np_err = require("base.np_err")
local np_id = require("base.np_id")
local l_file = require("l_file")
local upgrade = {}
local ipc_upgrade_file = '/nfsmem/upgrade/ipc_upgrade_file.lpk' -- 升级文件
local ipc_upgrade = '/nfsmem/upgrade/ipc_upgrade.txt' -- 升级标记
local ipc_root = ''
if l_sys.simulator then
-- 非目标平台, 重定位目录
ipc_upgrade_file = './upgrade/ipc_upgrade_file.lpk'
ipc_upgrade = './upgrade/ipc_upgrade.txt'
ipc_root = './upgrade/root'
end
local up_nsm = nil
local up_conn = {
id = 0,
blk_count = 0,
pf = nil,
pf_w_size = 0
}
local send = function (body)
assert(0 ~= up_conn.id)
local t = type(body)
if 'string' == t then
l_nsm_a.send(up_nsm, up_conn.id, body)
elseif 'table' == t then
local txt = cjson.encode(body)
l_nsm_a.send(up_nsm, up_conn.id, txt)
else
assert(false)
end
end
local close_connect = function ()
print('upgrade close connect.', up_conn.pf_w_size)
-- 关闭连接
local id = up_conn.id;
l_nsm_a.close(up_nsm, id)
-- 关闭文件
if nil ~= up_conn.pf then
l_file.close(up_conn.pf)
end
up_conn.id = 0
up_conn.pf = nil
up_conn.blk_count = 0;
up_conn.pf_w_size = 0;
end
local on_cmd_upgrade = function (json_obj)
local res_up = {
cmd = 'upgrade',
upgrade = {
code = 0
}
}
if nil == up_conn.pf then
up_conn.pf = l_file.open(ipc_upgrade_file, 'wb')
assert(0 == up_conn.blk_count)
end
send(res_up)
end
local on_cmd_upgrade_packs = function (json_obj)
local res_up_packs = {
cmd = 'upgrade_packs',
upgrade_packs = {
code = 0,
packs = up_conn.blk_count,
bits = up_conn.pf_w_size
}
}
send(res_up_packs)
end
local on_cmd_upgrade_ok = function (json_obj)
local res_up_ok = {
cmd = 'upgrade_ok',
upgrade_ok = {
code = 0,
all_packs = up_conn.blk_count,
all_bits = up_conn.pf_w_size
}
}
send(res_up_ok)
-- 校验数据包大小 决定是否可以升级
local up = false
local bits = util.t_item(json_obj, 'upgrade_ok', 'all_bits')
if 'number' == type(bits) and bits == up_conn.pf_w_size then
up = true
end
if nil ~= up_conn.pf then
l_file.close(up_conn.pf)
up_conn.pf = nil
end
if up then
-- 决定升级
local file = io.open(ipc_upgrade, 'w')
assert(file)
if file then
file:write('1')
file:close()
end
else
print('recv upgrade all_bits error!remove!')
os.remove(ipc_upgrade_file)
end
close_connect() -- 关闭连接
end
local on_commond = function (json_obj)
local cmd = json_obj['cmd'] or ''
if 'string' ~= type(cmd) then
send('{}')
return
end
local low_cmd = string.lower(cmd)
if 'upgrade' == low_cmd then
on_cmd_upgrade(json_obj)
elseif 'upgrade_packs' == low_cmd then
on_cmd_upgrade_packs(json_obj)
elseif 'upgrade_ok' == low_cmd then
on_cmd_upgrade_ok(json_obj)
else
send('{}')
end
end
local open_connect = function (id)
local file = io.open(ipc_upgrade, 'r')
if file then
io.close(file)
return false -- 已经准备要升级了, 不再接收连接
end
up_conn.id = id -- 只接受一次连接
return true
end
local on_recv_txt = function ()
-- 一次将所有文本信息读取完毕
while true do
local ret, code, body, id, main, sub = l_nsm_a.recv(up_nsm)
if ret then
if 0 == code then
if 0 ~= up_conn.id and id == up_conn.id then
local dec, json_obj = pcall(cjson.decode, body)
if dec then
on_commond(json_obj)
else
close_connect()
end
else
l_nsm_a.close(up_nsm, id)
end
elseif np_err.CONNECT == code then -- 新连接接入
if 0 == up_conn.id and open_connect(id) then
-- 只接受一次连接
else
l_nsm_a.close(up_nsm, id)
end
else
if 0 ~= up_conn.id and id == up_conn.id then
close_connect()
else
l_nsm_a.close(up_nsm, id) -- 连接断开
end
end
else
break -- 退出
end
end
end
local on_recv_md = function ()
while true do
local buf, id = l_nsm_a.recv_md(up_nsm)
if nil ~= buf then
if id == up_conn.id then
local ret = false
local w_size = 0
if nil ~= up_conn.pf then
ret, w_size= l_file.write(up_conn.pf, buf)
end
if ret then
up_conn.blk_count = up_conn.blk_count + 1 --写入成功, 计数+1
up_conn.pf_w_size = up_conn.pf_w_size + w_size --写入的数据量
--print('upgrade write:', up_conn.blk_count, up_conn.pf_w_size)
else
print('net upgrade l_file.write error!', ret)
l_sys.free(buf)
end
else
print('net upgrade id error!', id, up_conn.id)
l_sys.free(buf) -- 和当前连接对应不上
end
else
break
end
end
end
upgrade.on_recv = function ()
on_recv_txt()
on_recv_md()
return 0
end
upgrade.init = function ()
up_nsm = l_nsm_a.get('nsm_upgrade')
end
upgrade.quit = function ()
up_nsm = nil
end
return upgrade
|
local CircularBuffer = require(script.Parent.Parent.Parent.CircularBuffer)
local Signal = require(script.Parent.Parent.Parent.Signal)
local Constants = require(script.Parent.Parent.Parent.Constants)
local HEADER_NAMES = Constants.ServerJobsFormatting.ChartHeaderNames
local MAX_DATASET_COUNT = tonumber(settings():GetFVariable("NewDevConsoleMaxGraphCount"))
local SORT_COMPARATOR = {
[HEADER_NAMES[1]] = function(a, b) -- "Name"
return a.name < b.name
end,
[HEADER_NAMES[2]] = function(a, b) -- "DutyCycle(%)"
return a.dataStats.dataSet:back().data[1] < b.dataStats.dataSet:back().data[1]
end,
[HEADER_NAMES[3]] = function(a, b) -- "Steps Per Sec (/s)"
return a.dataStats.dataSet:back().data[2] < b.dataStats.dataSet:back().data[2]
end,
[HEADER_NAMES[4]] = function(a, b) -- "Step Time (ms)"
return a.dataStats.dataSet:back().data[3] < b.dataStats.dataSet:back().data[3]
end,
}
local minOfTable = require(script.Parent.Parent.Parent.Util.minOfTable)
local maxOfTable = require(script.Parent.Parent.Parent.Util.maxOfTable)
local getClientReplicator = require(script.Parent.Parent.Parent.Util.getClientReplicator)
local ServerJobsData = {}
ServerJobsData.__index = ServerJobsData
function ServerJobsData.new()
local self = {}
setmetatable(self, ServerJobsData)
self._serverJobsUpdated = Signal.new()
self._serverJobsData = {}
self._sortedJobsData = {}
self._sortType = HEADER_NAMES[1] -- Name
self._lastUpdate = 0
return self
end
function ServerJobsData:setSortType(sortType)
if SORT_COMPARATOR[sortType] then
self._sortType = sortType
-- do we need a mutex type thing here?
table.sort(self._sortedJobsData, SORT_COMPARATOR[self._sortType])
else
error(string.format("attempted to pass invalid sortType: %s", tostring(sortType)), 2)
end
end
function ServerJobsData:getSortType()
return self._sortType
end
function ServerJobsData:Signal()
return self._serverJobsUpdated
end
function ServerJobsData:getCurrentData()
return self._sortedJobsData
end
function ServerJobsData:updateServerJobsData(updatedJobs)
self._lastUpdate = os.time()
for key, data in pairs(updatedJobs) do
if not self._serverJobsData[key] then
local newBuffer = CircularBuffer.new(MAX_DATASET_COUNT)
newBuffer:push_back({
data = data,
time = self._lastUpdate,
})
self._serverJobsData[key] = {
max = data,
min = data,
dataSet = newBuffer,
}
local newEntry = {
name = key,
dataStats = self._serverJobsData[key],
}
table.insert(self._sortedJobsData, newEntry)
else
local currMax = {}
for i,v in pairs(self._serverJobsData[key].max) do
currMax[i] = v
end
local currMin = {}
for i, v in pairs(self._serverJobsData[key].min) do
currMin[i] = v
end
local update = {
data = data,
time = self._lastUpdate
}
local overwrittenEntry = self._serverJobsData[key].dataSet:push_back(update)
if overwrittenEntry then
for index, value in pairs(overwrittenEntry.data) do
if currMax[index] == value then
local iter = self._serverJobsData[key].dataSet:iterator()
local dat = iter:next()
currMax[index] = currMin[index]
while dat do
currMax[index] = dat.data[index] < currMax[index] and currMax[index] or dat.data[index]
dat = iter:next()
end
end
end
for index, value in pairs(overwrittenEntry.data) do
if currMin[index] == value then
local iter = self._serverJobsData[key].dataSet:iterator()
local dat = iter:next()
currMin[index] = currMax[index]
while dat do
currMin[index] = currMin[index] < dat.data[index] and currMin[index] or dat.data[index]
dat = iter:next()
end
end
end
end
self._serverJobsData[key].max = maxOfTable(currMax, data)
self._serverJobsData[key].min = minOfTable(currMin, data)
end
end
end
function ServerJobsData:start()
local clientReplicator = getClientReplicator()
if clientReplicator and not self._statsListenerConnection then
self._statsListenerConnection = clientReplicator.StatsReceived:connect(function(stats)
local serverJobsList = stats.Jobs
if serverJobsList then
self:updateServerJobsData(serverJobsList)
self._serverJobsUpdated:Fire(self._sortedJobsData)
end
end)
clientReplicator:RequestServerStats(true)
end
end
function ServerJobsData:stop()
if self._statsListenerConnection then
self._statsListenerConnection:Disconnect()
self._statsListenerConnection = nil
end
end
return ServerJobsData
|
--------------------------------------------------
-- Created By: Luciano
-- Description: Cover goes hiding under fire
--------------------------
--
local Behavior = CreateAIBehavior("Cover2Hide",
{
Alertness = 1,
-----------------------------------------------------
Constructor = function(self,entity)
entity:GettingAlerted();
-- entity.AI.changeCoverLastTime = _time;
-- entity.AI.changeCoverInterval = random(7,11);
-- entity.AI.fleeLastTime = _time;
-- entity.AI.lastLiveEnemyTime = _time;
-- entity.AI.lastBulletReactionTime = _time - 10;
-- entity.AI.lastFriendInWayTime = _time - 10;
entity.AI.lastBulletReactionTime = _time - 10;
entity:Readibility("taking_fire",1,1, 0.1,0.4);
self:HandleThreat(entity);
end,
-----------------------------------------------------
Destructor = function(self,entity)
end,
-----------------------------------------------------
HandleThreat = function(self, entity, sender)
local dt = _time - entity.AI.lastBulletReactionTime;
if(dt > 0.5) then
if(not sender or AI.Hostile(entity.id, sender.id)) then
entity.AI.lastBulletReactionTime = _time;
entity:SelectPipe(0,"do_nothing");
entity:SelectPipe(0,"cv_hide_unknown");
end
end
end,
-----------------------------------------------------
COVER_NORMALATTACK = function(self, entity)
-- Choose proper action after being interrupted.
AI_Utils:CommonContinueAfterReaction(entity);
end,
---------------------------------------------
OnEnemyMemory = function( self, entity )
-- called when the enemy stops having an attention target
end,
---------------------------------------------
OnNoTarget = function( self, entity )
-- called when the enemy stops having an attention target
-- self:HandleThreat(entity);
end,
---------------------------------------------
OnEnemySeen = function( self, entity, fDistance, data )
entity:MakeAlerted();
entity:TriggerEvent(AIEVENT_DROPBEACON);
local dist = AI.GetAttentionTargetDistance(entity.id);
if (entity.AI.firstContact) then
entity:Readibility("first_contact",1,3, 0.1,0.4);
AI.Signal(SIGNALFILTER_SENDER, 1, "ENEMYSEEN_FIRST_CONTACT",entity.id);
else
entity:Readibility("during_combat",1,3, 0.1,0.4);
AI.Signal(SIGNALFILTER_SENDER, 1, "ENEMYSEEN_DURING_COMBAT",entity.id);
end
AI.Signal(SIGNALFILTER_SENDER, 1, "TO_ATTACK",entity.id);
end,
---------------------------------------------
OnInterestingSoundHeard = function( self, entity, fDistance )
-- entity:TriggerEvent(AIEVENT_CLEAR);
end,
---------------------------------------------
OnThreateningSeen = function( self, entity )
entity:TriggerEvent(AIEVENT_DROPBEACON);
end,
---------------------------------------------
OnThreateningSoundHeard = function( self, entity, fDistance )
entity:TriggerEvent(AIEVENT_DROPBEACON);
end,
---------------------------------------------
OnSommethingSeen = function( self, entity, fDistance )
entity:TriggerEvent(AIEVENT_DROPBEACON);
end,
---------------------------------------------
OnEnemyDamage = function ( self, entity, sender,data)
entity.AI.coverCompromized = true;
-- set the beacon to the enemy pos
local shooter = System.GetEntity(data.id);
if(shooter) then
AI.SetBeaconPosition(entity.id, shooter:GetPos());
AI.Signal(SIGNALFILTER_SENDER,1,"INCOMING_FIRE",entity.id);
end
-- called when the enemy is damaged
self:HandleThreat(entity, shooter);
entity:Readibility("taking_fire",1,1, 0.1,0.4);
end,
---------------------------------------------
OnBulletRain = function(self, entity, sender, data)
entity:Readibility("bulletrain",1,1, 0.1,0.4);
self:HandleThreat(entity, sender);
local shooter = System.GetEntity(sender.id);
if(shooter) then
AI.SetBeaconPosition(entity.id, shooter:GetPos());
AI.Signal(SIGNALFILTER_SENDER,1,"INCOMING_FIRE",entity.id);
end
end,
---------------------------------------------
OnReload = function( self, entity )
end,
--------------------------------------------------------
OnHideSpotReached = function(self,entity,sender)
end,
---------------------------------------------
INCOMING_FIRE = function (self, entity, sender)
end,
})
|
local query = require 'lusty-store-mysql.query'
local connection = require 'lusty-store-mysql.store.mysql.connection'
local function keysAndValues(tbl)
local n, keys, values = 1, {}, {}
for k, v in pairs(tbl) do
keys[n] = k
if type(v) == 'number' then
values[n] = v
else
values[n] = ngx.quote_sql_str(v)
end
n = n + 1
end
return keys, values
end
local function makeUpdate(tbl)
local n, update = 1, {}
for k, v in pairs(tbl) do
if type(v) == 'number' then
update[n] = k..'='..v
else
update[n] = k..'='..ngx.quote_sql_str(v)
end
n=n+1
end
return table.concat(update, ' ,')
end
return {
handler = function(context)
local db, err = connection(lusty, config)
if not db then error(err) end
local q, m
if getmetatable(context.query) then
q, m = query(context.query)
else
q = context.query
end
local keys, values = keysAndValues(context.data)
local update = makeUpdate(context.data)
q = "UPDATE "..config.collection.." SET "..update.." "..(#q>0 and " WHERE "..q or "")..";"
local results = {}
local res, err, errno, sqlstate = db:query(q)
db:set_keepalive(config.idle_timeout or 600000, config.pool_size or 10)
if not res then
return nil, "Query |"..q.."| failed: "..err
end
return res
end
}
|
local Types = require(script.Parent.Parent.Types)
type Array<T> = Types.Array<T>
local function loadDescendants(parent: Instance)
local modules: Array<any> = {}
for _, descendant in parent:GetDescendants() do
if descendant:IsA("ModuleScript") then
table.insert(modules, require(descendant :: ModuleScript))
end
end
return modules
end
return loadDescendants
|
local myNAME = "merTorchbug"
local tbug = SYSTEMS:GetSystem("merTorchbug")
local strformat = string.format
function tbug.inspect(object, tabTitle, winTitle, recycleActive)
local inspector = nil
if rawequal(object, _G) then
inspector = tbug.getGlobalInspector()
inspector.control:SetHidden(false)
inspector:refresh()
elseif type(object) == "table" then
inspector = tbug.classes.ObjectInspector:acquire(object, tabTitle, recycleActive)
inspector.title:SetText(tbug.glookup(object) or winTitle or tostring(object))
inspector.control:SetHidden(false)
inspector:refresh()
elseif tbug.isControl(object) then
inspector = tbug.classes.ObjectInspector:acquire(object, tabTitle, recycleActive)
inspector.title:SetText(winTitle or tbug.getControlName(object))
inspector.control:SetHidden(false)
inspector:refresh()
else
df("no inspector for %q", tostring(object))
end
return inspector
end
local function evalString(source)
-- first, try to compile it with "return " prefixed,
-- this way we can evaluate things like "_G.tab[5]"
local func, err = zo_loadstring("return " .. source)
if not func then
-- failed, try original source
func, err = zo_loadstring(source, "<< " .. source .. " >>")
if not func then
return func, err
end
end
-- run compiled chunk in custom environment
return pcall(setfenv(func, tbug.env))
end
local function inspectResults(source, status, ...)
if not status then
local err = tostring(...)
err = err:gsub("(stack traceback)", "|cff3333%1", 1)
err = err:gsub("%S+/(%S+%.lua:)", "|cff3333> |c999999%1")
df("%s", err)
return
end
local firstInspector = nil
local globalInspector = nil
local nres = select("#", ...)
for ires = 1, nres do
local res = select(ires, ...)
if rawequal(res, _G) then
if not globalInspector then
globalInspector = tbug.getGlobalInspector()
globalInspector:refresh()
globalInspector.control:SetHidden(false)
globalInspector.control:BringWindowToTop()
end
else
local tabTitle = strformat("[%d]", ires)
if firstInspector then
firstInspector:openTabFor(res, tabTitle)
else
local recycle = not IsShiftKeyDown()
firstInspector = tbug.inspect(res, tabTitle, source, recycle)
end
end
end
if firstInspector then
firstInspector.control:BringWindowToTop()
end
end
function tbug.slashCommand(args)
local args = zo_strtrim(args)
if args ~= "" then
inspectResults(args, evalString(args))
elseif tbugGlobalInspector:IsHidden() then
inspectResults("_G", true, _G)
else
tbugGlobalInspector:SetHidden(true)
end
end
local function onAddOnLoaded(event, addOnName)
if addOnName ~= myNAME then return end
EVENT_MANAGER:UnregisterForEvent(myNAME, EVENT_ADD_ON_LOADED)
tbug.initSavedVars()
local env =
{
gg = _G,
am = ANIMATION_MANAGER,
cm = CALLBACK_MANAGER,
em = EVENT_MANAGER,
wm = WINDOW_MANAGER,
tbug = tbug,
conf = tbug.savedVars,
}
env.env = setmetatable(env, {__index = _G})
tbug.env = env
SLASH_COMMANDS["/tbug"] = tbug.slashCommand
end
EVENT_MANAGER:RegisterForEvent(myNAME, EVENT_ADD_ON_LOADED, onAddOnLoaded)
|
local APABadEnts = APABadEnts or {}
local log = APA.log
local isPlayer = APA.isPlayer
local physStop = APA.physStop
local IsValid = IsValid
local timer = timer
local hook = hook
function APA.SetBadEnt(ent,bool,ignorefrozen)
local phys = IsValid(ent) and ent.GetPhysicsObject and ent:GetPhysicsObject()
if bool then
local collisions = ent:GetCollisionGroup()
if (not ignorefrozen) and IsValid(phys) and not phys:IsMotionEnabled() then return end -- Don't apply on frozen entities.
if collisions == COLLISION_GROUP_WORLD then return end -- Don't apply on props that don't collide.
log('[BadEntity]',ent,' is now a BAD entity!') if APA.Settings.Debug:GetInt() > 0 then ent:SetColor(Color(255,0,0)) end
ent:SetNWBool("APABadEntity", true)
local inc = ((APA.Settings.BadTime:GetFloat() >= 0.15 and APA.Settings.BadTime:GetFloat() or 0.15))
ent.APAt = ent.APAt or {}
ent.APAt["block entity"] = true
ent.APAt["time stamp"] = (not ent.APAt["time stamp"]) and CurTime()+inc or ent.APAt["time stamp"]
log('[BadEntity]','Wait Time',Vector(0,0,(ent.APAt["time stamp"] or 0)):Distance(Vector(0,0,CurTime() or 0)),'seconds')
if table.HasValue(APABadEnts, ent) then return end -- Don't rebind if bound.
if not ent.APAt.Think then
ent.APAt.Think = function()
local checkheld = false
for _,v in next, constraint.GetAllConstrainedEntities(ent) do
if IsValid(v) then
checkheld = next(v.__APAPhysgunHeld or {}) == nil
if not checkheld then break end
end
end
if tonumber(ent.APAt["time stamp"] or 0) < CurTime() and checkheld then
local phys = IsValid(ent) and ent:GetPhysicsObject()
if IsValid(phys) then
if phys:GetVelocity():Length() <= 0.001 then
phys:SetVelocityInstantaneous(Vector(0,0,0))
phys:AddAngleVelocity(phys:GetAngleVelocity()*-1)
APA.SetBadEnt(ent,false)
end
end
end
end
end
ent.APAtCallback = function(ent, c)
local collisions = ent:GetCollisionGroup()
if collisions == COLLISION_GROUP_VEHICLE or collisions == COLLISION_GROUP_WEAPON or collisions == COLLISION_GROUP_WORLD then return false end
--^ Don't apply on props that don't collide with players.
local speed = c.OurOldVelocity:Length()
if speed < 8.4 then return end
if speed > 1000 then
c.HitObject:SetVelocity(c.HitObject:GetVelocity()*-speed)
c.HitObject:SetVelocityInstantaneous(Vector())
end
if IsValid(ent) and type(ent.APAt) == "table" then
ent.APAt["time stamp"] = CurTime()+0.15
if APA.Settings.AnnoySurf:GetBool() and isPlayer(c.HitEntity) then
ent.APANoPhysgun = (not ent.APANoPhysgun) and CurTime()+0.55 or ent.APANoPhysgun
if not IsValid(c.PhysObject) then return end
physStop(c.PhysObject)
physStop(c.HitEntity)
ent:ForcePlayerDrop()
c.PhysObject:EnableMotion(not APA.Settings.FreezeOnHit:GetBool())
c.PhysObject:SetVelocityInstantaneous(Vector(0,0,c.PhysObject:GetMass()*1.1))
c.PhysObject:Sleep()
end
if not isPlayer(c.HitEntity) then
timer.Simple(0.01, function()
if (speed > 95 or (IsValid(c.HitObject) and c.HitObject:GetVelocity():Length() > 75)) and not APA.IsWorld(c.HitEntity) then
if not ( c.HitEntity:GetNWBool("APABadEntity", false) ) then
APA.SetBadGroup(c.HitEntity,true)
else
ent.APAt["time stamp"] = CurTime()+0.15
end
end
end)
end
end
end
if not ent.APAfCallback then
ent.APAfCallback = ent:AddCallback( "PhysicsCollide", ent.APAtCallback )
end
if not table.HasValue(APABadEnts, ent) then
table.insert(APABadEnts, ent)
end
elseif ent and ent.APAt and type(ent.APAt) == 'table' then
log('[BadEntity]',ent,' is now a GOOD entity!') if APA.Settings.Debug:GetInt() > 0 then ent:SetColor(Color(255,255,255)) end
ent.APAt = nil
ent:SetNWBool("APABadEntity", false)
for _,v in next, constraint.GetAllConstrainedEntities(ent) do
if IsValid(v) then
v.APAForceBlock = nil
v.APAForceFreeze = nil
end
end
timer.Simple(3, function() if IsValid(ent) then ent.APANoPhysgun = nil end end)
table.RemoveByValue(APABadEnts, ent)
end
end
function APA.SetBadGroup(ent,bool)
local i = 0
local isvalid = function(v) return IsValid(v) and not v.PhysgunDisabled end
for _,v in next, constraint.GetAllConstrainedEntities(ent) do
if isvalid(v) then
timer.Simple((i <= 0 and i or i/100), function()
if isvalid(v) then
APA.SetBadEnt(v,bool)
end
end)
i = i + 1
end
end
end
function APA.IsEntBad(ent)
if ent and ent.APAt then return ent.APAt["block entity"] end
return ent:GetNWBool("APABadEntity", false)
end
timer.Create("APABaddieFinder", 0.75, 0, function()
for k,v in next, APABadEnts do
timer.Simple(k/100, function()
if v and v.APAt and v.APAt.Think then
v.APAt.Think()
end
end)
end
end)
hook.Add( "OnEntityCreated", "APAMethod0", function(ent)
timer.Simple(0.001, function()
if IsValid(ent) and not APA.IsWorld(ent) and not ent:IsVehicle() and not APA.Settings.Method:GetBool() then
APA.SetBadEnt(ent,true)
end
end)
end)
if APA.hasCPPI and APA.FindOwner then
hook.Add( "PhysgunPickup", "APAMethod0", function(ply,ent)
if (IsValid(ply) and IsValid(ent)) and ent.CPPICanPhysgun and ent:CPPICanPhysgun(ply) then
timer.Simple(0.001, function() -- Wierd hook order stuff.
if not APA.Settings.Method:GetBool() and not ent.PhysgunDisabled and IsValid(ent) then
APA.SetBadGroup(ent,true)
end
end)
end
end)
hook.Add( "CanTool", "APAMethod0", function(ply, tr, mode)
local ent = tr.Entity
if (IsValid(ply) and IsValid(ent)) and ent.CPPICanTool and ent:CPPICanTool(ply, mode) then
timer.Simple(0.01, function() -- Wierd hook order stuff.
if not APA.Settings.Method:GetBool() and not ent.PhysgunDisabled and IsValid(ent) then
APA.SetBadGroup(ent,true)
end
end)
end
end)
end
APA.initPlugin('method0') -- Init Plugin (Must match filename.)
|
local classic = require 'classic'
local DynaMaze, super = classic.class('DynaMaze', Env)
-- Constructor
function DynaMaze:_init(opts)
opts = opts or {}
super._init(self, opts)
-- Set change: none|blocking|shortcut
self.change = opts.change or 'none'
-- Create blank grid (y, x)
self.maze = torch.ByteTensor(6, 9):zero()
-- Place blocks
if self.change == 'none' then
self.maze[{{3, 5}, {3}}] = 1
self.maze[{{2}, {6}}] = 1
self.maze[{{4, 6}, {8}}] = 1
elseif self.change == 'blocking' then
self.maze[{{3}, {1, 8}}] = 1
elseif self.change == 'shortcut' then
self.maze[{{3}, {2, 9}}] = 1
end
-- Keep internal step counter
self.counter = 0
end
-- 2 states returned, of type 'int', of dimensionality 1, where x is 1-9 and y is 1-6
function DynaMaze:getStateSpace()
local state = {}
state['name'] = 'Box'
state['shape'] = {2}
state['low'] = {
1, -- x
1 -- y
}
state['high'] = {
9, -- x
6 -- y
}
return state
end
-- 1 action required, of type 'int', of dimensionality 1, between 1 and 4
function DynaMaze:getActionSpace()
local action = {}
action['name'] = 'Discrete'
action['n'] = 4
return action
end
-- Min and max reward
function DynaMaze:getRewardSpace()
return 0, 1
end
-- Reset position
function DynaMaze:_start()
if self.change == 'none' then
self.position = {1, 4}
else
self.position = {4, 1}
end
return self.position
end
-- Move up, right, down or left
function DynaMaze:_step(action)
action = action + 1 -- scale action
local reward = 0
local terminal = false
-- Calculate new position
local newX = self.position[1]
local newY = self.position[2]
if action == 1 then
-- Move up
newY = math.min(newY + 1, 6)
elseif action == 2 then
-- Move right
newX = math.min(newX + 1, 9)
elseif action == 3 then
-- Move down
newY = math.max(newY - 1, 1)
else
-- Move left
newX = math.max(newX - 1, 1)
end
-- Move if not blocked
if self.maze[{{newY}, {newX}}][1][1] == 0 then
self.position[1] = newX
self.position[2] = newY
end
-- Check if reached goal
if newX == 9 and newY == 6 then
reward = 1
terminal = true
end
-- Increment counter
self.counter = self.counter + 1
-- Change environment
if self.counter == 1000 and self.change == 'blocking' then
-- Open up hole in left of wall
self.maze[{{3}, {1}}] = 0
-- Fill up hole on right of wall
self.maze[{{3}, {9}}] = 1
-- Move agent in case it is now on top of wall
if self.position[1] == 9 and self.position[2] == 3 then
self.position[1] = 4
end
elseif self.counter == 3000 and self.change == 'shortcut' then
-- Open up hole in wall
self.maze[{{3}, {9}}] = 0
end
return reward, self.position, terminal
end
return DynaMaze
|
---
-- @author wesen
-- @copyright 2019-2020 wesen <wesen-ac@web.de>
-- @release 0.1
-- @license MIT
--
local Exception = require "AC-LuaServer.Core.Util.Exception.Exception"
---
-- The exception for the case that the remaining time of the current active game is attempted to be set to
-- a value that would cause a integer overflow that results in an instant game end.
--
-- @type MaximumRemainingTimeExceededException
--
local MaximumRemainingTimeExceededException = Exception:extend()
---
-- The exceedance of the maximum remaining time in milliseconds
--
-- @tfield int exceedanceInMilliseconds
--
MaximumRemainingTimeExceededException.exceedanceInMilliseconds = nil
---
-- The maximum allowed number of extend milliseconds
--
-- @tfield int maximumNumberOfExtendMilliseconds
--
MaximumRemainingTimeExceededException.maximumNumberOfExtendMilliseconds = nil
---
-- The time in milliseconds until the extra minute that may be unavailable because of the
-- integer overflow in the intermission check is available
--
-- @tfield int millisecondsUntilExtraMinuteCanBeUsed
--
MaximumRemainingTimeExceededException.millisecondsUntilExtraMinuteCanBeUsed = nil
---
-- MaximumRemainingTimeExceededException constructor.
--
-- @tparam int _exceedanceInMilliseconds The exceedance of the maximum remaining time in milliseconds
-- @tparam int _maximumNumberOfExtendMilliseconds The maxmimum allowed number of extend milliseconds
-- @tparam int _millisecondsUntilExtraMinuteCanBeUsed The time until the extra minute is available
--
function MaximumRemainingTimeExceededException:new(_exceedanceInMilliseconds, _maximumNumberOfExtendMilliseconds, _millisecondsUntilExtraMinuteCanBeUsed)
self.exceedanceInMilliseconds = _exceedanceInMilliseconds
self.maximumNumberOfExtendMilliseconds = _maximumNumberOfExtendMilliseconds
self.millisecondsUntilExtraMinuteCanBeUsed = _millisecondsUntilExtraMinuteCanBeUsed
end
-- Getters and Setters
---
-- Returns the exceedance of the maximum remaining time in milliseconds.
--
-- @treturn int The exceedance of the maximum remaining time in milliseconds
--
function MaximumRemainingTimeExceededException:getExceedanceInMilliseconds()
return self.exceedanceInMilliseconds
end
---
-- Returns the maxmimum allowed number of extend milliseconds.
--
-- @treturn int The maxmimum allowed number of extend milliseconds
--
function MaximumRemainingTimeExceededException:getMaximumNumberOfExtendMilliseconds()
return self.maximumNumberOfExtendMilliseconds
end
---
-- Returns the time until the extra minute is available.
--
-- @treturn int The time until the extra minute is available
--
function MaximumRemainingTimeExceededException:getMillisecondsUntilExtraMinuteCanBeUsed()
return self.millisecondsUntilExtraMinuteCanBeUsed
end
-- Public Methods
---
-- Returns this Exception's message as a string.
--
-- @treturn string The Exception message as a string
--
function MaximumRemainingTimeExceededException:getMessage()
return string.format(
"Could not set remaining time: Maximum remaining time would be exceeded by %i milliseconds",
self.exceedanceInMilliseconds
)
end
return MaximumRemainingTimeExceededException
|
-- "Dungeon Loot" [dungeon_loot]
-- Original by BlockMen, this entire file by Amoeba
--
-- config.lua
--
-- Note: All positive heights (above water level) are treated as depth 0.
-- Also, no comma after the item of a list.
-- Minimum number of rooms a dungeon should have for a chest to be generated
dungeon_loot.min_num_of_rooms = 4
-- Items on basic lists have three depth ranges for their listed amount
-- maximums; they get max/2 before first increase point (minimum of 1 if
-- amount is >0), the given max between the 1st and 2nd increase point,
-- and max*2 after the 2nd.
dungeon_loot.depth_first_basic_increase = 200
dungeon_loot.depth_second_basic_increase = 2000
-- The master list of loot types
-- Note that tools and weapons should always have max_amount = 1.
-- Chance is a probability between 0 (practically never) and 1 (always),
-- so change a chance to 0 if you don't want a type (eg. weapons) included
-- in your game (or -0.001 if you want to be REALLY sure).
dungeon_loot.loot_types = {
{name="treasure", max_amount = 10, chance = 0.7, type = "depth_cutoff"},
{name="tools", max_amount = 1, chance = 0.5, type = "depth_cutoff"},
{name="weapons", max_amount = 1, chance = 0.1, type = "depth_cutoff"},
{name="consumables", max_amount = 80, chance = 0.9, type = "basic_list"},
{name="seedlings", max_amount = 5, chance = 0.3, type = "basic_list"}
}
-- Loot type lists; these names MUST be exactly of the format:
-- "dungeon_loot.name_list" where "name" is in the above list
-- Depth cutoff lists
-- These must be in order of increasing depth (but can include the same item
-- more than once). Method: a random number between 1 and chest depth is
-- chosen, and the item in that range is added to the loot. Then, there's
-- a chance additional items of the same type are added to stack; if the
-- random number is much greater than the item's min_depth, the amount
-- can grow pretty big.
dungeon_loot.treasure_list = {
{name="default:steel_ingot", min_depth = 0},
{name="default:bronze_ingot", min_depth = 20},
{name="default:gold_ingot", min_depth = 45},
{name="default:diamond", min_depth = 150},
{name="default:gold_block", min_depth = 777},
{name="default:emerald", min_depth = 800},
{name="default:diamond_block", min_depth = 1800},
{name="default:emerald", min_depth = 2000}
}
dungeon_loot.tools_list = {
{name="default:pick_steel", min_depth = 0},
{name="default:shovel_diamond", min_depth = 38},
{name="default:pick_bronze", min_depth = 40},
{name="default:axe_diamond", min_depth = 95},
{name="default:pick_diamond", min_depth = 100}
}
dungeon_loot.weapons_list = {
{name="default:sword_steel", min_depth = 0},
{name="default:sword_bronze", min_depth = 50},
{name="default:sword_diamond", min_depth = 250}
}
-- Basic lists
-- These can be of two types, either with combined chance and amount,
-- or with the two variables separated. "chance" means each item has a
-- N/M chance of being chosen, where N is it's own chance and M is the
-- total sum of chances on the list. "amount" is the maximum amount of
-- items given at the middle depth range.
dungeon_loot.consumables_list = {
{name="default:apple", chance_and_amount = 20},
{name="default:torch", chance_and_amount = 30},
{name="default:stick", chance_and_amount = 10}
}
dungeon_loot.seedlings_list = {
{name="default:sapling", chance = 5, amount = 2},
{name="default:pine_sapling", chance = 10, amount = 2},
{name="default:junglesapling", chance = 15, amount = 2},
{name="default:acacia_sapling", chance = 15, amount = 2}
}
-- Add items from other mods here inside the appropriate
-- "if ... then ... end" test
-- For basic lists, just using insert without a value works fine.
-- For depth cutoff lists, you can use insert with a table index, eg.
-- table.insert(dungeon_loot.treasure_list, 5, {name="your_mod:platinum_ingot", min_depth = 120}
-- The above would add a new item to the treasure list as the 5th item,
-- moving diamond and all below it one down in the list. Just make sure
-- that the increasing min_depth order is kept.
-- Tips: With multiple insertions in a depth cutoff list, start from the
-- last item and work towards the beginning, then you don't have to calculate
-- your number of additions. Also, trying to make sure too many different
-- mods work together in a single list will probably give you a headache;
-- just create a new list (or two) for mods with lots of additions.
if minetest.get_modpath("farming") then
table.insert(dungeon_loot.consumables_list, {name="farming:bread", chance_and_amount = 10})
table.insert(dungeon_loot.seedlings_list, {name="farming:seed_wheat", chance = 1, amount = 10})
table.insert(dungeon_loot.seedlings_list, {name="farming:seed_cotton", chance = 20, amount = 5})
end
|
--- === hs.geometry ===
---
--- Mathematical functions
local geometry = require "hs.geometry.internal"
--- hs.geometry.rotateCCW(point, aroundpoint, ntimes = 1) -> point
--- Function
--- Rotates a point around another point N times.
function geometry.rotateCCW(point, aroundpoint, ntimes)
local p = {x = point.x, y = point.y}
for i = 1, ntimes or 1 do
local px = p.x
p.x = (aroundpoint.x - (p.y - aroundpoint.y))
p.y = (aroundpoint.y + (px - aroundpoint.x))
end
return p
end
--- hs.geometry.hypot(point) -> number
--- Function
--- Returns hypotenuse of a line defined from 0,0 to point.
function geometry.hypot(p)
return math.sqrt(p.x * p.x + p.y * p.y)
end
--- hs.geometry.rect(x, y, w, h) -> rect
--- Constructor
--- Convenience function for creating a rect-table.
function geometry.rect(x, y, w, h)
return {x = x, y = y, w = w, h = h}
end
--- hs.geometry.point(x, y) -> point
--- Constructor
--- Convenience function for creating a point-table.
function geometry.point(x, y)
return {x = x, y = y}
end
--- hs.geometry.size(w, h) -> size
--- Constructor
--- Convenience function for creating a size-table.
function geometry.size(w, h)
return {w = w, h = h}
end
--- hs.geometry.isPointInRect(point, rect) -> bool
--- Function
--- Tests whether a point falls inside a rect
---
--- Parameters:
--- * point - A table containing x and y co-ordinates
--- * rect - A table containing x and y co-ordinates, and w(idth) and h(eight) values
---
--- Returns:
--- * True if the point falls inside the rect, otherwise false
function geometry.isPointInRect(point, rect)
if (point["x"] >= rect["x"] and
point["y"] >= rect["y"] and
point["x"] < (rect["x"] + rect["w"]) and
point["y"] < (rect["y"] + rect["h"])) then
return true
end
return false
end
return geometry
|
-----------------------------------
-- Area: Mount Zhayolm
-- Door: Runic Seal
-- !pos 703 -18 382 61
-----------------------------------
local ID = require("scripts/zones/Mount_Zhayolm/IDs")
require("scripts/globals/besieged")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if player:hasKeyItem(tpz.ki.LEBROS_ASSAULT_ORDERS) then
local assaultid = player:getCurrentAssault()
local recommendedLevel = getRecommendedAssaultLevel(assaultid)
local armband = player:hasKeyItem(tpz.ki.ASSAULT_ARMBAND) and 1 or 0
player:startEvent(203, assaultid, -4, 0, recommendedLevel, 2, armband)
else
player:messageSpecial(ID.text.NOTHING_HAPPENS)
end
end
function onEventUpdate(player, csid, option, target)
local assaultid = player:getCurrentAssault()
local cap = bit.band(option, 0x03)
if cap == 0 then
cap = 99
elseif cap == 1 then
cap = 70
elseif cap == 2 then
cap = 60
else
cap = 50
end
player:setCharVar("AssaultCap", cap)
local party = player:getParty()
if party then
for i, v in ipairs(party) do
if not (v:hasKeyItem(tpz.ki.LEBROS_ASSAULT_ORDERS) and v:getCurrentAssault() == assaultid) then
player:messageText(target, ID.text.MEMBER_NO_REQS, false)
player:instanceEntry(target, 1)
return
elseif v:getZoneID() == player:getZoneID() and v:checkDistance(player) > 50 then
player:messageText(target, ID.text.MEMBER_TOO_FAR, false)
player:instanceEntry(target, 1)
return
end
end
end
player:createInstance(player:getCurrentAssault(), 63)
end
function onEventFinish(player, csid, option, target)
if csid == 208 or (csid == 203 and option == 4) then
player:setPos(0, 0, 0, 0, 63)
end
end
function onInstanceCreated(player, target, instance)
if instance then
instance:setLevelCap(player:getCharVar("AssaultCap"))
player:setCharVar("AssaultCap", 0)
player:setInstance(instance)
player:instanceEntry(target, 4)
player:delKeyItem(tpz.ki.LEBROS_ASSAULT_ORDERS)
player:delKeyItem(tpz.ki.ASSAULT_ARMBAND)
local party = player:getParty()
if party then
for i, v in ipairs(party) do
if v:getID() ~= player:getID() and v:getZoneID() == player:getZoneID() then
v:setInstance(instance)
v:startEvent(208, 2)
v:delKeyItem(tpz.ki.LEBROS_ASSAULT_ORDERS)
end
end
end
else
player:messageText(target, ID.text.CANNOT_ENTER, false)
player:instanceEntry(target, 3)
end
end
|
--------------------------------------------------------------------------------
-- Clientside utility functions
--------------------------------------------------------------------------------
local bitmap_font_1 = {
[10] = {
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0},
["."] = {
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,1,0},
[1] = {
0,0,0,1,
0,0,0,1,
0,0,0,1,
0,0,0,1,
0,0,0,1,
0,0,0,1,
0,0,0,1},
[2] = {
1,1,1,1,
0,0,0,1,
0,0,0,1,
1,1,1,1,
1,0,0,0,
1,0,0,0,
1,1,1,1},
[3] = {
1,1,1,1,
0,0,0,1,
0,0,0,1,
1,1,1,1,
0,0,0,1,
0,0,0,1,
1,1,1,1},
[4] = {
1,0,0,1,
1,0,0,1,
1,0,0,1,
1,1,1,1,
0,0,0,1,
0,0,0,1,
0,0,0,1},
[5] = {
1,1,1,1,
1,0,0,0,
1,0,0,0,
1,1,1,1,
0,0,0,1,
0,0,0,1,
1,1,1,1},
[6] = {
1,1,1,1,
1,0,0,0,
1,0,0,0,
1,1,1,1,
1,0,0,1,
1,0,0,1,
1,1,1,1},
[7] = {
1,1,1,1,
0,0,0,1,
0,0,0,1,
0,0,0,1,
0,0,0,1,
0,0,0,1,
0,0,0,1},
[8] = {
1,1,1,1,
1,0,0,1,
1,0,0,1,
1,1,1,1,
1,0,0,1,
1,0,0,1,
1,1,1,1},
[9] = {
1,1,1,1,
1,0,0,1,
1,0,0,1,
1,1,1,1,
0,0,0,1,
0,0,0,1,
0,0,0,1},
[0] = {
1,1,1,1,
1,0,0,1,
1,0,0,1,
1,0,0,1,
1,0,0,1,
1,0,0,1,
1,1,1,1},
}
--------------------------------------------------------------------------------
-- Draw bitmap digit
function Metrostroi.DrawClockDigit(cx,cy,scale,digit)
local bitmap = bitmap_font_1[digit]
if not bitmap then return end
local w=12*scale
local p=8*scale
for i=1,4*7 do
local x = (i-1)%4
local y = math.floor((i-1)/4)
if bitmap[i] == 1 then
for z=1,6,1 do
surface.SetDrawColor(Color(255,60,0,math.max(0,30-1*z*z)))
surface.DrawRect(cx+x*w-z*scale, cy+y*w-z*scale, p+2*z*scale, p+2*z*scale)
end
surface.SetDrawColor(Color(255,240,0,255))
surface.DrawRect(cx+x*w, cy+y*w, p, p)
end
end
end
function Metrostroi.PositionFromPanel(panel,button_id_or_vec,z,x,y,train)
local self = train or ENT
local panel = self.ButtonMap[panel]
if not panel then return Vector(0,0,0) end
if not panel.buttons then return Vector(0,0,0) end
-- Find button or read position
local vec
if type(button_id_or_vec) == "string" then
local button
for k,v in pairs(panel.buttons) do
if v.ID == button_id_or_vec then
button = v
break
end
end
vec = Vector(button.x + (button.radius and 0 or (button.w or 0)/2)+(x or 0),button.y + (button.radius and 0 or (button.h or 0)/2)+(y or 0),z or 0)
else
vec = button_id_or_vec
end
-- Convert to global coords
vec.y = -vec.y
vec:Rotate(panel.ang)
return panel.pos + vec * panel.scale
end
function Metrostroi.AngleFromPanel(panel,ang,train)
local self = train or ENT
local panel = self.ButtonMap[panel]
if not panel then return Vector(0,0,0) end
local true_ang = panel.ang + Angle(0,0,0)
if type(ang) == "Angle" then
true_ang:RotateAroundAxis(panel.ang:Forward(),ang.pitch)
true_ang:RotateAroundAxis(panel.ang:Right(),ang.yaw)
true_ang:RotateAroundAxis(panel.ang:Up(),ang.roll)
else
true_ang:RotateAroundAxis(panel.ang:Up(),ang or -90)
end
return true_ang
end
function Metrostroi.GenerateClientProps()
local self = ENT
local ret = "self.table = {\n"
--local reti = 0
for id, panel in pairs(self.ButtonMap) do
if not panel.buttons then continue end
if not panel.props then panel.props = {} end
for name, buttons in pairs(panel.buttons) do
--if reti > 8 then reti=0; ret=ret.."\n" end
if buttons.model then
local config = buttons.model
local name = config.name or buttons.ID
if config.model then
table.insert(panel.props,name)
self.ClientProps[name] = {
model = config.model or "models/metrostroi/81-717/button07.mdl",
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2),(config.x or 0),(config.y or 0)),
ang = Metrostroi.AngleFromPanel(id,config.ang),
color = config.color,
colora = config.colora,
skin = config.skin or 0,
config = config,
cabin = config.cabin,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = config.bscale,
scale = config.scale,
}
if config.var then
--ret=ret.."\""..config.var.."\","
--reti = reti + 1
if config.ratio then
else
local var = config.var
local vmin, vmax = config.vmin or 0,config.vmax or 1
local min,max = config.min or 0,config.max or 1
local speed,damping,stickyness = config.speed or 16,config.damping or false,config.stickyness or nil
local func = config.getfunc
if func then
if config.disable then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,func(ent,vmin,vmax,var),min,max,speed,damping,stickyness)
ent:HideButton(config.disable,ent:GetPackedBool(var))
end)
elseif config.disableinv then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,func(ent,vmin,vmax,var),min,max,speed,damping,stickyness)
ent:HideButton(config.disableinv,not ent:GetPackedBool(var))
end)
elseif config.disableoff and config.disableon then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,func(ent,vmin,vmax,var),min,max,speed,damping,stickyness)
ent:HideButton(config.disableoff,ent:GetPackedBool(var))
ent:HideButton(config.disableon,not ent:GetPackedBool(var))
end)
elseif config.disablevar then
table.insert(self.AutoAnims, function(ent)
ent:HideButton(name,ent:GetPackedBool(config.disablevar))
ent:Animate(name,func(ent,vmin,vmax,var),min,max,speed,damping,stickyness)
end)
else
table.insert(self.AutoAnims, function(ent) ent:Animate(name,func(ent,vmin,vmax),min,max,speed,damping,stickyness) end)
end
else
if config.disable then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness)
ent:HideButton(config.disable,ent:GetPackedBool(var))
end)
elseif config.disableinv then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness)
ent:HideButton(config.disableinv,not ent:GetPackedBool(var))
end)
elseif config.disableoff and config.disableon then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness)
ent:HideButton(config.disableoff,ent:GetPackedBool(var))
ent:HideButton(config.disableon,not ent:GetPackedBool(var))
end)
elseif config.disablevar then
table.insert(self.AutoAnims, function(ent)
ent:HideButton(name,ent:GetPackedBool(config.disablevar))
ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness)
end)
else
table.insert(self.AutoAnims, function(ent) ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness) end)
end
end
end
end
end
if config.sound or config.sndvol and config.var then
local id = config.sound or config.var
local sndid = config.sndid or buttons.ID
local vol,pitch,min,max = config.sndvol, config.sndpitch,config.sndmin,config.sndmax
local func,snd = config.getfunc, config.snd
local vmin, vmax = config.vmin or 0,config.vmax or 1
local var = config.var
local ang = config.sndang
--if func then
--self.ClientSounds[id] = {sndid,function(ent,var) return snd(func(ent,vmin,vmax),var) end,vol or 1,pitch or 1,min or 100,max or 1000,ang or Angle(0,0,0)}
--else
if not self.ClientSounds[id] then self.ClientSounds[id] = {} end
table.insert(self.ClientSounds[id],{sndid,function(ent,var) return snd(var > 0,var) end,vol or 1,pitch or 1,min or 100,max or 1000,ang or Angle(0,0,0)})
--end
end
if config.plomb then
local pconfig = config.plomb
local pname = name.."_pl"
if pconfig.model then
table.insert(panel.props,pname)
self.ClientProps[pname] = {
model = pconfig.model,
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2)+(pconfig.z or 0.2),(config.x or 0)+(pconfig.x or 0),(config.y or 0)+(pconfig.y or 0)),
ang = Metrostroi.AngleFromPanel(id,pconfig.ang or config.ang),
color = pconfig.color or pconfig.color,
skin = pconfig.skin or config.skin or 0,
config = pconfig,
cabin = pconfig.cabin,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = pconfig.bscale or config.bscale,
scale = pconfig.scale or config.scale,
}
end
if pconfig.var then
local var = pconfig.var
if pconfig.model then
table.insert(self.AutoAnims, function(ent)
ent:SetCSBodygroup(pname,1,ent:GetPackedBool(var) and 0 or 1)
end)
end
local id,tooltip = buttons.ID,buttons.tooltip
local pid,ptooltip = pconfig.ID,pconfig.tooltip
buttons.plombed = function(ent)
if ent:GetPackedBool(var) then
return Format("%s\n%s",buttons.tooltip,Metrostroi.GetPhrase("Train.Buttons.Sealed") or "Plombed"),pid,Color(255,150,150),true
else
return buttons.tooltip,id,false
end
end
end
--[[
if pconfig.var then
--ret=ret.."\""..pconfig.var.."\","
--reti = reti + 1
local var,animvar = pconfig.var,lname.."_anim"
local min,max = pconfig.min or 0,pconfig.max or 1
local speed = pconfig.speed or 10
table.insert(self.AutoAnims, function(ent)
--print(lname,ent.SmoothHide[lname])
local val = ent:Animate(animvar,ent:GetPackedBool(var) and max or min,0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
end]]
end
if config.lamp then
local lconfig = config.lamp
local lname = name.."_lamp"
table.insert(panel.props,lname)
self.ClientProps[lname] = {
model = lconfig.model or "models/metrostroi/81-717/button07.mdl",
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2)+(lconfig.z or 0.2),(config.x or 0)+(lconfig.x or 0),(config.y or 0)+(lconfig.y or 0)),
ang = Metrostroi.AngleFromPanel(id,lconfig.ang or config.ang),
color = lconfig.color or config.color,
skin = lconfig.skin or config.skin or 0,
config = lconfig,
cabin = lconfig.cabin,
igrorepanel = true,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = lconfig.bscale or config.bscale,
scale = lconfig.scale or config.scale,
}
if lconfig.anim then
table.insert(self.AutoAnims, function(ent)
ent:AnimateFrom(lname,name)
end)
end
if lconfig.var then
--ret=ret.."\""..lconfig.var.."\","
--reti = reti + 1
local var,animvar = lconfig.var,lname.."_anim"
local min,max = lconfig.min or 0,lconfig.max or 1
local speed = lconfig.speed or 10
local func = lconfig.getfunc
if func then
table.insert(self.AutoAnims, function(ent)
local val = ent:Animate(animvar,func(ent,min,max,var),0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
else
table.insert(self.AutoAnims, function(ent)
--print(lname,ent.SmoothHide[lname])
local val = ent:Animate(animvar,ent:GetPackedBool(var) and max or min,0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
end
end
end
if config.lamps then
for k,lconfig in ipairs(config.lamps) do
local lname = name.."_lamp"..k
table.insert(panel.props,lname)
self.ClientProps[lname] = {
model = lconfig.model or "models/metrostroi/81-717/button07.mdl",
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2)+(lconfig.z or 0.2),(config.x or 0)+(lconfig.x or 0),(config.y or 0)+(lconfig.y or 0)),
ang = Metrostroi.AngleFromPanel(id,lconfig.ang or config.ang),
color = lconfig.color or config.color,
skin = lconfig.skin or config.skin or 0,
config = lconfig,
cabin = lconfig.cabin,
igrorepanel = true,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = lconfig.bscale or config.bscale,
scale = lconfig.scale or config.scale,
}
if lconfig.anim then
table.insert(self.AutoAnims, function(ent)
ent:AnimateFrom(lname,name)
end)
end
if lconfig.var then
--ret=ret.."\""..lconfig.var.."\","
--reti = reti + 1
local var,animvar = lconfig.var,lname.."_anim"
local min,max = lconfig.min or 0,lconfig.max or 1
local speed = lconfig.speed or 10
local func = lconfig.getfunc
if func then
table.insert(self.AutoAnims, function(ent)
local val = ent:Animate(animvar,func(ent,min,max,var),0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
else
table.insert(self.AutoAnims, function(ent)
--print(lname,ent.SmoothHide[lname])
local val = ent:Animate(animvar,ent:GetPackedBool(var) and max or min,0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
end
end
end
end
if config.labels then
for k,aconfig in ipairs(config.labels) do
local aname = name.."_label"..k
table.insert(panel.props,aname)
self.ClientProps[aname] = {
model = aconfig.model or "models/metrostroi/81-717/button07.mdl",
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2)+(aconfig.z or 0.2),(config.x or 0)+(aconfig.x or 0),(config.y or 0)+(aconfig.y or 0)),
ang = Metrostroi.AngleFromPanel(id,aconfig.ang or config.ang),
color = aconfig.color or config.color,
colora = aconfig.colora or config.colora,
skin = aconfig.skin or config.skin or 0,
config = aconfig,
cabin = aconfig.cabin,
igrorepanel = true,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = aconfig.bscale or config.bscale,
scale = aconfig.scale or config.scale,
}
end
end
buttons.model = nil
end
end
end
end
function Metrostroi.GenerateClientProps()
local self = ENT
local ret = "self.table = {\n"
--local reti = 0
for id, panel in pairs(self.ButtonMap) do
if not panel.buttons then continue end
if not panel.props then panel.props = {} end
for name, buttons in pairs(panel.buttons) do
--if reti > 8 then reti=0; ret=ret.."\n" end
if buttons.model then
local config = buttons.model
local name = config.name or buttons.ID
if config.model then
table.insert(panel.props,name)
self.ClientProps[name] = {
model = config.model or "models/metrostroi/81-717/button07.mdl",
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2),(config.x or 0),(config.y or 0)),
ang = Metrostroi.AngleFromPanel(id,config.ang),
color = config.color,
colora = config.colora,
skin = config.skin or 0,
config = config,
cabin = config.cabin,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = config.bscale,
scale = config.scale,
}
if config.var then
--ret=ret.."\""..config.var.."\","
--reti = reti + 1
if config.ratio then
else
local var = config.var
local vmin, vmax = config.vmin or 0,config.vmax or 1
local min,max = config.min or 0,config.max or 1
local speed,damping,stickyness = config.speed or 16,config.damping or false,config.stickyness or nil
local func = config.getfunc
if func then
if config.disable then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,func(ent,vmin,vmax,var),min,max,speed,damping,stickyness)
ent:HideButton(config.disable,ent:GetPackedBool(var))
end)
elseif config.disableinv then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,func(ent,vmin,vmax,var),min,max,speed,damping,stickyness)
ent:HideButton(config.disableinv,not ent:GetPackedBool(var))
end)
elseif config.disableoff and config.disableon then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,func(ent,vmin,vmax,var),min,max,speed,damping,stickyness)
ent:HideButton(config.disableoff,ent:GetPackedBool(var))
ent:HideButton(config.disableon,not ent:GetPackedBool(var))
end)
elseif config.disablevar then
table.insert(self.AutoAnims, function(ent)
ent:HideButton(name,ent:GetPackedBool(config.disablevar))
ent:Animate(name,func(ent,vmin,vmax,var),min,max,speed,damping,stickyness)
end)
else
table.insert(self.AutoAnims, function(ent) ent:Animate(name,func(ent,vmin,vmax),min,max,speed,damping,stickyness) end)
end
else
if config.disable then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness)
ent:HideButton(config.disable,ent:GetPackedBool(var))
end)
elseif config.disableinv then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness)
ent:HideButton(config.disableinv,not ent:GetPackedBool(var))
end)
elseif config.disableoff and config.disableon then
table.insert(self.AutoAnims, function(ent)
ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness)
ent:HideButton(config.disableoff,ent:GetPackedBool(var))
ent:HideButton(config.disableon,not ent:GetPackedBool(var))
end)
elseif config.disablevar then
table.insert(self.AutoAnims, function(ent)
ent:HideButton(name,ent:GetPackedBool(config.disablevar))
ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness)
end)
else
table.insert(self.AutoAnims, function(ent) ent:Animate(name,ent:GetPackedBool(var) and vmax or vmin,min,max,speed,damping,stickyness) end)
end
end
end
end
end
if config.sound or config.sndvol and config.var then
local id = config.sound or config.var
local sndid = config.sndid or buttons.ID
local vol,pitch,min,max = config.sndvol, config.sndpitch,config.sndmin,config.sndmax
local func,snd = config.getfunc, config.snd
local vmin, vmax = config.vmin or 0,config.vmax or 1
local var = config.var
local ang = config.sndang
--if func then
--self.ClientSounds[id] = {sndid,function(ent,var) return snd(func(ent,vmin,vmax),var) end,vol or 1,pitch or 1,min or 100,max or 1000,ang or Angle(0,0,0)}
--else
if not self.ClientSounds[id] then self.ClientSounds[id] = {} end
table.insert(self.ClientSounds[id],{sndid,function(ent,var) return snd(var > 0,var) end,vol or 1,pitch or 1,min or 100,max or 1000,ang or Angle(0,0,0)})
--end
end
if config.plomb then
local pconfig = config.plomb
local pname = name.."_pl"
if pconfig.model then
table.insert(panel.props,pname)
self.ClientProps[pname] = {
model = pconfig.model,
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2)+(pconfig.z or 0.2),(config.x or 0)+(pconfig.x or 0),(config.y or 0)+(pconfig.y or 0)),
ang = Metrostroi.AngleFromPanel(id,pconfig.ang or config.ang),
color = pconfig.color or pconfig.color,
skin = pconfig.skin or config.skin or 0,
config = pconfig,
cabin = pconfig.cabin,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = pconfig.bscale or config.bscale,
scale = pconfig.scale or config.scale,
}
end
if pconfig.var then
local var = pconfig.var
if pconfig.model then
table.insert(self.AutoAnims, function(ent)
ent:SetCSBodygroup(pname,1,ent:GetPackedBool(var) and 0 or 1)
end)
end
local id,tooltip = buttons.ID,buttons.tooltip
local pid,ptooltip = pconfig.ID,pconfig.tooltip
buttons.plombed = function(ent)
if ent:GetPackedBool(var) then
return Format("%s\n%s",buttons.tooltip,Metrostroi.GetPhrase("Train.Buttons.Sealed") or "Plombed"),pid,Color(255,150,150),true
else
return buttons.tooltip,id,false
end
end
end
--[[
if pconfig.var then
--ret=ret.."\""..pconfig.var.."\","
--reti = reti + 1
local var,animvar = pconfig.var,lname.."_anim"
local min,max = pconfig.min or 0,pconfig.max or 1
local speed = pconfig.speed or 10
table.insert(self.AutoAnims, function(ent)
--print(lname,ent.SmoothHide[lname])
local val = ent:Animate(animvar,ent:GetPackedBool(var) and max or min,0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
end]]
end
if config.lamp then
local lconfig = config.lamp
local lname = name.."_lamp"
table.insert(panel.props,lname)
self.ClientProps[lname] = {
model = lconfig.model or "models/metrostroi/81-717/button07.mdl",
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2)+(lconfig.z or 0.2),(config.x or 0)+(lconfig.x or 0),(config.y or 0)+(lconfig.y or 0)),
ang = Metrostroi.AngleFromPanel(id,lconfig.ang or config.ang),
color = lconfig.color or config.color,
skin = lconfig.skin or config.skin or 0,
config = lconfig,
cabin = lconfig.cabin,
igrorepanel = true,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = lconfig.bscale or config.bscale,
scale = lconfig.scale or config.scale,
}
if lconfig.anim then
table.insert(self.AutoAnims, function(ent)
ent:AnimateFrom(lname,name)
end)
end
if lconfig.var then
--ret=ret.."\""..lconfig.var.."\","
--reti = reti + 1
local var,animvar = lconfig.var,lname.."_anim"
local min,max = lconfig.min or 0,lconfig.max or 1
local speed = lconfig.speed or 10
local func = lconfig.getfunc
local hide = lconfig.hidden
if func then
if hide then
table.insert(self.AutoAnims, function(ent)
if ent.Hidden[hide] then return end
local val = ent:Animate(animvar,func(ent,min,max,var),0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
else
table.insert(self.AutoAnims, function(ent)
local val = ent:Animate(animvar,func(ent,min,max,var),0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
end
else
if hide then
table.insert(self.AutoAnims, function(ent)
if ent.Hidden[hide] then return end
--print(lname,ent.SmoothHide[lname])
local val = ent:Animate(animvar,ent:GetPackedBool(var) and max or min,0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
else
table.insert(self.AutoAnims, function(ent)
--print(lname,ent.SmoothHide[lname])
local val = ent:Animate(animvar,ent:GetPackedBool(var) and max or min,0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
end
end
end
end
if config.lamps then
for k,lconfig in ipairs(config.lamps) do
local lname = name.."_lamp"..k
table.insert(panel.props,lname)
self.ClientProps[lname] = {
model = lconfig.model or "models/metrostroi/81-717/button07.mdl",
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2)+(lconfig.z or 0.2),(config.x or 0)+(lconfig.x or 0),(config.y or 0)+(lconfig.y or 0)),
ang = Metrostroi.AngleFromPanel(id,lconfig.ang or config.ang),
color = lconfig.color or config.color,
skin = lconfig.skin or config.skin or 0,
config = lconfig,
cabin = lconfig.cabin,
igrorepanel = true,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = lconfig.bscale or config.bscale,
scale = lconfig.scale or config.scale,
}
if lconfig.anim then
table.insert(self.AutoAnims, function(ent)
ent:AnimateFrom(lname,name)
end)
end
if lconfig.var then
--ret=ret.."\""..lconfig.var.."\","
--reti = reti + 1
local var,animvar = lconfig.var,lname.."_anim"
local min,max = lconfig.min or 0,lconfig.max or 1
local speed = lconfig.speed or 10
local func = lconfig.getfunc
if func then
if lconfig.hidden then
table.insert(self.AutoAnims, function(ent)
local val = ent:Animate(animvar,func(ent,min,max,var),0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
else
table.insert(self.AutoAnims, function(ent)
local val = ent:Animate(animvar,func(ent,min,max,var),0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
end
else
table.insert(self.AutoAnims, function(ent)
--print(lname,ent.SmoothHide[lname])
local val = ent:Animate(animvar,ent:GetPackedBool(var) and max or min,0,1,speed,false)
ent:ShowHideSmooth(lname,val)
end)
end
end
end
end
if config.labels then
for k,aconfig in ipairs(config.labels) do
local aname = name.."_label"..k
table.insert(panel.props,aname)
self.ClientProps[aname] = {
model = aconfig.model or "models/metrostroi/81-717/button07.mdl",
pos = Metrostroi.PositionFromPanel(id,config.pos or buttons.ID,(config.z or 0.2)+(aconfig.z or 0.2),(config.x or 0)+(aconfig.x or 0),(config.y or 0)+(aconfig.y or 0)),
ang = Metrostroi.AngleFromPanel(id,aconfig.ang or config.ang),
color = aconfig.color or config.color,
colora = aconfig.colora or config.colora,
skin = aconfig.skin or config.skin or 0,
config = aconfig,
cabin = aconfig.cabin,
igrorepanel = true,
hide = panel.hide or config.hide,
hideseat = panel.hideseat or config.hideseat,
bscale = aconfig.bscale or config.bscale,
scale = aconfig.scale or config.scale,
}
end
end
buttons.model = nil
end
end
end
--ret = ret.."\n}"
--SetClipboardText(ret)
end
function Metrostroi.InsertHide(panel,prop_name)
local self = ENT
if self.ButtonMap[panel] then
if not self.ButtonMap[panel].props then self.ButtonMap[panel].props = {} end
table.insert(self.ButtonMap[panel].props,prop_name)
end
end
--------------------------------------------------------------------------------
-- Training markers
--------------------------------------------------------------------------------
local prevV = 0
local A = 0
local D1true = 0
local D2true = 0
local prevTime
hook.Add("PostDrawOpaqueRenderables", "metrostroi-draw-stopmarker",function()
prevTime = prevTime or RealTime()
local dT = math.max(0.001,RealTime() - prevTime)
prevTime = RealTime()
-- Skip if disabled
if GetConVarNumber("metrostroi_stop_helper") ~= 1 then return end
-- Get seat and train
local seat = LocalPlayer():GetVehicle()
if not seat then return end
local train = seat:GetNW2Entity("TrainEntity")
if not IsValid(train) then return end
-- Calculate acceleration
local V = train:GetNW2Float("V",train:GetVelocity():Length()*0.01905)*0.277778
local newA = (V - prevV)/dT
prevV = V
-- Calculate marker position
A = train:GetNW2Float("A",A + (newA - A)*1.0*dT)
local T1 = math.abs(V/(A+1e-8))
local T2 = math.abs(V/(1.2+1e-8))
local D1 = T1*V + (T1^2)*A/2
local D2 = T2*V + (T2^2)*A/2
-- Smooth out D
D1 = math.min(200,math.max(0,D1))*0.65
D2 = math.min(200,math.max(0,D2))*0.70
D1true = D1true + (D1 - D1true)*12.0*dT
D2true = D2true + (D2 - D2true)*12.0*dT
local offset1 = D1true/0.01905
local offset2 = D2true/0.01905
-- Draw marker
if A > -0.1 then return end
-- if D1 > 195 then return end
if D2 > 195 then return end
local base_pos1 = train:LocalToWorld(Vector(500+offset1,80,10))
cam.Start3D2D(base_pos1,train:LocalToWorldAngles(Angle(0,-90,90)),1.0)
surface.SetDrawColor(255,255,255)
surface.DrawRect(-1,-1,8*20+2,4+2)
for i=0,19 do
surface.SetDrawColor(240,200,40)
surface.DrawRect(8*i+0,0,4,4)
surface.SetDrawColor(0,0,0)
surface.DrawRect(8*i+4,0,4,4)
end
surface.SetDrawColor(255,255,255)
surface.DrawRect(-1,-96,2,192)
surface.DrawRect(8*20,-96,2,192)
-- surface.SetTextColor(255,255,255)
-- surface.SetFont("Trebuchet24")
-- surface.SetTextPos(64-128,-30)
-- surface.DrawText(Format("%.1f m %.1f m/s %.1f m/s2",D,V,A))
-- surface.SetTextPos(64,-30)
-- surface.DrawText(Format("%.1f m %.0f sec",D,T))
cam.End3D2D()
local base_pos2 = train:LocalToWorld(Vector(500+offset2,80,10))
cam.Start3D2D(base_pos2,train:LocalToWorldAngles(Angle(0,-90,90)),1.0)
surface.SetDrawColor(240,40,40)
surface.DrawRect(-1,-1,8*20+2,4+2)
for i=0,19 do
surface.SetDrawColor(0,0,0)
surface.DrawRect(8*i+0,0,4,4)
surface.SetDrawColor(240,40,40)
surface.DrawRect(8*i+4,0,4,4)
end
surface.SetDrawColor(240,40,40)
surface.DrawRect(-1,-1+110,8*20+2,16+2)
for i=0,19 do
surface.SetDrawColor(0,0,0)
surface.DrawRect(8*i+0,110,4,16)
surface.SetDrawColor(240,40,40)
surface.DrawRect(8*i+4,110,4,16)
end
surface.SetDrawColor(240,40,40)
surface.DrawRect(-6,-96,6,192)
surface.DrawRect(8*20,-96,4,192)
cam.End3D2D()
end)
--------------------------------------------------------------------------------
-- Fix for gm_metrostroi 3D sky
--------------------------------------------------------------------------------
local player_state = {}
timer.Create("Metrostroi_3DSkyFix",1.0,0,function()
local player = LocalPlayer()
if not IsValid(player) then return end
if string.sub(game.GetMap(),1,13) ~= "gm_metrostroi" then return end
RunConsoleCommand("r_3dsky", (player:GetPos().z < -1024) and "0" or "1")
end)
function Metrostroi.GetTimedT(notsync)
local T0 = GetGlobalFloat("MetrostroiT0",os.time())+GetGlobalFloat("MetrostroiTY")
local T1 = GetGlobalFloat("MetrostroiT1",CurTime())
local dT
if notsync then
dT = (os.time()-T0) - (CurTime()-T1)
else
dT = (os.time()-T0 + (CurTime() % 1.0)) - (CurTime()-T1)
end
return dT
end
function Metrostroi.GetSyncTime(notsync)
return os.time()-Metrostroi.GetTimedT(notsync)
end
timer.Simple(0,function()
net.Start("MetrostroiUpdateTimeSync")
net.SendToServer()
end)
timer.Simple(0,function()
net.Start("metrostroi_cam_update") net.SendToServer()
end)
net.Receive("metrostroi_cam_update",function()
local ent = Entity(net.ReadUInt(16))
Metrostroi.RTCamera = ent
end)
local CamRT = surface.GetTextureID( "pp/rt" )
local CamWork = GetConVar("metrostroi_drawcams")
Metrostroi.CamTimers = Metrostroi.CamTimers or {}
Metrostroi.CamQueue = Metrostroi.CamQueue or {}
function Metrostroi.RenderCamOnRT(train,cpos,name,time,RT,post,pos,ang,x,y,scale,xmin,ymin)
if not CamWork then CamWork = GetConVar("metrostroi_drawcams") return end
if not CamWork:GetBool() then return end
name = train:EntIndex()..name
--print(name,Metrostroi.CamQueue[name])
if (not Metrostroi.CamTimers[name] or RealTime()-Metrostroi.CamTimers[name] > time) and not Metrostroi.CamQueue[name] then
Metrostroi.CamQueue[name] = table.insert(Metrostroi.CamQueue,{train,cpos,name,time,RT,post,pos,ang,x,y,scale,xmin,ymin})
end
end
function Metrostroi.SetCamPosAng(pos,ang)
if IsValid(Metrostroi.RTCamera) then
Metrostroi.RTCamera:SetPos(pos)
Metrostroi.RTCamera:SetAngles(ang)
end
end
hook.Add("Think","metrostroi_camera_move",function()
if IsValid(Metrostroi.RTCamera) then
Metrostroi.RTCamera:SetPos(Vector(0,0,-2^16))
Metrostroi.RTCamera:SetAngles(Angle(90,0,0))
end
if Metrostroi.RenderCam and Metrostroi.RenderedCam ~= RealTime() then
local camera = Metrostroi.RenderCam
Metrostroi.RenderCam = nil
if IsValid(camera[1]) then
local distance = camera[1]:LocalToWorld(camera[2]):Distance(LocalPlayer():GetPos())
if distance > 256 then return end
local x,y = camera[9],camera[10]
local scale = camera[11] or 1
local xmin,ymin = camera[12] or 0,camera[13] or 0
render.PushRenderTarget(camera[5],0,0,x, y)
render.Clear(0, 0, 0, 0)
cam.Start2D()
surface.SetTexture( CamRT )
surface.SetDrawColor( 255, 255, 255, 255 )
surface.DrawTexturedRectRotated((x/2-xmin)*scale,(y/2-ymin)*scale,x*scale,y*scale,0)
cam.End2D()
render.PopRenderTarget()
else
end
end
if #Metrostroi.CamQueue > 0 and not Metrostroi.RenderCam then
local cam = table.remove(Metrostroi.CamQueue,1)
Metrostroi.CamQueue[cam[3]] = nil
local name,time,post,pos,ang = cam[3],cam[4],cam[6],cam[7],cam[8]
if IsValid(post) then
debugoverlay.Sphere(post:LocalToWorld(pos),1,time,Color( 150, 105, 200 ),true)
debugoverlay.Text(post:LocalToWorld(pos),name,time,Color( 150, 105, 200 ),true)
debugoverlay.Line(post:LocalToWorld(pos),post:LocalToWorld(pos)+post:LocalToWorldAngles(ang):Forward()*25,time,Color( 150, 105, 200 ),true)
Metrostroi.RenderCam = cam
Metrostroi.SetCamPosAng(post:LocalToWorld(cam[7]),post:LocalToWorldAngles(cam[8]))
Metrostroi.CamTimers[cam[3]] = RealTime()
end
end
end)
local function rect_ol(x,y,w,h,c)
Metrostroi.DrawLine(x-1,y,x+w,y,c)
Metrostroi.DrawLine(x+w,y,x+w,y+h,c)
Metrostroi.DrawLine(x,y+h,x+w,y+h,c)
Metrostroi.DrawLine(x,y,x,y+h,c)
end
function Metrostroi.DrawLine(x1,y1,x2,y2,col,sz)
surface.SetDrawColor(col)
if x1 == x2 then
-- vertical line
local wid = (sz or 1) / 2
surface.DrawRect(x1-wid, y1, wid*2, y2-y1)
elseif y1 == y2 then
-- horizontal line
local wid = (sz or 1) / 2
surface.DrawRect(x1, y1-wid, x2-x1, wid*2)
else
-- other lines
local x3 = (x1 + x2) / 2
local y3 = (y1 + y2) / 2
local wx = math.sqrt((x2-x1) ^ 2 + (y2-y1) ^ 2)
local angle = math.deg(math.atan2(y1-y2, x2-x1))
draw.NoTexture()
surface.DrawTexturedRectRotated(x3, y3, wx, (sz or 1), angle)
end
end
function Metrostroi.DrawRectOutline(x,y,w,h,col,sz)
local wid = sz or 1
if wid < 0 then
for i=0, wid+1, -1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col)
end
elseif wid > 0 then
for i=0, wid-1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col)
end
end
end
function Metrostroi.DrawRectOL(x,y,w,h,col,sz,col1)
local wid = sz or 1
if wid < 0 then
for i=0, wid+1, -1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col)
end
elseif wid > 0 then
for i=0, wid-1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col)
end
end
surface.SetDrawColor(col1)
surface.DrawRect(x+math.max(0,sz-1),y+math.max(0,sz-1),w-math.max(0,(sz-0.5)*2),h-math.max(0,(sz-0.5)*1.5))
end
function Metrostroi.DrawTextRect(x,y,w,h,col,mat)
surface.SetDrawColor(col)
surface.SetMaterial(mat)
surface.DrawTexturedRect(x,y,w,h)
end
function Metrostroi.DrawTextRectOL(x,y,w,h,col,mat,sz,col1)
local wid = sz or 1
if wid < 0 then
for i=0, wid+1, -1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col1)
end
elseif wid > 0 then
for i=0, wid-1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col1)
end
end
surface.SetDrawColor(col)
surface.DrawRect(x+math.max(0,sz-1),y+math.max(0,sz-1),w-math.max(0,(sz-0.5)*2),h-math.max(0,(sz-0.5)*1.5))
surface.SetDrawColor(Color(col.r - 40,col.g - 40,col.b - 40))
surface.SetMaterial(mat)
surface.DrawTexturedRect(x+math.max(0,sz-1),y+math.max(0,sz-1),w-math.max(0,(sz-0.5)*2),h-math.max(0,(sz-0.5)*2))
end
local function recurePrecache(sound)
if type(sound) == "table" then
for k,snd in pairs(sound) do recurePrecache(snd) end
elseif type(sound) == "string" then
util.PrecacheSound(sound)
end
end
local function util_PrecacheSound(dir)
local files,dirs = file.Find(dir.."/*","GAME")
for _, fdir in pairs(dirs) do
util_PrecacheSound(dir.."/"..fdir)
end
for _,v in pairs(files) do
util.PrecacheSound(dir.."/"..v)
end
end
--util_PrecacheSound("sound/subway_trains")
matproxy.Add{
name = "TrainBodyColor",
init = function( self, mat, values )
-- Store the name of the variable we want to set
if values then self._MATresultVarC = values.resultvar end
end,
bind = function( self, mat, ent )
if ( self._MATresultVarC and ent.GetBodyColor ) then
mat:SetVector( self._MATresultVarC, ent:GetBodyColor() )
end
end
}
matproxy.Add{
name = "TrainBodyDecal",
init = function( self, mat, values )
-- Store the name of the variable we want to set
if values then self._MATresultVarD = values.resultvar end
end,
bind = function( self, mat, ent )
if ( self._MATresultVarD and ent.GetDirtLevel ) then
mat:SetFloat( self._MATresultVarD, ent:GetDirtLevel() )
end
end
}
RunConsoleCommand("r_rootlod",0) -- Train models only visible with High model quality
|
function Utils:ShowRules()
BeginScaleformMovieMethod(self.Scaleform, 'SHOW_SCREEN')
ScaleformMovieMethodAddParamInt(9)
EndScaleformMovieMethod()
end
|
local winapi = require("luawinapi")
print("UNDER_CE:", UNDER_CE)
print("WINVER:", string.format("0x%x", WINVER))
print("_WIN32_WINDOWS:", _WIN32_WINDOWS and string.format("0x%x", _WIN32_WINDOWS))
print("_WIN32_WINNT:", _WIN32_WINNT and string.format("0x%x", _WIN32_WINNT))
|
--[[
MIT License
Copyright (c) 2021 Michael Wiesendanger
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]--
-- luacheck: globals StaticPopupDialogs StaticPopup_Show SetBindingClick STANDARD_TEXT_FONT
-- luacheck: globals GetBindingAction SetBinding GetCurrentBindingSet SaveBindings
-- luacheck: globals StaticPopup_Hide
--[[
The keyBind (GM_KeyBind) is responsible for recording and setting keyBindings to gearSlots
on the gearBar.
Note that a keyBind belongs to exactly one button even if a user decides to use the same gearSlot
on multiple gearBars
KeyBinding rules:
- A keyBinding can consist of multiple keys
- Keys need to be combined with "-"
- Keybindings differentiate between normale keys and modifiers
Modifiers:
- A keyBinding can have the following modifiers RGGM_CONSTANTS.MODIFIER_KEYS
- A keyBinding can have multiple modifiers but not the same one multiple times
CTRL-CTRL-T (invalid)
CTRL-SHIFT-T (valid)
`lastRecordedKey` takes care of that
- Modifiers need to be mapped to their actual value in a keyBinding text RGGM_CONSTANTS.MODIFIER_KEY_MAPPING
Normal Keys:
- Once a normal key was added to a keyBinding text it cannot be followed by
a modifier `prohibitModifier` takes care of that
Examples:
T (valid)
CTRL-T (valid)
CTRL-SHIFT-T (valid)
CTRL (invalid)
CTRL-CTRL (invalid)
CTRL-CTRL-T (invalid)
T-CTRL (invalid)
]]--
local mod = rggm
local me = {}
mod.keyBind = me
me.tag = "KeyBind"
--[[
Whether the keyBinding is considered a valid one or not. Accept button to save
the keyBinding is only enabled after the keyBinding is considered valid.
]]--
local isKeyBindingValid = false
--[[
The keyBinding that was recorded so far
]]--
local recordedKeyBinding = ""
--[[
Track if modifiers are prohibited in the current recording. Keybinds can start with
a modifier but once something different than a modifier is recorded they are no longer
allowed in the sequence.
E.g
T-CTRL (invalid)
CTRL-T (valid)
]]--
local prohibitModifier = false
--[[
Locks the keyBinding from any further changes
]]--
local lockKeyBinding = false
--[[
Stores the last key that was recorded and added to the keyBindingText. Helps prevent
adding multiple modifiers of the same name.
E.g. CTRL-CTRL-T (invalid)
]]--
local lastRecordedKey = ""
--[[
The gearBarId of the gearBar that is being configured
]]--
local currentGearBarId
--[[
The gearSlot position that invoked the setting of a keyBinding
]]--
local currentGearSlotPosition
--[[
Popup dialog for setting a new keybind
]]--
StaticPopupDialogs["RGPVPW_SET_KEYBIND"] = {
text = rggm.L["gear_bar_configuration_key_binding_dialog"]
.. rggm.L["gear_bar_configuration_key_binding_dialog_initial"],
button1 = rggm.L["gear_bar_configuration_key_binding_dialog_accept"],
button2 = rggm.L["gear_bar_configuration_key_binding_dialog_cancel"],
OnShow = function(self)
me.ResetKeyBindingRecording()
-- setup scripts
_G[RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_SUB_MENU]:SetScript("OnKeyDown", function(_, key)
me.OnKeyDown(self, key)
end)
_G[RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_SUB_MENU]:SetScript("OnMouseDown", function(_, key)
me.OnKeyDown(self, key)
end)
_G[RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_SUB_MENU]:SetScript("OnMouseWheel", function(_, key)
me.OnMouseWheel(self, key)
end)
end,
OnHide = function()
-- remove script
_G[RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_SUB_MENU]:SetScript("OnKeyDown", nil)
_G[RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_SUB_MENU]:SetScript("OnMouseDown", nil)
_G[RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_SUB_MENU]:SetScript("OnMouseWheel", nil)
end,
OnAccept = function()
local gearBar = mod.gearBarManager.GetGearBar(currentGearBarId)
local gearSlot = gearBar.slots[currentGearSlotPosition]
if gearSlot ~= nil then
me.SetKeyBinding(gearBar.id, currentGearSlotPosition, recordedKeyBinding)
else
mod.logger.LogError(
me.tag,
"Failed to update keyBinding for gearBar with id: " .. gearBar.id
.. " at position: " .. currentGearSlotPosition
)
end
end,
OnCancel = function()
me.ResetKeyBindingRecording()
end,
timeout = 0,
whileDead = true,
preferredIndex = 3
}
--[[
Popup dialog for confirming the overriding of another keybind
]]--
StaticPopupDialogs["RGPVPW_SET_KEYBIND_OVERRIDE"] = {
text = rggm.L["gear_bar_configuration_key_binding_override_dialog"],
button1 = rggm.L["gear_bar_configuration_key_binding_dialog_override_yes"],
button2 = rggm.L["gear_bar_configuration_key_binding_dialog_override_no"],
OnShow = function()
StaticPopup_Hide("RGPVPW_SET_KEYBIND")
end,
OnAccept = function()
me.SetKeyBindingToGearSlot(currentGearBarId, recordedKeyBinding, currentGearSlotPosition)
StaticPopup_Hide("RGPVPW_SET_KEYBIND")
end,
OnCancel = function()
StaticPopup_Hide("RGPVPW_SET_KEYBIND")
end,
timeout = 0,
whileDead = true,
preferredIndex = 4
}
--[[
Function is called after each keydown and records them together to a full keyBind
@param {table} self
@param {string} key
]]--
function me.OnKeyDown(self, key)
me.KeyBindingOnKey(self, me.ConvertPressedKey(key))
end
--[[
Function is called after mousewheel up or down
@param {table} self
@param {string} direction
1 MOUSEWHEELUP
-1 MOUSEWHEELDOWN
]]--
function me.OnMouseWheel(self, direction)
if direction == RGGM_CONSTANTS.MOUSEWHEELUP then
me.KeyBindingOnKey(self, "MOUSEWHEELUP")
elseif direction == RGGM_CONSTANTS.MOUSEWHEELDOWN then
me.KeyBindingOnKey(self, "MOUSEWHEELDOWN")
else
mod.logger.LogError(me.tag, "Unable to determine mousewheel direction")
end
end
--[[
Function is called after each keydown and records them together to a full keyBind
@param {table} self
@param {string} key
]]--
function me.KeyBindingOnKey(self, key)
if lockKeyBinding then
mod.logger.LogInfo(me.tag, "KeyBinding is already locked no further changes allowed")
return
end
if lastRecordedKey == key then
mod.logger.LogDebug(me.tag, "Double key detected - ignoring")
return
end
lastRecordedKey = key
if recordedKeyBinding ~= "" then
recordedKeyBinding = recordedKeyBinding .. "-"
end
if not prohibitModifier then
for _, modifierKey in pairs(RGGM_CONSTANTS.MODIFIER_KEYS) do
if key == modifierKey then
recordedKeyBinding = recordedKeyBinding .. RGGM_CONSTANTS.MODIFIER_KEY_MAPPING[key]
isKeyBindingValid = false
me.UpdateDialogText(self)
me.UpdateDialog(self)
return
end
end
end
recordedKeyBinding = recordedKeyBinding .. key
me.LockKeyBinding()
prohibitModifier = true
isKeyBindingValid = true -- at least one "normal key" was added
me.UpdateDialogText(self)
me.UpdateDialog(self)
mod.logger.LogInfo(me.tag, "Keybinding recorded: " .. recordedKeyBinding)
end
--[[
@param {string} key
@return {string}
The converted key
]]--
function me.ConvertPressedKey(key)
-- special case middle mouse button needs to be converted
if key == "MiddleButton" then
return "BUTTON3"
end
return string.upper(key)
end
--[[
Reset keyBinding recording
]]--
function me.ResetKeyBindingRecording()
recordedKeyBinding = ""
prohibitModifier = false
lockKeyBinding = false
lastRecordedKey = ""
isKeyBindingValid = false
end
--[[
Lock keyBinding and stop recording any further keys
@param {table} dialog
]]--
function me.LockKeyBinding()
_G[RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_SUB_MENU]:SetScript("OnKeyDown", nil)
lockKeyBinding = true
end
--[[
Update the dialogs text
@param {table} dialog
]]--
function me.UpdateDialogText(dialog)
dialog.text:SetText(rggm.L["gear_bar_configuration_key_binding_dialog"] .. " " .. recordedKeyBinding)
end
--[[
Update dialog related button
@param {table} dialog
]]--
function me.UpdateDialog(dialog)
if isKeyBindingValid then
dialog.button1:Enable() -- enable accept button
else
dialog.button1:Disable() -- disable accept button
end
end
--[[
Set keybinds
@param {number} gearBarId
@param {table} gearSlotPosition
@param {string} keyBinding
The keyBinding to set. Will reset the gearSlot if nil or empty
]]--
function me.SetKeyBinding(gearBarId, gearSlotPosition, keyBinding)
-- unbind keybindings on gearSlot
if keyBinding == nil or keyBinding == "" then
me.UnsetKeyBinding(gearBarId, gearSlotPosition)
return
end
local action = GetBindingAction(keyBinding)
if action ~= "" and action ~= nil then
--[[
This keybind is already in use somewhere. Make sure to log this information and reset
the keybinding.
]]--
mod.logger.LogInfo(me.tag, "Keybinding is already in use: " .. action)
StaticPopup_Show("RGPVPW_SET_KEYBIND_OVERRIDE")
else
mod.logger.LogDebug(me.tag, "Keybinding is not in use")
me.SetKeyBindingToGearSlot(gearBarId, keyBinding, gearSlotPosition)
end
end
--[[
Unset keybinding e.g. when a gearSlot with a binding is deleted or if keyBinding
was left empty when accepting the keyBinding
Will be ignored when trying to unset a gearSlot that does not have a keybinding
@param {number} gearBarId
@param {number} gearSlotPosition
]]--
function me.UnsetKeyBinding(gearBarId, gearSlotPosition)
local gearSlot = mod.gearBarManager.GetGearSlot(gearBarId, gearSlotPosition)
if gearSlot.keyBinding == nil then
mod.logger.LogInfo(me.tag, "GearSlot has no keybinding set. Nothing to reset")
return
end
mod.logger.LogInfo(me.tag,
"Keybinding - resetting gearBar{" .. gearBarId .. "}gearSlot{" .. gearSlotPosition .. "} keybind")
mod.logger.LogDebug(me.tag, "Current keybinding before resetting: " .. gearSlot.keyBinding)
SetBinding(gearSlot.keyBinding)
mod.gearBarManager.SetSlotKeyBinding(gearBarId, gearSlotPosition, nil)
mod.gearBarConfigurationSubMenu.UpdateGearBarConfigurationMenu()
me.SaveBindings()
end
--[[
Remove keybinding from slot if the keybinding is ours
@param {table} gearSlot
]]--
function me.UnsetKeyBindingFromGearSlot(gearSlot)
local action = GetBindingAction(gearSlot.keyBinding)
if action ~= "" and action ~= nil then
mod.logger.LogInfo(me.tag, "GearSlot has keyBinding set: " .. action)
local match = string.match(action, RGGM_CONSTANTS.ELEMENT_GEAR_BAR_BASE_FRAME_NAME)
if match then
mod.logger.LogInfo(me.tag, "Action found does match GearMenus keyBinding pattern. Removing...")
SetBinding(gearSlot.keyBinding)
me.SaveBindings()
else
mod.logger.LogDebug("Action does not match GearMenus keyBinding pattern. Ignoring keyBinding...")
end
end
end
--[[
Set keyBind to a specific gearSlot
Note: Will override keyBinds if already set
@param {number} gearBarId
@param {string} keyBinding
@param {number} gearSlotPosition
]]--
function me.SetKeyBindingToGearSlot(gearBarId, keyBinding, gearSlotPosition)
local uiGearBar = mod.gearBarStorage.GetGearBar(gearBarId)
local uiGearSlot = uiGearBar.gearSlotReferences[gearSlotPosition]
mod.logger.LogInfo(me.tag, "Set new keybinding " .. keyBinding .. " to " .. uiGearSlot:GetName())
SetBinding(keyBinding) -- reset binding
if SetBinding(keyBinding, "CLICK " .. uiGearSlot:GetName() .. ":LeftButton") then
mod.logger.LogInfo(me.tag, "Successfully changed keyBind")
mod.gearBarManager.SetSlotKeyBinding(gearBarId, gearSlotPosition, keyBinding)
-- update the configuration sub menu (show proper keyBinding after change)
mod.gearBarConfigurationSubMenu.UpdateGearBarConfigurationMenu()
-- save keyBindings to wow-cache
me.SaveBindings()
me.CleanupKeyBindingOnSlots(gearBarId, gearSlotPosition, keyBinding)
else
mod.logger.LogWarn(me.tag, "Failed to update keybinding: " .. keyBinding .. " to " .. uiGearSlot:GetName())
mod.logger.PrintUserError(rggm.L["gear_bar_configuration_key_binding_user_error"])
end
end
--[[
Search through all gearBars for leftover keyBinding text. After a new button receives a
keyBinding we check other slots (and other gearBars) for the same keyBinding. At this point
the keyBinding is already overwritten but visually it will still be displayed if not cleaned up
@param {number} newGearBarId
The gearBarId where the gearSlot belongs to with the new keyBinding
@param {number} newGearSlotPosition
The gearSlot position of the slot that received the new keyBinding
@param {string} keyBinding
The keyBinding that was set
]]--
function me.CleanupKeyBindingOnSlots(newGearBarId, newGearSlotPosition, keyBinding)
for _, gearBar in pairs(mod.gearBarManager.GetGearBars()) do
for position, gearSlot in pairs(gearBar.slots) do
if gearBar.id ~= newGearBarId or position ~= newGearSlotPosition then
if gearSlot.keyBinding == keyBinding then
mod.logger.LogInfo(
me.tag, "Leftover keyBinding found - resetting {" .. gearBar.id .. "} slotPos {" .. position .. "}")
mod.gearBarManager.SetSlotKeyBinding(gearBar.id, position, nil)
end
end
end
end
end
--[[
After deleting a gearSlot from the configuration it can happen that a slot moves to another position to avoid
any gaps. This however means that keyBindings might point to the wrong slot. To prevent that we check if the action
for the shortcut matches the expectation and if not we fix it by silently updating the keybind to the proper slot
@param {number} gearBarId
]]--
function me.CheckKeyBindingSlots(gearBarId)
local gearBar = mod.gearBarManager.GetGearBar(gearBarId)
for position, gearSlot in pairs(gearBar.slots) do
if gearSlot.keyBinding ~= "" and gearSlot.keyBinding ~= nil then
mod.logger.LogDebug(me.tag, "Checking slot{" .. position .. "} with keyBinding " .. gearSlot.keyBinding)
local action = GetBindingAction(gearSlot.keyBinding)
if action ~= "" and action ~= nil then
local _, _, _, slotPosition = string.find(action, "GM_GearBarFrame_(%d+)Slot_(%d)")
if tonumber(slotPosition) ~= position then
mod.logger.LogDebug(me.tag, "Expected action to have position: " .. position .. " but was : " .. slotPosition)
local uiGearBar = mod.gearBarStorage.GetGearBar(gearBarId)
local uiGearSlot = uiGearBar.gearSlotReferences[position]
if SetBinding(gearSlot.keyBinding, "CLICK " .. uiGearSlot:GetName() .. ":LeftButton") then
mod.logger.LogDebug(me.tag, "Fixed keyBinding action")
-- update the configuration sub menu (show proper keyBinding after change)
mod.gearBarConfigurationSubMenu.UpdateGearBarConfigurationMenu()
-- save keyBindings to wow-cache
me.SaveBindings()
end
end
end
end
end
end
--[[
Blizzard api for saving keybinds. If this is not called after a change the keyBinds are lost after
a reload of WoW
]]--
function me.SaveBindings()
mod.logger.LogInfo(me.tag, "Save bindings in - " .. GetCurrentBindingSet())
SaveBindings(GetCurrentBindingSet())
end
--[[
Show Keybinding dialog to record and save keyBinding to the passed gearSlot
UI Interface entrypoint
@param {table} gearBarId
@param {number} gearSlotPosition
]]--
function me.SetKeyBindingForGearSlot(gearBarId, gearSlotPosition)
currentGearBarId = gearBarId
currentGearSlotPosition = gearSlotPosition
StaticPopup_Show("RGPVPW_SET_KEYBIND")
end
--[[
Callback for UPDATE_BINDINGS event. Iterate all keyBindings in all gearBars and check if they
are still valid. KeyBinds could have been changed outside of gearMenu. If this case is detected we remove
the visual representation of that keyBind from gearMenu
]]--
function me.OnUpdateKeyBindings()
mod.logger.LogDebug(me.tag, "UPDATE_BINDINGS event. Checking gearMenus keyBinds")
local gearBars = mod.gearBarManager.GetGearBars()
-- iterate all keybindings of all gearBars and check if they are still bound correctly
for i = 1, #gearBars do
for position, gearSlot in pairs(gearBars[i].slots) do
if gearSlot.keyBinding ~= nil then
mod.logger.LogDebug(me.tag, "gearSlot: " .. position .. " has a keyBinding set: " .. gearSlot.keyBinding)
local action = GetBindingAction(gearSlot.keyBinding)
if action == nil or action == "" then
mod.logger.LogInfo(me.tag, "Found a gearBar keyBinding that is not actually set. Resetting keyBind")
mod.gearBarManager.SetSlotKeyBinding(gearBars[i].id, position, nil)
end
end
end
end
end
--[[
Convert actual keybinding text to a shorter one to be displayed on top of action buttons
@param {string} keyBindingText
return {string}
]]--
function me.ConvertKeyBindingText(keyBindingText)
local convertedKeyBindingText = string.gsub(string.lower(keyBindingText), "ctrl", "c")
convertedKeyBindingText = string.gsub(convertedKeyBindingText, "shift", "s")
convertedKeyBindingText = string.gsub(convertedKeyBindingText, "alt", "a")
return convertedKeyBindingText
end
|
--[[----------------------------------------------------------------------------
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
Full scene evaluation of DeepMask/SharpMask
------------------------------------------------------------------------------]]
require 'torch'
require 'cutorch'
require 'image'
local cjson = require 'cjson'
local tds = require 'tds'
local coco = require 'coco'
paths.dofile('DeepMask.lua')
paths.dofile('SharpMask.lua')
--------------------------------------------------------------------------------
-- parse arguments
local cmd = torch.CmdLine()
cmd:text()
cmd:text('full scene evaluation of DeepMask/SharpMask')
cmd:text()
cmd:argument('-model', 'model to load')
cmd:text('Options:')
cmd:option('-datadir', 'data/', 'data directory')
cmd:option('-seed', 1, 'manually set RNG seed')
cmd:option('-gpu', 1, 'gpu device')
cmd:option('-split', 'val', 'dataset split to be used (train/val)')
cmd:option('-np', 500,'number of proposals')
cmd:option('-thr', .2, 'mask binary threshold')
cmd:option('-save', false, 'save top proposals')
cmd:option('-startAt', 1, 'start image id')
cmd:option('-endAt', 5000, 'end image id')
cmd:option('-smin', -2.5, 'min scale')
cmd:option('-smax', .5, 'max scale')
cmd:option('-sstep', .5, 'scale step')
cmd:option('-timer', false, 'breakdown timer')
cmd:option('-dm', false, 'use DeepMask version of SharpMask')
local config = cmd:parse(arg)
--------------------------------------------------------------------------------
-- various initializations
torch.setdefaulttensortype('torch.FloatTensor')
cutorch.setDevice(config.gpu)
torch.manualSeed(config.seed)
math.randomseed(config.seed)
local maskApi = coco.MaskApi
local meanstd = {mean={ 0.485, 0.456, 0.406 }, std={ 0.229, 0.224, 0.225 }}
--------------------------------------------------------------------------------
-- load model and config
print('| loading model file... ' .. config.model)
local m = torch.load(config.model..'/model.t7')
local c = m.config
for k,v in pairs(c) do if config[k] == nil then config[k] = v end end
local epoch = 0
if paths.filep(config.model..'/log') then
for line in io.lines(config.model..'/log') do
if string.find(line,'train') then epoch = epoch + 1 end
end
print(string.format('| number of examples seen until now: %d (%d epochs)',
epoch*config.maxload*config.batch,epoch))
end
local model = m.model
model:inference(config.np)
model:cuda()
--------------------------------------------------------------------------------
-- directory to save results
local savedir = string.format('%s/epoch=%d/',config.model,epoch)
print(string.format('| saving results results in %s',savedir))
os.execute(string.format('mkdir -p %s',savedir))
os.execute(string.format('mkdir -p %s/t7',savedir))
os.execute(string.format('mkdir -p %s/jsons',savedir))
if config.save then os.execute(string.format('mkdir -p %s/res',savedir)) end
--------------------------------------------------------------------------------
-- create inference module
local scales = {}
for i = config.smin,config.smax,config.sstep do table.insert(scales,2^i) end
if torch.type(model)=='nn.DeepMask' then
paths.dofile('InferDeepMask.lua')
elseif torch.type(model)=='nn.SharpMask' then
paths.dofile('InferSharpMask.lua')
end
local infer = Infer{
np = config.np,
scales = scales,
meanstd = meanstd,
model = model,
iSz = config.iSz,
dm = config.dm,
timer = config.timer,
}
--------------------------------------------------------------------------------
-- get list of eval images
local annFile = string.format('%s/annotations/instances_%s2014.json',
config.datadir,config.split)
local coco = coco.CocoApi(annFile)
local imgIds = coco:getImgIds()
imgIds,_ = imgIds:sort()
--------------------------------------------------------------------------------
-- function: encode proposals
local function encodeProps(props,np,img,k,masks,scores)
local t = (k-1)*np
local enc = maskApi.encode(masks)
for i = 1, np do
local elem = tds.Hash()
elem.segmentation = tds.Hash(enc[i])
elem.image_id=img.id
elem.category_id=1
elem.score=scores[i][1]
props[t+i] = elem
end
end
--------------------------------------------------------------------------------
-- function: convert props to json and save
local function saveProps(props,savedir,s,e)
--t7
local pathsvt7 = string.format('%s/t7/props-%d-%d.t7', savedir,s,e)
torch.save(pathsvt7,props)
--json
local pathsvjson = string.format('%s/jsons/props-%d-%d.json', savedir,s,e)
local propsjson = {}
for _,prop in pairs(props) do -- hash2table
local elem = {}
elem.category_id = prop.category_id
elem.image_id = prop.image_id
elem.score = prop.score
elem.segmentation={
size={prop.segmentation.size[1],prop.segmentation.size[2]},
counts = prop.segmentation.counts or prop.segmentation.count
}
table.insert(propsjson,elem)
end
local jsonText = cjson.encode(propsjson)
local f = io.open(pathsvjson,'w'); f:write(jsonText); f:close()
collectgarbage()
end
--------------------------------------------------------------------------------
-- function: read image
local function readImg(datadir,split,fileName)
local pathImg = string.format('%s/%s2014/%s',datadir,split,fileName)
local inp = image.load(pathImg,3)
return inp
end
--------------------------------------------------------------------------------
-- run
print('| start eval')
local props, svcount = tds.Hash(), config.startAt
for k = config.startAt,config.endAt do
xlua.progress(k,config.endAt)
-- load image
local img = coco:loadImgs(imgIds[k])[1]
local input = readImg(config.datadir,config.split,img.file_name)
local h,w = img.height,img.width
-- forward all scales
infer:forward(input)
-- get top proposals
local masks,scores = infer:getTopProps(config.thr,h,w)
-- encode proposals
encodeProps(props,config.np,img,k,masks,scores)
-- save top masks?
if config.save then
local res = input:clone()
maskApi.drawMasks(res, masks, 10)
image.save(string.format('%s/res/%d.jpg',savedir,k),res)
end
-- save proposals
if k%500 == 0 then
saveProps(props,savedir,svcount,k); props = tds.Hash(); collectgarbage()
svcount = svcount + 500
end
collectgarbage()
end
if config.timer then infer:printTiming() end
collectgarbage()
print('| finish')
|
local f = function() return function() end end
local t = {
nil,
[false] = 'Lua 5.1',
[true] = 'Lua 5.2',
[1/'-0'] = 'Lua 5.3',
[1] = 'LuaJIT'
}
local version = t[1] or t[1/0] or t[f()==f()]
print(version)
--[[
网上大神根据lua 各个版本的特性写的
通过判断 每个版本的table实现和function 实现的不同
来获得运行的lua 版本
]]
|
newTable = {}
table.insert(newTable,"first")
table.insert(newTable,"second")
table.insert(newTable,"third")
-- 求长度
print(#newTable)
-- 跳着插入
newTable[5] = "fourth"
print(newTable[9])
-- 求长度
print(#newTable)
|
--- RectSegmentBuilder
--- Builder Pattern constructor for a RectSegment
local RectSegment = require(script.Parent.RectSegment)
local root = script.Parent.Parent
local Builder = require(root.Builder)
local util = root.Util
local t = require(util.t)
local RectSegmentBuilder = {
ClassName = "RectSegmentBuilder";
}
RectSegmentBuilder.__index = RectSegmentBuilder
setmetatable(RectSegmentBuilder, Builder)
function RectSegmentBuilder.new()
local self = setmetatable(Builder.new(), RectSegmentBuilder)
self.Wedge = nil
self.P0 = Vector3.new()
self.P1 = Vector3.new()
self.P2 = Vector3.new()
self.P3 = Vector3.new()
return self
end
-- makes sure everything is setup properly
-- runs an "any" check on the following properties
local BuilderCheck = Builder.Check({
"Wedge"
})
function RectSegmentBuilder:Build()
assert(BuilderCheck(self))
return RectSegment.fromData({
Name = self.Name,
Wedge = self.Wedge,
P0 = self.P0,
P1 = self.P1,
P2 = self.P2,
P3 = self.P3,
})
end
function RectSegmentBuilder:WithWedge(wedge)
assert(t.instanceIsA("WedgePart")(wedge))
self.Wedge = wedge
return self
end
function RectSegmentBuilder:WithP0(offset)
assert(t.Vector3(offset))
self.P0 = offset
return self
end
function RectSegmentBuilder:WithP1(offset)
assert(t.Vector3(offset))
self.P1 = offset
return self
end
function RectSegmentBuilder:WithP2(offset)
assert(t.Vector3(offset))
self.P2 = offset
return self
end
function RectSegmentBuilder:WithP3(offset)
assert(t.Vector3(offset))
self.P3 = offset
return self
end
return RectSegmentBuilder
|
--- @module ChooseOccUI 选择枪械的UI控制
--- @copyright Lilith Games, Avatar Team
--- @author Sharif Ma
local ChooseOccUI, this = ModuleUtil.New('ChooseOccUI', ClientBase)
local defaultId = 1001
local showPnlBtnRotateSpeed = 5
local selectColor = Color(93, 53, 35, 255)
local noSelectColor = Color(255, 255, 255, 255)
local selectImg = 'UI/Picture/Toggle_A'
local noSelectImg = 'UI/Picture/Toggle_N'
--- 初始化函数
function ChooseOccUI:Init()
self.root = world:CreateInstance('ChooseOcc', 'ChooseOcc', localPlayer.Local)
self.showPnlBtn = ButtonBase:new(self.root.ShowPnlBtn, UIBase.AniTypeEnum.Scale)
self.chooseBtn = ButtonBase:new(self.root.OccPnl.DesPnl.ChooseBtn, UIBase.AniTypeEnum.Scale)
self.closeBtn = ButtonBase:new(self.root.OccPnl.BtnClose, UIBase.AniTypeEnum.Scale)
self.occPnl = self.root.OccPnl
self.difficultyTxt = self.root.OccPnl.DesPnl.ImgDifficulty.DifficultyTxt
self.gunTxt = self.root.OccPnl.DesPnl.GunNameTxt
self.posTxt = self.root.OccPnl.DesPnl.ImgPosition.PosTxt
self.posImg = self.root.OccPnl.DesPnl.ImgPosition.ImgPosType
self.moveFill = self.root.OccPnl.DesPnl.ImgMoveInfo.MoveInfo.Fill
self.fireFill = self.root.OccPnl.DesPnl.ImgFireInfo.FireInfo.Fill
self.disFill = self.root.OccPnl.DesPnl.ImgDisInfo.DisInfo.Fill
self.gunImg = self.root.OccPnl.DesPnl.ImgSample.ImgGunType
self.chooseBtnList = {}
self.root.Order = 750
self.selectId = -1
self.pos1_A, self.pos2_A, self.pos1_B, self.pos2_B = Vector3.Zero, Vector3.Zero, Vector3.Zero, Vector3.Zero
self.sceneId = 0
self.active = false
self.frameCount = 0
local curNum = 0
local occConfig = {}
for i, v in pairs(Config.Occupation) do
table.insert(occConfig, v)
end
table.sort(
occConfig,
function(a, b)
return a.Order > b.Order
end
)
for i, v in pairs(occConfig) do
local btn = ButtonBase:new('ChooseOccBtn', UIBase.AniTypeEnum.Scale, self.occPnl.BtnsPnl)
local occId = v.Id
btn:SetValue('AnchorsX', Vector2(0, 1))
btn:SetValue('AnchorsY', Vector2(curNum * 0.2, curNum * 0.2 + 0.18))
btn:SetValue('Size', Vector2.Zero)
btn:SetValue('Text', v.Name)
btn:BindHandler('OnClick', self.ShowOccInfo, occId)
btn:SetSound('OnClick', 116)
self.chooseBtnList[occId] = btn
invoke(
function()
wait()
btn:CallFunction('ToTop')
end
)
curNum = curNum + 1
end
self.showPnlBtn:BindHandler('OnClick', self.ShowPnlBtnClick)
self.showPnlBtn:SetSound('OnClick', 110)
--print(self.showPnlBtn.m_startFinalSize, self.showPnlBtn.m_endFinalSize)
self.chooseBtn:BindHandler('OnClick', self.ChooseOccBtnClick)
self.chooseBtn:SetSound('OnClick', 112)
self.closeBtn:BindHandler('OnClick', self.ShowPnlBtnClick)
self.closeBtn:SetSound('OnClick', 110)
self.ShowOccInfo(defaultId)
self.occPnl:SetActive(false)
self.showPnlBtn:CallFunction('SetActive', false)
self.enable = false
end
--- Update
--- @param dt number delta time
function ChooseOccUI:Update(dt, tt)
if not self.enable then
return
end
if localPlayer.PlayerType then
local team = localPlayer.PlayerType.Value
if team == Const.TeamEnum.Team_A then
---检测是否在A队伍出生区域内
if self:CheckInRange(localPlayer, self.pos1_A, self.pos2_A) then
self:EnterBornArea()
else
self:LeaveBornArea()
end
elseif team == Const.TeamEnum.Team_B then
---检测是否在B队伍出生区域内
if self:CheckInRange(localPlayer, self.pos1_B, self.pos2_B) then
self:EnterBornArea()
else
self:LeaveBornArea()
end
end
end
end
function ChooseOccUI:FixUpdate(_dt)
if not self.showPnlBtn:GetValue('ActiveSelf') then
return
end
local sizeX = math.sin(self.frameCount / math.pi / 2) * 10
self.showPnlBtn:SetValue('Ico.Size', Vector2.One * sizeX)
local curAngle = self.showPnlBtn:GetValue('RotateIco.Angle')
self.showPnlBtn:SetValue('RotateIco.Angle', curAngle - showPnlBtnRotateSpeed)
self.frameCount = self.frameCount + 1
end
function ChooseOccUI:ShowPnlBtnClick()
local self = ChooseOccUI
if self.active then
NetUtil.Fire_C('StartAnimationEvent', localPlayer, 'ShowOccPnl', true)
self.active = false
else
self.occPnl:SetActive(true)
NetUtil.Fire_C('StartAnimationEvent', localPlayer, 'ShowOccPnl', false)
self.active = true
end
end
function ChooseOccUI:ChooseOccBtnClick()
local self = ChooseOccUI
if not Config.Occupation[self.selectId] then
return
end
NetUtil.Fire_S('PlayerTryChangeOccEvent', localPlayer, self.selectId)
end
function ChooseOccUI.ShowOccInfo(_id)
local self = ChooseOccUI
if self.selectId == _id then
return
end
self.difficultyTxt.Text = Config.Occupation[_id].Difficulty
self.gunTxt.Text = Config.Occupation[_id].Gun
self.posTxt.Text = Config.Occupation[_id].Pos
self.moveFill.FillAmount = Config.Occupation[_id].Move
self.fireFill.FillAmount = Config.Occupation[_id].Fire
self.disFill.FillAmount = Config.Occupation[_id].Dis
self.gunImg.Texture = ResourceManager.GetTexture('UI/Icon/' .. Config.Occupation[_id].GunImg)
self.posImg.Texture = ResourceManager.GetTexture('UI/Icon/' .. Config.Occupation[_id].PosImg)
self.chooseBtnList[_id]:SetValue('TextColor', selectColor)
self.chooseBtnList[_id]:SetValue('Image', ResourceManager.GetTexture(selectImg))
if self.chooseBtnList[self.selectId] then
self.chooseBtnList[self.selectId]:SetValue('TextColor', noSelectColor)
self.chooseBtnList[self.selectId]:SetValue('Image', ResourceManager.GetTexture(noSelectImg))
end
self.selectId = _id
end
---更改职业成功后隐藏UI
function ChooseOccUI:ChangeOccEventHandler()
--self.occPnl:SetActive(false)
if self.active then
NetUtil.Fire_C('StartAnimationEvent', localPlayer, 'ShowOccPnl', true)
self.active = false
end
end
function ChooseOccUI:AnimationStateEventHandler(_dataName, _state)
if _state == 'Complete' and _dataName == 'ShowOccPnl' then
if not self.active then
self.occPnl:SetActive(false)
end
end
end
function ChooseOccUI:SetActive(_active)
--self.occPnl:SetActive(_active)
if _active == self.active then
return
end
if _active then
self.occPnl:SetActive(true)
end
self.active = _active
NetUtil.Fire_C('StartAnimationEvent', localPlayer, 'ShowOccPnl', not _active)
end
---游戏开始后的事件,显示选择职业的按钮和界面
function ChooseOccUI:GameStart(_mode, _sceneId, _pointsList, _sceneObj)
self.sceneId = _sceneId
self.showPnlBtn:CallFunction('SetActive', true)
self.pos1_A = Config.Scenes[_sceneId].BornArea[1][1]
self.pos2_A = Config.Scenes[_sceneId].BornArea[1][2]
self.pos1_B = Config.Scenes[_sceneId].BornArea[2][1]
self.pos2_B = Config.Scenes[_sceneId].BornArea[2][2]
self.enable = true
end
function ChooseOccUI:GameStartEventHandler()
self:SetActive(false)
self.showPnlBtn:CallFunction('SetActive', false)
end
---判断玩家是否在一个区域内
function ChooseOccUI:CheckInRange(_player, _pos1, _pos2)
local x1, x2 = _pos1.X, _pos2.X
local z1, z2 = _pos1.Z, _pos2.Z
local x, z = _player.Position.X, _player.Position.Z
if x >= x1 and x <= x2 or x >= x2 and x <= x1 then
if z >= z1 and z <= z2 or z >= z2 and z <= z1 then
return true
end
end
return false
end
---进入己方出生区域内
function ChooseOccUI:EnterBornArea()
self.showPnlBtn:CallFunction('SetActive', true)
PlayerOccLogic:Invincible(true)
end
---离开己方出生区域
function ChooseOccUI:LeaveBornArea()
self.showPnlBtn:CallFunction('SetActive', false)
PlayerOccLogic:Invincible(false)
end
function ChooseOccUI:GameOverEventHandler()
self:SetActive(false)
self.showPnlBtn:CallFunction('SetActive', false)
end
return ChooseOccUI
|
if settings.startup["enable-loaderhaul"].value == true and mods["miniloader"] and mods["deadlock-beltboxes-loaders"] and settings.startup["deadlock-enable-loaders"].value == true then
local function createPlatform(prefix, filter, mask_tint)
local function name()
if prefix == nil and filter == false then
return "miniloader-inserter"
elseif prefix == nil and filter == true then
return "filter-miniloader-inserter"
elseif prefix ~= nil and filter == false then
return prefix .. "-miniloader-inserter"
elseif prefix ~= nil and filter == true then
return prefix .. "-filter-miniloader-inserter"
end
end
local p = data.raw.inserter[name()]
if filter == true then
p.platform_picture = {
sheets = {
{
hr_version = {
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-shadow.png",
height = 96,
priority = "medium",
width = 144,
scale = 0.5,
shift = { 0.5, 0 },
},
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-shadow.png",
height = 48,
priority = "medium",
width = 72,
scale = 1,
shift = { 0.5, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-base.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-base.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-mask.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
tint = mask_tint,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-mask.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
tint = mask_tint,
},
{
hr_version = {
filename = "__project-corona__/graphics/entity/hr-filter-loader-mask.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
tint = filter_tint,
shift = { 0, 0 },
},
filename = "__project-corona__/graphics/entity/filter-loader-mask.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
tint = filter_tint,
},
}
}
p.localised_description = { "entity-description.deadlock-filter-loader" }
else
p.platform_picture = {
sheets = {
{
hr_version = {
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-shadow.png",
height = 96,
priority = "medium",
width = 144,
scale = 0.5,
shift = { 0.5, 0 },
},
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-shadow.png",
height = 48,
priority = "medium",
width = 72,
scale = 1,
shift = { 0.5, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-base.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-base.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-mask.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
tint = mask_tint,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-mask.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
tint = mask_tint,
}
}
}
p.localised_description = { "entity-description.deadlock-loader" }
end
return p
end
local miniloader_platform = createPlatform(nil, false, tint)
local miniloader_filter_platform = createPlatform(nil, true, tint)
local fast_miniloader_platform = createPlatform("fast", false, fast_tint)
local fast_filter_miniloader_platform = createPlatform("fast", true, fast_tint)
local express_miniloader_platform = createPlatform("express", false, express_tint)
local express_filter_miniloader_platform = createPlatform("express", true, express_tint)
local function createStructure(prefix, filter, mask_tint)
local function name()
if prefix == nil and filter == false then
return "miniloader-loader"
elseif prefix == nil and filter == true then
return "filter-miniloader-loader"
elseif prefix ~= nil and filter == false then
return prefix .. "-miniloader-loader"
elseif prefix ~= nil and filter == true then
return prefix .. "-filter-miniloader-loader"
end
end
local s = data.raw["loader-1x1"][name()]
if filter == true then
s.structure = {
back_patch = {
sheet = {
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-back.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-back.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
},
},
direction_in = {
sheets = {
{
hr_version = {
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-shadow.png",
height = 96,
priority = "medium",
width = 144,
scale = 0.5,
shift = { 0.5, 0 },
},
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-shadow.png",
height = 48,
priority = "medium",
width = 72,
scale = 1,
shift = { 0.5, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-base.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-base.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-mask.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
tint = mask_tint,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-mask.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
tint = mask_tint,
},
{
hr_version = {
filename = "__project-corona__/graphics/entity/hr-filter-loader-mask.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
tint = filter_tint,
},
filename = "__project-corona__/graphics/entity/filter-loader-mask.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
tint = filter_tint,
},
},
},
direction_out = {
sheets = {
{
hr_version = {
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-shadow.png",
height = 96,
priority = "medium",
width = 144,
scale = 0.5,
shift = { 0.5, 0 },
},
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-shadow.png",
height = 48,
priority = "medium",
width = 72,
scale = 1,
shift = { 0.5, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-base.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
y = 96,
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-base.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
y = 48,
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-mask.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
tint = mask_tint,
y = 96
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-mask.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
tint = mask_tint,
y = 48
},
{
hr_version = {
filename = "__project-corona__/graphics/entity/hr-filter-loader-mask.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
tint = filter_tint,
y = 96
},
filename = "__project-corona__/graphics/entity/filter-loader-mask.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
tint = filter_tint,
y = 48
},
}
}
}
s.localised_description = { "entity-description.deadlock-filter-loader" }
else
s.structure = {
back_patch = {
sheet = {
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-back.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-back.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
},
},
direction_in = {
sheets = {
{
hr_version = {
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-shadow.png",
height = 96,
priority = "medium",
width = 144,
scale = 0.5,
shift = { 0.5, 0 },
},
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-shadow.png",
height = 48,
priority = "medium",
width = 72,
scale = 1,
shift = { 0.5, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-base.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-base.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-mask.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
tint = mask_tint,
shift = { 0, 0 },
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-mask.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
tint = mask_tint,
},
},
},
direction_out = {
sheets = {
{
hr_version = {
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-shadow.png",
height = 96,
priority = "medium",
width = 144,
scale = 0.5,
shift = { 0.5, 0 },
},
draw_as_shadow = true,
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-shadow.png",
height = 48,
priority = "medium",
width = 72,
scale = 1,
shift = { 0.5, 0 },
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-base.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
y = 96,
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-base.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
y = 48
},
{
hr_version = {
filename = "__deadlock-beltboxes-loaders__/graphics/entities/high/loader-mask.png",
height = 96,
priority = "extra-high",
width = 96,
scale = 0.5,
shift = { 0, 0 },
tint = mask_tint,
y = 96
},
filename = "__deadlock-beltboxes-loaders__/graphics/entities/low/loader-mask.png",
height = 48,
priority = "extra-high",
width = 48,
scale = 1,
shift = { 0, 0 },
tint = mask_tint,
y = 48
},
},
}
}
s.localised_description = { "entity-description.deadlock-loader" }
end
return s
end
local miniloader_structure = createStructure(nil, false, tint)
local miniloader_filter_structure = createStructure(nil, true, tint)
local fast_miniloader_structure = createStructure("fast", false, fast_tint)
local fast_filter_miniloader_structure = createStructure("fast", true, fast_tint)
local express_miniloader_structure = createStructure("express", false, express_tint)
local express_filter_miniloader_structure = createStructure("express", true, express_tint)
data:extend({
miniloader_platform,
miniloader_filter_platform,
fast_miniloader_platform,
fast_filter_miniloader_platform,
express_miniloader_platform,
express_filter_miniloader_platform,
miniloader_structure,
miniloader_filter_structure,
fast_miniloader_structure,
fast_filter_miniloader_structure,
express_miniloader_structure,
express_filter_miniloader_structure,
})
if mods["boblogistics"] and mods["deadlock-integrations"] then
if settings.startup["bobmods-logistics-beltoverhaul"].value == true then
local basic_miniloader_platform = createPlatform("basic", false, basic_tint)
local basic_miniloader_structure = createStructure("basic", false, basic_tint)
data:extend({
basic_miniloader_platform,
basic_miniloader_structure,
})
end
local turbo_miniloader_platform = createPlatform("turbo", false, turbo_tint)
local turbo_filter_miniloader_platform = createPlatform("turbo", true, turbo_tint)
local ultimate_miniloader_platform = createPlatform("ultimate", false, ultimate_tint)
local ultimate_filter_miniloader_platform = createPlatform("ultimate", true, ultimate_tint)
local turbo_miniloader_structure = createStructure("turbo", false, turbo_tint)
local turbo_filter_miniloader_structure = createStructure("turbo", true, turbo_tint)
local ultimate_miniloader_structure = createStructure("ultimate", false, ultimate_tint)
local ultimate_filter_miniloader_structure = createStructure("ultimate", true, ultimate_tint)
data:extend({
turbo_miniloader_platform,
turbo_filter_miniloader_platform,
ultimate_miniloader_platform,
ultimate_filter_miniloader_platform,
turbo_miniloader_structure,
turbo_filter_miniloader_structure,
ultimate_miniloader_structure,
ultimate_filter_miniloader_structure,
})
end
end
|
date = "Today is 17/7/1991"
d = string.match(date, "%d+/%d+/%d+")
print(d)
|
function BiteLeap:GetMeleeBase()
return 0.7, 1
end
|
local App = script:FindFirstAncestor("App")
local UIBlox = App.Parent
local Core = UIBlox.Core
local Packages = UIBlox.Parent
local t = require(Packages.t)
local Roact = require(Packages.Roact)
local Cryo = require(Packages.Cryo)
local Dictionary = Cryo.Dictionary
local List = Cryo.List
local Images = require(App.ImageSet.Images)
local validateImageSetData = require(Core.ImageSet.Validator.validateImageSetData)
local ControlState = require(Core.Control.Enum.ControlState)
local withStyle = require(Core.Style.withStyle)
local getContentStyle = require(Core.Button.getContentStyle)
local PlayerTileButton = require(App.Tile.PlayerTile.PlayerTileButton)
local RelevancyInfo = require(App.Tile.PlayerTile.RelevancyInfo)
local SpringAnimatedItem = require(UIBlox.Utility.SpringAnimatedItem)
local Tile = require(App.Tile.BaseTile.Tile)
local PlayerTile = Roact.PureComponent:extend("PlayerTile")
local imageType = t.union(t.string, validateImageSetData)
PlayerTile.validateProps = t.strictInterface({
title = t.string,
subtitle = t.string,
thumbnail = t.optional(t.union(t.string, t.table)),
buttons = t.optional(t.array(t.strictInterface({
icon = t.optional(imageType),
onActivated = t.optional(t.callback),
isSecondary = t.optional(t.boolean),
isDisabled = t.optional(t.boolean),
}))),
relevancyInfo = t.optional(t.strictInterface({
text = t.optional(t.string),
icon = t.optional(imageType),
onActivated = t.optional(t.callback),
})),
tileSize = t.optional(t.UDim2),
onActivated = t.optional(t.callback),
[Roact.Ref] = t.optional(t.table),
})
PlayerTile.defaultProps = {
buttons = {},
relevancyInfo = {
text = "",
icon = nil,
onActivated = function() end,
},
tileSize = UDim2.new(0, 150, 0, 150),
onActivated = function() end,
title = "",
subtitle = ""
}
local ANIMATION_SPRING_SETTINGS = {
dampingRatio = 1,
frequency = 4,
}
local CONTENT_STATE_COLOR = {
[ControlState.Default] = "SystemPrimaryContent",
}
local VIGNETTE = Images["component_assets/vignette_246"]
local OUTER_BUTTON_PADDING = 10
local BUTTON_HEIGHT = 36
local function footer(props)
return withStyle(function(style)
return Roact.createElement("Frame", {
AutomaticSize = Enum.AutomaticSize.XY,
BackgroundTransparency = 1,
}, {
RelevancyInfo = Roact.createElement(RelevancyInfo, {
text = props.relevancyInfo.text,
icon = props.relevancyInfo.icon,
onActivated = props.relevancyInfo.onActivated,
tileSize = props.tileSize,
}),
})
end)
end
local function thumbnailOverlayComponents(props)
return withStyle(function(style)
local primaryContentStyle = getContentStyle(CONTENT_STATE_COLOR, props.controlState, style)
return Roact.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.new(1, 0, 1, 0),
}, {
ButtonBackgroundGradient = not Cryo.isEmpty(props.buttons) and Roact.createElement("Frame", {
Size = UDim2.new(1, 0, 0, BUTTON_HEIGHT + OUTER_BUTTON_PADDING*2),
AnchorPoint = Vector2.new(0, 1),
Position = UDim2.new(0, 0, 1, 0),
LayoutOrder = 1,
}, {
UIGradient = Roact.createElement("UIGradient", {
Rotation = 90,
Color = ColorSequence.new({
ColorSequenceKeypoint.new(0, style.Theme.BackgroundUIContrast.Color),
ColorSequenceKeypoint.new(1, style.Theme.BackgroundUIContrast.Color),
}),
Transparency = NumberSequence.new({
NumberSequenceKeypoint.new(0, 1),
NumberSequenceKeypoint.new(1, style.Theme.BackgroundUIContrast.Transparency),
}),
}),
UICorner = Roact.createElement("UICorner", {
CornerRadius = UDim.new(0, 8),
})
}),
HoverTransparency = Roact.createElement(SpringAnimatedItem.AnimatedImageLabel, {
springOptions = ANIMATION_SPRING_SETTINGS,
animatedValues = {
imageTransparency = props.mouseEntered and 0.6 or 1,
},
mapValuesToProps = function(values)
return {
ImageTransparency = values.imageTransparency,
}
end,
regularProps = {
Size = UDim2.new(1, 0, 1, 0),
BackgroundTransparency = 1,
Image = VIGNETTE.Image,
ImageRectSize = VIGNETTE.ImageRectSize,
ImageRectOffset = VIGNETTE.ImageRectOffset,
ImageColor3 = primaryContentStyle.Color,
ImageTransparency = 0,
LayoutOrder = 2,
[Roact.Event.MouseEnter] = props.hoverMouseEnter,
[Roact.Event.MouseLeave] = props.hoverMouseLeave,
},
}, {
corner = Roact.createElement("UICorner", {
CornerRadius = UDim.new(0, 8),
}),
}),
ButtonContainer = Roact.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.new(1, 0, 1, 0),
ZIndex = 2,
}, {
PlayerTileButtons = Roact.createElement("Frame", {
BackgroundTransparency = 1,
Position = UDim2.new(1, 0, 1, 0),
Size = UDim2.new(0, props.tileSize.X.Offset - (OUTER_BUTTON_PADDING * 2), 0, BUTTON_HEIGHT),
AnchorPoint = Vector2.new(1, 1),
LayoutOrder = 3,
ZIndex = 2,
}, List.join(List.map(props.buttons, function(button)
return Roact.createElement(PlayerTileButton, {
buttonHeight = BUTTON_HEIGHT,
tileSize = props.tileSize,
icon = button.icon,
isSecondary = button.isSecondary,
isDisabled = button.isDisabled,
onActivated = button.onActivated,
mouseEnter = props.hoverMouseEnter,
mouseLeave = props.hoverMouseLeave,
})
end), {
Roact.createElement("UIListLayout", {
HorizontalAlignment = Enum.HorizontalAlignment.Right,
Padding = UDim.new(0, 10),
FillDirection = Enum.FillDirection.Horizontal,
})
})),
UIPadding = Roact.createElement("UIPadding", {
PaddingBottom = UDim.new(0, OUTER_BUTTON_PADDING),
PaddingRight = UDim.new(0, OUTER_BUTTON_PADDING),
}),
}),
})
end)
end
function PlayerTile:init()
self.firstButtonIcon = Roact.createRef()
self.secondButtonIcon = Roact.createRef()
self.mouseEntered = false
self.state = {
controlState = ControlState.Initialize,
mouseEntered = false
}
self.onStateChanged = function(oldState, newState)
self:setState({
controlState = newState,
})
if self.props.onStateChanged then
self.props.onStateChanged(oldState, newState)
end
end
self.hoverMouseEnter = function()
self:setState({
mouseEntered = true,
})
end
self.hoverMouseLeave = function()
self:setState({
mouseEntered = false,
})
end
end
function PlayerTile:render()
local tileSize = self.props.tileSize
local title = self.props.title
local onActivated = self.props.onActivated
local thumbnail = self.props.thumbnail
return withStyle(function(style)
return Roact.createElement("Frame", {
Size = tileSize,
Position = UDim2.new(0, 0, 0, 0),
BackgroundTransparency = 1,
LayoutOrder = 1,
[Roact.Ref] = self.props[Roact.Ref],
}, {
Tile = Roact.createElement(Tile, {
footer = footer(Dictionary.join(self.props, {
controlState = self.state.controlState,
})),
hasRoundedCorners = true,
innerPadding = OUTER_BUTTON_PADDING,
name = title,
subtitle = self.props.subtitle,
titleTextLineCount = 1,
onActivated = onActivated,
thumbnail = thumbnail,
backgroundImage = Images[style.Theme.PlayerBackgroundDefault.Image],
thumbnailOverlayComponents = thumbnailOverlayComponents(Dictionary.join(self.props, {
hoverMouseEnter = self.hoverMouseEnter,
hoverMouseLeave = self.hoverMouseLeave,
mouseEntered = self.state.mouseEntered,
})),
})
})
end)
end
return PlayerTile
|
local config = {}
config.areaID = 1000
config.db =
{
STDictDBMgr = {ip = "127.0.0.1", port = 3306, db = "dict", user = "root", pwd = "123456"},
STInfoDBMgr = {ip = "127.0.0.1", port = 3306, db = "info", user = "root", pwd = "123456"},
STLogDBMgr = {ip = "127.0.0.1", port = 3306, db = "log", user = "root", pwd = "123456"},
}
config.docker =
{
{
dockerListenHost="::",
dockerPubHost="127.0.0.1",
dockerListenPort=16001,
clientPubHost="127.0.0.1",
clientPubPort=26000,
services={"STLogDBMgr", "STAvatarMgr", "STAvatar", "STInfoDBMgr"},
dockerID = 1,
},
{
dockerListenHost="::",
dockerPubHost="127.0.0.1",
dockerListenPort=16002,
clientPubHost="127.0.0.1",
clientPubPort=26001,
webPubHost="127.0.0.1",
webPort=26080,
services={"STWebAgent", "STOfflineMgr", "STMinitorMgr", "STAvatar"},
dockerID = 2,
},
{
desc="异构服务器, 注释掉该配置则起服忽略该服务的存在.",
dockerListenHost="::",
dockerPubHost="127.0.0.1",
dockerListenPort=16099,
dockerWhite={"192.168.", "127.0."},
services={"STWorldMgr"},
dockerID = 3,
},
}
config.world =
{
dockerID = 3,
dockerListenHost="::",
dockerListenPort=16099,
sceneListenHost="::",
scenePubHost="127.0.0.1",
sceneListenPort=16088,
}
config.scenes =
{
{
lineID = 1,
clientListenHost="::",
clientPubHost="127.0.0.1",
clientListenPort=17101,
},
{
lineID = 2,
clientListenHost="::",
clientPubHost="127.0.0.1",
clientListenPort=17102,
},
{
lineID = 3,
clientListenHost="::",
clientPubHost="127.0.0.1",
clientListenPort=17103,
},
{
lineID = 4,
clientListenHost="::",
clientPubHost="127.0.0.1",
clientListenPort=17104,
},
}
return config
|
qui_hyang = {
use = async(function(player)
local t = {graphic = convertGraphic(309, "item"), color = 0}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
if player.warpOut == 0 then
player:sendMinitext("Unable to warp out.")
return
end
if player.state == 1 then
player:sendMinitext("You need a physical body in order to use this yellow scroll.")
return
end
local opts = {"Home"}
if player.clan ~= 0 then
table.insert(opts, "Clan hall")
end
if player.class >= 10 then
table.insert(opts, "Subpath Circle")
end
table.insert(opts, "Main Inn")
local choice = player:menuString("Where do you wish to go?", opts)
if choice == "Home" then
player:returnFunc()
return
elseif choice == "Subpath Circle" then
player:returnToSubpath()
return
elseif choice == "Clan hall" then
player:returnToClan()
return
elseif choice == "Main Inn" then
player:returnToInn()
else
return
end
end)
}
|
local math = require("math")
local error, type = error, type
local luasimplex = require("luasimplex")
local abs = math.abs
-- Constants -------------------------------------------------------------------
local TOLERANCE: number = 1e-7
local NONBASIC_LOWER: integer = 1
local NONBASIC_UPPER: integer = -1
local NONBASIC_FREE: integer = 2
local BASIC: integer = 0
-- Computation parts -----------------------------------------------------------
local function compute_pi(M: table, I: table)
-- pi = basic_costs' * Binverse
local nrows: integer, pi: number[], Bi: number[], TOL: number = M.nrows, I.pi, I.Binverse, I.TOLERANCE
local basic_costs: number[] = I.basic_costs
for i = 1, nrows do pi[i] = 0 end
for i = 1, nrows do
local c: number = basic_costs[i]
if abs(c) > TOL then
for j = 1, nrows do
pi[j] = pi[j] + c * Bi[(i-1)*nrows + j]
end
end
end
end
local function compute_reduced_cost(M: table, I: table)
-- reduced cost = cost - pi' * A
local reduced_costs: number[], status: integer[], TOL: number = I.reduced_costs, I.status, I.TOLERANCE
local indexes: integer[], elements: number[], row_starts: integer[] = M.indexes, M.elements, M.row_starts
local pi: number[] = I.pi
local nvars: integer = M.nvars
local nrows: integer = M.nrows
local costs: number[] = I.costs
-- initialise with costs (phase 2) or zero (phase 1 and basic variables)
for i = 1, nvars do
reduced_costs[i] = status[i] ~= 0 and costs[i] or 0
end
-- Compute rcs 'sideways' - work through elements of A using each one once
-- the downside is that we write to reduced_costs frequently
for i = 1, nrows do
local p = pi[i]
if abs(p) > TOL then
for j = row_starts[i], row_starts[i+1]-1 do
local k: integer = indexes[j]
if status[k] ~= 0 then
reduced_costs[k] = reduced_costs[k] - p * elements[j]
end
end
end
end
end
local function find_entering_variable(M: table, I: table)
local TOL: number = -I.TOLERANCE
-- Find the variable with the "lowest" reduced cost, keeping in mind that it might be at its upper bound
local cycles: integer, minrc: number, entering_index: integer = math.maxinteger, 0.0, -1
local nvars: integer = M.nvars
local status: integer[] = I.status
local reduced_costs: number[] = I.reduced_costs
local basic_cycles: integer[] = I.basic_cycles
for i = 1, nvars do
local s: integer, rc: number = status[i]
if s == NONBASIC_FREE then
rc = -abs(reduced_costs[i])
else
rc = s * reduced_costs[i]
end
local c: integer = basic_cycles[i]
if (c < cycles and rc < TOL) or (c == cycles and rc < minrc) then
minrc = rc
cycles = basic_cycles[i]
entering_index = i
end
end
return entering_index
end
local function compute_gradient(M: table, I: table, entering_index: integer, g)
-- gradient = Binverse * entering column of A
local nrows: integer, Bi: number[] = M.nrows, I.Binverse
local indexes: integer[], elements: number[], row_starts: integer[] = M.indexes, M.elements, M.row_starts
local gradient: number[] = {}
if g then
gradient = g
for i = 1, nrows do gradient[i] = 0 end
else
gradient = table.numarray(nrows, 0)
end
for i = 1, nrows do
local v: number
local found: integer = 0
for j = row_starts[i], row_starts[i+1]-1 do
local column: integer = indexes[j]
if column == entering_index then
v = elements[j]
found = 1
break
elseif column > entering_index then
break
end
end
if found == 1 then
for j = 1, nrows do
gradient[j] = gradient[j] + v * Bi[(j-1)*nrows + i]
end
end
end
return gradient
end
local function find_leaving_variable(M: table, I: table, entering_index: integer, gradient: number[])
local TOL: number = I.TOLERANCE
local status: integer[] = I.status
local reduced_costs: number[] = I.reduced_costs
local xu: number[] = I.xu
local xl: number[] = I.xl
local x: number[] = I.x
local nrows: integer, nvars: integer = M.nrows, M.nvars
local basics: integer[] = I.basics
local s: integer = status[entering_index]
if s == NONBASIC_FREE then
s = reduced_costs[entering_index] > 0 and -1 or 1
end
local max_change: number, leaving_index: integer, to_lower = xu[entering_index] - xl[entering_index], -1
for i = 1, nrows do
local g: number = gradient[i] * -s
if abs(g) > TOL then
local j: integer, bound: number = basics[i]
local found_bound: integer = 0
if g > 0 then
if xu[j] < math.huge then
bound = xu[j]
found_bound = 1
end
else
if xl[j] > -math.huge then
bound = xl[j]
found_bound = 1
end
end
if found_bound == 1 then
local z: number = (bound - x[j]) / g
-- we prefer to get rid of artificials when we can
if z < max_change or (j > nvars and z <= max_change) then
max_change = z
leaving_index = i
to_lower = g < 0
end
end
end
end
return leaving_index, max_change * s, to_lower
end
local function update_variables(M: table, I: table)
local c: number = I.max_change
local basics: integer[] = I.basics
local x: number[] = I.x
local gradient: number[] = I.gradient
local nrows: integer = M.nrows
for i = 1, nrows do
local j: integer = basics[i]
x[j] = x[j] - c * gradient[i]
end
end
local function update_Binverse(M: table, I: table)
local nrows: integer, li: integer, Bi: number[] = M.nrows, I.leaving_index, I.Binverse
local gradient: number[] = I.gradient
local ilg: number = 1.0 / gradient[li]
for i = 1, nrows do
if i ~= li then
local gr: number = gradient[i] * ilg
for j = 1, nrows do
Bi[(i-1)*nrows + j] = Bi[(i-1)*nrows + j] - gr * Bi[(li-1)*nrows + j]
end
end
end
for j = 1, nrows do
Bi[(li-1)*nrows + j] = Bi[(li-1)*nrows + j] * ilg
end
end
-- Initialisation --------------------------------------------------------------
local function initialise_real_variables(M: table, I: table, offset: integer)
local nvars: integer = M.nvars
local I_xu: number[] = I.xu
local I_xl: number[] = I.xl
local I_x: number[] = I.x
local M_xu: number[] = M.xu
local M_xl: number[] = M.xl
local status: integer[] = I.status
for ii = 1, nvars do
local i: integer = ii + offset
I_xu[i], I_xl[i] = M_xu[i], M_xl[i]
if M_xl[i] == -math.huge and M_xu[i] == math.huge then
I_x[i] = 0
status[i] = NONBASIC_FREE
elseif abs(M_xl[i]) < abs(M_xu[i]) then
I_x[i] = M_xl[i]
status[i] = NONBASIC_LOWER
else
I_x[i] = M_xu[i]
status[i] = NONBASIC_UPPER
end
end
end
local function initialise_artificial_variables(M: table, I: table, offset: integer)
local nrows: integer, nvars: integer = M.nrows, M.nvars
local indexes: integer[], elements: number[], row_starts: integer[] = M.indexes, M.elements, M.row_starts
local b: number[] = M.b
local xu: number[] = I.xu
local xl: number[] = I.xl
local x: number[] = I.x
local basic_costs: number[] = I.basic_costs
local basics: integer[] = I.basics
local status: integer[] = I.status
for ii = 1, nrows do
local i: integer = ii + offset
local z: number = b[i]
for j = row_starts[i], row_starts[i+1]-1 do
z = z - elements[j] * x[indexes[j]]
end
local k: integer = nvars + i
x[k] = z
status[k] = BASIC
basics[i] = k
if z < 0 then
basic_costs[i], xl[k], xu[k] = -1, -math.huge, 0
else
basic_costs[i], xl[k], xu[k] = 1, 0, math.huge
end
if type(M) == "table" and M.variable_names and M.constraint_names then
M.variable_names[k] = M.constraint_names[i].."_ARTIFICIAL"
end
end
end
local function initialise(M: table, I: table, S, c_arrays)
local offset: integer = c_arrays and -1 or 0
local nrows: integer = M.nrows
if not S.TOLERANCE then S.TOLERANCE = TOLERANCE end
I.TOLERANCE = S.TOLERANCE
initialise_real_variables(M, I, offset)
initialise_artificial_variables(M, I, offset)
local Binverse: number[] = I.Binverse
for i = 1, nrows do Binverse[(i-1)*nrows + i + offset] = 1 end
return I
end
-- Solve -----------------------------------------------------------------------
local function solve(M: table, I: table, S)
local TOLERANCE: number = I.TOLERANCE
local x: number[] = I.x
local basic_costs: number[] = I.basic_costs
local basics: integer[] = I.basics
local status: integer[] = I.status
local x: number[] = I.x
local xu: number[] = I.xu
local xl: number[] = I.xl
local basic_cycles: integer[] = I.basic_cycles
local nvars: integer, nrows: integer = M.nvars, M.nrows
I.iterations = 0
I.phase = 1
local monitor = S.monitor
while true do
I.iterations = I.iterations + 1
if monitor then monitor(M, I, S, "iteration") end
if I.iterations > 10000 then
luasimplex.error("Iteration limit", M, I, S)
end
compute_pi(M, I)
compute_reduced_cost(M, I)
I.entering_index = find_entering_variable(M, I)
if monitor then monitor(M, I, S, "entering_variable") end
if I.entering_index == -1 then
if I.phase == 1 then
for i = 1, nrows do
if basics[i] > nvars and abs(x[basics[i]]) > TOLERANCE then
luasimplex.error("Infeasible", M, I, S)
end
end
I.costs = M.c
for i = 1, nrows do
if basics[i] <= nvars then
basic_costs[i] = M.c[basics[i] ]
end
end
I.phase = 2
else
break -- optimal
end
else
local entering_index: integer = I.entering_index
basic_cycles[entering_index] = basic_cycles[entering_index] + 1
compute_gradient(M, I, entering_index, I.gradient)
local to_lower
I.leaving_index, I.max_change, to_lower = find_leaving_variable(M, I, entering_index, I.gradient)
if monitor then monitor(M, I, S, "leaving_variable") end
local max_change: number = I.max_change
local leaving_index: integer = I.leaving_index
local costs: number[] = I.costs
if I.phase == 2 and max_change >= math.huge / 2 then
luasimplex.error("Unbounded", M, I, S)
end
if abs(max_change) > TOLERANCE then
for i = 1, nvars do
basic_cycles[i] = 0
end
end
update_variables(M, I)
x[entering_index] = x[entering_index] + max_change
if leaving_index ~= -1 then
update_Binverse(M, I)
local rli: integer = basics[leaving_index]
x[rli] = to_lower and xl[rli] or xu[rli]
status[rli] = to_lower and NONBASIC_LOWER or NONBASIC_UPPER
basics[leaving_index] = entering_index
basic_costs[leaving_index] = costs[entering_index]
status[entering_index] = BASIC
else
status[entering_index] = -status[entering_index]
end
end
end
local objective = 0
for i = 1, nvars do
objective = objective + x[i] * M.c[i]
end
return objective, x, I.iterations
end
--------------------------------------------------------------------------------
ravi.compile(initialise)
ravi.compile(initialise_artificial_variables)
ravi.compile(initialise_real_variables)
ravi.compile(compute_pi)
ravi.compile(compute_reduced_cost)
ravi.compile(compute_gradient)
ravi.compile(find_leaving_variable)
ravi.compile(find_entering_variable)
ravi.compile(update_Binverse)
ravi.compile(update_variables)
ravi.compile(solve)
return
{
initialise = initialise,
solve = solve,
compute_gradient = compute_gradient,
find_leaving_variable = find_leaving_variable,
}
-- EOF -------------------------------------------------------------------------
|
return function()
local Reducers = script.Parent.Parent.Reducers
local DevConsoleReducer = require(Reducers.DevConsoleReducer)
local DevConsoleDisplayOptions = require(Reducers.DevConsoleDisplayOptions)
local MainView = require(Reducers.MainView)
local MemoryData = require(Reducers.MemoryData)
local NetworkData = require(Reducers.NetworkData)
local ScriptsData = require(Reducers.ScriptsData)
local DataStoresData = require(Reducers.DataStoresData)
local ServerStatsData = require(Reducers.ServerStatsData)
local ServerJobsData = require(Reducers.ServerJobsData)
local ActionBindingsData = require(Reducers.ActionBindingsData)
local MicroProfiler = require(Reducers.MicroProfiler)
it("has the expected fields, and only the expected fields", function()
local state = DevConsoleReducer(nil, {})
local expectedKeys = {
DisplayOptions = DevConsoleDisplayOptions(nil, {}),
MainView = MainView(nil, {}),
MemoryData = MemoryData(nil, {}),
NetworkData = NetworkData(nil, {}),
ScriptsData = ScriptsData(nil, {}),
DataStoresData = DataStoresData(nil, {}),
ServerStatsData = ServerStatsData(nil, {}),
ServerJobsData = ServerJobsData(nil, {}),
ActionBindingsData = ActionBindingsData(nil, {}),
MicroProfiler = MicroProfiler(nil, {}),
}
for key in pairs(expectedKeys) do
assert(state[key] ~= nil, string.format("Expected field %q", key))
end
for key in pairs(state) do
assert(expectedKeys[key] ~= nil, string.format("Did not expect field %q", key))
end
end)
end
|
--!A cross-platform build utility based on Lua
--
-- 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.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file repository.lua
--
-- define module
local sandbox_core_package_repository = sandbox_core_package_repository or {}
-- load modules
local global = require("base/global")
local project = require("project/project")
local repository = require("package/repository")
local raise = require("sandbox/modules/raise")
local import = require("sandbox/modules/import")
-- get repository directory
function sandbox_core_package_repository.directory(is_global)
return repository.directory(is_global)
end
-- get repository url from the given name
function sandbox_core_package_repository.get(name, is_global)
return repository.get(name, is_global)
end
-- add repository url to the given name
function sandbox_core_package_repository.add(name, url, branch, is_global)
-- add it
local ok, errors = repository.add(name, url, branch, is_global)
if not ok then
raise(errors)
end
end
-- remove repository from gobal or local directory
function sandbox_core_package_repository.remove(name, is_global)
-- remove it
local ok, errors = repository.remove(name, is_global)
if not ok then
raise(errors)
end
end
-- clear all repositories from global or local directory
function sandbox_core_package_repository.clear(is_global)
-- clear all repositories
local ok, errors = repository.clear(is_global)
if not ok then
raise(errors)
end
end
-- get all repositories from global or local directory
function sandbox_core_package_repository.repositories(is_global)
-- add main global xmake repository
local repositories = {}
if is_global and global.get("network") ~= "private" then
-- import fasturl
import("net.fasturl")
-- sort main urls
local mainurls = {"https://github.com/xmake-io/xmake-repo.git", "https://gitlab.com/tboox/xmake-repo.git", "https://gitee.com/tboox/xmake-repo.git"}
fasturl.add(mainurls)
mainurls = fasturl.sort(mainurls)
-- add main url
if #mainurls > 0 then
local repo = repository.load("xmake-repo", mainurls[1], "master", true)
if repo then
table.insert(repositories, repo)
end
end
end
-- load repositories from repository cache
for name, repoinfo in pairs(table.wrap(repository.repositories(is_global))) do
local url = repoinfo
local branch = nil
if type(repoinfo) == "table" then
url = repoinfo[1]
branch = repoinfo[2]
end
local repo = repository.load(name, url, branch, is_global)
if repo then
table.insert(repositories, repo)
end
end
-- load repositories from project file
--
-- in project xmake.lua:
--
-- add_repositories("other-repo https://github.com/other/other-repo.git dev")
--
if not is_global then
for _, repo in ipairs(table.wrap(project.get("repositories"))) do
local repoinfo = repo:split('%s')
if #repoinfo <= 3 then
local repo = repository.load(repoinfo[1], repoinfo[2], repoinfo[3], is_global)
if repo then
table.insert(repositories, repo)
end
else
raise("invalid repository: %s", repo)
end
end
end
-- load repository from builtin program directory
if is_global then
local repo = repository.load("builtin-repo", path.join(os.programdir(), "repository"), nil, true)
if repo then
table.insert(repositories, repo)
end
end
-- get the repositories
return repositories
end
-- return module
return sandbox_core_package_repository
|
package("mem")
set_kind("library", {headeronly = true})
set_homepage("https://github.com/0x1F9F1/mem")
set_description("A collection of C++11 headers useful for reverse engineering")
add_urls("https://github.com/0x1F9F1/mem/archive/refs/tags/$(version).tar.gz",
"https://github.com/0x1F9F1/mem.git")
add_versions("1.0.0", "db1e58b040ea39ec5794fc1dcc6749c81b062579d9f6b086d035266456bccaf3")
on_install("windows", "linux", function (package)
os.cp("include/mem", package:installdir("include"))
end)
on_test(function (package)
assert(package:has_cxxfuncs("mem::module::main()", {includes = "mem/module.h", configs = {languages = "c++11"}}))
end)
|
--[[
License : GLPv3, see LICENCE in root of repository
Authors : Nikolay Fiykov, v1
--]]
wifi = {}
wifi.__index = wifi
wifi.NULLMODE = 0
wifi.STATION = 1
wifi.SOFTAP = 2
wifi.STATIONAP = 3
wifi.OPEN = 14
wifi.WPA_PSK = 15
wifi.WPA2_PSK = 16
wifi.WPA_WPA2_PSK = 17
wifi.wifiModeEnum = {wifi.STATION, wifi.SOFTAP, wifi.STATIONAP, wifi.NULLMODE}
wifi.wifiAuthEnum = {wifi.OPEN, wifi.WPA_PSK, wifi.WPA2_PSK, wifi.WPA_WPA2_PSK}
wifi.stationModeEnum = {wifi.STATION, wifi.STATIONAP}
return wifi
|
--- @class Joystick
Joystick = GameObject:extend()
--- @field working boolean
--- @field stickSize int
--- @field sw number
--- @field sh number
--- @field changeRange number
--- @field relative boolean
--- @field resetPosition func
function Joystick:new()
self.working=false
self.stickSize=30
self.sw,self.sh = love.graphics.getDimensions()
self.changeRange = 0.25
self.relative = false
self.depth = 0
self:resetPosition()
end
function Joystick:resetPosition()
--self.size=setting.ctrlSize/gw
--self.cx = setting.ctrlX
--self.cy = setting.ctrlY
self.size = 20
self.cx = 40
self.cy = gh - 40
end
function Joystick:inBound()
return love.mouse.getX()< love.graphics.getWidth()/2
end
local function getDist(x,y,z,w)
return math.sqrt((x-z)*(x-z) + (y-w)*(y-w))
end
function Joystick:limitToRound()
local dist=getDist(self.cx,self.cy,self.sx,self.sy)
if dist>self.size then
local dx = (self.sx-self.cx)* self.size/dist
local dy = (self.sy-self.cy)* self.size/dist
self.sx= self.cx+(self.sx-self.cx)* self.size/dist
self.sy= self.cy+(self.sy-self.cy)* self.size/dist
--self.cx=self.cx+(self.sx-self.cx)* self.size/dist/10
--self.cy=self.cy+(self.sy-self.cy)* self.size/dist/10
end
end
function Joystick:getValue()
if self.left then
self.vx= (self.sx-self.cx)/self.size
self.vy= (self.sy-self.cy)/self.size
else
self.vx= 0
self.vy= 0
end
end
function Joystick:testTouch()
local touches = love.touch.getTouches()
self.left = false
self.right = false
self.mx,self.my = 0,0
--touches[1] = love.mouse.isDown(1)
for i, id in ipairs(touches) do
--local x,y = love.touch.getPosition(id)
p_print(i,id)
local x,y = love.mouse.getPosition()
if x< self.sw/2 then
self.left = true
self.mx,self.my = x,y
p_print(self.mx,self.my)
else
self.right = true
self.rx,self.ry = x,y
p_print(self.mx,self.my)
end
end
end
function Joystick:update(dt)
--p_print("joystick update")
self:testTouch()
if self.relative then
if self.working then
if self.left then
self.sx,self.sy = self.mx,self.my
self.limitToRound()
else
self.cx=nil
self.working=false
return
end
else
self.working = self.left
if self.working then
self.cx,self.cy = self.mx,self.my
self.sx,self.sy = self.cx, self.cy
end
end
else
if self.left then
self.sx,self.sy = self.mx,self.my
self:limitToRound()
end
end
self:getValue()
end
function Joystick:control(tank,dt)
if self.vx > self.changeRange then
if self.vy< - self.changeRange then -- right up
if self.lastDown == "up" then
self.currentDown = "right"
elseif self.lastDown == "right" then
self.currentDown = "up"
end
elseif self.vy > self.changeRange then --right down
if self.lastDown == "down" then
self.currentDown = "right"
elseif self.lastDown == "right" then
self.currentDown = "down"
end
else --right
self.lastDown = "right"
self.currentDown = "right"
end
elseif self.vx< - self.changeRange then
if self.vy< - self.changeRange then -- left up
if self.lastDown == "up" then
self.currentDown = "left"
elseif self.lastDown == "left" then
self.currentDown = "up"
end
elseif self.vy > self.changeRange then --left down
if self.lastDown == "left" then
self.currentDown = "left"
elseif self.lastDown == "left" then
self.currentDown = "down"
end
else --left
self.lastDown = "left"
self.currentDown = "left"
end
elseif self.vy>self.changeRange then
self.lastDown = "down"
self.currentDown = "down"
elseif self.vy<-self.changeRange then
self.lastDown = "up"
self.currentDown = "up"
else
self.currentDown = "none"
end
if self.currentDown == "up" then
if tank.rot == 0 then
tank.dx = 0
tank.dy = - tank.speed*dt
else
tank.rot = 0
end
elseif self.currentDown == "down" then
if tank.rot == 2 then
tank.dx = 0
tank.dy = tank.speed*dt
else
tank.rot = 2
end
elseif self.currentDown == "left" then
if tank.rot == 3 then
tank.dy = 0
tank.dx = - tank.speed*dt
else
tank.rot = 3
end
elseif self.currentDown == "right" then
if tank.rot == 1 then
tank.dy = 0
tank.dx = tank.speed*dt
else
tank.rot = 1
end
end
if self.right then
tank:fire()
end
end
function Joystick:draw()
love.graphics.setColor(1, 1, 1, 0.7)
love.graphics.circle("line", self.cx, self.cy, self.size)
if self.left then
love.graphics.setColor(1, 1,1, 0.5)
love.graphics.circle("fill", self.sx, self.sy, self.stickSize)
end
if self.right then
love.graphics.setColor(1, 1,1, 0.5)
love.graphics.circle("fill", self.rx, self.ry, self.stickSize)
end
self:getValue()
love.graphics.print(string.format("axis x: %0.2f; axis y: %0.2f",self.vx,self.vy),100,100)
end
return Joystick
|
return require("lapis.db.model")
|
--
-- Please see the license.html file included with this distribution for
-- attribution and copyright information.
--
function onInit()
local node = getDatabaseNode();
if node then
node.createChild("level0");
node.createChild("level1");
node.createChild("level2");
node.createChild("level3");
node.createChild("level4");
node.createChild("level5");
node.createChild("level6");
node.createChild("level7");
node.createChild("level8");
node.createChild("level9");
end
end
function onFilter(w)
return w.getFilter();
end
function addEntry()
return createWindow();
end
function onDrop(x, y, draginfo)
if isReadOnly() then
return false;
end
local winLevel = getWindowAt(x, y);
if not winLevel then
return false;
end
-- Draggable spell name to move spells
if draginfo.isType("spellmove") then
local node = winLevel.getDatabaseNode();
if node then
local nodeSource = draginfo.getDatabaseNode();
local nodeNew = SpellManager.addSpell(nodeSource, node.getChild("..."), DB.getValue(node, "level"));
if nodeNew then
nodeSource.delete();
winLevel.spells.setVisible(true);
DB.setValue(window.getDatabaseNode().getChild("..."), "spellmode", "string", "standard");
end
end
return true;
-- Spell link with level information (i.e. class spell list)
elseif draginfo.isType("spelldescwithlevel") then
local node = winLevel.getDatabaseNode();
if node then
local nodeSource = draginfo.getDatabaseNode();
local nodeNew = SpellManager.addSpell(nodeSource, node.getChild("..."), DB.getValue(node, "level"));
if nodeNew then
winLevel.spells.setVisible(true);
DB.setValue(window.getDatabaseNode().getChild("..."), "spellmode", "string", "standard");
end
end
return true;
-- Spell link with no level information
elseif draginfo.isType("shortcut") then
local sDropClass, sSource = draginfo.getShortcutData();
if sDropClass == "spelldesc" or sDropClass == "spelldesc2" then
local node = winLevel.getDatabaseNode();
if node then
local nodeSource = DB.findNode(sSource);
local nodeNew = SpellManager.addSpell(nodeSource, node.getChild("..."), DB.getValue(node, "level"));
if nodeNew then
winLevel.spells.setVisible(true);
DB.setValue(window.getDatabaseNode().getChild("..."), "spellmode", "string", "standard");
end
return true;
end
end
end
end
|
-- Colorscheme
local c = {
"{{ CS_TERM[0] }}",
"{{ CS_TERM[1] }}",
"{{ CS_TERM[2] }}",
"{{ CS_TERM[3] }}",
"{{ CS_TERM[4] }}",
"{{ CS_TERM[5] }}",
"{{ CS_TERM[6] }}",
"{{ CS_TERM[7] }}",
"{{ CS_TERM[8] }}",
"{{ CS_TERM[9] }}",
"{{ CS_TERM[10] }}",
"{{ CS_TERM[11] }}",
"{{ CS_TERM[12] }}",
"{{ CS_TERM[13] }}",
"{{ CS_TERM[14] }}",
"{{ CS_TERM[15] }}"
}
-- Return
local r = {
black = "{{ CS_BG }}",
white = "{{ CS_FG }}",
grey = c[9],
red = c[2],
accent = "{{ CS_ACC }}",
transparent = "#00000000",
cs = c
}
alpha = "80"
r.black_semi = r.black .. alpha
r.white_semi = r.white .. alpha
r.white_semi = r.grey .. alpha
r.accent_semi = r.accent .. alpha
return r
|
object_tangible_tcg_series3_greeter_deed_battle_droid = object_tangible_tcg_series3_shared_greeter_deed_battle_droid:new {
}
ObjectTemplates:addTemplate(object_tangible_tcg_series3_greeter_deed_battle_droid, "object/tangible/tcg/series3/greeter_deed_battle_droid.iff")
|
local M = {}
local telescope_mapper = require "rb.telescope.mappings"
function M.set(client)
local opts = {noremap = true, silent = true}
-- install servers
vim.api.nvim_set_keymap('n', '<leader>lsp', "<cmd>lua require('rb.lsp.install_servers').lsp_install_servers()<CR>", opts)
-- gives definition & references
vim.api.nvim_set_keymap('n', '<leader>gr', "<cmd>Lspsaga lsp_finder<CR>", opts)
-- vim.api.nvim_set_keymap('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts)
vim.api.nvim_set_keymap('n', '<leader>h', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
-- vim.api.nvim_set_keymap('n', '<leader>h', "<cmd>Lspsaga hover_doc<CR>", opts)
vim.api.nvim_set_keymap('n', '<leader>gs', "<cmd>Lspsaga signature_help<CR>", opts)
-- Diagnostic
-- vim.api.nvim_set_keymap('n','<leader>fe', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts)
-- vim.api.nvim_set_keymap('n','<leader>fe', '<cmd>:LspDiagnostics 0<CR>', opts)
vim.api.nvim_set_keymap('n', '<leader>dd', "<cmd>lua require('rb.lsp.functions').show_diagnostics()<CR>", opts)
vim.api.nvim_set_keymap('n', '<leader>fE', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
-- vim.api.nvim_set_keymap('n', '<leader>d', "<cmd>Lspsaga show_line_diagnostics<CR>", opts)
vim.api.nvim_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
vim.api.nvim_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
-- vim.api.nvim_set_keymap('n', '[d', "<cmd><Lspsaga diagnostic_jump_prev<CR>", opts)
-- vim.api.nvim_set_keymap('n', ']d', "<cmd>Lspsaga diagnostic_jump_next<CR>", opts);
--
vim.api.nvim_set_keymap("n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
vim.api.nvim_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
vim.api.nvim_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
vim.api.nvim_set_keymap('n', '<leader>lc', ':lua print(vim.inspect(vim.lsp.get_active_clients()))<CR>', opts)
vim.api.nvim_set_keymap('n', '<leader>lp', ":lua print(vim.lsp.get_log_path())<CR>", opts)
-- vim.api.nvim_set_keymap('n','<leader>fcl', ":lua vim.cmd('e'..vim.lsp.get_log_path())<CR>", opts)
vim.api.nvim_set_keymap('n', '<leader>li', ':LspInfo()<CR>', opts)
if client.definitionProvider then
vim.api.nvim_set_keymap('n', 'gD', "<cmd>Lspsaga preview_definition<CR>", opts)
vim.api.nvim_set_keymap('n', 'gt', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
end
if client.implementationProvider then vim.api.nvim_set_keymap('n', '<leader>gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts) end
if client.referencesProvider then
-- vim.api.nvim_set_keymap('n','<leader>tr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
vim.api.nvim_set_keymap('n', '<leader>gr', "<cmd>lua require('telescope.builtin').lsp_references()<CR>", opts)
end
-- vim.api.nvim_set_keymap('n','<leader>fa', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
-- vim.api.nvim_set_keymap('v', '<leader>fa', "<cmd>'<,'>lua vim.lsp.buf.range_code_action()<cr>", opts)
vim.api.nvim_set_keymap('n', '<leader>ca', "<cmd>lua require('telescope.builtin').lsp_code_actions({ timeout = 1000 })<CR>", opts)
vim.api.nvim_set_keymap('v', '<leader>car', "<cmd>lua require('telescope.builtin').lsp_range_code_actions({ timeout = 1000 })<CR>", opts)
vim.api.nvim_set_keymap('n', 'gx', "<cmd>Lspsaga code_action<CR>", opts)
-- vim.api.nvim_set_keymap('v', '<leader>fa', "<cmd>'<,'>lua require('lspsaga.codeaction').range_code_action()<CR>", opts) ]]
if client.renameProvider then
-- vim.api.nvim_set_keymap('n','<leader>rr','<cmd>lua vim.lsp.buf.rename()<CR>', opts)
vim.api.nvim_set_keymap('n', '<leader>rr', "<cmd>Lspsaga rename<CR>", opts)
end
vim.api.nvim_set_keymap('n', '<leader>bf', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
if client.documentRangeFormattingProvider then vim.api.nvim_set_keymap('n', '<leader>bF', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts) end
-- Typescript
vim.api.nvim_set_keymap("n", "<leader>to", ":TSLspOrganize<CR>", opts)
vim.api.nvim_set_keymap("n", "<leader>tc", ":TSLspFixCurrent<CR>", opts)
-- vim.api.nvim_set_keymap("n", "gr", ":TSLspRenameFile<CR>", 'lsp', 'lsp_', '')
vim.api.nvim_set_keymap("n", "<leader>ti", ":TSLspImportAll<CR>", opts)
-- Telescope
telescope_mapper("gr", "lsp_references", nil, true)
telescope_mapper("gI", "lsp_implementations", nil, true)
telescope_mapper("<space>wd", "lsp_document_symbols", {ignore_filename = true}, true)
telescope_mapper("<space>ww", "lsp_dynamic_workspace_symbols", {ignore_filename = true}, true)
-- telescope_mapper("<space>ca", "lsp_code_actions", nil, true)
end
return M
|
factory.require("machines/crafting")
factory.require("machines/belt")
factory.require("machines/ind_furnace")
factory.require("machines/ind_squeezer")
factory.require("machines/wire_drawer")
factory.require("machines/grinder")
factory.require("machines/stp")
factory.require("machines/swapper")
factory.require("machines/arm")
factory.require("machines/taker")
factory.require("machines/qarm")
factory.require("machines/oarm")
factory.require("machines/autocrafter")
if factory.setting_enabled("Fan") then
factory.require("machines/fan")
end
if factory.setting_enabled("Vacuum") then
factory.require("machines/vacuum")
factory.require("machines/upward_vacuum")
end
if factory.setting_enabled("Miner") then
factory.require("machines/miner")
end
|
local settings = {}
local buttons_tbl = {}
buttons_tbl[1] = {
x = nil,
y = nil,
z = nil,
width = nil,
height = nil,
function action()
end,
}
function settings.draw()
end
function settings.update(dt)
end
return settings
|
HedgewarsScriptLoad("/Scripts/Locale.lua")
local player = nil
local enemy = nil
function onGameInit()
Map = "Castle"
Theme = "Nature"
Seed = 0
GameFlags = gfInfAttack
TurnTime = 45 * 1000
CaseFreq = 0
MinesNum = 0
Explosives = 0
AddTeam(loc("Hero Team"), 14483456, "Simple", "Island", "Default", "Hedgewars")
player = AddHog(loc("Good Dude"), 0, 80, "NoHat") --NoHat
AddTeam(loc("Bad Team"), 1175851, "Simple", "Island", "Default", "Hedgewars")
enemy = AddHog("Bad Guy", 1, 40, "NoHat")
end
function onGameStart()
ShowMission(loc("The Great Escape"), loc("Get out of there!"), loc("Elimate your captor."), -amGrenade, 0)
------ GIRDER LIST ------
PlaceGirder(1042,564,0)
PlaceGirder(1028,474,6)
PlaceGirder(1074,474,6)
PlaceGirder(1050,385,0)
PlaceGirder(1175,731,7)
PlaceGirder(1452,905,2)
PlaceGirder(1522,855,4)
PlaceGirder(1496,900,3)
PlaceGirder(1682,855,4)
PlaceGirder(1773,887,2)
PlaceGirder(1647,901,1)
PlaceGirder(1871,883,6)
PlaceGirder(1871,723,6)
PlaceGirder(1774,768,6)
PlaceGirder(1773,767,6)
PlaceGirder(1821,904,1)
PlaceGirder(1822,802,3)
PlaceGirder(1820,723,1)
PlaceGirder(1782,678,4)
PlaceGirder(1822,661,0)
PlaceGirder(1822,644,0)
PlaceGirder(1742,644,0)
PlaceGirder(1742,661,0)
PlaceGirder(1694,676,2)
PlaceGirder(1903,635,0)
------ HEALTH CRATE LIST ------
SpawnHealthCrate(1476,169)
SpawnHealthCrate(1551,177)
SpawnHealthCrate(1586,200)
SpawnHealthCrate(1439,189)
SpawnHealthCrate(1401,211)
SpawnHealthCrate(1633,210)
------ MINE LIST ------
tempG = AddGear(1010,680,gtMine, 0, 0, 0, 0)
SetTimer(tempG, 1)
tempG = AddGear(1031,720,gtMine, 0, 0, 0, 0)
SetTimer(tempG, 1)
tempG = AddGear(1039,748,gtMine, 0, 0, 0, 0)
SetTimer(tempG, 1)
tempG = AddGear(1051,777,gtMine, 0, 0, 0, 0)
SetTimer(tempG, 1)
tempG = AddGear(1065,796,gtMine, 0, 0, 0, 0)
SetTimer(tempG, 1)
tempG = AddGear(1094,800,gtMine, 0, 0, 0, 0)
SetTimer(tempG, 1)
------ REPOSITION LIST ------
SetGearPosition(player,1050,534)
SetGearPosition(enemy,1512,158)
SetHealth(player, 1)
SetHealth(enemy, 1)
------ AMMO CRATE LIST ------
SpawnAmmoCrate(1632,943,5)
SpawnAmmoCrate(1723,888,12)
SpawnAmmoCrate(1915,599,1)
------ UTILITY CRATE LIST ------
SpawnUtilityCrate(1519,945,15)
SpawnUtilityCrate(1227,640,6)
SpawnUtilityCrate(1416,913,18)
------ END LOADING DATA ------
end
function onGameTick()
if TurnTimeLeft == TurnTime-1 then
SetWind(100)
end
end
function onGearDelete(gear)
if (GetGearType(gear) == gtCase) and (CurrentHedgehog == player) then
if GetHealth(gear) > 0 then
AddGear(GetX(gear), GetY(gear), gtGrenade, 0, 0, 0, 1)
end
elseif gear == player then
ShowMission(loc("The Great Escape"), loc("MISSION FAILED"), loc("Oh no! Just try again!"), -amSkip, 0)
elseif gear == enemy then
ShowMission(loc("The Great Escape"), loc("MISSION SUCCESSFUL"), loc("Congratulations!"), 0, 0)
end
end
function onAmmoStoreInit()
SetAmmo(amGrenade, 1, 0, 0, 1)
SetAmmo(amParachute, 1, 0, 0, 1)
SetAmmo(amFirePunch, 0, 0, 0, 3)
SetAmmo(amPickHammer, 0, 0, 0, 1)
SetAmmo(amBlowTorch, 0, 0, 0, 1)
SetAmmo(amShotgun, 0, 0, 0, 1)
SetAmmo(amSkip, 9, 0, 0, 0)
end
|
local STP = require("StackTracePlus")
local Page = {}
local function bla()
error("oops")
end
local function foo()
bla()
end
Page.render = foo
function main()
local p = {}
setmetatable(p, { __index = Page })
local x = "render"
p[x]()
end
xpcall(main, function() print(STP.stacktrace()) end)
|
function Chatbox:OnResolutionChanged(new_width, new_height)
Theme.set_option('chatbox_width', new_width * 0.375)
Theme.set_option('chatbox_height', new_height * 0.45)
Theme.set_option('chatbox_x', math.scale(8))
Theme.set_option('chatbox_y', new_height - Theme.get_option('chatbox_height') - math.scale(64))
local entry_height = Theme.set_option('chatbox_text_entry_height', math.scale(38)) or math.scale(38)
Theme.set_option('chatbox_text_entry_text_size', entry_height * 0.9)
if Chatbox.panel then
Chatbox.panel:Remove()
Chatbox.panel = nil
end
end
function Chatbox:PlayerBindPress(player, bind, pressed)
if IsValid(PLAYER) and PLAYER:has_initialized() and (string.find(bind, 'messagemode') or string.find(bind, 'messagemode2')) and pressed then
if string.find(bind, 'messagemode2') then
PLAYER.typing_team_chat = true
else
PLAYER.typing_team_chat = false
end
Chatbox.show()
return true
end
end
function Chatbox:GUIMousePressed(mouseCode, aim_vector)
if IsValid(Chatbox.panel) then
Chatbox.hide()
end
end
function Chatbox:HUDShouldDraw(element)
if element == 'CHudChat' then
return false
end
end
function Chatbox:CreateFonts()
Font.create('chat_font', {
font = 'Montserrat Medium',
size = 16
})
Font.create('chat_font_bold', {
font = 'Montserrat ExtraBold',
size = 16
})
Font.create('chat_font_italic', {
font = 'Montserrat Medium',
size = 16,
italic = true
})
Font.create('chat_font_italic_bold', {
font = 'Montserrat ExtraBold',
size = 16,
italic = true
})
end
function Chatbox:OnThemeLoaded(current_theme)
local scrw, scrh = ScrW(), ScrH()
current_theme:set_option('chatbox_text_small_size', math.scale(Config.get('small_font_size')))
current_theme:set_option('chatbox_text_normal_size', math.scale(Config.get('default_font_size')))
current_theme:set_option('chatbox_text_big_size', math.scale(Config.get('big_font_size')))
current_theme:set_option('chatbox_width', scrw * 0.375)
current_theme:set_option('chatbox_height', scrh * 0.45)
current_theme:set_option('chatbox_x', math.scale(8))
current_theme:set_option('chatbox_y', scrh - current_theme:get_option('chatbox_height') - math.scale(64))
current_theme:set_option('chatbox_fix_alignment', true)
current_theme:set_option('chatbox_padding', math.scale(8))
local entry_height = current_theme:set_option('chatbox_text_entry_height', math.scale(32))
local text_size = current_theme:set_option('chatbox_text_entry_text_size', entry_height * 0.75)
local font_size = current_theme:get_option('chatbox_text_normal_size')
current_theme:set_font('chatbox_normal', 'chat_font', font_size)
current_theme:set_font('chatbox_bold', 'chat_font_bold', font_size)
current_theme:set_font('chatbox_italic', 'chat_font_italic', font_size)
current_theme:set_font('chatbox_italic_bold', 'chat_font_italic_bold', font_size)
current_theme:set_font('chatbox_syntax', 'flRobotoCondensed', math.scale(24))
current_theme:set_font('chatbox_text_entry', 'chat_font', text_size)
current_theme:set_color('chat_text_entry_background', Color(0, 0, 0, 215))
end
function Chatbox:ChatboxTextEntered(text)
if text and text != '' then
Cable.send('fl_chat_player_say', text)
end
Chatbox.hide()
end
function Chatbox:ChatboxMessageCompiled(compiled)
local to_print = {}
for k, v in pairs(compiled) do
if istable(v) and v.text or IsColor(v) then
table.insert(to_print, IsColor(v) and v or v.text)
end
end
table.insert(to_print, '\n')
MsgC(unpack(to_print))
end
Cable.receive('fl_chat_message_add', function(message_data)
if !IsValid(Chatbox.panel) then
if Theme.initialized() then
Chatbox.create()
else
return
end
end
Chatbox.panel:add_message(message_data)
chat.PlaySound()
end)
|
-- Rewrite this file however you please to style it for your theme.
-- The actor names are are used to find and control certain actors.
-- If you leave out the actors for "max_offset", then the user will have no
-- buttons for "max_offset", but everything will still work fine.
-- So leave out any parts you don't want buttons for.
local button_area_width= 96
local button_area_height= 0 -- Set after positioning buttons.
local positions= {
{lef, top},
{rig, top},
{rig, bot},
{lef, bot},
}
local function calc_positions()
local lef= 4
local rig= _screen.w - (button_area_width) - 4
local top= 4
local bot= _screen.h - (button_area_height) - 4
positions= {
{lef, top},
{rig, top},
{rig, bot},
{lef, bot},
}
end
-- next_open_pos is changed by each actor as it initializes, so the actors
-- are automatically positioned, no matter how many or few there are.
local next_open_pos= 0
local function button_click(self)
self:stoptweening()
:linear(.1):zoom(.75)
:linear(.1):zoom(1)
end
local function value_handler(name)
return Def.ActorFrame{
Name= name, InitCommand= function(self)
local y= next_open_pos + 16
next_open_pos= next_open_pos + 32
self:zoom(.5):xy(24, y)
end,
Def.BitmapText{
Name= "value_text", Font= "Common Normal", InitCommand= function(self)
self:horizalign(right):x(-2):strokecolor{0, 0, 0, 1}
end,
},
Def.BitmapText{
Font= "Common Normal", InitCommand= function(self)
self:horizalign(left):x(2):strokecolor{0, 0, 0, 1}
:settext(THEME:GetString("EditModPreview", name))
end,
},
Def.Sprite{
Name= "increase_button", Texture= THEME:GetPathG("", "up_button.png"),
InitCommand= function(self)
self:xy(-16, -24)
end,
ClickCommand= button_click,
},
Def.Sprite{
Name= "decrease_button", Texture= THEME:GetPathG("", "up_button.png"),
InitCommand= function(self)
self:xy(-16, 24):basezoomy(-1)
end,
ClickCommand= button_click,
},
}
end
local function bool_handler(name)
return Def.ActorFrame{
Name= name, InitCommand= function(self)
local y= next_open_pos + 8
next_open_pos= next_open_pos + 16
self:zoom(.5):xy(16, y)
end,
Def.Sprite{
Name= "checkbox",
-- don't feel like drawing a checkbox.
Texture= THEME:GetPathG("", "up_button.png"),
InitCommand= function(self)
self:rotationz(90):x(-10)
end,
-- SetCommand is used to initialize the actor.
SetCommand= function(self, params)
if params.value then
self:rotationz(90)
else
self:rotationz(-90)
end
end,
-- ClickCommand is used when the actor is clicked.
ClickCommand= function(self, params)
self:playcommand("Set", params)
end,
},
Def.BitmapText{
Font= "Common Normal", InitCommand= function(self)
self:horizalign(left):x(2):strokecolor{0, 0, 0, 1}
:settext(THEME:GetString("EditModPreview", name))
end
},
}
end
return Def.ActorFrame{
InitCommand= function(self)
-- The size is for the area where the buttons are visible.
button_area_height= next_open_pos
calc_positions()
self:GetChild("bg"):playcommand("Size")
self:setsize(button_area_width, button_area_height)
end,
PositionCommand= function(self, params)
local pid= ((params.corner-1)%#positions)+1
self:xy(positions[pid][1], positions[pid][2])
end,
ShowCommand= function(self)
self:visible(true)
end,
HideCommand= function(self)
self:visible(false)
end,
Def.Quad{
Name= "bg", SizeCommand= function(self)
self:setsize(button_area_width, button_area_height)
:diffuse{0, 0, 0, .5}
:xy(button_area_width/2, button_area_height/2)
end,
},
value_handler("max_offset"),
value_handler("min_offset"),
value_handler("playback_speed"),
value_handler("zoom"),
value_handler("corner"),
bool_handler("paused"),
bool_handler("show_preview"),
bool_handler("full_screen"),
bool_handler("reload_mods"),
}
|
local args = { ... }
local ui = args[1]
assert(ui, 'Imevul UI library not found')
local gfx = ui.lib.cobalt.graphics
---@class Button : Text Builds on top of the Text class, but also draws an outline and provides an onClick event
---@field public color string Text color of the button
---@field public background string Background color of the button
local Button = ui.lib.class(ui.modules.Text, function(this, data)
ui.modules.Text.init(this, data)
data = data or {}
this.color = data.color or nil
this.background = data.background or nil
this.type = 'Button'
end)
---@see Object#_draw
function Button:_draw()
gfx.setBackgroundColor(self.background or self.config.theme.primary or colors.cyan)
gfx.clear()
gfx.setColor(self.background or self.config.theme.primary or colors.cyan)
gfx.rect('fill', 0, 0, self.width, self.height)
gfx.setColor(self.color or self.config.theme.text or colors.white)
ui.modules.Text._draw(self)
gfx.setColor(self.config.theme.text or colors.white)
gfx.setBackgroundColor(self.config.theme.background or colors.black)
end
---Called when we detect that the button should be clicked. Can also be called manually.
---@public
function Button:click()
if self.callbacks.onClick then
self.callbacks.onClick(self)
end
end
---@see Object#_keyReleased
function Button:_keyReleased(key, keyCode)
ui.modules.Text._keyReleased(self, key, keyCode)
if key == 'space' then
self:click()
end
end
---@see Object#_mouseReleased
function Button:_mouseReleased(x, y, button)
ui.modules.Text._mouseReleased(self, x, y, button)
self:click()
end
return Button
|
local ffi = require("ffi")
-- without this we get errors such as "attempt to redefine XXX"
local old_cdef = ffi.cdef
local exists = {}
ffi.cdef = function(def)
if exists[def] then
return
end
exists[def] = true
return old_cdef(def)
end
local old_udp = ngx.socket.udp
ngx.socket.udp = function(...)
local socket = old_udp(...)
socket.send = function(...)
error("ngx.socket.udp:send please mock this to use in tests")
end
return socket
end
local old_tcp = ngx.socket.tcp
ngx.socket.tcp = function(...)
local socket = old_tcp(...)
socket.send = function(...)
error("ngx.socket.tcp:send please mock this to use in tests")
end
return socket
end
ngx.log = function(...) end
ngx.print = function(...) end
require "busted.runner"({ standalone = false })
|
--- === Quitter ===
--
-- Quits configured apps if they have not been used since a specified amount of time.
local obj = {}
obj.__index = obj
-- Metadata
obj.name = "Quitter"
obj.version = "0.1"
obj.author = "Alpha Chen <alpha@kejadlen.dev>"
obj.license = "MIT - https://opensource.org/licenses/MIT"
obj.logger = hs.logger.new("quitter", "debug")
obj.lastFocused = {}
--- Quitter.quitAppsAfter
--- Variable
--- Table of applications to quit when unused.
obj.quitAppsAfter = {}
--- Quitter:start()
--- Method
--- Start Quitter
---
--- Parameters:
--- * None
function obj:start()
self:reset()
-- Reset if we're waking from sleep
self.watcher = hs.caffeinate.watcher.new(function(event)
if event ~= hs.caffeinate.watcher.systemDidWake then return end
self:reset()
end)
-- Set last focused time for relevant apps
self.windowFilter = hs.window.filter.new(false)
for app, _ in pairs(self.quitAppsAfter) do
self.windowFilter:allowApp(app)
end
self.windowFilter:subscribe(hs.window.filter.windowUnfocused, function(window, appName)
local name = window:application():name()
self.lastFocused[name] = os.time()
end)
self.timer = hs.timer.doEvery(60, function()
self:reap()
end):start()
return self
end
--- Quitter:stop()
--- Method
--- Stop Quitter
---
--- Parameters:
--- * None
function obj:stop()
self.watcher:stop()
self.windowFilter:unsubscribe(hs.window.filter.windowFocused)
self.timer:stop()
end
function obj:reset()
hs.fnutils.ieach(hs.application.runningApplications(), function(app)
local name = app:name()
local duration = self.quitAppsAfter[name]
if not duration then return false end
self.lastFocused[name] = os.time()
end)
end
function obj:reap()
self.logger.d("reaping")
local appsToQuit = hs.fnutils.ifilter(hs.application.runningApplications(), function(app)
local appName = app:name()
-- Don't quit the currently focused app
if app:isFrontmost() then return false end
local duration = self.quitAppsAfter[appName]
if not duration then return false end
local lastFocused = self.lastFocused[appName]
if not lastFocused then return false end
self.logger.d("app: " .. appName .. " last focused at " .. lastFocused)
return (os.time() - lastFocused) > duration
end)
for _, app in pairs(appsToQuit) do
hs.notify.new({
title = "Hammerspoon",
informativeText = "Quitting " .. app:name(),
withdrawAfter = 2,
}):send()
app:kill()
self.lastFocused[app:name()] = nil
end
end
return obj
|
local Point = {}
function Point:new(x, y, z)
local point = {}
point.x = x
point.y = y
point.z = z
return point
end
return Point
|
MarketMaxAmount = 2000
MarketMaxAmountStackable = 64000
MarketMaxPrice = 999999999
MarketMaxOffers = 100
MarketAction = {Buy = 0, Sell = 1}
MarketRequest = {MyOffers = 0xFFFE, MyHistory = 0xFFFF}
MarketOfferState = {
Active = 0,
Cancelled = 1,
Expired = 2,
Accepted = 3,
AcceptedEx = 255
}
MarketCategory = {
All = 0,
Armors = 1,
Amulets = 2,
Boots = 3,
Containers = 4,
Decoration = 5,
Food = 6,
HelmetsHats = 7,
Legs = 8,
Others = 9,
Potions = 10,
Rings = 11,
Runes = 12,
Shields = 13,
Tools = 14,
Valuables = 15,
Ammunition = 16,
Axes = 17,
Clubs = 18,
DistanceWeapons = 19,
Swords = 20,
WandsRods = 21,
PremiumScrolls = 22,
TibiaCoins = 23,
MetaWeapons = 255
}
MarketCategory.First = MarketCategory.Armors
MarketCategory.Last = MarketCategory.TibiaCoins
MarketCategoryWeapons = {
[MarketCategory.Ammunition] = {slots = {255}},
[MarketCategory.Axes] = {
slots = {255, InventorySlotOther, InventorySlotLeft}
},
[MarketCategory.Clubs] = {
slots = {255, InventorySlotOther, InventorySlotLeft}
},
[MarketCategory.DistanceWeapons] = {
slots = {255, InventorySlotOther, InventorySlotLeft}
},
[MarketCategory.Swords] = {
slots = {255, InventorySlotOther, InventorySlotLeft}
},
[MarketCategory.WandsRods] = {
slots = {255, InventorySlotOther, InventorySlotLeft}
}
}
MarketCategoryStrings = {
[0] = 'All',
[1] = 'Armors',
[2] = 'Amulets',
[3] = 'Boots',
[4] = 'Containers',
[5] = 'Decoration',
[6] = 'Food',
[7] = 'Helmets and Hats',
[8] = 'Legs',
[9] = 'Others',
[10] = 'Potions',
[11] = 'Rings',
[12] = 'Runes',
[13] = 'Shields',
[14] = 'Tools',
[15] = 'Valuables',
[16] = 'Ammunition',
[17] = 'Axes',
[18] = 'Clubs',
[19] = 'Distance Weapons',
[20] = 'Swords',
[21] = 'Wands and Rods',
[22] = 'Premium Scrolls',
[23] = 'Tibia Coins',
[255] = 'Weapons'
}
function getMarketCategoryName(id)
if table.haskey(MarketCategoryStrings, id) then
return MarketCategoryStrings[id]
end
end
function getMarketCategoryId(name)
local id = table.find(MarketCategoryStrings, name)
if id then return id end
end
MarketItemDescription = {
Armor = 1,
Attack = 2,
Container = 3,
Defense = 4,
General = 5,
DecayTime = 6,
Combat = 7,
MinLevel = 8,
MinMagicLevel = 9,
Vocation = 10,
Rune = 11,
Ability = 12,
Charges = 13,
WeaponName = 14,
Weight = 15,
MagicShieldCapacity = 16,
Cleave = 17,
DamageReflection = 18,
PerfectShot = 19,
ImbuingSlots = 20
}
MarketItemDescription.First = MarketItemDescription.Armor
MarketItemDescription.Last = MarketItemDescription.ImbuingSlots
MarketItemDescriptionStrings = {
[1] = 'Armor',
[2] = 'Attack',
[3] = 'Container',
[4] = 'Defense',
[5] = 'Description',
[6] = 'Use Time',
[7] = 'Combat',
[8] = 'Min Level',
[9] = 'Min Magic Level',
[10] = 'Vocation',
[11] = 'Rune',
[12] = 'Ability',
[13] = 'Charges',
[14] = 'Weapon Type',
[15] = 'Weight',
[16] = 'Magic Shield Capacity',
[17] = 'Cleave',
[18] = 'Damage Reflection',
[19] = 'Perfect Shot',
[20] = 'Imbuing Slots'
}
function getMarketDescriptionName(id)
if table.haskey(MarketItemDescriptionStrings, id) then
return MarketItemDescriptionStrings[id]
end
end
function getMarketDescriptionId(name)
local id = table.find(MarketItemDescriptionStrings, name)
if id then return id end
end
MarketSlotFilters = {
[InventorySlotOther] = "Two-Handed",
[InventorySlotLeft] = "One-Handed",
[255] = "Any"
}
MarketFilters = {Vocation = 1, Level = 2, Depot = 3, SearchAll = 4}
MarketFilters.First = MarketFilters.Vocation
MarketFilters.Last = MarketFilters.Depot
function getMarketSlotFilterId(name)
local id = table.find(MarketSlotFilters, name)
if id then return id end
end
function getMarketSlotFilterName(id)
if table.haskey(MarketSlotFilters, id) then return MarketSlotFilters[id] end
end
|
return function()
local lastCalls = {}
return {
callback = function(...)
table.insert(lastCalls, { ... })
end,
getNumberOfCalls = function()
return #lastCalls
end,
expectToBeCalledWith = function(...)
local lastCall = lastCalls[#lastCalls]
assert(lastCall, "was never called")
local expectedParams = { ... }
for index, expectedValue in ipairs(expectedParams) do
assert(lastCall[index] == expectedValue, string.format(
"Expected %s for arg # %s. Got %s instead",
tostring(expectedValue),
index,
tostring(lastCall[index])
))
end
end,
getLastCall = function()
return lastCalls[#lastCalls]
end,
clear = function()
lastCalls = {}
end,
}
end
|
--3L·MyonMyonMyon
local m=37564842
local cm=_G["c"..m]
if not pcall(function() require("expansions/script/c37564765") end) then require("script/c37564765") end
cm.named_with_myon=3
function cm.initial_effect(c)
c:SetUniqueOnField(1,0,m)
senya.leff(c,m)
c:EnableReviveLimit()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(cm.lfuscon)
e1:SetOperation(cm.lfusop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetTargetRange(1,0)
e2:SetTarget(function(e,c)
return not senya.check_set_3L(c)
end)
c:RegisterEffect(e2)
end
function cm.effect_operation_3L(c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(300)
e1:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e1,true)
return e1
end
function cm.lfusfilter(c)
return senya.check_fusion_set_3L(c) and c:IsOnField()
end
function cm.mfilter(c)
return c:IsFusionType(TYPE_EFFECT) and not c:IsHasEffect(6205579)
end
function cm.filter_extra(c,ec,chkfnf)
if bit.band(chkfnf,0x100)~=0 then return false end
return c:IsFaceup() and c:IsCanBeFusionMaterial(ec)
end
function cm.lfuscon(e,g,gc,chkfnf)
if g==nil then return true end
local f1=cm.lfusfilter
local f2=cm.mfilter
local chkf=bit.band(chkfnf,0xff)
local mg=g:Filter(Card.IsCanBeFusionMaterial,nil,e:GetHandler())
local tp=e:GetHandlerPlayer()
local exg=Duel.GetMatchingGroup(cm.filter_extra,tp,0,LOCATION_MZONE,nil,e:GetHandler(),chkfnf)
mg:Merge(exg)
if gc then
if not gc:IsCanBeFusionMaterial(e:GetHandler()) then return false end
return senya.lfuscheck_gc(mg,gc,f1,f2,chkf) or senya.filter_sayuri_3L(gc,e:GetHandler(),chkfnf)
end
return senya.lfuscheck(mg,f1,f2,chkf) or mg:IsExists(senya.filter_sayuri_3L,1,nil,e:GetHandler(),chkfnf)
end
function cm.lfusop(e,tp,eg,ep,ev,re,r,rp,gc,chkfnf)
local f1=cm.lfusfilter
local f2=cm.mfilter
local chkf=bit.band(chkfnf,0xff)
local g=eg:Filter(Card.IsCanBeFusionMaterial,nil,e:GetHandler())
local exg=Duel.GetMatchingGroup(cm.filter_extra,tp,0,LOCATION_MZONE,nil,e:GetHandler(),chkfnf)
g:Merge(exg)
if gc then
if senya.filter_sayuri_3L(gc,e:GetHandler(),chkfnf) and (not senya.lfuscheck_gc(g,gc,f1,f2,chkf) or Duel.SelectYesNo(tp,37564914*16)) then
Duel.SetFusionMaterial(Group.FromCards(gc))
return
end
local fs=(chkf==PLAYER_NONE or aux.FConditionCheckF(gc,chkf))
local sg=Group.CreateGroup()
if f1(gc) then sg:Merge(g:Filter(f2,gc)) end
if f2(gc) then sg:Merge(g:Filter(f1,gc)) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FMATERIAL)
local g1=sg:FilterSelect(tp,senya.lchkffilter,1,1,nil,nil,chkf,fs)
Duel.SetFusionMaterial(g1)
return
end
if g:IsExists(senya.filter_sayuri_3L,1,nil,e:GetHandler(),chkfnf) and (not senya.lfuscheck(g,f1,f2,chkf) or Duel.SelectYesNo(tp,37564914*16)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FMATERIAL)
local g1=g:FilterSelect(tp,senya.filter_sayuri_3L,1,1,nil,e:GetHandler(),chkfnf)
Duel.SetFusionMaterial(g1)
return
end
local sg=g:Filter(aux.FConditionFilterF2c,nil,f1,f2)
local g1=nil
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FMATERIAL)
if chkf~=PLAYER_NONE then
g1=sg:FilterSelect(tp,aux.FConditionCheckF,1,1,nil,chkf)
else g1=sg:Select(tp,1,1,nil) end
local tc1=g1:GetFirst()
sg:RemoveCard(tc1)
local b1=f1(tc1)
local b2=f2(tc1)
if b1 and not b2 then sg:Remove(aux.FConditionFilterF2r,nil,f1,f2) end
if b2 and not b1 then sg:Remove(aux.FConditionFilterF2r,nil,f2,f1) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FMATERIAL)
local g2=sg:Select(tp,1,1,nil)
g1:Merge(g2)
Duel.SetFusionMaterial(g1)
end
|
--- 过滤器:单字在先
function single_char_first_filter(input)
local l = {}
for cand in input:iter() do
if (utf8.len(cand.text) == 1) then
yield(cand)
else
table.insert(l, cand)
end
end
for cand in ipairs(l) do
yield(cand)
end
end
--- 计算器
--- @KyleBing 2022-01-17
function calculator(input, seg)
if string.find(input, 'coco') ~= nil then -- 匹配 coco 开头的字符串
local _, _, a, operation, b = string.find(input, "coco(%d+%.?%d+)([%+%-%*/])(%d+%.?%d+)")
local result = 0
if operation == '+' then
result = a + b
elseif operation == '-' then
result = a - b
elseif operation == '*' then
result = a * b
elseif operation == '/' then
result = a / b
end
yield(Candidate("coco", seg.start, seg._end, result, "计算器"))
end
end
function date_translator(input, seg)
if (input == "date") then
--- Candidate(type, start, end, text, comment)
yield(Candidate("date", seg.start, seg._end, os.date("%Y-%m-%d"), ""))
yield(Candidate("date", seg.start, seg._end, os.date("%Y年%m月%d日"), ""))
yield(Candidate("date", seg.start, seg._end, os.date("%Y.%m.%d"), ""))
yield(Candidate("date", seg.start, seg._end, os.date("%Y/%m/%d"), ""))
yield(Candidate("date", seg.start, seg._end, os.date("%m-%d-%Y"), ""))
end
if (input == "time") then
--- Candidate(type, start, end, text, comment)
yield(Candidate("time", seg.start, seg._end, os.date("%H:%M"), ""))
yield(Candidate("time", seg.start, seg._end, os.date("%Y%m%d%H%M%S"), ""))
yield(Candidate("time", seg.start, seg._end, os.date("%H:%M:%S"), ""))
end
-- @JiandanDream
-- https://github.com/KyleBing/rime-wubi86-jidian/issues/54
if (input == "week") then
local weakTab = {'日', '一', '二', '三', '四', '五', '六'}
yield(Candidate("week", seg.start, seg._end, "周"..weakTab[tonumber(os.date("%w")+1)], ""))
yield(Candidate("week", seg.start, seg._end, "星期"..weakTab[tonumber(os.date("%w")+1)], ""))
end
end
|
local languages = require("tabset.config").get_languages_config()
local defaults = require("tabset.config").get_defaults()
local logic = {}
function logic.set_settings()
local tabwidth = defaults.tabwidth
local expandtab = defaults.expandtab
if languages[vim.o.filetype] ~= nil then
tabwidth = languages[vim.o.filetype].tabwidth
expandtab = languages[vim.o.filetype].expandtab
end
vim.o.tabstop = tabwidth
vim.o.shiftwidth = tabwidth
vim.o.expandtab = expandtab
end
return logic
|
imgui.SetNextWindowPos(0, 0)
imgui.SetNextWindowSize(500,400)
if imgui.Begin("Test", nil, { "NoTitleBar", "NoResize", "NoMove", "NoBringToFrontOnFocus" }) then
imgui.End()
end
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BseArrangeList_pb', package.seeall)
local BSEARRANGELIST = protobuf.Descriptor();
local BSEARRANGELIST_TOTALNUM_FIELD = protobuf.FieldDescriptor();
local BSEARRANGELIST_ARRINFO_FIELD = protobuf.FieldDescriptor();
BSEARRANGELIST_TOTALNUM_FIELD.name = "totalnum"
BSEARRANGELIST_TOTALNUM_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseArrangeList.totalnum"
BSEARRANGELIST_TOTALNUM_FIELD.number = 1
BSEARRANGELIST_TOTALNUM_FIELD.index = 0
BSEARRANGELIST_TOTALNUM_FIELD.label = 2
BSEARRANGELIST_TOTALNUM_FIELD.has_default_value = false
BSEARRANGELIST_TOTALNUM_FIELD.default_value = 0
BSEARRANGELIST_TOTALNUM_FIELD.type = 5
BSEARRANGELIST_TOTALNUM_FIELD.cpp_type = 1
BSEARRANGELIST_ARRINFO_FIELD.name = "arrInfo"
BSEARRANGELIST_ARRINFO_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseArrangeList.arrInfo"
BSEARRANGELIST_ARRINFO_FIELD.number = 2
BSEARRANGELIST_ARRINFO_FIELD.index = 1
BSEARRANGELIST_ARRINFO_FIELD.label = 3
BSEARRANGELIST_ARRINFO_FIELD.has_default_value = false
BSEARRANGELIST_ARRINFO_FIELD.default_value = {}
BSEARRANGELIST_ARRINFO_FIELD.message_type = ARRANGEINFO_PB_ARRANGEINFO
BSEARRANGELIST_ARRINFO_FIELD.type = 11
BSEARRANGELIST_ARRINFO_FIELD.cpp_type = 10
BSEARRANGELIST.name = "BseArrangeList"
BSEARRANGELIST.full_name = ".com.xinqihd.sns.gameserver.proto.BseArrangeList"
BSEARRANGELIST.nested_types = {}
BSEARRANGELIST.enum_types = {}
BSEARRANGELIST.fields = {BSEARRANGELIST_TOTALNUM_FIELD, BSEARRANGELIST_ARRINFO_FIELD}
BSEARRANGELIST.is_extendable = false
BSEARRANGELIST.extensions = {}
BseArrangeList = protobuf.Message(BSEARRANGELIST)
_G.BSEARRANGELIST_PB_BSEARRANGELIST = BSEARRANGELIST
|
return {
tllmlv = {
acceleration = 0.071,
activatewhenbuilt = true,
brakerate = 1.65,
buildcostenergy = 960,
buildcostmetal = 206,
builddistance = 96,
builder = true,
buildpic = "tllmlv.dds",
buildtime = 3921,
canassist = true,
canbeassisted = true,
canguard = true,
canmove = true,
canpatrol = false,
canreclaim = false,
canreclamate = 0,
canrepair = true,
canrestore = false,
canstop = 1,
category = "ALL MOBILE TINY SURFACE",
collisionvolumeoffsets = "0 -3 0",
collisionvolumescales = "27 18 37",
collisionvolumetype = "box",
corpse = "dead",
defaultmissiontype = "Standby",
description = "Stealthy Minelayer/Minesweeper",
explodeas = "BIG_UNITEX",
firestandorders = 1,
footprintx = 2,
footprintz = 2,
idleautoheal = 5,
idletime = 1800,
leavetracks = true,
losemitheight = 22,
maneuverleashlength = 640,
mass = 206,
maxdamage = 245,
maxslope = 16,
maxvelocity = 2.524,
maxwaterdepth = 0,
metalmake = 0,
mobilestandorders = 1,
movementclass = "TANK3",
name = "Podger",
objectname = "TLLMLV",
onoffable = false,
radaremitheight = 25,
seismicsignature = 0,
selfdestructas = "BIG_UNIT",
shownanospray = false,
sightdistance = 201,
standingfireorder = 0,
standingmoveorder = 1,
stealth = true,
steeringmode = 1,
trackoffset = 12,
trackstrength = 5,
trackstretch = 1,
tracktype = "StdTank",
trackwidth = 30,
turninplace = 0,
turninplaceanglelimit = 140,
turninplacespeedlimit = 1.66584,
turnrate = 629,
unitname = "tllmlv",
workertime = 40,
buildoptions = {
[1] = "tlldt",
[2] = "tlltower",
[3] = "tllmine1",
[3] = "tllmine5",
[4] = "tllmine2",
[7] = "tllmine4",
[8] = "tllmine6",
},
customparams = {
buildpic = "tllmlv.dds",
faction = "TLL",
},
featuredefs = {
dead = {
blocking = true,
collisionvolumeoffsets = "0.399993896484 1.98730468792e-06 0.533332824707",
collisionvolumescales = "20.5333251953 11.8133239746 27.7333221436",
collisionvolumetype = "Box",
damage = 416,
description = "Podger Wreckage",
energy = 0,
featuredead = "heap",
footprintx = 3,
footprintz = 3,
metal = 154,
object = "TLLMLV_DEAD",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
heap = {
blocking = false,
damage = 520,
description = "Podger Debris",
energy = 0,
footprintx = 3,
footprintz = 3,
metal = 82,
object = "3X3B",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
},
nanocolor = {
[1] = 0.332,
[2] = 0.332,
[3] = 0.332,
},
sfxtypes = {
pieceexplosiongenerators = {
[1] = "piecetrail0",
[2] = "piecetrail1",
[3] = "piecetrail2",
[4] = "piecetrail3",
[5] = "piecetrail4",
[6] = "piecetrail6",
},
},
sounds = {
build = "nanlath1",
canceldestruct = "cancel2",
repair = "repair1",
underattack = "warning1",
working = "reclaim1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "varmmove",
},
select = {
[1] = "varmsel",
},
},
weapondefs = {
minesweep = {
areaofeffect = 512,
avoidfeature = false,
collidefriendly = false,
craterareaofeffect = 0,
craterboost = 0,
cratermult = 0,
edgeeffectiveness = 0.25,
explosiongenerator = "custom:MINESWEEP",
intensity = 0,
metalpershot = 0,
name = "MineSweep",
noselfdamage = true,
range = 200,
reloadtime = 3,
rgbcolor = "0 0 0",
thickness = 0,
tolerance = 100,
turret = true,
weapontimer = 0.1,
weapontype = "Cannon",
weaponvelocity = 3650,
damage = {
default = 20,
subs = 5,
},
},
},
weapons = {
[1] = {
def = "MINESWEEP",
onlytargetcategory = "MINE",
},
},
},
}
|
--priority.lua
local ipairs = ipairs
local FAIL = luabt.FAIL
local SUCCESS = luabt.SUCCESS
local node_execute = luabt.node_execute
local PriorityNode = class()
function PriorityNode:__init(...)
self.name = "priority"
self.children = {...}
end
function PriorityNode:run(btree, node_data)
for _, node in ipairs(self.children) do
local status = node_execute(node, btree, node_data.__level + 1)
if status == SUCCESS then
return status
end
end
return FAIL
end
function PriorityNode:close(btree)
for _, node in ipairs(self.children) do
local child_data = btree[node]
if child_data and child_data.is_open then
child_data.is_open = false
if node.close then
node:close(btree, child_data)
end
end
end
end
return PriorityNode
|
local util = require('pretty-fold.util')
local v = vim.v
local bo = vim.bo
local opt = vim.opt
local fn = vim.fn
local M = {}
---@param config? table
---@return string content modified first nonblank line of the folded region
function M.content(config)
---The content of the 'content' section.
---@type string
local content = fn.getline(v.foldstart)
---The list of comment characters for the current buffer, where all Lua magic
---characters are escaped.
---@type string[]
local comment_signs = fn.split(bo.commentstring, '%s')
-- Add additional comment signs from 'config.comment_signs' table.
if not vim.tbl_isempty(config.comment_signs) then
comment_signs = {
#comment_signs == 1 and unpack(comment_signs) or comment_signs,
unpack(config.comment_signs)
}
end
-- comment_signs = vim.tbl_flatten(comment_signs)
comment_signs = util.unique_comment_signs(comment_signs)
table.sort(comment_signs, function(a, b)
if type(a) == "table" then a = a[1] end
if type(b) == "table" then b = b[1] end
return #a > #b and true or false
end)
---Table with comment signs lengths.
---@type number[]
local comment_signs_len = vim.deepcopy(comment_signs)
for i, p in ipairs(comment_signs) do
if type(p) == "string" then
-- comment_signs_len[i] = fn.strdisplaywidth(p)
comment_signs_len[i] = #p
comment_signs[i] = vim.pesc(p)
elseif type(p) == "table" then
-- comment_signs_len[i][1] = fn.strdisplaywidth(p[1])
-- comment_signs_len[i][2] = fn.strdisplaywidth(p[2])
comment_signs_len[i][1] = #p[1]
comment_signs_len[i][2] = #p[2]
comment_signs[i][1] = vim.pesc(p[1])
comment_signs[i][2] = vim.pesc(p[2])
end
end
-- if vim.tbl_isempty(comment_signs) then
-- comment_signs[1] = ''
-- comment_signs_len[1] = 0
-- end
if config.remove_fold_markers then
local fdm = opt.foldmarker:get()[1]
content = content:gsub(vim.pesc(fdm)..'%d*', ''):gsub('%s+$', '')
end
-- If after removimg fold markers and comment signs we get blank line,
-- take next nonblank.
local blank = content:match('^%s*$') and true or false
local only_comment_sign = false
if not blank then
for _, c in ipairs(comment_signs) do
if content:match( table.concat{'^%s*', c[1] or c, '$'} ) then
only_comment_sign = true
break
end
end
end
if blank or only_comment_sign then
local line_num = fn.nextnonblank(v.foldstart + 1)
if line_num ~= 0 and line_num <= v.foldend then
if config.process_comment_signs or blank then
content = fn.getline(line_num)
else
local add_line = vim.trim(fn.getline(line_num))
for _, c in ipairs(comment_signs) do
add_line = add_line:gsub( table.concat{'^', c[1] or c, '%s*'}, '')
end
content = table.concat({ content, ' ', add_line })
end
end
end
if not vim.tbl_isempty(config.stop_words) then
for _, w in ipairs(config.stop_words) do
content = content:gsub(w, '')
end
end
if type(config.add_close_pattern) == "boolean" -- Add matchup pattern
and config.add_close_pattern
then
local str = content
local found_patterns = {}
for _, pat in ipairs(config.matchup_patterns) do
local found = {}
local start, stop = nil, 0
while stop do
start, stop = str:find(pat[1], stop + 1)
if start then
table.insert(found, { start = start, stop = stop, pat = pat[1] })
end
end
local num_op = #found ---number of opening patterns
if num_op > 0 then
start, stop = nil, 0
while stop do
start, stop = str:find(pat[2], stop + 1)
if start then
table.insert(found, { start = start, stop = stop, pat = pat[2] })
end
-- If number of closing patterns become equal to number of openning
-- patterns, then break.
if #found - num_op == num_op then break end
end
end
if num_op > 0 and num_op ~= #found then
table.sort(found, function(a, b)
return a.start < b.start and true or false
end)
local str_parts = {}
table.insert(str_parts, str:sub(1, found[1].start - 1))
for i = 1, #found - 1 do
table.insert(str_parts, str:sub(found[i].stop + 1, found[i+1].start - 1))
end
table.insert(str_parts, str:sub(found[#found].stop + 1))
str = table.concat(str_parts, ' ')
---previous, current, next
local p, c, n = nil, 1, 2
while true do
if found[c].pat == pat[1] and found[n].pat == pat[2] then
table.remove(found, n)
table.remove(found, c)
if p then
c, n = p, c
p = p > 1 and p-1 or nil
end
else
c, n = c + 1, n + 1
p = (p or 0) + 1
end
if n > #found then break end
end
end
for _, f in ipairs(found) do
table.insert(found_patterns, { pat = pat, pos = f.start })
end
end
table.sort(found_patterns, function(a, b)
return a.pos < b.pos and true or false
end)
if not vim.tbl_isempty(found_patterns) then
local comment_str = ''
for _, c in ipairs(comment_signs) do
local c_start = content:find(table.concat{'%s*', c[1] or c, '.*$'})
if c_start then
comment_str = content:sub(c_start)
content = content:sub(1, c_start - 1)
break
end
end
local ellipsis = #found_patterns[#found_patterns].pat[2] == 1 and '...' or ' ... '
str = { content, ellipsis }
for i = #found_patterns, 1, -1 do
table.insert(str, found_patterns[i].pat[2])
end
table.insert(str, comment_str)
content = table.concat(str)
end
elseif config.add_close_pattern == 'last_line' then
if config.add_close_pattern then -- Add matchup pattern
local last_line = fn.getline(v.foldend)
for _, c in ipairs(vim.tbl_flatten(comment_signs)) do
last_line = last_line:gsub(c..'.*$', '')
end
last_line = vim.trim(last_line)
for _, p in ipairs(config.matchup_patterns) do
if content:find( p[1] ) and last_line:find( p[2] ) then
local ellipsis = (#p[2] == 1) and '...' or ' ... '
local comment_str = ''
for _, c in ipairs(comment_signs) do
local c_start = content:find(table.concat{'%s*', c[1] or c, '.*$'})
if c_start then
comment_str = content:sub(c_start)
content = content:sub(1, c_start - 1)
break
end
end
content = table.concat{ content, ellipsis, last_line, comment_str }
break
end
end
end
end
if config.process_comment_signs then
for i, sign in ipairs(comment_signs) do
content = content:gsub(sign,
(config.process_comment_signs == 'spaces' and string.rep(' ', comment_signs_len[i]))
or
(config.process_comment_signs == 'delete' and '')
)
end
end
-- Replace all tabs with spaces with respect to %tabstop.
content = content:gsub('\t', string.rep(' ', bo.tabstop))
if config.keep_indentation then
local opening_blank_substr = content:match('^%s%s+')
if opening_blank_substr then
content = content:gsub(
opening_blank_substr,
config.fill_char:rep(#opening_blank_substr - 1)..' ',
-- config.fill_char:rep(fn.strdisplaywidth(opening_blank_substr) - 1)..' ',
1)
end
elseif config.sections.left[1] == 'content' then
content = content:gsub('^%s*', '') -- Strip all indentation.
else
content = content:gsub('^%s*', ' ')
end
content = content:gsub('%s*$', '')
content = content..' '
-- Exchange all occurrences of multiple spaces inside the text with
-- 'fill_char', like this:
-- "// Text" -> "// ==== Text"
for blank_substr in content:gmatch('%s%s%s+') do
content = content:gsub(
blank_substr,
' '..string.rep(config.fill_char, #blank_substr - 2)..' ',
1)
end
return content
end
---@return string
function M.number_of_folded_lines()
return string.format('%d lines', v.foldend - v.foldstart + 1)
end
---@return string
function M.percentage()
local folded_lines = v.foldend - v.foldstart + 1 -- The number of folded lines.
local total_lines = vim.api.nvim_buf_line_count(0)
local pnum = math.floor(100 * folded_lines / total_lines)
if pnum == 0 then
pnum = tostring(100 * folded_lines / total_lines):sub(2, 3)
elseif pnum < 10 then
pnum = ' '..pnum
end
return pnum .. '%'
end
return setmetatable(M, {
__index = function(_, custom_section)
return custom_section
end
})
|
data:extend(
{
{
type = "technology",
name = "fluid-handling",
icon = "__Engineersvsenvironmentalist__/graphics/icons/storage/heavy-oil-barrel.png",
prerequisites = {"oil-processing"},
effects =
{
{
type = "unlock-recipe",
recipe = "small-pump"
},
{
type = "unlock-recipe",
recipe = "empty-barrel"
},
{
type = "unlock-recipe",
recipe = "fill-crude-oil-barrel"
},
{
type = "unlock-recipe",
recipe = "empty-crude-oil-barrel"
},
{
type = "unlock-recipe",
recipe = "fill-heavy-oil-barrel"
},
{
type = "unlock-recipe",
recipe = "empty-heavy-oil-barrel"
},
{
type = "unlock-recipe",
recipe = "fill-light-oil-barrel"
},
{
type = "unlock-recipe",
recipe = "empty-light-oil-barrel"
},
{
type = "unlock-recipe",
recipe = "fill-lubricant-barrel"
},
{
type = "unlock-recipe",
recipe = "empty-lubricant-barrel"
},
{
type = "unlock-recipe",
recipe = "fill-sulfuric-acid-barrel"
},
{
type = "unlock-recipe",
recipe = "empty-sulfuric-acid-barrel"
},
{
type = "unlock-recipe",
recipe = "empty-fluid-canister"
},
{
type = "unlock-recipe",
recipe = "liquid-fuel-canister"
},
{
type = "unlock-recipe",
recipe = "empty-liquid-fuel-canister"
},
{
type = "unlock-recipe",
recipe = "ferric-chloride-canister"
},
{
type = "unlock-recipe",
recipe = "empty-ferric-chloride-canister"
},
{
type = "unlock-recipe",
recipe = "gas-canister"
},
{
type = "unlock-recipe",
recipe = "hydrogen-canister"
},
{
type = "unlock-recipe",
recipe = "empty-hydrogen-canister"
},
{
type = "unlock-recipe",
recipe = "oxygen-canister"
},
{
type = "unlock-recipe",
recipe = "empty-oxygen-canister"
},
{
type = "unlock-recipe",
recipe = "nitrogen-canister"
},
{
type = "unlock-recipe",
recipe = "empty-nitrogen-canister"
},
{
type = "unlock-recipe",
recipe = "chlorine-canister"
},
{
type = "unlock-recipe",
recipe = "empty-chlorine-canister"
},
{
type = "unlock-recipe",
recipe = "hydrogen-chloride-canister"
},
{
type = "unlock-recipe",
recipe = "empty-hydrogen-chloride-canister"
},
{
type = "unlock-recipe",
recipe = "petroleum-gas-canister"
},
{
type = "unlock-recipe",
recipe = "empty-petroleum-gas-canister"
},
},
unit =
{
count = 75,
ingredients = {{"science-pack-1", 1}, {"science-pack-2", 1}},
time = 30
},
order = "d-a-a"
},
}
)
|
local class = require 'middleclass'
local Vector = class('Vector')
function Vector:initialize(x, y)
self.x = x or 0
self.y = y or 0
end
function Vector.__add(v1, v2)
return Vector(v1.x + v2.x, v1.y + v2.y)
end
function Vector.__sub(v1, v2)
return Vector(v1.x - v2.x, v1.y - v2.y)
end
function Vector:__unm()
return Vector(-self.x, -self.y)
end
function Vector.__mul(a, b)
if type(a) == 'number' then
return Vector(b.x * a, b.y * a)
elseif type(b) == 'number' then
return Vector(a.x * b, a.y * b)
else
return Vector(a.x * b.x, a.y * b.y)
end
end
function Vector.__div(a, b)
if type(a) == 'number' then
return Vector(a/ b.x , a / b.y)
elseif type(b) == 'number' then
return Vector(a.x / b, a.y / b)
else
return Vector(a.x / b.x, a.y / b.y)
end
end
function Vector.__eq(v1, v2)
return v1.x == v2.x and v1.y == v2.y
end
function Vector:__tostring()
return '(' .. self.x .. ', ' .. self.y .. ')'
end
function Vector:__len()
return self:magnitude()
end
function Vector:pack()
return {self.x, self.y}
end
function Vector:unpack()
return self.x, self.y
end
function Vector:sqrMagnitude()
return Vector.dot(self, self)
end
function Vector:magnitude()
return math.sqrt(self:sqrMagnitude())
end
function Vector:normalized()
return self / self:magnitude()
end
function Vector:rotated(phi)
local c = math.cos(phi)
local s = math.sin(phi)
return Vector(
c * self.x - s * self.y,
s * self.x + c * self.y
)
end
function Vector.static.dot(v1, v2)
return v1.x * v2.x + v1.y * v2.y
end
-- function Vector.static.cross(v1, v2)
-- return Vector(
-- v1.y * v2.z - v1.z * v2.y,
-- v1.z * v2.x - v1.x * v2.z,
-- v1.x * v2.y - v1.y * v2.x
-- )
-- end
return Vector
|
local _, ns = ...
local oUF = ns.oUF or oUF
assert(oUF, 'oUF not loaded')
local IsInInstance = IsInInstance
local UnitCanAttack = UnitCanAttack
local UpdateTarget = function(self)
local _, instanceType = IsInInstance();
local targetIcon = self.ArenaTargetIcon
if instanceType == 'arena' then
local ID = self.unit:match('arena(%d)') or self:GetID() or 0
local unit = 'arena'..tostring(ID)..'target'
local _, targetClass = UnitClass(unit)
if targetIcon.showEnemy then
if targetClass and (not UnitCanAttack("player", unit)) then
targetIcon.Icon:SetTexture("Interface\\TARGETINGFRAME\\UI-CLASSES-CIRCLES.BLP")
targetIcon.Icon:SetTexCoord(unpack(CLASS_ICON_TCOORDS[targetClass]))
targetIcon.Name:SetText(UnitName(unit))
targetIcon:Show()
else
targetIcon:Hide()
end
else
if targetClass then
targetIcon.Icon:SetTexture("Interface\\TARGETINGFRAME\\UI-CLASSES-CIRCLES.BLP")
targetIcon.Icon:SetTexCoord(unpack(CLASS_ICON_TCOORDS[targetClass]))
targetIcon.Name:SetText(UnitName(unit))
targetIcon:Show()
else
targetIcon:Hide()
end
end
else
targetIcon:Hide()
end
end
local Update = function(self, event, unit)
if event == 'ARENA_OPPONENT_UPDATE' and unit ~= self.unit then return; end
local targetIcon = self.ArenaTargetIcon
local _, instanceType = IsInInstance();
targetIcon.instanceType = instanceType
if(targetIcon.PreUpdate) then targetIcon:PreUpdate(event) end
if instanceType == 'arena' then
UpdateTarget(self)
end
if(targetIcon.PostUpdate) then targetIcon:PostUpdate(event) end
end
local Enable = function(self)
local targetIcon = self.ArenaTargetIcon
if targetIcon then
self:RegisterEvent("ARENA_OPPONENT_UPDATE", Update, true)
self:RegisterEvent("PLAYER_ENTERING_WORLD", Update, true)
self:SetScript('OnUpdate', UpdateTarget)
if not targetIcon.Icon then
targetIcon.Icon = targetIcon:CreateTexture(nil, "OVERLAY")
targetIcon.Icon:SetAllPoints(targetIcon)
targetIcon.Icon:SetTexture("Interface\\TARGETINGFRAME\\UI-CLASSES-CIRCLES.BLP")
end
targetIcon:Show()
return true
end
end
local Disable = function(self)
local targetIcon = self.ArenaTargetIcon
if targetIcon then
self:UnregisterEvent("PLAYER_ENTERING_WORLD", Update)
self:UnregisterEvent("ARENA_OPPONENT_UPDATE", Update)
self:SetScript('OnUpdate', nil)
targetIcon:Hide()
end
end
oUF:AddElement('ArenaTargetIcon', Update, Enable, Disable)
|
-- create node Not
require "moon.sg"
local node = moon.sg.new_node("sg_not")
if node then
node:set_pos(moon.mouse.get_position())
end
|
------------------------------------------
-- Effortless wmii-style dynamic tagging.
------------------------------------------
-- Lucas de Vries <lucas@glacicle.org>
-- Licensed under the WTFPL version 2
-- * http://sam.zoy.org/wtfpl/COPYING
-----------------------------------------
-- Cut version
-----------------------------------------
-- Grab environment
local ipairs = ipairs
local awful = require("awful")
local table = table
local capi = {
screen = screen,
}
-- Eminent: Effortless wmii-style dynamic tagging
module("eminent")
-- Grab the original functions we're replacing
local deflayout = nil
local orig = {
new = awful.tag.new,
taglist = awful.widget.taglist.new,
filter = awful.widget.taglist.filter.all,
}
-- Return tags with stuff on them, mark others hidden
function gettags(screen)
local tags = {}
for k, t in ipairs(capi.screen[screen]:tags()) do
if t.selected or #t:clients() > 0 then
awful.tag.setproperty(t, "hide", false)
table.insert(tags, t)
else
awful.tag.setproperty(t, "hide", true)
end
end
return tags
end
-- Pre-create tags
awful.tag.new = function (names, screen, layout)
deflayout = layout and layout[1] or layout
return orig.new(names, screen, layout)
end
-- Taglist label functions
awful.widget.taglist.filter.all = function (t, args)
if t.selected or #t:clients() > 0 then
return orig.filter(t, args)
end
end
|
local vmath = {}
function vmath.vec(x, y)
return {x, y}
end
function vmath.add(a, b)
return {a[1] + b[1], a[2] + b[2]}
end
function vmath.sub(a, b)
return {a[1] - b[1], a[2] - b[2]}
end
function vmath.mul(a, s)
return {a[1] * s, a[2] * s}
end
function vmath.copy(v)
return {v[1], v[2]}
end
function vmath.len(v)
return math.sqrt(v[1]*v[1] + v[2]*v[2])
end
function vmath.normed(v)
local len = vmath.len(v) + 1e-5
return {v[1] / len, v[2] / len}
end
function vmath.ortho(v)
return {v[2], -v[1]}
end
function vmath.dot(a, b)
return a[1]*b[1] + a[2]*b[2]
end
function vmath.angle(v)
return math.atan2(v[2], v[1])
end
function vmath.split(v, normal)
normal = vmath.normed(normal)
local coeff = vmath.dot(v, normal)
local vNormal = vmath.mul(normal, coeff)
local vTangent = vmath.sub(v, vNormal)
return vNormal, vTangent
end
return vmath
|
--- Discord message snowflake definition.
-- Dependencies: `snowflakes`, `reaction`, `novus.api`, `novus.cache`, `novus.cache.view`
-- @module snowflakes.message
-- @alias message
--imports--
local api = require"novus.api"
local util = require"novus.snowflakes.helpers"
local cache = require"novus.cache"
local snowflake = require"novus.snowflakes"
local modifiable = require"novus.snowflakes.mixins.modifiable"
local reaction = require"novus.snowflakes.channel.reaction"
local view = require"novus.cache.view"
local cqueues = require"cqueues"
local json = require"cjson"
local null = json.null
local running = cqueues.running
local setmetatable = setmetatable
local gettime = cqueues.monotime
local snowflakes = snowflake.snowflakes
local patterns = util.patterns
local ipairs = ipairs
local insert = table.insert
local includes = util.includes
local getmetatable = getmetatable
local type = type
--start-module--
local _ENV = snowflake "message"
--[[
id snowflake id of the message
channel_id snowflake id of the channel the message was sent in
guild_id? snowflake id of the guild the message was sent in
author* user object the author of this message (not guaranteed to be a valid user, see below)
member? partial guild member object member properties for this message's author
content string contents of the message
timestamp ISO8601 timestamp when this message was sent
edited_timestamp ?ISO8601 timestamp when this message was edited (or null if never)
tts boolean whether this was a TTS message
mention_everyone boolean whether this message mentions everyone
mentions array of user objects, with an additional partial member field users specifically mentioned in the message
mention_roles array of role object ids roles specifically mentioned in this message
attachments array of attachment objects any attached files
embeds array of embed objects any embedded content
reactions? array of reaction objects reactions to the message
nonce? ?snowflake used for validating a message was sent
pinned boolean whether this message is pinned
webhook_id? snowflake if the message is generated by a webhook, this is the webhook's id
type integer type of message
activity? message activity object sent with Rich Presence-related chat embeds
application? message application object sent with Rich Presence-related chat embeds
]]
schema {
"channel_id" --4
,"guild_id" -- 5
,"author_id" --6
,"type" -- 7
,"content" -- 8
,"timestamp" --9
,"edited_timestamp" -- 10
,"tts" -- 11
,"attachments" -- 12
,"embeds" -- 13
,"nonce" -- 14
,"pinned" -- 15
,"mention_everyone" -- 16
,"mentions" -- 17
,"mention_roles" -- 18
,"reactions" -- 19
,"webhook_id" -- 20
,"activity" -- 21
,"application" -- 22
,"mentioned"
}
--- A discord message object.
-- @table message
-- @within Objects
-- @int id
-- @tparam number life
-- @tparam function cache
-- @int channel_id
-- @tparam integer|nil guild_id
-- @int author_id
-- @int type See @{novus.enums.messagetype|message types}
-- @str content
-- @str timestamp
-- @str edited_timestamp
-- @tparam boolean tts
-- @tab attachments
-- @tab embeds
-- @tparam string|nil nonce
-- @tparam boolean pinned
-- @tparam boolean mention_everyone
-- @tab mentions
-- @tab mention_roles
-- @tparam table(reaction)|nil reactions
-- @tparam integer|nil webhook_id
-- @tparam table|nil activity
-- @tparam table|nil application
function processor.mentions(inmentions, state)
local mentions = {}
if inmentions then
for i, u in ipairs(inmentions) do
local uid = util.uint(u.id)
if not state.cache.user[uid] then
snowflakes.user.new_from(state, u, state.cache.methods.user)
end
mentions[i] = uid
end
end
return mentions
end
function processor.reactions(inreactions, state)
local out = {}
if inreactions then
out = {}
for _, r in ipairs(inreactions) do
local new = reaction.new_from(state, r)
out[new.emoji_id] = new
end
end
return out
end
function processor.author(user, state)
if user then
local uid = util.uint(user.id)
snowflakes.user.upsert(state, user)
return uid, "author_id"
end
end
function new_from(state, payload)
local channel_id, guild_id =
util.uint(payload.channel_id)
,util.uint(payload.guild_id)
local mycache = state.cache.message[channel_id]
local method = state.cache.methods.message[channel_id]
if mycache == nil then
mycache = util.cache()
state.cache.message[channel_id] = mycache
method = cache.inserter(mycache)
state.cache.methods.message[channel_id] = method
end
return setmetatable({
util.uint(payload.id)
,gettime()
,method
,channel_id
,guild_id
,processor.author(payload.author, state)
,payload.type
,payload.content
,payload.timestamp
,payload.edited_timestamp
,payload.tts
,payload.attachments
,payload.embeds
,payload.nonce
,payload.pinned
,payload.mention_everyone
,processor.mentions(payload,mentions, state)
,payload.mention_roles
,processor.reactions(payload.reactions, state)
,payload.webhook_id
},_ENV)
end
_ENV = modifiable(_ENV, api.edit_message) -- endow with modify
function methods.edit(message, arg, ...)
local content = null
if type(arg) == 'string' then
content = arg:format(...)
end
return modify(message, {content = content})
end
function methods.edit_embed(message, embed)
local content = null
if type(embed) == 'table' then
content = embed
end
return modify(message, {embed = content})
end
function methods.pin(message)
local state = running():novus()
local success, data, err = api.add_pinned_channel_message(state.api, message[4], message[1])
if success and data then
message[15] = true
return message
else
return false, err
end
end
function methods.unpin(message)
local state = running():novus()
local success, data, err = api.delete_pinned_channel_message(state.api, message[4], message[1])
if success and data then
message[15] = false
return message
else
return false, err
end
end
function methods.add_reaction(message, emoji)
local typ = getmetatable(emoji)
if typ and typ == snowflakes.emoji then
emoji = emoji.nonce
elseif typ and typ == snowflakes.reaction then
return methods.add_reaction(message, emoji.emoji)
elseif type(emoji) ~= 'string' then
return false
end
local state = running():novus()
local success, data, err = api.create_reaction(state.api, message[4], message[1], emoji)
if success and data then
return message
else
return false, err
end
end
function methods.remove_reaction(message, emoji, user)
local typ = getmetatable(emoji)
if typ and typ == snowflakes.emoji then
emoji = emoji.nonce
elseif typ and typ == snowflakes.reaction then
return methods.remove_reaction(message, emoji.emoji, user)
elseif type(emoji) ~= 'string' then
return false
end
local state = running():novus()
local id = snowflake.id(user)
local success, data, err
if id then
success, data, err = api.delete_user_reaction(state.api, message[4], message[1], emoji, id)
else
success, data, err = api.delete_own_reaction(state.api, message[4], message[1], emoji)
end
if success and data then
return message
else
return false, err
end
end
function methods.remove_all_reactions(message)
local state = running():novus()
local success, data, err = api.delete_all_reactions(state.api, message[4], message[1])
if success and data then
return message
else
return false, err
end
end
function methods.delete(message)
local state = running():novus()
local success, data, err = api.delete_message(state.api, message[4], message[1])
if success and data then
local channel = snowflakes.channel.get_from(state, message[4])
channel[6] = view.remove(channel[6], message[1])
return message
else
return false, err
end
end
function methods.reply(message, ...)
local channel = snowflakes.channel.get(message[4])
return channel:send(...)
end
local function get_mentions(key, value, set)
return includes(set, key) and value
end
function properties.full_mentions(message)
return view.from(running():novus().cache.user, get_mentions, message[17])
end
local function get_reactions(_, id)
return snowflakes.reaction.get(id)
end
function properties.full_reactions(message)
return view.from(message[19], get_reactions)
end
local imt = {}
imt.__call = ipairs
local function iiter(t)
return setmetatable(t, imt)
end
function properties.mentioned(message)
local new = iiter{}
for pos, m in patterns.mentions(message[8]) do
m.position = pos
local name = m.type .. 's'
new[name] = new[name] or iiter{}
insert(new, m)
insert(new[name], m)
end
message[23] = new
return new
end
function properties.author(message)
return message[6] and snowflakes.user.get(message[6])
end
function properties.channel(message)
return snowflakes.channel.get(message[4])
end
function properties.guild_id(message)
message[5] = message.channel.guild_id
return message[5]
end
function properties.guild(message)
return message.guild_id and snowflakes.guild.get(message[5])
end
function properties.member(message)
return message.guild_id and snowflakes.member.get(message[5], message[6])
end
function properties.link(message)
return "https://discordapp.com/channels/%s/%s/%s" % {
message.guild_id or '@me'
,message.channel_id
,message.id
}
end
function get_from(state, channel_id, id)
local mcache = state.cache.message[channel_id]
if mcache and mcache[id] then return mcache[id]
else
local success, data, err = api.get_channel_message(state.api, channel_id, id)
if success then
return new_from(state, data)
else
return nil, err
end
end
end
function destroy_from(state, msg)
state.cache.message[msg.channel_id][msg.id] = nil
if msg.cache then
msg.cache = nil
end
end
__gc = nil
--end-module--
return _ENV
|
object_tangible_deed_player_house_deed_jedi_house_deed = object_tangible_deed_player_house_deed_shared_jedi_house_deed:new {
}
ObjectTemplates:addTemplate(object_tangible_deed_player_house_deed_jedi_house_deed, "object/tangible/deed/player_house_deed/jedi_house_deed.iff")
|
-- 流量控制脚本, 设置一个TTL = 1的HASH对象, 有2个entry, 分别是当前请求次数current和当前最大请求次数max;
-- 当current + 1 > max时则返回0, 当HASH对象不存在或者current + 1 <= max时返回1;
-- 参数: ARGV[1]:服务名; ARGV[2]: qps
-- 返回0表示达到限流, 返回1表示OK
local servId = ARGV[1]
if nil == servId then
servId = "global"
end
local HASH_KEY = "goate:ratelimiter:" .. ARGV[1]
local mapResult = redis.call("hgetall", HASH_KEY)
-- 判断hgetall是否为空
if nil == next(mapResult) then
local max = ARGV[2]
if nil == max then
max = 100
end
redis.call("hmset", HASH_KEY, "current", 1, "max", max)
redis.call("expire", HASH_KEY, 1)
return 1
end
-- 将hgetall的返回对象转换成table(hashKey-val)
local limiterMap = {}
local nextkey
for i, v in ipairs(mapResult) do
if i % 2 == 1 then
nextkey = v
else
limiterMap[nextkey] = v
end
end
local current = tonumber(limiterMap["current"])
local max = tonumber(limiterMap["max"])
if current + 1 > max then
return 0
end
redis.call("hincrby", HASH_KEY, "current", 1)
return 1
|
local helper = require("suball.lib.testlib.helper")
local suball = helper.require("suball")
describe("suball", function()
it("can substitute various cases strings with keeping them cases", function()
helper.set_lines([[
TEST_CASE
test_case
test-case
TestCase
testCase]])
local key = ":%" .. suball.map("test_case", "") .. vim.api.nvim_eval('"case_test\\<CR>"')
vim.api.nvim_feedkeys(key, "nx", true)
assert.lines([[
CASE_TEST
case_test
case-test
CaseTest
caseTest]])
end)
it("can substitute various cases strings even if target and input are one word", function()
helper.set_lines([[
TEST
test
Test]])
local key = ":%" .. suball.map("test", "") .. vim.api.nvim_eval('"case\\<CR>"')
vim.api.nvim_feedkeys(key, "nx", true)
assert.lines([[
CASE
case
Case]])
end)
end)
|
object_tangible_terminal_planning_table_keren_imp = object_tangible_terminal_shared_planning_table_keren_imp:new {
}
ObjectTemplates:addTemplate(object_tangible_terminal_planning_table_keren_imp, "object/tangible/terminal/planning_table_keren_imp.iff")
|
---- Test/gimmick lang
-- Not an example of how you should translate something. See english.lua for that.
local L = LANG.CreateLanguage("Swedish chef")
local gsub = string.gsub
local function Borkify(word)
local b = string.byte(word:sub(1, 1))
if b > 64 and b < 91 then
return "Bork"
end
return "bork"
end
local realised = false
-- Upon selection, borkify every english string.
-- Even with all the string manipulation this only takes a few ms.
local function LanguageChanged(old, new)
if realised or new != "swedish chef" then return end
local eng = LANG.GetUnsafeNamed("english")
for k, v in pairs(eng) do
L[k] = gsub(v, "[{}%w]+", Borkify)
end
realised = true
end
hook.Add("TTTLanguageChanged", "ActivateChef", LanguageChanged)
-- As fallback, non-existent indices translated on the fly.
local GetFrom = LANG.GetTranslationFromLanguage
setmetatable(L,
{
__index = function(t, k)
local w = GetFrom(k, "english") or "bork"
return gsub(w, "[{}%w]+", "BORK")
end
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.