Ir para conteúdo

Featured Replies

Postado
  • Este é um post popular.

QUIZ

Fala, grande reino! Tudo beleza?

Eu estava aqui a deriva, sem nada para fazer, quando um colega me chamou no msn e pediu para eu revisar um código que ele havia feito para um NPC. A função era bem simples, o tal NPC iria fazer perguntas ao jogador que devia responder-las corretamente, caso errasse, duas criaturas configuráveis iriam aparecer.

Quando eu dei uma olhada no código, tomei um grande susto, era algo caótico, tudo embaralhado. Se você quer dar uma olhada, tenha certeza de ter um coração forte.


local focus = 0

local talk_start = 0

local target = 0

local following = false

local attacking = false


function onThingMove(creature, thing, oldpos, oldstackpos)


end



function onCreatureAppear(creature)


end



function onCreatureDisappear(cid, pos)

	  if focus == cid then

		  selfSay('Good bye then.')

		  focus = 0

		  talk_start = 0

	  end

end



function onCreatureTurn(creature)


end



function msgcontains(txt, str)

	  return (string.find(txt, str) and not string.find(txt, '(%w+)' .. str) and not string.find(txt, str .. '(%w+)'))

end



function onCreatureSay(cid, type, msg)

	  msg = string.lower(msg)


	  if (msgcontains(msg, 'hi') and (focus == 0)) and getDistanceToCreature(cid) < 4 then

		  selfSay('Hello Mortal, i impressed that you have come up here, strength ive seen that you have, now lets see your mind, ok?')

		  focus = cid

		  talk_start = os.clock()


	  elseif msgcontains(msg, 'hi') and (focus ~= cid) and getDistanceToCreature(cid) < 4 then

		  selfSay('Sorry, ' .. creatureGetName(cid) .. '! I talk to you in a minute.')


	elseif focus == cid then

		talk_start = os.clock()


		if msgcontains(msg, 'yes') then

			selfSay('that ring of mana shield?')

			talk_state = 1


		elseif msgcontains(msg, 'energy ring') then

			selfSay('what is the name of the npc that makes addons?')

			talk_state = 1


		elseif msgcontains(msg, 'raphael') then

			selfSay('what is the name of the famous rune who is most used by persons?')

			talk_state = 2


		elseif msgcontains(msg, 'sudden death rune') then

			selfSay('complete that "one ring to rule them..?')

			talk_state = 3


		elseif msgcontains(msg, 'sudden death rune') then

		elseif msgcontains(msg, 'sd') or msgcontains(msg, 'frigo') or msgcontains(msg, 'mimimi	') then

	frost1pos = {x=582, y=190, z=9}

	frost2pos = {x=581, y=189, z=9}

	doSummonCreature("Energy Balrog", frost1pos)

	doSummonCreature("Energy Balrog", frost2pos)

			selfSay('Wrong, i will to you a present.')

			talk_state = 3


		elseif msgcontains(msg, 'bye') then

	frost1pos = {x=582, y=190, z=9}

	frost2pos = {x=581, y=189, z=9}

	doSummonCreature("Energy Balrog", frost1pos)

	doSummonCreature("Energy Balrog", frost2pos)

			selfSay('Wrong, i will to you a present.')

			talk_state = 3


		elseif msgcontains(msg, 'energy ring') then

			selfSay('Correct, lets go to next question?')

			talk_state = 2


		elseif msgcontains(msg, 'Addons') then

		frost1pos = {x=582, y=190, z=9}

	frost2pos = {x=581, y=189, z=9}

	doSummonCreature("Energy Balrog", frost1pos)

	doSummonCreature("Energy Balrog", frost2pos)

			selfSay('Resposta Incorreta! ai esta...')

			talk_state = 2


		elseif msgcontains(msg, 'energy ring') then

			selfSay('Correct, lets go to next question?')

			talk_state = 1


		elseif msgcontains(msg, 'utamo') then

	frost1pos = {x=582, y=190, z=9}

	frost2pos = {x=581, y=189, z=9}

	doSummonCreature("Energy Balrog", frost1pos)

	doSummonCreature("Energy Balrog", frost2pos)

			selfSay('Wrong, i will to you a present.')

			talk_state = 1


		elseif msgcontains(msg, 'leave') then

			selfSay('Do you wish to leave the training camp?')

			talk_state = 2



		elseif talk_state == 4 then

			if msgcontains(msg, 'end') then

		local position = {x=581, y=189, z=9}

doTeleportThing(cid, position)

doBroadcastMessage("Congratulations 'creatureGetName(cid)',  is the way to the last room of the temple of Gods, and a step of immortality.")

				else

					selfSay('Sorry, you don't have enough money.')

				end


			talk_state = 0

	elseif msgcontains(msg, 'all') then

				local position = {x=581, y=189, z=9}

doTeleportThing(cid, position)

doSendMagicEffect(getCreaturePosition(cid), CONST_ME_ENERGYAREA)

doBroadcastMessage("Congratulations 'creatureGetName(cid)',  is the way to the last room of the temple of Gods, and a step of immortality.")	


		elseif msgcontains(msg, 'bye') and getDistanceToCreature(cid) < 4 then

			selfSay('Good bye, |PLAYERNAME|!')

			focus = 0

			talk_start = 0

		end

	end

end



function onCreatureChangeOutfit(creature)


end



function onThink()


if (os.clock() - talk_start) > 30 then

		  if focus > 0 then

			  selfSay('How rude!')

		  end

			  focus = 0

	  end

	if focus ~= 0 then

		if getDistanceToCreature(focus) > 5 then

			selfSay('Good bye then.')

			focus = 0

		end

	end

end

Claro que eu, como scripter, não podia deixar algo tão caótico reinar sobre os servidores alheios. Decidi então apagar tudo, recriar o NPC do zero, preservando a função que ele deveria desempenhar. Veja abaixo!
INSTALAÇÃO E CONFIGURAÇÃO data/npc/scripts

--[[

NPC de Perguntas e Respostas

Criado por Bruno Lopes / Lpz


&#169; 2011 TibiaKing

]]--


local focuses = {}

local talk_start = 0


local topic = {}


local var = 0


local quiz = {

	[1] = {"What is the ring of mana?", "energy ring"},

	[2] = {"Who sells addons?", "raphael"}

}


local monster = {"Orc", 2}


local prize = {

	question = 100,

	all = 10000

}


function onCreatureSay(cid, type, msg)

	local msg = msg:lower() or ""

	if getNpcDistanceTo(cid) > 3 then

		return false

	end


	if doMessageCheck(msg, {"hi", "hello"}) and not(isFocused(cid, focuses)) then

		selfSay("Hello, ".. getCreatureName(cid) ..". Can you answer my questions? heh...", cid)

		addFocus(cid, focuses)

		selfFocus(cid)

		topic[cid] = 100

		talk_start = os.clock()

	elseif doMessageCheck(msg, {"hi", "hello"}) and #focuses ~= 0 then

		selfSay("Sorry, ".. getCreatureName(cid) ..". I am talking with another person, wait!", cid)

	end


	if doMessageCheck(msg, {"bye", "farewell", "goodbye"}) and isFocused(cid, focuses) then

		selfSay("Bye-bye, hehe!", cid)

		removeFocus(cid, focuses)

	end


	if topic[cid] == 100 then

		if doMessageCheck(msg, "yes") then

			selfSay("To start my challenge, just say {ready}. I will ask you some questions.", cid)

			topic[cid] = 1

		elseif doMessageCheck(msg, "no") then

			selfSay("Huh? Why are you here then?", cid)

			removeFocus(cid, focuses)

			topic[cid] = 0

		end

	elseif topic[cid] == 1 then

		if var == 0 then

			if doMessageCheck(msg, "ready") then

				var = 1

				selfSay(quiz[var][1], cid)

			end

		elseif var >= 1 then

			if var <= #quiz then

				if doMessageCheck(msg, quiz[var][2]) then

					selfSay("CORRECT!", cid)

					doPlayerAddMoney(cid, prize.question)

					var = var+1

					if var > #quiz then

						selfSay("CONGRATULATIONS! YOU HAVE FINISHED ALL QUESTIONS!", cid)

						doPlayerAddMoney(cid, prize.all)

					else

						selfSay(quiz[var][1], cid)

					end

				else

					selfSay("YOU HAVE WRONG MY QUESTION! GUARDS, COME HERE!", cid)

					var = 0

					topic[cid] = 0

					removeFocus(cid, focuses)

					for i = 1, monster[2] do

						doCreateMonster(monster[1], getNpcPos())

					end

				end

			end

		end

	end	

	return true

end


function onThink()

	for _, cid in ipairs(focuses) do

		if isPlayer(cid) and isFocused(cid, focuses) then

			if os.clock() > (talk_start + 180) then

				talk_start = 0

				selfSay("Hmph!")

				closeShopWindow(cid)

				removeFocus(cid, focuses)

			elseif getNpcDistanceTo(cid) > 3 then

				talk_start = 0

				selfSay("How Rude!")

				closeShopWindow(cid)

				removeFocus(cid, focuses)

			end

		end

	end

	lookAtFocus(focuses)

end

Bom, eu fiz o arquivo .lua que você iria associar a algum npc de seu servidor, deixo o arquivo .xml por sua conta. Como é um NPC que faz perguntas, você pode configurar o seu NPC do jeito que você quiser, com as perguntas que você quiser. Veja abaixo como proceder:

local quiz = {

	[1] = {"What is the ring of mana?", "energy ring"},

	[2] = {"Who sells addons?", "raphael"}

}

Para adicionar novas perguntas, basta você colocar uma vírgula na última linha e criar uma nova linha conforme o modelo:

local quiz = {

	[1] = {"What is the ring of mana?", "energy ring"},

	[2] = {"Who sells addons?", "raphael"},

        [3] = {"PERGUNTA", "RESPOSTA"},

        [4] = {"PERGUNTA", "RESPOSTA"}

}

Há também algumas outras configurações básicas para você fazer, as criaturas que irão aparecer caso o jogador erre a pergunta e a quantidade. Também você pode configurar a quantidade de dinheiro que o jogador ganha quando acerta uma pergunta e a quantidade de dinheiro do prêmio final.

local monster = {"Orc", 2}


local prize = {

	question = 100,

	all = 10000

}


OBSERVAÇÕES Para evitar quaisquer erros no script, substitua o conteúdo de npc.lua em data/npc/lib por este que estou passando abaixo:


É isso aê, galerinha do tibiaKing!

Até o próximo tópico. :)


function selfSayChannel(cid, message)

	return selfSay(message, cid, false)

end


function selfMoveToThing(id)

	errors(false)

	local thing = getThing(id)


	errors(true)

	if(thing.uid == 0) then

		return

	end


	local t = getThingPosition(id)

	selfMoveTo(t.x, t.y, t.z)

	return

end


function selfMoveTo(x, y, z)

	local position = {x = 0, y = 0, z = 0}

	if(type(x) ~= "table") then

		position = Position(x, y, z)

	else

		position = x

	end


	if(isValidPosition(position)) then

		doSteerCreature(getNpcId(), position)

	end

end


function selfMove(direction, flags)

	local flags = flags or 0

	doMoveCreature(getNpcId(), direction, flags)

end


function selfTurn(direction)

	doCreatureSetLookDirection(getNpcId(), direction)

end


function getNpcDistanceTo(id)

	errors(false)

	local thing = getThing(id)


	errors(true)

	if(thing.uid == 0) then

		return nil

	end


	local c = getCreaturePosition(id)

	if(not isValidPosition(c)) then

		return nil

	end


	local s = getCreaturePosition(getNpcId())

	if(not isValidPosition(s) or s.z ~= c.z) then

		return nil

	end


	return math.max(math.abs(s.x - c.x), math.abs(s.y - c.y))

end


function doMessageCheck(message, keyword)

	if(type(keyword) == "table") then

		return table.isStrIn(message, keyword)

	end


	local a, b = message:lower(), keyword:lower()

	if(keyword == message) then

		return true

	end


	return message:find(keyword) and not message:find('(%w+)' .. keyword)

end


function doNpcSellItem(cid, itemid, amount, subType, ignoreCap, inBackpacks, backpack)

	local amount, subType, ignoreCap, item = amount or 1, subType or 1, ignoreCap and true or false, 0

	if(isItemStackable(itemid)) then

		if(isItemRune(itemid)) then

			amount = amount * subType

		end


		local count = amount

		repeat

			item = doCreateItemEx(itemid, math.min(100, count))

			if(doPlayerAddItemEx(cid, item, ignoreCap) ~= RETURNVALUE_NOERROR) then

				return 0, 0

			end


			count = count - math.min(100, count)

		until count == 0

		return amount, 0

	end


	local a = 0

	if(inBackpacks) then

		local container, b = doCreateItemEx(backpack, 1), 1

		for i = 1, amount do

			item = doAddContainerItem(container, itemid, subType)

			if(itemid == ITEM_PARCEL) then

				doAddContainerItem(item, ITEM_LABEL)

			end


			if(isInArray({(getContainerCapById(backpack) * b), amount}, i)) then

				if(doPlayerAddItemEx(cid, container, ignoreCap) ~= RETURNVALUE_NOERROR) then

					b = b - 1

					break

				end


				a = i

				if(amount > i) then

					container = doCreateItemEx(backpack, 1)

					b = b + 1

				end

			end

		end


		return a, b

	end


	for i = 1, amount do

		item = doCreateItemEx(itemid, subType)

		if(itemid == ITEM_PARCEL) then

			doAddContainerItem(item, ITEM_LABEL)

		end


		if(doPlayerAddItemEx(cid, item, ignoreCap) ~= RETURNVALUE_NOERROR) then

			break

		end


		a = i

	end


	return a, 0

end


function doRemoveItemIdFromPosition(id, n, position)

	local thing = getThingFromPos({x = position.x, y = position.y, z = position.z, stackpos = 1})

	if(thing.itemid ~= id) then

		return false

	end


	doRemoveItem(thing.uid, n)

	return true

end


function getNpcName()

	return getCreatureName(getNpcId())

end


function getNpcPos()

	return getThingPosition(getNpcId())

end


function selfGetPosition()

	local t = getThingPosition(getNpcId())

	return t.x, t.y, t.z

end


function isFocused(cid, t)

	for i, v in pairs(t) do

		if(v == cid) then

			return true

		end

	end

	return false

end


function addFocus(focus, t)

	if(not isFocused(focus, t)) then

		table.insert(t, focus)

	end

end


function setFocus(t)

	for i, v in pairs(t) do

		if(isPlayer(v)) then

			doNpcSetCreatureFocus(v)

			return

		end

	end

	doNpcSetCreatureFocus(0)

end


function removeFocus(cid, t)

	for i, v in pairs(t) do

		if(v == cid) then

			table.remove(t, i)

			selfFocus(0)

			break

		end

	end

end


function doCreatureSayWithDelay(cid,text,type,delay,e)

   if delay<=0 then

	  doCreatureSay(cid,text,type)

   else

	  local func=function(pars)

					doCreatureSay(pars.cid,pars.text,pars.type)

					pars.e.done=TRUE

				 end

	  e.done=FALSE

	  e.event=addEvent(func,delay,{cid=cid, text=text, type=type, e=e})

   end

end


function cancelNPCTalk(events)

	local ret = 1

	for aux = 1,table.getn(events) do

		if events[aux].done==FALSE then

			stopEvent(events[aux].event)

		else

			ret = ret+1

		end

	end

	events = nil

	return(ret)

end


function doNpcTalk(msgs,interval,pcid)

	local e={}

	local ret={}

	interval = interval or 10000

	for aux = 1, #msgs do

		e[aux]={}

		doCreatureSayWithDelay(getNpcCid(),msgs[aux],TALKTYPE_PRIVATE_NP,(aux-1)*interval,e[aux],pcid)

		table.insert(ret,e[aux])

	end

	return ret

end


msgcontains = doMessageCheck

checkMsg = doMessageCheck

moveToPosition = selfMoveTo

moveToCreature = selfMoveToThing

selfMoveToCreature = selfMoveToThing

selfMoveToPosition = selfMoveTo

isPlayerPremiumCallback = isPremium

doPosRemoveItem = doRemoveItemIdFromPosition

doRemoveItemIdFromPos = doRemoveItemIdFromPosition

doNpcBuyItem = doPlayerRemoveItem

doNpcSetCreatureFocus = selfFocus

getNpcCid = getNpcId

lookAtFocus = setFocus

getDistanceTo = getNpcDistanceTo

getDistanceToCreature = getNpcDistanceTo

getNpcDistanceToCreature = getNpcDistanceTo

Editado por Lpz (veja o histórico de edições)

  • Respostas 22
  • Visualizações 5.6k
  • Created
  • Última resposta

Top Posters In This Topic

  • 2 weeks later...
Postado

que putaria é essa cara?agora fikei irrato que bosta seu ripperzinho vc q criou?AHAHAHAHAHAHAHAHAA

MENTIRA!

esse script eu usava em 2010 no meu otserver, tenho imagens no blog dele irei tentar procurar na net é q deletei o site! esse npc peguei no tibiaking e lembro que é igualzinho !

ta uma putaria isso podem procurar em npc lá na area de script do tibiaking q tem esse npc!!

aff

OLHA ESSES APRENDIZES Q VC COLOCAM, POXA AGORA FIKEI IRRATO QUE ISSO PORFAVOR REMOVEM O TOPICO E FALEI COM O COLEX ELE N AUTORIZOU A ELE POSTAR!

LINK ORIGINAL:

http://www.tibiaking.com/forum/topic/23955-npc-quiz-tutorial/

FOI VOCE QUE CRIOU? SEU RIPPERZINHO.. NAO SABE NEM RIPPAR!!

VC NAO MERECE APRENDIZ!

Editado por DevilMoon (veja o histórico de edições)

cachorro_magro.jpg      

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.6k

Informação Importante

Confirmação de Termo