Jump to content
Sign in to follow this  
V3ct0r

Система промокодов

Recommended Posts

[Скрипт] Система промокодов

 

Данный скрипт реализует простую систему промокодов. Игроки могут использовать промокоды для получения предметов. Промокоды вводятся в канал местного чата через косую черту, например:

/agjtjSfsaAS34

 

Промокод можно использовать только один раз. Для хранения промокодов используется текстовый файл.

 

 

Требования

 

Для работы скрипта требуется GameServer.exe с поддержкой функции HandleChat() - обработчик сообщений в местный чат.

 

 

Установка скрипта

 

1) Создайте файл с названием "pkodev.promo.lua" в следующей директории GameServer:

GameServer\resource\script\calculate\mods

2) Запишите в файл следующий код:

-- Print a log
print("Loading pkodev.promo.lua")

-- Check that HandleChat function exists
if (HandleChat == nil) then
	
	-- Write a log
	print("pkodev.promo.lua: Warning, the HandleChat() function is not exist!")
	
	-- Do not load the script
	return
	
end

-- Promocodes system
promo = promo or { }

-- Name of the file with promocodes
promo.file = "promocodes.dat"

-- List with promocodes
promo.list = {}

-- Save data to file
promo.save = function(path)
	
	-- Open the file
	local file, msg = io.open(path, "w")
	
	-- Check that file is open
	if (file == nil) then
		
		-- Write a log
		LG("pkodev.mod.promo", string.format("Can't save the list with promocodes to the file '%s': '%s'!", path, msg))
		return false
		
	end
	
	-- Write data
	for key, value in promo.list do
		
		-- Write a line
		local ret = file:write(string.format("{%s, %d, %d}\n", value.code, value.id, value.count))

		-- Check that line is written
		if (ret == false) then
		
			-- Write a log
			LG("pkodev.mod.promo", string.format("Can't write the data to the file '%s'!", path))
			return false
		
		end
	
	end
	
	-- Flush the data
	file:flush()
	
	-- Close the file
	file:close()
	
	-- Write a log
	LG("pkodev.mod.promo", string.format("The list with promocodes has been successfully saved to the file '%s'!", path))
	return true
	
end

-- Load data from file
promo.load = function(path)
	
	-- Remove old promocodes
	for k in pairs (promo.list) do
		promo.list[k] = nil
	end
	
	-- Open the file
	local file, msg = io.open(path, "r")
	
	-- Check that file is open
	if (file == nil) then
		
		-- Write a log
		LG("pkodev.mod.promo", string.format("Can't load the list with promocodes from the file '%s': '%s'!", path, msg))
		return false
		
	end

	-- Read file line by line
	for line in file:lines() do
			
		-- Extract data from the line
		local ret, _, code_, id_, count_ = string.find(line, "^{([A-Za-z0-9]+)%s*,%s*([0-9]+)%s*,%s*([0-9]+)}$")
		
		-- Check that string matches the pattern
		if (ret ~= nil) then
			
			-- Add data to the list
			table.insert(
				promo.list,
				{ 
					code  = code_,
					id    = id_,
					count = count_,
				}
			)
			
		end
		
	end
	
	-- Close the file
	file:close()
	
	-- Write a log
	LG("pkodev.mod.promo", string.format("%d promocodes have been succsessfully loaded from file '%s'!", table.getn(promo.list), path))
	return true

end

-- Handle chat function hook
promo.hadle_chat__original = HandleChat
HandleChat = function(role, msg)
	
	-- Check that message has the '/' symbol
	if ( string.sub(msg, 1, 1) == "/" ) then
	
		-- Get promocode
		local ret, _, code_ = string.find(msg, "^/([A-Za-z0-9]+)%s*$")
		
		-- Check that promocode is found
		if (ret ~= nil) then
			
			-- Search the promocode in the list
			for key, value in pairs(promo.list) do
				
				-- Compare promocodes
				if (value.code == code_) then
					
					-- Write a message
					BickerNotice(role, string.format("You entered the promocode '%s': %s x %d!",
						value.code, GetItemName(value.id), value.count) )
						
					
					-- Give an item
					GiveItem(role, 0, value.id, value.count, 0)
					
					-- Write a log
					LG("pkodev.mod.promo", string.format("Player '%s' entered a promocode '%s' and received '%s' x %d!",
						GetChaDefaultName(role), value.code, GetItemName(value.id), value.count) )
						
					-- Remove the promocode from the list
					promo.list[key] = nil
					
					-- Save the list to the file
					promo.save(promo.file)
					
					-- Synchronize the promocodes list
					local packet = GetPacket()
					WriteCmd(packet, 4015)
					WriteDword(packet, GetRoleID(role))
					WriteString(packet, string.format("promo.list[%d]=nil", key))
					SendPacket(role, packet)
					
					-- Do not call the original function HandleChat()
					return 0
					
				end
				
			end
			
		end
		
	end
	
	-- Call the original function HandleChat()
	return promo.hadle_chat__original(role, msg)
	
end

promo.load(promo.file)

3) Подключите файл "pkodev.promo.lua" в начале файла "SkillEffect.lua" (\GameServer\resource\script\calculate)  после включения файла "functions.lua":

dofile(GetResPath("script\\calculate\\mods\\pkodev.promo.lua"))

4) В корневой директории GameServer.exe создайте файл "promocodes.dat" и запишите в него список промокодов в следующем формате:

{<Промокод>, <ID предмета>, <Количество предметов>}

Например:

{agjtjSfsaAS34, 1849, 45}
{kgjKKKsnggklsaa, 885, 1}
{0004121aAf, 1848, 10}

 

 

Использование скрипта

 

1) Чтобы задействовать промокод, игрок должен ввести его в канал местного чата, например:

/agjtjSfsaAS34

В результате игрок получит Кекс х 45.

 

2) Логи использования промокодов можно найти в файле:

GameServer\LOG\log\pkodev.mod.promo.txt

 

 

Что можно улучшить

 

1) В качестве награды можно также выдавать золото, бафы и другие бонусы;

2) Список промокодов можно хранить в базе данных, например, с применением библиотеки LuaSQL;

3) Можно сделать промокоды многоразовыми, но один игрок может использовать промокод только раз.

 

 

  • Like 3

Share this post


Link to post
Share on other sites

Тут такая штука я могу промо использовать не один раз а несколько раз при заходе на другую карту которая на другом гс работает😕

  • Thanks 1

Share this post


Link to post
Share on other sites

Привет, @small666!

 

Обновил скрипт системы: добавил синхронизацию списка промокодов между всеми GameServer.exe. Теперь должно работать как было задумано.

  • Thanks 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...