Ir para conteúdo

Featured Replies

Postado
  • Este é um post popular.

Olá! Fiz uma adaptação no evento "SafeZone" criado e disponibilizado aqui no TK por @Movie e @luanluciano93.

 

 

Agora o evento é compatível para TFS 0.4.

 

IMPORTANTE:  Como mencionado anteriormente, o evento foi criado por "Movie" e "LuanLuciano93". Eu (imperius) APENAS ADAPTEI para funcionar em TFS 0.4. Todos os créditos do evento vão para os criadores originais. Além disso, é importante alertar que esta adaptação não está 100%.

 

Abaixo está todo o processo explicando como configurar e rodar o evento em seu servidor!

 

 

Vídeo demonstrativo:

 

 

 

em data > lib > crie um arquivo chamado safeZone.lua

 

Spoiler

--[[
    Evento criado por LuanLuciano93 e Movie (Movie#4361)
--]]

SAFEZONE_CONFIG = {
    effectArea       = CONST_ME_SMALLPLANTS,
    tileActionId     = 69241,
    protectionTileId = {9562, 9563, 9564, 9565}, -- ID dos pisos que serão criados
    minPlayers       = 2,  -- Limite minimo de jogadores.
    maxPlayers       = 14, -- Limite maximo de jogadores.
    levelMin         = 1,  -- Level  minimo para participar.
    days = {
        ["Monday"]    = {"19:30"}, -- Segunda
		["Tuesday"]   = {"19:30"}, -- Terça
		["Wednesday"] = {"19:30"}, -- Quarta
		["Thursday"]  = {"19:30"}, -- Quinta
		["Friday"]    = {"19:30"}, -- Sexta
		["Saturday"]  = {"19:30"}, -- Sábado
		["Sunday"]    = {"19:30"}  -- Domingo
    },
    broadcast = {      -- NÃO ALTERE |totalParticipants|, |position|, |playerName| e |minutesToStart|.
        prefix         = "[SafeZone]",
        start          = "O evento ira comecar agora com |totalParticipants| participantes! Boa sorte!",
        noParticipants = "O evento nao foi iniciado por falta de participantes!",
        open           = "O evento foi aberto, voce tem |minutesToStart| minuto(s) para entrar no portal do evento que se encontra no templo!",
        finish         = "O evento foi finalizado e o ganhador foi |playerName|! Parabens!",
        winner         = "|playerName| terminou o evento em |position| lugar!"
    },
    reward = {
    -- [colocacao] = {{itemID, quantidade}, etc...}
       [1] = {{2160, 80}, {2520, 1}},
       [2] = {{2160, 50}},
       [3] = {{2160, 25}}
    },
    position = {
        openTeleport   = {x = 32365, y = 32236, z = 7}, -- Posição onde o teleport será aberto para participar do evento.
        leaveEvent     = {x = 32369, y = 32241, z = 7}, -- Posição onde o jogador será teleportado ao perder / ganhar o evento.
        arenaCenter    = {x = 32337, y = 31934, z = 7}, -- Posição do centro da arena do evento.
        arenaLeftTop   = {x = 32332, y = 31930, z = 7}, -- Posição do canto superior esquerdo da arena.
        arenaRightDown = {x = 32342, y = 31939, z = 7}  -- Posição do canto inferior direito  da arena.
    },
    lifeColor = { -- cores do outfit
        [1] = 94, -- red
        [2] = 77, -- orange
        [3] = 79  -- yellow
    },
    timeInMinutes = {
        closeTP = 1 -- Tempo em que o TP fechará após o evento ser anunciado.
    }
}

-- == [ RECOMENDO NÃO MEXER NAS FUNÇÕES ABAIXO ] == --

-- Responsável por inserir o jogador como um participante do evento.
function insertPlayerInSafeZone(playerId)
    local query = db.query or db.executeQuery
    query("INSERT INTO safezone_participants (cid, life) VALUES ('"..playerId.."', 3) LIMIT 1")
end

-- Retorna a quantidade de jogadores que estão participando do evento.
function totalPlayersInSafeZone()
    local queryResult = db.storeQuery("SELECT COUNT(id) as total FROM safezone_participants")
    return result.getDataInt(queryResult, "total")
end

-- Retorna todos os "cid" dos jogadores que estão participando do evento.
function getPlayersIdInSafeZone() 
    local queryResult = db.storeQuery("SELECT cid FROM safezone_participants")
    local players = {}
    if not queryResult then
        return players
    else
        table.insert(players, result.getDataInt(queryResult, "cid"))
        while result.next(queryResult) do
          local result = result.getDataInt(queryResult, "cid")
          table.insert(players, result)
        end
        return players
    end
end

 

 

 

data > globalevents > globalevents.xml

 

Spoiler

<!-- SafeZone -->
<globalevent name="safeZone" interval="60000" event="script" value="safeZoneEvent.lua"/>

 

 

 

em data > globalevents > scripts > crie um arquivo chamado safeZoneEvent.lua

 

Spoiler

--[[
    Evento criado por LuanLuciano93 e Movie (Movie#4361)
--]]

function onThink(interval)

	local hrs = tostring(os.date("%X")):sub(1, 5)

	if SAFEZONE_CONFIG.days[os.date("%A")] and isInArray(SAFEZONE_CONFIG.days[os.date("%A")], hrs) then

		local from = SAFEZONE_CONFIG.position.arenaLeftTop
		local to   = SAFEZONE_CONFIG.position.arenaRightDown

		-- função para converter minutos em milissegundos
		function minutesToMillis(minutes)
			return minutes * 1000 * 60
		end

		-- responsável por atualizar o outfit do jogador de acordo com a quantidade vidas restantes.
		function changeOutfitLifeInSafeZone(playerId, qntLife)
			local color  = SAFEZONE_CONFIG.lifeColor[qntLife]
			local outfit = getPlayerSex(playerId) == 0 and 136 or 128
							  
			local conditionOutfitLife = createConditionObject(CONDITION_OUTFIT)
			setConditionParam(conditionOutfitLife, CONDITION_PARAM_TICKS, -1)
			addOutfitCondition(conditionOutfitLife, {lookType = outfit, lookHead = color, lookBody = color, lookLegs = color, lookFeet = color})
			doAddCondition(playerId, conditionOutfitLife)
		end

		
		-- Remove uma vida do jogador, se ele não tiver mais vidas, é removido do evento.
		function removeLifePlayerInSafeZone(playerId)
			local lifePlayer = getPlayerLifeInSafeZone(playerId) - 1
			if lifePlayer >= 1 then
				changeOutfitLifeInSafeZone(playerId, lifePlayer)
				db.executeQuery("UPDATE safezone_participants SET life = life - 1 WHERE cid = " ..playerId.. " LIMIT 1")
			else
				removePlayerInSafeZone(playerId)
			end
		end

		-- Retorna a quantidade de pisos que serão criados na rodada.
		function totalProtectionTileInSafeZone()
			local totalPlayers = totalPlayersInSafeZone()
			if totalPlayers >= 10 then
				return totalPlayers - 3
			else
				return totalPlayers - 1
			end
		end

		-- Remove um jogador do evento.
		function removePlayerInSafeZone(playerId) 
			if checkToRewardPlayerInSafeZone(playerId, totalPlayersInSafeZone()) then
				db.query("DELETE FROM safezone_participants WHERE cid = '"..playerId.."' LIMIT 1")
				doTeleportThing(playerId, SAFEZONE_CONFIG.position.leaveEvent, true)
				checkAndSetWinnerInSafeZone()
				doRemoveCondition(playerId, CONDITION_OUTFIT)
				return true
			end
		end

		-- Verifica se o jogador ficou em "primeiro", "segundo" ou "terceiro" lugador.
		-- Se sim, receberá as recompensas correspondentes a sua colocação.
		function checkToRewardPlayerInSafeZone(playerId, placement)
			if placement > 0 and placement <= 3 then

				if placement > 1 then
					local placementName = (placement == 2) and "segundo" or "terceiro"
		
					local broadcast = string.gsub(SAFEZONE_CONFIG.broadcast.winner, "|playerName|", getCreatureName(playerId))
					local broadcast = string.gsub(broadcast, "|position|", placementName)
					doBroadcastMessage(SAFEZONE_CONFIG.broadcast.prefix.." "..broadcast)
					insertWinnerInSafeZone(playerId, placement)
				end
		
				local bagReward = doCreateItemEx(1992)
				for _, reward in pairs(SAFEZONE_CONFIG.reward[placement]) do
					doAddContainerItemEx(bagReward, doCreateItemEx(reward[1], reward[2]))
				end
				doPlayerAddItemEx(playerId, bagReward)

			end
			return true
		end

		-- Responsável por verificar se o evento possui um vencedor do primeiro lugar.
		function checkAndSetWinnerInSafeZone()
			if totalPlayersInSafeZone() == 1 then
				local playerId = selectWinnerInSafeZone()
				doBroadcastMessage(SAFEZONE_CONFIG.broadcast.prefix.." "..string.gsub(SAFEZONE_CONFIG.broadcast.finish, "|playerName|", getCreatureName(playerId)))
				insertWinnerInSafeZone(playerId, 1)
				removePlayerInSafeZone(playerId)
			end
		end

		-- Responsável por inserir o jogador vencedor na tabela.
		function insertWinnerInSafeZone(playerId, placement)
			local date  = os.date("%Y-%m-%d %H:%M:%S")
			local query = db.query or db.executeQuery
			db.executeQuery("INSERT INTO safezone_winners (player_id, placement, date) VALUES ('"..getPlayerGUID(playerId).."', '"..tonumber(placement).."', '"..date.."') LIMIT 1")
			return true
		end

		-- Responsável por selecionar o jogador, vencedor do evento.
		function selectWinnerInSafeZone()
			local queryResult = db.storeQuery("SELECT cid FROM safezone_participants LIMIT 1")
			return result.getDataInt(queryResult, "cid")
		end

		-- Responsável por retornar a quantidade de vidas restantes de um jogador.
		function getPlayerLifeInSafeZone(playerId) 
			local queryResult = db.storeQuery("SELECT life FROM safezone_participants WHERE cid = '"..playerId.."' LIMIT 1")
			return (queryResult) and result.getDataInt(queryResult, "life") or 0
		end

		-- Remove todos os jogadores do evento.
		-- Utilizado em caso de não houver jogadores suficientes para começar o evento.
		function removeAllPlayersInSafeZone() 
			for _, playerId in pairs(getPlayersIdInSafeZone()) do
				doTeleportThing(playerId, SAFEZONE_CONFIG.position.leaveEvent, true)
			end
			db.query("DELETE FROM safezone_participants")
		end

		-- Atualiza os outfits de todos os participantes de acordo com a vida inicial "3".
		function changeOutfitStartInSafeZone()
			for _, playerId in pairs(getPlayersIdInSafeZone()) do
				changeOutfitLifeInSafeZone(playerId, 3)
			end
		end

		-- Responsável por verificar se o jogador está ou não pisando no protection tile.
		function moveToEventSafeTile(playerId, tileID)
			local tilePlayer = getTileItemById(getCreaturePosition(playerId), tileID)
			if tilePlayer.actionid ~= SAFEZONE_CONFIG.tileActionId then
			  removeLifePlayerInSafeZone(playerId)
			end
		end
		
		-- Responsável por criar o efeito em área somente aonde não tiver os protection tile.
		function createEffectAreaInSafeZone(playerId, tileID)
			for x = from.x, to.x do
			for y = from.y, to.y do
			for z = from.z, to.z do
				pos = {x = x, y = y, z = z, stackpos = 253}
				local effect = (getTileItemById(pos, tileID).actionid == SAFEZONE_CONFIG.tileActionId) and "" or doSendMagicEffect(pos, CONST_ME_SMALLPLANTS)
			end
			end
			end
			 moveToEventSafeTile(playerId, tileID)
		  end		

		-- Responsável por remover todos os protections tiles da arena.
		function removeProtectTilesInSafeZone(tileID, positionTile)
			local tile = getTileItemById(positionTile, tileID)
			if tile.uid > 0 then
				doRemoveItem(tile.uid, 1)
			end
		end

		-- Responsável por criar novos protections tiles em posições aleatorias da arena.
		function createProtectTileInSafeZone()
			local randomTileId = SAFEZONE_CONFIG.protectionTileId[math.random(1, #SAFEZONE_CONFIG.protectionTileId)]
			for i, playerId in pairs(getPlayersIdInSafeZone()) do
				local randomPositionTile = {x=math.random(from.x,to.x), y=math.random(from.y,to.y), z=math.random(from.z,to.z)}
				doItemSetAttribute(doCreateItem(randomTileId, 1, randomPositionTile), "aid", SAFEZONE_CONFIG.tileActionId)
				if i >= totalPlayersInSafeZone() then
					doRemoveItem(getTileItemById(randomPositionTile, randomTileId).uid)
				end
				addEvent(createEffectAreaInSafeZone, 8700, playerId, randomTileId)
				addEvent(removeProtectTilesInSafeZone, 9000, randomTileId, randomPositionTile)
			end
			addEvent(createProtectTileInSafeZone, 16000)
		end
			
		-- responsável por verificar se há ou não jogadores suficientes para começar.
		function checkToStartSafeZone()
			doRemoveItem(getTileItemById(SAFEZONE_CONFIG.position.openTeleport, 1387).uid)
			
			if totalPlayersInSafeZone() >= SAFEZONE_CONFIG.minPlayers then
				doBroadcastMessage(SAFEZONE_CONFIG.broadcast.prefix.." "..string.gsub(SAFEZONE_CONFIG.broadcast.start, "|totalParticipants|", totalPlayersInSafeZone()))
				changeOutfitStartInSafeZone()
				addEvent(createProtectTileInSafeZone, 10000)
			else
				removeAllPlayersInSafeZone()
				doBroadcastMessage(SAFEZONE_CONFIG.broadcast.prefix.." "..SAFEZONE_CONFIG.broadcast.noParticipants)
			end
		end

		-- abre o teleport do evento.
		function openTeleportInSafeZone()
			local openTeleport = doCreateItem(1387, 1, SAFEZONE_CONFIG.position.openTeleport)
			doItemSetAttribute(openTeleport, "aid", 6925)
			doBroadcastMessage(SAFEZONE_CONFIG.broadcast.prefix.." "..string.gsub(SAFEZONE_CONFIG.broadcast.open, "|minutesToStart|", SAFEZONE_CONFIG.timeInMinutes.closeTP))
			addEvent(checkToStartSafeZone, minutesToMillis(SAFEZONE_CONFIG.timeInMinutes.closeTP))
		end
		
		openTeleportInSafeZone()
	end
	return true
end

 

 

 

data > movements > movements.xml

 

Spoiler

<!-- SafeZone -->
<movevent type="StepIn" actionid="6925" event="script" value="safeZoneMovement.lua"/>

 

 

 

em data > movements > scripts > crie um arquivo chamado safeZoneMovement.lua

 

Spoiler

--[[
    Evento criado por LuanLuciano93 e Movie (Movie#4361)
--]]

function onStepIn(cid, item, position, lastPosition, fromPosition, toPosition, actor)

    -- Verifica se o jogador possui o level minimo para participar do evento.
    if getPlayerLevel(cid) < SAFEZONE_CONFIG.levelMin then
        doPlayerSendCancel(cid, SAFEZONE_CONFIG.broadcast.prefix.." Voce precisa ser level "..SAFEZONE_CONFIG.levelMin.." ou maior para entrar no evento.")
        doTeleportThing(cid, fromPosition, true)
        doSendMagicEffect(getCreaturePosition(cid), CONST_ME_POFF)
        return true
    end

    -- Verifica se o limite máximo de jogadores foi ultrapassado.
    if totalPlayersInSafeZone() == SAFEZONE_CONFIG.maxPlayers then
        doPlayerSendCancel(cid, SAFEZONE_CONFIG.broadcast.prefix.." o evento alcancou o limite maximo de jogadores.")
        doTeleportThing(cid, fromPosition, true)
        doSendMagicEffect(getCreaturePosition(cid), CONST_ME_POFF)
        return true
    end

    -- Se o jogador estiver usando "stealth ring" não poderá entrar no evento.
    local ring = getPlayerSlotItem(cid, CONST_SLOT_RING)
    if ring and ring.itemid == 2202 then
      doPlayerSendCancel(cid, SAFEZONE_CONFIG.broadcast.prefix.." Voce nao pode entrar com um stealth ring no evento.")
      doTeleportThing(cid, fromPosition, true)
      doSendMagicEffect(getCreaturePosition(cid), CONST_ME_POFF)
      return true
  end

    doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, SAFEZONE_CONFIG.broadcast.prefix.." Voce entrou no evento. Boa sorte!")
    doTeleportThing(cid, SAFEZONE_CONFIG.position.arenaCenter, true)
    doSendMagicEffect(getCreaturePosition(cid), CONST_ME_TELEPORT)
    insertPlayerInSafeZone(cid)

  return true
end

 

 

 

por fim, vá até o banco de dados do seu servidor e adicione o seguinte código em "SQL"

 

Spoiler

CREATE TABLE safezone_participants (
  id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  cid varchar(255) NOT NULL,
  life tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


CREATE TABLE safezone_winners (
  id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  player_id INT(11) NOT NULL,
  placement TINYINT(1) NOT NULL,
  date DATETIME NOT NULL
) CHARSET=utf8mb4;

 

 

É isso! Espero ter ajudado o pessoal do TFS 0.4 :)

  • 4 months later...
Postado

Quando um player tenta entrar no evento da esse erro:

Spoiler

mysql_real_query(): INSERT INTO safezone_participants (cid, life) VALUES ('268453441', 3) LIMIT 1 - MYSQL ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'LIMIT 1' at line 1 (1064)



Consegue dar suporte?

Edit: Consegui arrumar o problema retirando o LIMIT 1 do final da linha, e adicionei `safezone_participants` e `safezone_winners` em todos as menções do mesmo em que se encontravam como safezone_participants e safezone_winners.

Editado por King Laker
Achei o problema e o corrigi. (veja o histórico de edições)

VlVKQKC.png&key=d5c17620ae9567a1f898dd7a

 

 

 

  • 532144234_Logo_NTO_BLOOD_Finish_HIM_By_Antonio_Luckas(3).png.fd58d1af125a7e82ccdd751637e9ca93.png
Postado
21 horas atrás, King Laker disse:

Quando um player tenta entrar no evento da esse erro:

  Ocultar conteúdo

mysql_real_query(): INSERT INTO safezone_participants (cid, life) VALUES ('268453441', 3) LIMIT 1 - MYSQL ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'LIMIT 1' at line 1 (1064)



Consegue dar suporte?

Edit: Consegui arrumar o problema retirando o LIMIT 1 do final da linha, e adicionei `safezone_participants` e `safezone_winners` em todos as menções do mesmo em que se encontravam como safezone_participants e safezone_winners.

 

retira o limit 1 que deve funcionar.

Postado
Em 19/08/2023 em 19:43, Celulose disse:

 

retira o limit 1 que deve funcionar.

Eu ja tinha resolvido o problema, inclusive adicionei um comentário em como resolvi.

VlVKQKC.png&key=d5c17620ae9567a1f898dd7a

 

 

 

  • 532144234_Logo_NTO_BLOOD_Finish_HIM_By_Antonio_Luckas(3).png.fd58d1af125a7e82ccdd751637e9ca93.png

Participe da conversa

Você pode postar agora e se cadastrar mais tarde. Se você tem uma conta, faça o login para postar com sua conta.

Visitante
Responder

Quem Está Navegando 0

  • Nenhum usuário registrado visualizando esta página.

Estatísticas dos Fóruns

  • Tópicos 96.9k
  • Posts 519.7k

Informação Importante

Confirmação de Termo