I have a student who wanted to make a game in App Lab. In this game, he wants to have a type of storage area for the player to access at anytime. A backpack of sorts where the player can gain things from each level in order to bring it to another and help in the next. Any suggestions as to how this could be coded are appreciated.
it’d probably be best to store inventory as a object in a keyvalue, however know that for some reason CDO complains about directly storing objects directly as keyvalues, if you want to avoid it you can store it as a string if you really care about avoiding the warnings. then make the storage unique by using the user id provided to you by CDO below will be a demo
var inventory = {oranges: 2};
var userId = encodeURI(getUserId());
setKeyValue(userID, storage)
you can avoid the warnings if you like by using JSON.stringify
and JSON.parse
but you’ll end up having to re-encode and decode the object this time so your better off just ignoring it because that issue only pertains to tables and we are using keyvalues. by storing it under one key we can access all the data for the user without needing any table entries, you can also use setKeyValueSync
and getKeyValueSync
to avoid any race conditions you may have with handling the data if you don’t wish to complicate thing further with callbacks that the original functions need to ensure the data has been saved correctly
Varrience
Hi @jcostanza,
I think it depends on the skill level of your student and how deep in to the world of JavaScript they would like to go. If they’re trying to use their skills from CSP (and you’ve gotten to Lists) then I might suggest creating a list for the backpack items where each index in the list represents a specific thing that is available in the game, and the value stores how many of those things the player has. For example:
// healing potion, wand, hamster
var backpack = [0, 0, 0]
If at some point in the game, the player found a healing potion, the event for picking it up (clicking on it?) would include the following code:
backpack[0] += 1 // 0 hardcoded because we know this is where the healing potion data is stored.
Is this the most elegant or efficient way of doing this? Absolutely not. But it is totally accessible to a student trying to imagine a new behavior with their current skills.
If your student wanted to dig a little deeper, I would encourage them to explore using the data type Dictionary instead of a List. This will both use up less space in memory, and allow them to dynamically add items to the backpack without keeping the placeholder space in the list. Dictionaries are super useful, but are generally beyond the scope of this course!