### Advanced Seasonal Leaderboard Management - Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Covers the setup and management of advanced, multi-board seasonal leaderboards. This includes configuring boards, submitting scores for specific seasons, retrieving seasonal rankings, and handling season-end rewards and resets. It utilizes `RankingBoardConfig`, `_RankingConfigDataSetLogic`, and `_RankingDataStorageLogic`. ```lua -- Configure ranking board local boardConfig = RankingBoardConfig.new() boardConfig.BoardId = 1 boardConfig.BoardName = "PvP Arena Rankings" boardConfig.SeasonDuration = 2592000 -- 30 days in seconds boardConfig.RewardTable = { {Rank = 1, ItemId = 9001, Count = 100}, {Rank = 2, ItemId = 9001, Count = 50}, {Rank = 3, ItemId = 9001, Count = 25} } _RankingConfigDataSetLogic:RegisterBoard(boardConfig) -- Submit score to specific board and season local userId = "player123" local boardId = 1 local seasonId = _RankingDataStorageLogic:GetCurrentSeasonId(boardId) local score = 2500 _RankingDataStorageLogic:SubmitScore(userId, boardId, seasonId, score) -- Get rankings for specific board and season local rankings = _RankingDataStorageLogic:GetBoardRankings(boardId, seasonId, 100) for rank, entry in ipairs(rankings) do print(rank .. ". " .. entry.UserId .. " - " .. entry.Score .. " points") end -- Get player's rank in specific board local playerRank = _RankingDataStorageLogic:GetPlayerRankInBoard(userId, boardId, seasonId) if playerRank then print("Your arena rank: #" .. playerRank.Rank) print("Your points: " .. playerRank.Score) end -- Check if season has ended and distribute rewards if _RankingDataStorageLogic:IsSeasonEnded(boardId) then _RankingDataStorageLogic:DistributeSeasonRewards(boardId) _RankingDataStorageLogic:StartNewSeason(boardId) end -- Get multiple board rankings local boardIds = {1, 2, 3} for _, bId in ipairs(boardIds) do local boardRankings = _RankingDataStorageLogic:GetBoardRankings(bId, seasonId, 10) print("Board " .. bId .. " top 10:") -- Display rankings end ``` -------------------------------- ### Manage Dialogues in Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Provides functions to manage a dialogue system, including starting, showing, and ending dialogues, as well as retrieving dialogue data. It supports character-by-character text display and branching conversations. Dependencies include _DialogLogic and _DialogDataLogic. ```lua -- Start a dialogue sequence _DialogLogic:StartDialog("welcome_dialog") -- Show specific script by ID _DialogLogic:ShowScript("script_001") -- End/close dialogue _DialogLogic:End() -- Get dialogue data local scriptData = _DialogDataLogic:GetScriptData("script_001") print("Dialogue text: " .. scriptData.Text) print("Speaker: " .. scriptData.Speaker) -- Get first script in a dialogue sequence local firstScript = _DialogDataLogic:GetFirstScriptData("welcome_dialog") -- Dialogue data structure example (defined in DataSet) -- DialogData: -- Id: "welcome_dialog" -- Scripts: [ -- { ScriptId: "script_001", Text: "Welcome to the village!", Speaker: "Elder", NextScript: "script_002" }, -- { ScriptId: "script_002", Text: "How can I help you?", Speaker: "Elder", Selections: [...] } -- ] ``` -------------------------------- ### Recycle Scroll View - Optimized UI Scrolling - Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Provides examples for using the Recycle Scroll View component for optimized UI scrolling. It demonstrates coordinate conversion and touch input validation to prevent UI flickering during fast scrolling. ```lua -- Convert touch point coordinates for scroll view local touchPoint = Vector2.new(100, 200) local convertedPoint = _ScrollLogic:GetTouchPoint(touchPoint) -- Validate touch input local touchId = 1 if _ScrollLogic:IsValidTouch(touchId) then -- Process touch event print("Valid touch detected") end -- Typical usage: Attach to GridViewComponent or custom scroll implementation -- The package handles recycling cells automatically when scrolling -- Prevents flickering by reusing UI elements instead of creating/destroying them ``` -------------------------------- ### Get Game Event Data and Status - Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Retrieves event data by ID, lists all active or visible events, and filters events by type. It also checks if a specific event is active and retrieves its current status. This function relies on the `_GameEventLogic` global object and related enumerations like `GameEventStatusEnum` and `GameEventTypeEnum`. ```lua -- Get event data by ID local eventId = 1001 local eventStruct = _GameEventLogic:GetStruct(eventId) if eventStruct then print("Event: " .. eventStruct.DefId) print("Status: " .. eventStruct.Status) print("Next transition: " .. eventStruct.NextTransitionTime) end -- Get all currently active events local activeEvents = _GameEventLogic:GetActiveStructList() for _, event in pairs(activeEvents) do print("Active event: " .. event.DefId) -- Apply event bonuses or modifications if event.DefId == 5001 then -- Double XP event playerXpMultiplier = 2.0 end end -- Get visible events (Preview, Active, or Grace state) local visibleEvents = _GameEventLogic:GetVisibleStructList() for _, event in pairs(visibleEvents) do if event.Status == GameEventStatusEnum.Preview then print("Coming soon: " .. event.DefId) elseif event.Status == GameEventStatusEnum.Active then print("Active now: " .. event.DefId) elseif event.Status == GameEventStatusEnum.Grace then print("Ending soon: " .. event.DefId) end end -- Filter events by type local eventEnum = GameEventTypeEnum.ExpBoost local expEvents = _GameEventLogic:GetStructListByEnum(eventEnum) -- Check if specific event is active if _GameEventLogic:IsActiveState(eventId) then print("Event " .. eventId .. " is currently active") -- Apply event logic end -- Get event status local status = _GameEventLogic:GetStatus(eventId) if status == GameEventStatusEnum.Active then print("Event is active") elseif status == GameEventStatusEnum.Preview then print("Event coming soon") elseif status == GameEventStatusEnum.Grace then print("Event ending soon - grace period") elseif status == GameEventStatusEnum.Close then print("Event has ended") elseif status == GameEventStatusEnum.Awaiting then print("Event not yet started") end ``` -------------------------------- ### Execute Commands in Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Demonstrates how to execute commands from strings, specifically targeting client or server environments. It also shows how to register custom server-side commands with parameter parsing and admin checks. Dependencies include _CommandLogic, _AdminLogic, and _ItemFactoryLogic. ```lua -- Execute a command from string _CommandLogic:ExecuteCommandBySpace("teleport 100 200") -- Execute on client side _CommandLogic:TryExecuteInClient("setSpeed 2.0") -- Execute on server side (admin only) _CommandLogic:TryExecuteInServer("giveItem 1001 100") -- Register custom commands in ServerCommandLogic.mlua function ServerCommandLogic:GetAllActions() return { giveItem = function(params) local userId = params.userId local itemId = tonumber(params[1]) local count = tonumber(params[2]) if _AdminLogic:IsAdmin(userId) then -- Grant items to player _ItemFactoryLogic:TryAddMultipleItems(userId, {{ItemId = itemId, Count = count}}, {}) print("Granted " .. count .. " of item " .. itemId) else print("Admin permission required") end end, teleport = function(params) local x = tonumber(params[1]) local y = tonumber(params[2]) -- Teleport logic end } end ``` -------------------------------- ### Shop System - In-Game Currency Store - Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Shows how to use the in-game shop system for purchases with custom currencies. Covers checking purchase limits, attempting purchases, and handling purchase completion events. ```lua -- Get player's Shop component local playerShop = self.Entity:GetComponent(PlayerShop) -- Purchase with in-game currency local shopProductId = "weapon_sword_001" if playerShop:CanPurchaseMore(shopProductId) then local success = playerShop:TryPurchaseItem(shopProductId) if success then print("Item purchased successfully") else print("Purchase failed - insufficient currency or other error") end end -- Check purchase count local count = playerShop:GetPurchaseCount(shopProductId) print("Purchased " .. count .. " times") -- Listen for purchase completed event @EventSender() function OnPurchaseCompleted(event: PurchaseCompletedEvent) print("Product purchased: " .. event.ProductId) print("Quantity: " .. event.Quantity) print("Total cost: " .. event.TotalCost) end ``` -------------------------------- ### Key Binding System: Input Configuration and Management (Lua) Source: https://context7.com/msw-git/mswpackages/llms.txt Initializes and manages player input key mappings, including changing bindings, resetting to defaults, and validating keys. It utilizes _InputLogic for handling input configurations. Outputs include success/failure messages and assigned slot/key information. ```lua -- Initialize key mappings with default configuration local inputConfig = PlayerGameOptionInputPCStruct.new() inputConfig.KeyMappings = { [InputSlotEnum.Jump] = KeyCode.Space, [InputSlotEnum.Attack] = KeyCode.Z, [InputSlotEnum.Skill1] = KeyCode.A, [InputSlotEnum.Skill2] = KeyCode.S } _InputLogic:InitKeyMapping(inputConfig) -- Change a key binding local slotEnum = InputSlotEnum.Jump local newKey = KeyCode.W if _InputLogic:TryChangeKeyMap(slotEnum, newKey) then print("Key binding changed successfully") else print("Failed to change key binding - invalid key or conflict") end -- Reset to default key mappings _InputLogic:ResetKeyMap() -- Get slot assigned to a key local key = KeyCode.Space local slot = _InputLogic:GetSlotEnumByKey(key) if slot then print("Key is assigned to slot: " .. slot) end -- Get key assigned to a slot local assignedKey = _InputLogic:GetKeyBySlotEnum(InputSlotEnum.Jump) print("Jump is assigned to: " .. _InputLogic:GetSymbol(assignedKey)) -- Validate keyboard key if _InputLogic:IsValidKeyboardKey(KeyCode.Escape) then print("Escape key is valid for binding") end -- Get display symbol for key local symbol = _InputLogic:GetSymbol(KeyCode.LeftShift) print("Key symbol: " .. symbol) -- Output: Key symbol: LShift ``` -------------------------------- ### Global Configuration API (MSW Lua) Source: https://context7.com/msw-git/mswpackages/llms.txt Provides a system for storing and retrieving game-wide settings. Supports saving configuration values with options for client synchronization and retrieving values by ID. Admin functionality is required for saving configurations. ```lua local configStruct = GlobalConfigDataStruct.new() configStruct.Id = 100 configStruct.Name = "MaxPlayerLevel" configStruct.DefaultValue = "200" configStruct.ClientSync = true -- Sync to all clients _GlobalConfigLogic:RequestSaveGlobalConfigValue(configStruct) -- Retrieve configuration value local maxLevel = _GlobalConfigLogic:GetValue(100) print("Max player level: " .. maxLevel) -- Output: Max player level: 200 -- Load specific config from database _GlobalConfigLogic:RequestLoadGlobalConfigValue(100) ``` -------------------------------- ### World Shop - Premium Currency Purchases - Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Illustrates how to integrate with the WorldShop service for premium currency transactions. Includes checking purchase limits, attempting purchases, and setting up custom callbacks for purchase events. ```lua -- Get player's WorldShop component local playerWorldShop = self.Entity:GetComponent(PlayerWorldShop) -- Attempt to purchase an item local productId = "premium_package_001" -- Check if player can purchase if playerWorldShop:CanPurchaseMore(productId) then playerWorldShop:TryPurchaseItem(productId) else print("Purchase limit reached for this product") end -- Get purchase count for a product local purchaseCount = playerWorldShop:GetPurchaseCount(productId) print("Player has purchased this item " .. purchaseCount .. " times") -- Set up custom purchase callbacks playerWorldShop.onPurchase = function(self, productId, userInventoryItem) print("Processing purchase for: " .. productId) return true -- Allow purchase end playerWorldShop.onPurchaseSuccess = function(self, productId, userInventoryItem, addItemResultStruct) print("Purchase successful!") -- Grant items or perform post-purchase logic end playerWorldShop.onPurchaseFailed = function(self, productId, userInventoryItem, errorCode) print("Purchase failed with error: " .. errorCode) end ``` -------------------------------- ### Lua: Implement Probabilistic Item Drops with _DropLogic Source: https://context7.com/msw-git/mswpackages/llms.txt This Lua code demonstrates how to use the _DropLogic API for various item drop scenarios. It covers single drops, multiple independent rolls, random selections from groups, and simulating drops for testing. It also shows how to incorporate bonus rate events into drop calculations. The system relies on a defined data structure for drop tables. ```lua -- Single drop (pick one item from weighted group) local dropId = 1001 -- Drop table ID local rollCount = 1 -- Number of times to roll local rateMul = 1.0 -- Rate multiplier (1.0 = 100%, 2.0 = 200% drop rate) local countMul = 1 -- Quantity multiplier local results = {} _DropLogic:DropSingle(dropId, rollCount, rateMul, countMul, results) for _, result in pairs(results) do print("Dropped: Item " .. result.ItemId .. " x" .. result.Count) end -- Output: Dropped: Item 2001 x 5 -- Multi drop (multiple independent rolls) local multiDropId = 2001 local multiResults = {} _DropLogic:DropMulti(multiDropId, 3, 1.5, 1, multiResults) -- Performs 3 independent rolls with 150% drop rate for _, result in pairs(multiResults) do print("Dropped: Item " .. result.ItemId .. " x" .. result.Count) end -- Output: -- Dropped: Item 3001 x 1 -- Dropped: Item 3005 x 2 -- Dropped: Item 3010 x 1 -- Random drop from single group local dropSingleGroupId = 5001 local randomResults = {} _DropLogic:RandomDropSingle(dropSingleGroupId, 1, randomResults) -- Select specific item from drop group by index local index = 2 -- Select the 3rd item (0-indexed) local openCount = 1 local selectResults = {} _DropLogic:SelectDropSingle(dropSingleGroupId, index, openCount, selectResults) -- Simulate drops for testing (logs to console) _DropLogic:SimulateDropSingle(dropId, 100, 1.0, 1) -- Runs 100 simulations and logs statistical results _DropLogic:SimulateDropMulti(multiDropId, 100, 1.0, 1) -- Example drop table data structure (defined in DataSet) -- DropSingleData: -- Id: 1001 -- Drops: [ -- {ItemId: 2001, Weight: 50, MinCount: 1, MaxCount: 5}, -- {ItemId: 2002, Weight: 30, MinCount: 1, MaxCount: 3}, -- {ItemId: 2003, Weight: 20, MinCount: 1, MaxCount: 1} -- ] -- -- Total weight: 100 -- Item 2001: 50% chance -- Item 2002: 30% chance -- Item 2003: 20% chance -- Using drops with bonus rate events local bonusRate = 2.0 -- 200% drop rate event local bonusResults = {} _DropLogic:DropSingle(dropId, 1, bonusRate, 1, bonusResults) ``` -------------------------------- ### Collections Library: Stack, Queue, PriorityQueue, Set, LinkedList Data Structures (Lua) Source: https://context7.com/msw-git/mswpackages/llms.txt Demonstrates the usage of various data structures provided by the Collections Library. Includes Stack (LIFO), Queue (FIFO), PriorityQueue (min-heap), Set (unique elements), and LinkedList (doubly-linked list) with common operations like add, remove, peek, dequeue, union, intersection, and subset checks. ```lua -- Stack (LIFO - Last In, First Out) local stack = _CollectionFactoryLogic:GetStack() stack:Push(10) stack:Push(20) stack:Push(30) print(stack:Peek()) -- Output: 30 (top element) print(stack:Pop()) -- Output: 30 (removes and returns) print(stack:Count()) -- Output: 2 local stackArray = stack:ToArray() -- stackArray = {10, 20} stack:Clear() print(stack:IsEmpty()) -- Output: true -- Queue (FIFO - First In, First Out) local queue = _CollectionFactoryLogic:GetQueue() queue:Enqueue("first") queue:Enqueue("second") queue:Enqueue("third") print(queue:Peek()) -- Output: "first" print(queue:Dequeue()) -- Output: "first" (removes and returns) print(queue:Count()) -- Output: 2 local queueArray = queue:ToArray() -- queueArray = {"second", "third"} -- Priority Queue (Min-Heap - lower priority number = higher priority) local pq = _CollectionFactoryLogic:GetPriorityQueue() pq:Enqueue("low priority task", 10) pq:Enqueue("critical task", 1) pq:Enqueue("medium priority task", 5) print(pq:Peek()) -- Output: "critical task" print(pq:Dequeue()) -- Output: "critical task" (priority 1) print(pq:Dequeue()) -- Output: "medium priority task" (priority 5) print(pq:Dequeue()) -- Output: "low priority task" (priority 10) -- Set (unique elements, no duplicates) local set1 = _CollectionFactoryLogic:GetSet() set1:Add(1) set1:Add(2) set1:Add(3) set1:Add(2) -- Duplicate, won't be added print(set1:Contains(2)) -- Output: true print(set1:Count()) -- Output: 3 set1:Remove(2) print(set1:Contains(2)) -- Output: false -- Set operations local set2 = _CollectionFactoryLogic:GetSet() set2:Add(3) set2:Add(4) set2:Add(5) local unionSet = set1:Union(set2) -- unionSet contains: {1, 3, 4, 5} local intersectSet = set1:Intersect(set2) -- intersectSet contains: {3} local subtractSet = set1:Subtract(set2) -- subtractSet contains: {1} print(set1:IsSubset(set2)) -- Output: false print(set1:IsEqual(set2)) -- Output: false -- LinkedList (doubly-linked list) local list = _CollectionFactoryLogic:GetLinkedList() list:AddLast("a") list:AddLast("b") list:AddLast("c") list:AddFirst("start") -- List: start -> a -> b -> c local nodeB = list:Find("b") list:AddAfter(nodeB, "middle") -- List: start -> a -> b -> middle -> c list:AddBefore(nodeB, "before") -- List: start -> a -> before -> b -> middle -> c print(list:GetFirst()) -- Output: "start" print(list:GetLast()) -- Output: "c" local firstNode = list:GetFirstNode() print(firstNode.Value) -- Output: "start" print(firstNode.Next.Value) -- Output: "a" print(list:RemoveFirst()) -- Output: "start" print(list:RemoveLast()) -- Output: "c" -- List: a -> before -> b -> middle list:Remove("before") -- List: a -> b -> middle print(list:Contains("b")) -- Output: true print(list:Count()) -- Output: 3 local array = list:ToArray() -- array = {"a", "b", "middle"} local nodeArray = list:ToNodeArray() -- Array of LinkedListNode objects list:Clear() print(list:IsEmpty()) -- Output: true ``` -------------------------------- ### Manage Player Data and Bans in Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Enables comprehensive player management, including banning, unbanning, and kicking players with specified reasons and durations. It also covers accessing and saving player data components, including basic information like name and level. Dependencies include _PlayerBanLogic, playerEntity, PlayerData, and _DateTimeLogic. ```lua -- Ban a player local userId = "player123" local reason = "Violating terms of service" local endTime = _DateTimeLogic:GetTimeElapsed() + 86400 * 7 -- 7 days _PlayerBanLogic:RequestBanUser(userId, reason, endTime) -- Unban a player _PlayerBanLogic:RequestUnbanUser(userId) -- Kick player from game _PlayerBanLogic:RequestKickUser(userId) -- Access player data component local playerData = playerEntity:GetComponent(PlayerData) -- Get player basic info local basicInfo = playerData.PlayerBasicInfo print("Player name: " .. basicInfo.Name) print("Player level: " .. basicInfo.Level) -- Save player data to database playerData:SaveToDB() -- Load player data callback function PlayerData:OnLoadedDataFromDB(loadedData) if loadedData then self.PlayerBasicInfo = loadedData.PlayerBasicInfo print("Player data loaded successfully") else -- Initialize new player data self.PlayerBasicInfo = PlayerBasicInfo.new() end end ``` -------------------------------- ### Mail System API (MSW Lua) Source: https://context7.com/msw-git/mswpackages/llms.txt Implements an in-game mail system for sending global broadcasts or individual player messages, including item attachments and expiration dates. Supports sending, fetching mail lists, and revoking mail. ```lua -- Send global mail to all players with item attachments local items = { {ItemId = 1001, Count = 100}, -- 100 gold {ItemId = 2005, Count = 1} -- Special reward } _GMMailLogic:RequestSaveGlobalMail( "Daily Login Reward", "Thank you for playing! Here's your daily reward.", "Game Master", 7, -- Retention days _DateTimeLogic:GetTimeElapsed(), _DateTimeLogic:GetTimeElapsed() + 86400, -- Available for 24 hours items ) -- Send mail to specific player local userId = "player123" _GMMailLogic:RequestSavePlayerMail( userId, "Special Achievement Reward", "Congratulations on reaching level 50!", "Achievement System", 30, _DateTimeLogic:GetTimeElapsed(), _DateTimeLogic:GetTimeElapsed() + 604800, -- Available for 1 week {{ItemId = 3001, Count = 1}} ) -- Fetch player's mail list _GMMailLogic:RequestGetPlayerMails(userId) -- Revoke/cancel a mail local mailUUID = "550e8400-e29b-41d4-a716-446655440000" _GMMailLogic:RequestRevokeMail(mailUUID) ``` -------------------------------- ### Basic Leaderboard Operations - Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Demonstrates submitting scores, retrieving top rankings, and checking a player's rank using the basic leaderboard system. It interacts with `_RankingDataStorageLogic` and `_RankingDataCacheLogic` for score management and cache updates. ```lua -- Submit score to ranking (server-side) local userId = "player123" local score = 15000 _RankingDataStorageLogic:SubmitScore(userId, score) -- Get top N players local topCount = 10 local topRankings = _RankingDataStorageLogic:GetTopRankings(topCount) for rank, entry in ipairs(topRankings) do print(rank .. ". " .. entry.UserId .. " - Score: " .. entry.Score) end -- Output: -- 1. player456 - Score: 20000 -- 2. player123 - Score: 15000 -- 3. player789 - Score: 12000 -- Get player's current rank local playerRank = _RankingDataStorageLogic:GetPlayerRank(userId) if playerRank then print("Your rank: #" .. playerRank.Rank) print("Your score: " .. playerRank.Score) end -- Refresh ranking cache (periodic update) _RankingDataCacheLogic:RefreshCache() ``` -------------------------------- ### Resource Management (Currency & Rechargeable) - Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Illustrates the creation and manipulation of game resources, including standard currencies like gold and rechargeable resources such as stamina. It details adding/subtracting values, checking resource availability, initializing rechargeable properties, and updating resource states over time using `_ResourceFactoryLogic`, `ResourceTypeEnum`, and `_DateTimeLogic`. ```lua -- Create standard resource (e.g., gold) local goldResource = _ResourceFactoryLogic:CreateResource(ResourceTypeEnum.Gold, playerEntity) goldResource:Setup(ResourceTypeEnum.Gold, 1000, playerEntity) -- Add/subtract gold goldResource:Add(500) print("Gold: " .. goldResource:GetValue()) -- Output: Gold: 1500 goldResource:Subtract(200) print("Gold: " .. goldResource:GetValue()) -- Output: Gold: 1300 -- Check if enough resources if goldResource:HasEnough(100) then print("Player has enough gold") end -- Create rechargeable resource (e.g., stamina) local staminaResource = _ResourceFactoryLogic:CreateResource(ResourceTypeEnum.Stamina, playerEntity) local maxStamina = 100 local rechargeValue = 1 -- Recharge 1 stamina per interval local rechargeInterval = 300 -- Every 5 minutes (300 seconds) local currentTime = _DateTimeLogic:GetTimeElapsed() staminaResource:InitializeRechargeableResource(maxStamina, rechargeValue, rechargeInterval, currentTime) -- Use stamina staminaResource:Subtract(10) -- Update rechargeable resource (call periodically) local newTime = _DateTimeLogic:GetTimeElapsed() staminaResource:Update(newTime) print("Current stamina: " .. staminaResource:GetValue()) print("Max stamina: " .. staminaResource:GetMaxValue()) -- Check time until next recharge local timeRemaining = staminaResource:GetTimeUntilNextRecharge(newTime) print("Next recharge in: " .. timeRemaining .. " seconds") -- Set max value staminaResource:SetMaxValue(150) ``` -------------------------------- ### Inventory Management: Item Operations and Factory Additions (Lua) Source: https://context7.com/msw-git/mswpackages/llms.txt Manages player inventory including equipping, unequipping, using, discarding, locking items, checking counts, and adding items via a factory. It interacts with PlayerInventory and ItemFactoryLogic components. Outputs include success/failure messages and item counts. ```lua -- Get player's inventory component local playerInventory = self.Entity:GetComponent(PlayerInventory) -- Equip gear local gearGUID = "550e8400-e29b-41d4-a716-446655440000" local jobType = 1 -- Warrior playerInventory:RequestAttachNormalGear(jobType, gearGUID) -- Unequip gear local gearCategory = GearCategoryEnum.Weapon playerInventory:RequestDetachNormalGear(jobType, gearCategory) -- Use consumable item local itemGUID = "550e8400-e29b-41d4-a716-446655440001" local useCount = 1 playerInventory:RequestUseItem(itemGUID, useCount) -- Discard items playerInventory:RequestDiscardItem(itemGUID, 5) -- Lock/unlock item playerInventory:RequestLockItem(itemGUID, true) -- Lock playerInventory:RequestLockItem(itemGUID, false) -- Unlock -- Check item count local itemId = 1001 -- Potion local currentTime = _DateTimeLogic:GetTimeElapsed() local count = playerInventory:GetItemCount(itemId, currentTime) print("Player has " .. count .. " potions") -- Check available inventory space local itemCategory = ItemCategoryEnum.Usable local hasSpace = playerInventory:HasRemainSlotCount(itemCategory) if hasSpace then print("Inventory has space for more items") end -- Add items using factory (server-side) local userId = "player123" local items = { {ItemId = 1001, Count = 10}, -- 10 potions {ItemId = 2001, Count = 1, EndDateSeconds = _DateTimeLogic:GetTimeElapsed() + 86400} -- 1 day expiration } local resultStruct = AddMultipleItemResultStruct.new() local success = _ItemFactoryLogic:TryAddMultipleItems(userId, items, resultStruct) if success then print("Items added successfully") for _, item in pairs(resultStruct.AddedItems) do print("Added: " .. item.ItemId .. " x" .. item.Count) end else print("Failed to add items: " .. resultStruct.FailReason) end -- Delete items local deleteParam = DeleteItemParam.new() deleteParam.ItemId = 1001 deleteParam.Count = 5 local deleteResult = DeleteItemResultStruct.new() local deleteSuccess = _ItemFactoryLogic:TryDeleteItem(userId, deleteParam, deleteResult) ``` -------------------------------- ### UI Component Package: Reusable UI Elements (Lua) Source: https://context7.com/msw-git/mswpackages/llms.txt Illustrates the usage of reusable UI components from the MSW UI Component Package within a Lua scripting environment. This package provides prefabs and scripts for common interface elements like buttons, panels, and progress bars, intended for use in the MSW editor. ```lua -- This package primarily consists of UI prefab assets and component scripts -- that can be imported and used in the MSW editor. -- -- Usage: Import the .modpackage file and access UI components through -- the MSW editor's asset browser. Components can be dragged into scenes -- and customized through the property inspector. -- -- Common UI components included: -- - Button variants with different styles -- - Panel layouts and containers -- - Dialog boxes and modal windows -- - Progress bars and sliders -- - List and grid view templates -- - Icon and image containers -- - Text labels with formatting -- -- Example of using a UI component in code: local buttonComponent = uiElement:GetComponent(UIButton) buttonComponent.OnClick = function() print("Button clicked!") end local progressBar = uiElement:GetComponent(UIProgressBar) progressBar:SetValue(0.75) -- 75% filled progressBar:SetColor(Color.green) local listView = uiElement:GetComponent(UIListView) listView:SetData(itemList) listView:Refresh() ``` -------------------------------- ### MapleStory Toast: Notification Popup System (Lua) Source: https://context7.com/msw-git/mswpackages/llms.txt Implements a toast notification system that displays messages with optional parameter interpolation, animations, and decorations. It uses the _MaplestoryToast global object for showing, hiding, and updating notifications. Notifications can be customized with colors, durations, and visual elements. ```lua -- Show basic toast notification _MaplestoryToast:Show( "You received gold!", {}, Color.yellow, 3, -- Duration in seconds {}, true -- Use fading animation ) -- Show toast with parameter interpolation local goldAmount = "1000" _MaplestoryToast:Show( "You received ## gold!", {goldAmount}, Color.yellow, 3, {}, true ) -- Output: "You received 1000 gold!" -- Show toast with multiple parameters _MaplestoryToast:Show( "Player ## defeated ## monsters!", {"Alice", "50"}, Color.white, 5, {}, true ) -- Show toast with decoration images local decorations = { Left = "UI/Toast/LeftDecoration", Middle = "UI/Toast/MiddleDecoration", Right = "UI/Toast/RightDecoration", Portrait = "UI/Toast/PlayerPortrait" } _MaplestoryToast:Show( "Achievement Unlocked: ##", {"Dragon Slayer"}, Color.gold, 4, decorations, true ) -- Update displayed arguments dynamically local newArgs = {"2000"} _MaplestoryToast:ChangeArgs(newArgs) -- Hide toast manually _MaplestoryToast:Hide() ``` -------------------------------- ### Quest and Achievement System - Lua Source: https://context7.com/msw-git/mswpackages/llms.txt Demonstrates how to manage quests and achievements using the PlayerQuest and PlayerAchievement components. It covers accepting, completing, abandoning, and tracking progress for quests, as well as accepting achievements. ```lua -- Get player's quest component local playerQuest = self.Entity:GetComponent(PlayerQuest) -- Accept multiple quests local questIds = {1001, 1002, 1003} playerQuest:RequestAcceptQuests(questIds) -- Process action events to track progress local actionEvent = ActionEvent.new() actionEvent.ActionType = QuestActionTypeEnum.KillMonster actionEvent.TargetId = 5001 -- Monster ID actionEvent.Value = 1 -- Killed 1 monster playerQuest:OnActionEvent(actionEvent) -- Complete quests local completedQuestIds = {1001} playerQuest:RequestCompleteQuests(completedQuestIds) -- Abandon quests playerQuest:RequestAbandonQuests({1002}) -- Check quest state local questData = playerQuest:GetQuestData(1001) if questData.State == QuestStateEnum.Completed then print("Quest completed!") -- Award rewards end -- Achievement example (similar API) local playerAchievement = self.Entity:GetComponent(PlayerAchievement) playerAchievement:RequestAcceptAchievements({2001, 2002}) playerAchievement:OnActionEvent(actionEvent) ``` -------------------------------- ### GM Message System API (MSW Lua) Source: https://context7.com/msw-git/mswpackages/llms.txt Manages in-game notifications and scheduled messages for players. Allows adding, modifying, and removing messages with specific timings and display durations. Includes functionality to open an admin UI for message management via hotkey. ```lua local messageStruct = GMMessageStruct.new() messageStruct.Id = 1 messageStruct.Message = "Welcome to the game! Double XP event active!" messageStruct.StartTime = _DateTimeLogic:GetTimeElapsed() + 60 -- Start in 60 seconds messageStruct.EndTime = _DateTimeLogic:GetTimeElapsed() + 3600 -- End in 1 hour messageStruct.ShowSeconds = 5 -- Display for 5 seconds messageStruct.ShowIntervalSeconds = 300 -- Show every 5 minutes _GMMessageLogic:RequestAddOrModifyMessage(messageStruct) -- Remove a message by ID _GMMessageLogic:RequestRemoveMessage(1) -- Open admin tool for managing messages (F11 hotkey) _GMMessageLogic:RequestOpenUITool() ``` -------------------------------- ### Game Event System - Scheduled Events with Lifecycle Source: https://context7.com/msw-git/mswpackages/llms.txt This section details the functions available for interacting with the game event scheduling system. It includes methods for retrieving events by ID, fetching lists of active or visible events, filtering events by type, and checking event statuses. ```APIDOC ## Game Event Logic Functions ### GetStruct Retrieves the data structure for a specific game event by its ID. * **Method:** `_GameEventLogic:GetStruct(eventId)` * **Parameters:** * `eventId` (number) - Required - The unique identifier of the event. * **Returns:** * `eventStruct` (table) - The event data structure, or nil if not found. * `DefId` (number) - The definition ID of the event. * `Status` (string) - The current status of the event (e.g., Preview, Active, Grace, Close). * `NextTransitionTime` (number) - Unix timestamp for the next state transition. ### GetActiveStructList Retrieves a list of all currently active game events. * **Method:** `_GameEventLogic:GetActiveStructList()` * **Returns:** * `activeEvents` (table) - A list of active event data structures. * Each element is an event structure similar to `GetStruct`'s return. ### GetVisibleStructList Retrieves a list of events that are currently visible (Preview, Active, or Grace state). * **Method:** `_GameEventLogic:GetVisibleStructList()` * **Returns:** * `visibleEvents` (table) - A list of visible event data structures. * Each element is an event structure similar to `GetStruct`'s return. ### GetStructListByEnum Retrieves a list of events filtered by a specific event type. * **Method:** `_GameEventLogic:GetStructListByEnum(eventEnum)` * **Parameters:** * `eventEnum` (enum) - Required - The enum representing the event type to filter by (e.g., `GameEventTypeEnum.ExpBoost`). * **Returns:** * `expEvents` (table) - A list of event data structures matching the specified type. ### IsActiveState Checks if a specific event is currently in the 'Active' state. * **Method:** `_GameEventLogic:IsActiveState(eventId)` * **Parameters:** * `eventId` (number) - Required - The unique identifier of the event. * **Returns:** * `boolean` - True if the event is active, false otherwise. ### GetStatus Retrieves the current status of a specific game event. * **Method:** `_GameEventLogic:GetStatus(eventId)` * **Parameters:** * `eventId` (number) - Required - The unique identifier of the event. * **Returns:** * `status` (enum) - The current status of the event (e.g., `GameEventStatusEnum.Active`, `GameEventStatusEnum.Preview`). ## Event State Transitions ### OnGameEventStateChanged Event Listener This function is called when the status of a game event changes. It allows for reacting to events starting or ending. * **Trigger:** Annotated with `@EventSender()` * **Event Data:** `event: GameEventStateChangedEvent` * `EventId` (number) - The ID of the event that changed. * `NewStatus` (enum) - The new status of the event (e.g., `GameEventStatusEnum.Active`). ### Example Usage: ```lua @EventSender() function OnGameEventStateChanged(event: GameEventStateChangedEvent) print("Event " .. event.EventId .. " changed to status: " .. event.NewStatus) if event.NewStatus == GameEventStatusEnum.Active then -- Event just started - activate bonuses ActivateEventBonuses(event.EventId) elseif event.NewStatus == GameEventStatusEnum.Close then -- Event ended - deactivate bonuses DeactivateEventBonuses(event.EventId) end end ``` ## Game Event Schedule Data Structure Example This is an example of the data structure for a game event schedule, typically defined in `DataSet`. ```lua -- GameEventScheduleData: -- Id: 1001 -- DefId: 5001 (Event definition ID) -- Disable: false -- PreviewStartTime: 1638316800 (Unix timestamp) -- PreviewEndTime: 1638320400 -- ActiveStartTime: 1638320400 -- ActiveEndTime: 1638406800 -- GraceStartTime: 1638406800 -- GraceEndTime: 1638410400 -- CloseTime: 1638410400 ``` ```