This guide is adapted from our Reconstructing Fun video series, where we explore how to build popular game mechanics using Nakama and Hiro. You can watch the full video below and follow our channel on YouTube for the latest updates.
In the vibrant landscape of gaming, achievements serve as milestones marking the player’s journey, offering both satisfaction and tangible rewards. They’re the unsung heroes of player retention, providing goals that keep the experience fresh and engaging.
In this guide we’ll explore how you can quickly integrate quests and achievements using Nakama and Hiro to produce gameplay experiences similar to that of Blizzard’s massively successful Hearthstone quests system.
Once that’s out of the way, you can familiarize yourself with the full project code we’ll be using in this guide by cloning the Quests repository from GitHub.
Next we define our InitModule function, which is called when the server starts up. Here we’ll initialize the Hiro systems - Achievements, Economy and Inventory - we’ll be using, and register the RPC functions we’ll be implementing.
funcInitModule(ctxcontext.Context,loggerruntime.Logger,db*sql.DB,nkruntime.NakamaModule,initializerruntime.Initializer)error{props,ok:=ctx.Value(runtime.RUNTIME_CTX_ENV).(map[string]string)if!ok{returnerrors.New("invalid context runtime env")}env,ok:=props["ENV"]if!ok||env==""{returnerrors.New("'ENV' key missing or invalid in env")}hiroLicense,ok:=props["HIRO_LICENSE"]if!ok||hiroLicense==""{returnerrors.New("'HIRO_LICENSE' key missing or invalid in env")}binPath:="hiro.bin"systems,err:=hiro.Init(ctx,logger,nk,initializer,binPath,hiroLicense,hiro.WithAchievementsSystem(fmt.Sprintf("base-achievements-%s.json",env),true),hiro.WithEconomySystem(fmt.Sprintf("base-economy-%s.json",env),true),hiro.WithInventorySystem(fmt.Sprintf("base-inventory-%s.json",env),true))iferr!=nil{returnerr}returnnil}
The Hiro Inventory system enables you to define and manage the items that can be collected and used by players in your game. In this example, we’ll use the Inventory system to define the various rewards that players can acquire when they complete achievements, setting attributes like their name, description, maximum count, stackability, and rarity.
The Hiro Economy system enables you to define and manage the currencies that players can earn and spend in your game, and also define the currencies and amounts that each player begins the game with.
Here we define the currencies and amounts that each player begins the game with, as well as the items that each player begins the game with. In this example, we’ve started the player with a blank slate so that we can more easily demonstrate the quest rewards being given to the player.
The Hiro Achievements system allows you to define and manage the various achievements within your game. These can be one-off or recurring achievements that players can complete to earn various rewards or prestige. Achievements can also have specific pre-conditions that a player must meet before they can contribute towards their completion. They can also have nested sub achievements should your gameplay design require this.
{"achievements":{"first_victory":{"name":"First Victory","description":"Win your first game.","category":"once","count":0,"max_count":1,"reward":{"guaranteed":{"currencies":{"coins":{"min":1000}}}},"additional_properties":{"icon_name":"wins"}}},// ...
}
For our game, we have created several one-off achievements as well as both daily and weekly recurring achievements that all reward the player with some form of currency or in-game item.
This file bootstraps our game with a list of systems to be used, and provides a list of systems for deterministic start-up. In our case, we’re initializing the Inventory, Economy and Achievements core systems from Hiro.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ...systems.Add(nakamaSystem);// Add the Inventory systemvarinventorySystem=newInventorySystem(logger,nakamaSystem);systems.Add(inventorySystem);// Add the Economy systemvareconomySystem=newEconomySystem(logger,nakamaSystem,EconomyStoreType.Unspecified);systems.Add(economySystem);// Add the Achievements systemvarachievementsSystem=newAchievementsSystem(logger,nakamaSystem);systems.Add(achievementsSystem);returnTask.FromResult(systems);// ...
// ...publicasyncTaskInitAsync(){// Get the Economy system and listen for updates._economySystem=this.GetSystem<EconomySystem>();SystemObserver<EconomySystem>.Create(_economySystem,OnEconomySystemUpdated);// Get the Achievements system and listen for updates._achievementsSystem=this.GetSystem<AchievementsSystem>();SystemObserver<AchievementsSystem>.Create(_achievementsSystem,OnAchievementsSystemUpdated);// Refresh both systems to get the latest data.awaitTask.WhenAll(_economySystem.RefreshAsync(),_achievementsSystem.RefreshAsync());}privatevoidOnEconomySystemUpdated(EconomySystemeconomySystem){coinsCounter.text=_economySystem.Wallet["coins"].ToString("N0");gemsCounter.text=_economySystem.Wallet["gems"].ToString("N0");}privatevoidOnAchievementsSystemUpdated(AchievementsSystemachievementsSystem){// Populate the once achievementsUpdateQuestGrid(onceGrid,_achievementsSystem.GetAvailableAchievements("once"),false);// Populate the daily achievementsUpdateQuestGrid(dailyGrid,_achievementsSystem.GetAvailableRepeatAchievements("daily"),true);// Populate the weekly achievementsUpdateQuestGrid(weeklyGrid,_achievementsSystem.GetAvailableRepeatAchievements("weekly"),true);}privatevoidUpdateQuestGrid(Transformgrid,IEnumerable<IAchievement>achievements,boolrepeating){// Clear existing items from the UI.foreach(Transformchildingrid){Destroy(child.gameObject);}// Iterate through each achievement and update the UI.foreach(varachievementinachievements){// Determine if the Achievement has been claimed.varclaimed=achievement.ClaimTimeSec>0;// Get the icon name from the Achievement's AdditionalProperties metadata if possible.variconName="count";if(achievement.AdditionalProperties.TryGetValue("icon_name",outvarn)){iconName=n;}// Instantiate a Quest Item UI element and initialize it with the appropriate display data.varquestItem=Instantiate(questItemPrefab,grid);questItem.Init(achievement.Description,achievement.Count,achievement.MaxCount,iconName,repeating,claimed);// Listen for click events and claim the Achievement when it is clicked.questItem.ClaimClicked+=async()=>{// Claim the Achievement.varachievementsUpdateAck=await_achievementsSystem.ClaimAchievementsAsync(new[]{achievement.Id});// Refresh the Economy system so that we can update the UI appropriately after claiming.await_economySystem.RefreshAsync();// Show the Reward popup panel.ShowClaimRewardPanel(achievementsUpdateAck);};}}privatevoidShowClaimRewardPanel(IAchievementsUpdateAckack){// Inline function to update the Reward popup panel UI for an Achievement's rewards.voidAddAchievementRewardToRewardPanel(IAchievementachievement){// Iterate through the Item rewards and add them to the UI.foreach(variteminachievement.Reward.Items){varrewardItem=Instantiate(rewardItemPrefab,rewardGrid);rewardItem.GetComponent<QuestsRewardItemUI>().Init(item.Key,item.Value);}// Iterate through the Energy Modifier rewards and add them to the UI.foreach(varenergyModifierinachievement.Reward.EnergyModifiers){varrewardItem=Instantiate(rewardItemPrefab,rewardGrid);vartext=energyModifier.Operator=="infinite"?"∞":energyModifier.Value.ToString();vartimespan=TimeSpan.FromSeconds(energyModifier.DurationSec);text+=$" ({timespan.TotalMinutes}m) ";rewardItem.GetComponent<QuestsRewardItemUI>().Init(energyModifier.Id,text);}// Iterate through the Currency rewards and add them to the UI.foreach(varcurrencyinachievement.Reward.Currencies){varrewardItem=Instantiate(rewardItemPrefab,rewardGrid);rewardItem.GetComponent<QuestsRewardItemUI>().Init(currency.Key,currency.Value);}}// Clear existing rewards from the reward panel.foreach(TransformchildinrewardGrid){Destroy(child.gameObject);}// Add rewards from normal achievements.foreach(varachievementinack.Achievements){AddAchievementRewardToRewardPanel(achievement.Value);}// Add rewards from repeat achievements.foreach(varachievementinack.RepeatAchievements){AddAchievementRewardToRewardPanel(achievement.Value);}// Show the reward popup.rewardPanel.gameObject.SetActive(true);}// ...