Jump to content

save-system


Recommended Posts

  • Moderators

Parece ter algo errado nesta linha:

if weaponData[tostring(i)] then -- Se existe o ID "i" de arma na table, então:

Está convertendo 'i' para string, e se não constar na chave a referência como uma string irá falhar a verificação. Tente removendo o tostring.

Link to comment
3 minutes ago, DNL291 said:

Parece ter algo errado nesta linha:


if weaponData[tostring(i)] then -- Se existe o ID "i" de arma na table, então:

Está convertendo 'i' para string, e se não constar na chave a referência como uma string irá falhar a verificação. Tente removendo o tostring.

Vou tentar fazer aquilo que falei e dps se n der eu tento isso

 

Link to comment
  • Other Languages Moderators
3 minutes ago, Lord Henry said:

@DNL291 sim. Tem que converter pra string pois o JSON sempre indexa a table com índices de string. ["1"], ["2"], ["algumaCoisa"]

Dessa forma, weaponData[ i ] não existe. Pois não existe nenhum elemento com índice numérico. Se converter o valor numérico de i para string, dai existe.

Edited by Lord Henry
Link to comment
  • Moderators
5 minutes ago, Lord Henry said:

@DNL291 sim. Tem que converter pra string pois o JSON sempre indexa a table com índices de string. ["1"], ["2"], ["algumaCoisa"]

Mas o fromJSON já não vai retornar convertido aquela tabela original do toJSON? Já faz um tempo que não mexo com essa função, não lembro se ela retorna com índice em string.

  • Thanks 1
Link to comment
  • Other Languages Moderators
17 minutes ago, DNL291 said:

Mas o fromJSON já não vai retornar convertido aquela tabela original do toJSON? Já faz um tempo que não mexo com essa função, não lembro se ela retorna com índice em string.

O fromJSON vai retornar uma table indexada em strings. É uma table normal, mas os índices são strings em vez de números.

Exemplo:

tableQualquer = {1, 30, 0, "oi"}
data = toJSON (tableQualquer) -- data = "[{"1": 1, "4": "oi", "2": 30, "3": 0}]" -- Sim, ele aleatoriza a ordem dos elementos. A não ser que vc force a ordem como eu fiz no código.
novaData = fromJSON (data)
--[[
novaData = {
	["1"] = 1,
	["4"] = "oi",
	["2"] = 30,
	["3"] = 0
}
]]

O toJSON também aleatoriza os elementos, caso vc declare a table inteira em vez dos elementos separadamente.

Edited by Lord Henry
Link to comment

Resetei todas as datas e n foi

https://imge.to/i/jWCPF

function playerLogin (thePreviousAccount, theCurrentAccount, autoLogin)
	if not (isGuestAccount (getPlayerAccount (source))) then
		local accountData = getAccountData (theCurrentAccount, "funmodev2-money")
		if (accountData) then
			local playerMoney = getAccountData (theCurrentAccount, "funmodev2-money")
			local playerSkin = getAccountData (theCurrentAccount, "funmodev2-skin")
			local playerHealth = getAccountData (theCurrentAccount, "funmodev2-health")
			local playerArmor = getAccountData (theCurrentAccount, "funmodev2-armor")
			local playerX = getAccountData (theCurrentAccount, "funmodev2-x")
			local playerY = getAccountData (theCurrentAccount, "funmodev2-y")
			local playerZ = getAccountData (theCurrentAccount, "funmodev2-z")
			local playerInt = getAccountData (theCurrentAccount, "funmodev2-int")
			local playerDim = getAccountData (theCurrentAccount, "funmodev2-dim")
			local playerWanted = getAccountData (theCurrentAccount, "funmodev2-wantedlevel")
			local playerTeam = getAccountData (theCurrentAccount, "funmodev2-Team")
			spawnPlayer (source, playerX, playerY, playerZ +1, 0, playerSkin, playerInt, playerDim)
			setPlayerMoney (source, playerMoney)
			setTimer (setElementHealth, 500, 1, source, playerHealth)
			setTimer (setPedArmor, 500, 1, source, playerArmor)
			setTimer (setPlayerWantedLevel, 500, 1, source, playerWanted)
			if getAccountData (theCurrentAccount, "funmodev2-weapons") then
				local weaponData = fromJSON (getAccountData (account, "funmodev2-weapons")) -- Converte a string JSON em uma table.
				for i=1, 46 do -- Para cada ID de arma, faça: (seria do 0 ao 46, mas não precisa obter a mão do jogador)
					if weaponData[tostring(i)] then -- Se existe o ID "i" de arma na table, então:
						giveWeapon (source, i, weaponData[tostring(i)]) -- Os índices da table JSON sempre são em string.
					end
				end
			end
			setCameraTarget (source)
			fadeCamera (source, true, 2.0)
		else
			spawnPlayer (source, 1481.0855712891, -1771.2996826172, 18.795753479004, 0, 78, 0, 0)
			setPlayerMoney (source, 200)
			setCameraTarget (source)
			fadeCamera (source, true, 2.0)
		end
	end
end
addEventHandler ("onPlayerLogin", root, playerLogin)

function onLogout ()
	kickPlayer (source, nil, "Logging out is disallowed.")
end
addEventHandler ("onPlayerLogout", root, onLogout)

function onQuit (quitType, reason, responsibleElement)
	if not (isGuestAccount (getPlayerAccount (source))) then
		account = getPlayerAccount (source)
		if (account) then
			local x, y, z = getElementPosition (source)
			setAccountData (account, "funmodev2-money", tostring (getPlayerMoney (source)))
			setAccountData (account, "funmodev2-skin", tostring (getPedSkin (source)))
			setAccountData (account, "funmodev2-health", tostring (getElementHealth (source)))
			setAccountData (account, "funmodev2-armor", tostring (getPedArmor (source)))
			setAccountData (account, "funmodev2-R", r)
			setAccountData (account, "funmodev2-G", g)
			setAccountData (account, "funmodev2-B", b)
			setAccountData (account, "funmodev2-x", x)
			setAccountData (account, "funmodev2-y", y)
			setAccountData (account, "funmodev2-z", z)
			setAccountData (account, "funmodev2-int", getElementInterior (source))
			setAccountData (account, "funmodev2-dim", getElementDimension (source))
			setAccountData (account, "funmodev2-wantedlevel", getPlayerWantedLevel (source))
			local ammo = {}
			for i=0,12 do --Weapon Slots
				for k=1,46 do --Weapon IDs (seria do 0 ao 46, mas não precisa obter a mão do jogador, arma 0.)
					if getPedWeapon (source, i) == k then
						ammo[k] = getPedTotalAmmo (source, i)
					end
				end
			end
			setAccountData (account, "funmodev2-weapons", toJSON ( { ammo[1], ammo[2], ammo[3], ammo[4], ammo[5], ammo[6], ammo[7], ammo[8], ammo[9], ammo[10], ammo[11], ammo[12], ammo[13], ammo[14], ammo[15], ammo[16], ammo[17], ammo[18], ammo[19], ammo[20], ammo[21], ammo[22], ammo[23], ammo[24], ammo[25], ammo[26], ammo[27], ammo[28], ammo[29], ammo[30], ammo[31], ammo[32], ammo[33], ammo[34], ammo[35], ammo[36], ammo[37], ammo[38], ammo[39], ammo[40], ammo[41], ammo[42], ammo[43], ammo[44], ammo[45], ammo[46] } ))
		end
	end
end
addEventHandler ("onPlayerQuit", root, onQuit)

function onWasted (totalAmmo, killer, killerWeapon, bodypart, stealth)
	if not (isGuestAccount (getPlayerAccount(source))) then
		local theWeapon = getPedWeapon (source)
		local weaponAmmo = getPedTotalAmmo (source)
		fadeCamera (source, false)
		setTimer (spawnPlayer, 1000, 1, source, 2036.1735839844, -1413.0563964844, 16.9921875, 0, getPedSkin (source), 0, 0, getPlayerTeam(source))
		setTimer (setCameraTarget, 1250, 1, source)
		setTimer (fadeCamera, 2000, 1, source, true)
		setTimer (giveWeapon, 2000, 1, source, theWeapon, weaponAmmo, true)
	end
end
addEventHandler ("onPlayerWasted", root, onWasted)

function setTeam ()
	local account = getPlayerAccount (source) -- gets players account
	local team = getAccountData (account, "team") -- gets players team
	if (team) and getTeamFromName (team) then
		setPlayerTeam (source, getTeamFromName (team)) -- sets players team
	end
end
addEventHandler ("onPlayerLogin", root, setTeam) -- sets players team on login
 
function save()
	local team = getPlayerTeam (source) -- Gets the players team
	local account = getPlayerAccount (source)
	if (team) and not isGuestAccount (account) then -- Checks to see if the player is a guest or not
		setAccountData (account, "team", getTeamName (team)) --saves team
	end
end
addEventHandler ("onPlayerQuit", root, save) -- saves team on quit

 

Link to comment

É erro com algum script mesmo, tirou todos e foi, vou testando de um em um para ver qual ta interferindo

 

1 minute ago, carlos eduardo said:

É erro com algum script mesmo, tirou todos e foi, vou testando de um em um para ver qual ta interferindo

 

vou botar os scripts de um em um

Link to comment
  • Other Languages Moderators

É algum resource interferindo na função giveWeapon. Acontece quando vc dá esse nome pra alguma função. Por isso vc não pode dar qualquer nome pras funções, precisa ser um nome que não é usado pelo MTA.

Exemplo de função com nome ilegal:

function giveWeapon ()
	-- Faz alguma coisa.
end

 

Quando vc encontrar o resource que está causando conflito, nos mostre qual foi.

Link to comment
  • Moderators
48 minutes ago, Lord Henry said:

O fromJSON vai retornar uma table indexada em strings. É uma table normal, mas os índices são strings em vez de números.

Exemplo:


tableQualquer = {1, 30, 0, "oi"}
data = toJSON (tableQualquer) -- data = "[{"1": 1, "4": "oi", "2": 30, "3": 0}]" -- Sim, ele aleatoriza a ordem dos elementos. A não ser que vc force a ordem como eu fiz no código.
novaData = fromJSON (data)
--[[
novaData = {
	["1"] = 1,
	["4"] = "oi",
	["2"] = 30,
	["3"] = 0
}
]]

O toJSON também aleatoriza os elementos, caso vc declare a table inteira em vez dos elementos separadamente.

Testei aqui, e foi conforme eu imaginei, o valor de fromJSON retornou a tabela da mesma forma que foi definida, sem índices como string. Sendo que o loop com número no index funcionou normalmente.

Código:

local mytable = { 'red', 'blue', 'dark blue', 'green' }
jsondata = toJSON(mytable)
iprint("toJSON table = ", jsondata)
restoredtable = fromJSON(jsondata)
iprint("table padrao =", restoredtable)

for i=1, #restoredtable do
    print( restoredtable[i] )
end

Resultado:

[20:44:41] INFO: "toJSON table = "    '[ [ "red", "blue", "dark blue", "green" ] ]'
[20:44:41] INFO: "table padrao ="    { "red", "blue", "dark blue", "green" }
[20:44:41] INFO: red
[20:44:41] INFO: blue
[20:44:41] INFO: dark blue
[20:44:41] INFO: green

 

Link to comment
  • Moderators
Just now, Lord Henry said:

@DNL291 tente de novo mas agora indexe a primeira table com números.

A primeira, a tabela 'jsondata'? Com ela não vai funcionar pois está no formato JSON.

A minha questão foi justamente com a tabela obtida do fromJSON. A 'weaponData' assim como postei aqui:

1 hour ago, DNL291 said:

Parece ter algo errado nesta linha:


if weaponData[tostring(i)] then -- Se existe o ID "i" de arma na table, então:

Está convertendo 'i' para string, e se não constar na chave a referência como uma string irá falhar a verificação. Tente removendo o tostring.

 

Link to comment
  • Moderators
16 minutes ago, Lord Henry said:

A primeira table é a mytable faça ela com índices numéricos.

A tabela original também funciona. Ela já recebe índices numéricos em sequencia mesmo quando não-declarado.

Ou seja, fazer isso é uma redundância:

local mytable = { [1] = 'red', [2] = 'blue', [3] = 'dark blue', [4] = 'green' }

Pois já será interpretada dessa forma mesmo sem definir esses índices em sequencia.

Aqui os resultados do teste com 'mytable' de qualquer forma:

local mytable = { 'red', 'blue', 'dark blue', 'green' }

print(mytable[1])
iprint(mytable)

-- resultados:
[21:05:31] INFO: red
[21:05:31] INFO: { "red", "blue", "dark blue", "green" }

EDIT:

5 minutes ago, carlos eduardo said:

O problema era o painel de login

Se puder nos mostre aqui o que estava impedindo o save de funcionar, isso pode ajudar outras pessoas caso tenham esse tipo de conflito também.

@carlos eduardo

Link to comment
9 minutes ago, DNL291 said:

 

Se puder nos mostre aqui o que estava impedindo o save de funcionar, isso pode ajudar outras pessoas caso tenham esse tipo de conflito também.

@carlos eduardo

eu peguei um codigo da net de save system, e com a ajuda do Lord ele criou um sistema melhor de salvar as armas e tambem eu tive que desativar meu painelLogin(não sei o motivo de conflito deles)

Codigo:

function playerLogin (thePreviousAccount, theCurrentAccount, autoLogin)
	if not (isGuestAccount (getPlayerAccount (source))) then
		local accountData = getAccountData (theCurrentAccount, "funmodev2-money")
		if (accountData) then
			local playerMoney = getAccountData (theCurrentAccount, "funmodev2-money")
			local playerSkin = getAccountData (theCurrentAccount, "funmodev2-skin")
			local playerHealth = getAccountData (theCurrentAccount, "funmodev2-health")
			local playerArmor = getAccountData (theCurrentAccount, "funmodev2-armor")
			local playerX = getAccountData (theCurrentAccount, "funmodev2-x")
			local playerY = getAccountData (theCurrentAccount, "funmodev2-y")
			local playerZ = getAccountData (theCurrentAccount, "funmodev2-z")
			local playerInt = getAccountData (theCurrentAccount, "funmodev2-int")
			local playerDim = getAccountData (theCurrentAccount, "funmodev2-dim")
			local playerWanted = getAccountData (theCurrentAccount, "funmodev2-wantedlevel")
			local playerTeam = getAccountData (theCurrentAccount, "funmodev2-Team")
			spawnPlayer (source, playerX, playerY, playerZ +1, 0, playerSkin, playerInt, playerDim)
			setPlayerMoney (source, playerMoney)
			setTimer (setElementHealth, 500, 1, source, playerHealth)
			setTimer (setPedArmor, 500, 1, source, playerArmor)
			setTimer (setPlayerWantedLevel, 500, 1, source, playerWanted)
			if getAccountData (theCurrentAccount, "funmodev2-weapons") then
				local weaponData = fromJSON (getAccountData (account, "funmodev2-weapons")) -- Converte a string JSON em uma table.
				for i=1, 46 do -- Para cada ID de arma, faça: (seria do 0 ao 46, mas não precisa obter a mão do jogador)
					if weaponData[tostring(i)] then -- Se existe o ID "i" de arma na table, então:
						giveWeapon (source, i, weaponData[tostring(i)]) -- Os índices da table JSON sempre são em string.
					end
				end
			end
			setCameraTarget (source)
			fadeCamera (source, true, 2.0)
		else
			spawnPlayer (source, 1481.0855712891, -1771.2996826172, 18.795753479004, 0, 78, 0, 0)
			setPlayerMoney (source, 200)
			setCameraTarget (source)
			fadeCamera (source, true, 2.0)
		end
	end
end
addEventHandler ("onPlayerLogin", root, playerLogin)

function onLogout ()
	kickPlayer (source, nil, "Logging out is disallowed.")
end
addEventHandler ("onPlayerLogout", root, onLogout)

function onQuit (quitType, reason, responsibleElement)
	if not (isGuestAccount (getPlayerAccount (source))) then
		account = getPlayerAccount (source)
		if (account) then
			local x, y, z = getElementPosition (source)
			setAccountData (account, "funmodev2-money", tostring (getPlayerMoney (source)))
			setAccountData (account, "funmodev2-skin", tostring (getPedSkin (source)))
			setAccountData (account, "funmodev2-health", tostring (getElementHealth (source)))
			setAccountData (account, "funmodev2-armor", tostring (getPedArmor (source)))
			setAccountData (account, "funmodev2-R", r)
			setAccountData (account, "funmodev2-G", g)
			setAccountData (account, "funmodev2-B", b)
			setAccountData (account, "funmodev2-x", x)
			setAccountData (account, "funmodev2-y", y)
			setAccountData (account, "funmodev2-z", z)
			setAccountData (account, "funmodev2-int", getElementInterior (source))
			setAccountData (account, "funmodev2-dim", getElementDimension (source))
			setAccountData (account, "funmodev2-wantedlevel", getPlayerWantedLevel (source))
			local ammo = {}
			for i=0,12 do --Weapon Slots
				for k=1,46 do --Weapon IDs (seria do 0 ao 46, mas não precisa obter a mão do jogador, arma 0.)
					if getPedWeapon (source, i) == k then
						ammo[k] = getPedTotalAmmo (source, i)
					end
				end
			end
			setAccountData (account, "funmodev2-weapons", toJSON ( { ammo[1], ammo[2], ammo[3], ammo[4], ammo[5], ammo[6], ammo[7], ammo[8], ammo[9], ammo[10], ammo[11], ammo[12], ammo[13], ammo[14], ammo[15], ammo[16], ammo[17], ammo[18], ammo[19], ammo[20], ammo[21], ammo[22], ammo[23], ammo[24], ammo[25], ammo[26], ammo[27], ammo[28], ammo[29], ammo[30], ammo[31], ammo[32], ammo[33], ammo[34], ammo[35], ammo[36], ammo[37], ammo[38], ammo[39], ammo[40], ammo[41], ammo[42], ammo[43], ammo[44], ammo[45], ammo[46] } ))
		end
	end
end
addEventHandler ("onPlayerQuit", root, onQuit)

function onWasted (totalAmmo, killer, killerWeapon, bodypart, stealth)
	if not (isGuestAccount (getPlayerAccount(source))) then
		local theWeapon = getPedWeapon (source)
		local weaponAmmo = getPedTotalAmmo (source)
		fadeCamera (source, false)
		setTimer (spawnPlayer, 1000, 1, source, 2036.1735839844, -1413.0563964844, 16.9921875, 0, getPedSkin (source), 0, 0, getPlayerTeam(source))
		setTimer (setCameraTarget, 1250, 1, source)
		setTimer (fadeCamera, 2000, 1, source, true)
		setTimer (giveWeapon, 2000, 1, source, theWeapon, weaponAmmo, true)
	end
end
addEventHandler ("onPlayerWasted", root, onWasted)

function setTeam ()
	local account = getPlayerAccount (source) -- gets players account
	local team = getAccountData (account, "team") -- gets players team
	if (team) and getTeamFromName (team) then
		setPlayerTeam (source, getTeamFromName (team)) -- sets players team
	end
end
addEventHandler ("onPlayerLogin", root, setTeam) -- sets players team on login
 
function save()
	local team = getPlayerTeam (source) -- Gets the players team
	local account = getPlayerAccount (source)
	if (team) and not isGuestAccount (account) then -- Checks to see if the player is a guest or not
		setAccountData (account, "team", getTeamName (team)) --saves team
	end
end
addEventHandler ("onPlayerQuit", root, save) -- saves team on quit

EDIT:Se o Lord permitir eu posso criar um winrar do script para te mandar.

Edited by carlos eduardo
  • Like 1
Link to comment
  • Moderators

A propósito, percebi que tem um loop de todas armas dentro do loop dos slots, isso poderia ser simplificado assim:

local weapons = {} 
for slot=0, 12 do 
    local weapon = getPedWeapon(player, slot) 
    local ammo = getPedTotalAmmo(player, slot)
  
    weapons[weapon] = ammo
end

Já que cada slot é reservado para determinadas armas, exemplo: Slot 2 > pistola, desert e pistola silenciosa. Mas com esse loop vai percorrer todos ids ignorando essa definição do jogo.

Edit:

Certo @carlos eduardo

2 minutes ago, carlos eduardo said:

EDIT:Se o Lord permitir eu posso criar um winrar do script para te mandar.

Não precisa, só perguntei para saber se você modificou algo em especifico para corrigir o tal conflito, mas você já disse que foi no resource do login.

Link to comment
Just now, DNL291 said:

A propósito, percebi que tem um loop de todas armas dentro do loop dos slots, isso poderia ser simplificado assim:


local weapons = {} for slot=0, 12 do     local weapon = getPedWeapon(player, slot)     local ammo = getPedTotalAmmo(player, slot)      weapons[weapon] = ammoend

Já que cada slot é reservado para determinadas armas, exemplo: Slot 2 > pistola, desert e pistola silenciosa. Mas com esse loop vai percorrer todos ids ignorando essa definição do jogo.

Eu vou continuar com esse script, pois não sou tão bom em criar uns complexos.Melhor eu deixar ele assim ^^

Pode ja fechar o topico se quiser eu acho

Link to comment
  • Other Languages Moderators

Seguindo os testes de JSON:

Spoiler



local mytable = { [1] = 'red', [2] = 'blue', [3] = 'dark blue', [4] = 'green' }
jsondata = toJSON(mytable)
iprint("toJSON table = ", jsondata)
restoredtable = fromJSON(jsondata)
iprint("table padrao = ", restoredtable)

for i=1, #restoredtable do
    print( restoredtable[i] )
end

Resultado:


INFO: "toJSON table = "    '[ { "1": "red", "2": "blue", "4": "green", "3": "dark blue" } ]'
INFO: "table padrao = "    {
  ["1"] = "red",
  ["2"] = "blue",
  ["3"] = "dark blue",
  ["4"] = "green"
}

Outro teste, mais parecido com o caso do save-system:


local mytable = { [1] = 1, [4] = 1, [25] = 90, [30] = 180 }
jsondata = toJSON(mytable)
iprint("toJSON table = ", jsondata)
restoredtable = fromJSON(jsondata)
iprint("table padrao =", restoredtable)

for i=1, #restoredtable do
    print( restoredtable[i] )
end

Resultado:


INFO: "toJSON table = "    '[ { "1": 1, "25": 90, "4": 1, "30": 180 } ]'
INFO: "table padrao ="    {
  ["1"] = 1,
  ["25"] = 90,
  ["30"] = 180,
  ["4"] = 1
}

E por fim um teste igual ao do save-system: (porém em vez de ser até 64 itens, fiz só até 10)


local mytable = { [1] = 1, [4] = 1, [7] = 90, [10] = 180 }
jsondata = toJSON({mytable[1], mytable[2], mytable[3], mytable[4], mytable[5], mytable[6], mytable[7], mytable[8], mytable[9], mytable[10]})
iprint("toJSON table = ", jsondata)
restoredtable = fromJSON(jsondata)
iprint("table padrao =", restoredtable)

for i=1, #restoredtable do
    print( restoredtable[i] )
end

Resultado:


INFO: "toJSON table = "    '[ { "1": 1, "4": 1, "7": 90, "10": 180 } ]'
INFO: "table padrao ="    {
  ["1"] = 1,
  ["10"] = 180,
  ["4"] = 1,
  ["7"] = 90
}


 

Em nenhum deles o loop FOR funcionou.

Edited by Lord Henry
Colocado dentro de spoiler pra evitar spam.
Link to comment
  • Moderators

@Lord Henry Pois é, quando o índice é definido na tabela, toJSON/fromJSON define esse índice como string. Não sabia disso, por isso imaginei que o tostring podia estar causando erro.

Se criar a tabela sem index funciona (o meu teste); mas se tiver com [index] = valor, JSON vai deixar como string.

Voltando ao assunto:

Eu fiz o save das armas/munição e adaptei ao código do save-system, fiz nessa lógica, que evita o excesso nos loops:

19 hours ago, DNL291 said:

 


local weapons = {} 
for slot=0, 12 do 
    local weapon = getPedWeapon(player, slot) 
    local ammo = getPedTotalAmmo(player, slot)
  
    weapons[weapon] = ammo
end

Também coloquei pra remover as armas no logout/onResourceStop, para não bugar.

Código:

function playerLogin (thePreviousAccount, theCurrentAccount)
    local accountData = getAccountData (theCurrentAccount, "funmodev2-money")
    if (accountData) then
        local playerMoney = getAccountData (theCurrentAccount, "funmodev2-money")
        local playerSkin = getAccountData (theCurrentAccount, "funmodev2-skin")
        local playerHealth = getAccountData (theCurrentAccount, "funmodev2-health")
        local playerArmor = getAccountData (theCurrentAccount, "funmodev2-armor")
        local playerX = getAccountData (theCurrentAccount, "funmodev2-x")
        local playerY = getAccountData (theCurrentAccount, "funmodev2-y")
        local playerZ = getAccountData (theCurrentAccount, "funmodev2-z")
        local playerInt = getAccountData (theCurrentAccount, "funmodev2-int")
        local playerDim = getAccountData (theCurrentAccount, "funmodev2-dim")
        local playerWanted = getAccountData (theCurrentAccount, "funmodev2-wantedlevel")
        local team = getAccountData (theCurrentAccount, "team")

        if (team) and getTeamFromName(team) then
            setPlayerTeam(source, getTeamFromName(team)) -- sets players team
        end

        spawnPlayer (source, playerX, playerY, playerZ +1, 0, playerSkin, playerInt, playerDim)
        setPlayerMoney (source, playerMoney)
        setTimer (setElementHealth, 500, 1, source, playerHealth)
        setTimer (setPedArmor, 500, 1, source, playerArmor)
        setTimer (setPlayerWantedLevel, 500, 1, source, playerWanted)
        setCameraTarget (source, source)
        fadeCamera(source, true, 2.0)
    else
        spawnPlayer (source, 1481.0855712891, -1771.2996826172, 18.795753479004, 0,78, 0, 0)
        setPlayerMoney (source, 200)
        setCameraTarget (source, source)
        fadeCamera(source, true, 2.0)   
    end
    loadPlayerData( source )
end
addEventHandler ("onPlayerLogin", getRootElement(), playerLogin)

function onQuit()
    local account = getPlayerAccount (source)
    if (account) then
        local x,y,z = getElementPosition (source)
        setAccountData (account, "funmodev2-money", tostring (getPlayerMoney (source)))
        setAccountData (account, "funmodev2-skin", tostring (getElementModel (source)))
        setAccountData (account, "funmodev2-health", tostring (getElementHealth (source)))
        setAccountData (account, "funmodev2-armor", tostring (getPedArmor (source)))
        --setAccountData (account, "funmodev2-R", r) -- nenhum valor definido
        --setAccountData (account, "funmodev2-G", g)
        --setAccountData (account, "funmodev2-B", b)
        setAccountData (account, "funmodev2-x", x)
        setAccountData (account, "funmodev2-y", y)
        setAccountData (account, "funmodev2-z", z)
        setAccountData (account, "funmodev2-int", getElementInterior (source))
        setAccountData (account, "funmodev2-dim", getElementDimension (source))
        setAccountData (account, "funmodev2-wantedlevel", getPlayerWantedLevel (source))

        local team = getPlayerTeam(source) -- Gets the players team
        if (team) then -- Checks to see if the player is a guest or not
            setAccountData(account, "team", getTeamName(team)) --saves team
        end
    end
    savePlayerData( source )
end
addEventHandler ("onPlayerQuit", getRootElement(), onQuit)

function onWasted(totalAmmo, killer, killerWeapon, bodypart, stealth)
    if not( isGuestAccount (getPlayerAccount(source)) ) then
      local theWeapon = getPedWeapon (source)
      local weaponAmmo = getPedTotalAmmo (source)
      fadeCamera (source, false)
      setTimer (spawnPlayer, 1000, 1, source, 2036.1735839844, -1413.0563964844, 16.9921875, 0, getElementModel (source), 0, 0, getPlayerTeam(source))
      setTimer (setCameraTarget, 1250, 1, source, source)
      setTimer (fadeCamera, 2000, 1, source, true)
      setTimer (giveWeapon, 2000, 1, source, theWeapon, weaponAmmo, true)
    end
  end
addEventHandler ("onPlayerWasted", getRootElement(), onWasted)

function loadPlayerData ( player )
    local acc = getPlayerAccount(player)
    if isGuestAccount(acc) then return end


    local weapons = getAccountData(acc, "funmodev2-weapons") 
    if (weapons) then 
        for weapon, ammo in pairs(fromJSON(weapons)) do 
            giveWeapon(player, weapon, ammo, true) 
        end 
    end
end
addEventHandler ("onResourceStart", resourceRoot, function() for i,p in ipairs(getElementsByType("player")) do loadPlayerData(p) end end)

function savePlayerData ( player, acc )
    local acc = ( eventName == "onPlayerLogout" and acc or getPlayerAccount(player) )
    if isGuestAccount(acc) then return end

    local playerWeapons = {}
    for slot = 0, 12 do
        local weapon = getPedWeapon( player, slot )
        if ( weapon > 0 ) then
            local ammo = getPedTotalAmmo( player, slot )
            if ( ammo > 0 ) then
                playerWeapons[ weapon ] = ammo
            end
        end
    end
    setAccountData( acc, "funmodev2-weapons", toJSON ( playerWeapons ) )
  
    if eventName == "onResourceStop" or eventName == "onPlayerLogout" then
        takeAllWeapons( player )
    end
end
addEventHandler ("onPlayerLogout", root, function ( acc ) savePlayerData(source, acc) end)
addEventHandler ("onResourceStop", resourceRoot, function() for i,p in ipairs(getElementsByType("player")) do savePlayerData(p) end end)

 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...