Data & Storage Options -- What is available and deciding which one to use
Construct2 offers several data and storage options for use in your games. This activity introduces you to a few of those options.
Turn In: Dictionary-Testing.capx, StoreItLocal.capx, and Array-Display.capx
Sometimes your game needs to remember things that take place during game play or look up information needed during game play. In this activity we are going to look at a few of the data & storage objects in Construct2 and how they work.
The Dictionary object stores information in a key/value pair format. The key is the unique name the information is stored under and the value is the information stored. Keys are case sensitive so the key Sue is different than sue because one has a capital letter as the first letter and the other one has a small first letter. The Dictionary object only remembers the information during the game session so once you click Run layout and/or refresh your browser, the Dictionary object information is lost.
We are going to store names and scores into a Dictionary object then display them on the screen. While you can Run layout as you do some of the initial steps, there is nothing to see until we get through the steps to store and display the Dictionary object information.
Create a new project called Dictionary-Testing.capx, you can use the default layout and window sizes.
Double-click on the layout to insert a new object, pick Dictionary and name it PlayerScore, click Insert. You will see PlayerScore in the Objects window but will not show up on Layout 1.
Insert two Text box objects and a Button object onto the layout. The name of the first Text box should be PlayerName, the second Text box should be named Score, and the name of the button should be SubmitScore. Click on the SubmitScore button and in the properties on the left, change the Text from OK to Save Score. You may have to stretch the button a little to the right to see the words "Save Score".
Add event, SubmitScore->On clicked. Add action, PlayerScore->Add Key. For the name of the key, remove the "" and type in PlayerName.Text and for the Value type in Score.Text
Insert Text object named ScoreList and Button named ShowScores. Click on the ScoreList and stretch it to the right and also down so that it is wider than before and quite a bit longer than originally. Click on the ShowScores button and in the Properties on the left, change the Text from OK to Display Scores (and adjust the size of the button to show those words).
Add event, ShowScores->On clicked. Right click on the event just created and pick Add Condition the PlayerScore->For each key. Add action, ScoreList->Append text.
Run layout and in the first text box, type a name then type a number into the second text box and click on the Save Score. Type in a different name and number and click the Save Score button. Do a few more different names and numbers. Then click on the Display Scores button. Click on the Display Scores button again. Put in another name and number and Save Score then Display Scores.
Notice a few things. When you click on the Save Score button, your name and number remain which makes you wonder if it did anything. When you first Run layout, you see the word Text where ScoreList is and when you click on the Display Scores button, you see the numbers that you typed in then the next time you click it then it shows those numbers repeated. After adding a new score and clicking on the Display Scores you see the previous numbers and the new one at the end. We will clean those things up and review a few of the events and actions created above.
In Layout 1, click on ScoreList then in the Properties on the left, remove the word Text from the Text property. Text will not longer be on Layout 1 and also not be there when you Run layout.
When people click a button, they want to know the information was accepted or the action was taken. On the Event sheet 1, find the SubmitScore->On clicked and Add action below the existing action. Pick ScoreList, click Next, pick "Set text", click Next, for the Text type in (or copy/paste) the line below exactly as you see it and click on Done.
"Added: " & PlayerName.Text & " with score of " & PlayerScore.Get(PlayerName.Text)
Click on Add action for the SubmitScore->On clicked again, select PlayerName, click Next, pick Set text, click Next, click Done. Click Add action for SubmitScore->On clicked, pick Score, click Next, pick Set text, click Next, click Done.
Run layout. The word text is not longer there. Type in a name and a number and click on Save Score. ScoreList should show something like "Added: Tim with score of 49" (where Tim and 49 would be the name and number you typed in). Also, the name and number you typed in are no longer displayed.
Notice in the "Added" line that we used, anything in quotes is a string literal which means it is displayed exactly like in the quotation marks. The & character joins different parts together (the technical term is concatenation). The PlayerName.Text is pulling the name from the text box. The PlayerScore.Get(PlayerName.Text) is getting the number from the Dictionary object using the name as the key value. To retrieve items from the Dictionary object you use its key. The last thing we did was set the PlayerName and Score text boxes to "" which means it cleared out what was typed in. This is nice because new name/number can be typed in without removing the previous ones and it also lets the person clicking the button know that something happened.
We also want to make the Display Scores button show a nicer score display, specifically who received which score and we also do not want the scores to repeat each time we click the Show Scores button.
Double click on the ScoreList->Append PlayerScore.CurrentValue action then change the Text to the following and click on Done.
PlayerScore.CurrentKey & " -- " & PlayerScore.CurrentValue & newline
Run layout and put in a few different names and numbers then click on Display Scores. We do see the name a few dashes and the score. The newline puts each of those on a new line. But it shows our last Added line and when we click Display Scores multiple times, we do see the information repeated. Please note, if some of the lines at the bottom or to the right are chopped off, stretch the ScoreList text object more to the right and more down to size it properly. Make sure it is in the dotted line representing the window size or click and drag to move it to the left and up more.
So, we still have something to fix up. To make the adjustment, when the ShowScore button is clicked, we want to clear out ScoreList. Then we want to go through and display each key in the PlayerScore dictionary object.
Click in the Event with two conditions that includes ShowScores->On clicked. It will have a yellow background. Press the S key which creates a new Subevent. Choose PlayerScore, click Next, then choose "For each key" and click Done. You should see PlayerScore->For each key indented under the event that has both ShowScores->On clicked and PlayerScore->For each key. We have a duplicate event so right click on the "PlayerScore->For each key" that is after ShowScores->On clicked and above the other PlayerScore->For each key then pick the Delete option to remove it. Left click on the ScoreList action and drag it down into the Add action for the PlayerScore->For each key. Beside ShowScores->On clicked, click on the Add action then pick ScoreList, click Next, pick Set text, click Next, then click Done. This is clear the ScoreList when the button is clicked then the subevent will append each of the player name and player scores into the ScoreList. Run layout, put in some different names and numbers, then click on the Display Scores button a few times. Add a few more name/number and click on the Display Scores. Put in the same name as before (capital/small letters the same) and a different number then Save and Display. Note that it replaces the previous number for that name.
Note: Click on the Refresh in your browser and click on Display Scores ... the scores are gone. Click on Run layout then click on Display Scores ... the scores are gone. The Dictionary object only retains values from the current browser session.
You can save and close Dictionary-Testing.capx
Local storage stores information in the browser across sessions. As long as you use the same web browser and that web browser's local storage is not cleared then that value is available to the game.
Because loading and saving values in local storage can take a little bit of time, there are events to do the load/save and other events that are triggered when the load/save has completed.
Create a new project named StoreItLocal.capx with the default layout and window sizes. Add a new Text object and name it BestScore then change the Text from Text to 0 (in the Properties of BestScore on the left side). Add a button named SaveBest then change the Ok text to "Save Best". Add a button named LoadBest then change the Ok text to "Load Best". Add a Text box named OneScore and a Button named SaveScore (change the Ok Text to Save Score).
Create a new Global variable by right clicking in the empty area of Event sheet 1 and pick Add global variable. Name the variable TopScore of type number and the initial value of 0. This will store the top score. To display the TopScore, click Add event then System->Every tick then Add action, pick BestScore, click Next, pick Set text, click Next, type in TopScore, then click on Done.
We want to update the TopScore variable with any score that is bigger than the current TopScore. Add event, SaveScore->On clicked. Click to select the event just created then press the letter S to create a new subevent. Pick System, click Next, pick Compare variable, click Next, pick variable TopScore with the Comparison of "Less than" and OneScore.Text as the Value. Beside that subevent, click on Add action then System, click Next, pick Set value, click Next, pick variable TopScore with Score.Text as the Value, and click Done. Add another action under the one just created ... OneScore->Set text ... click Done to clear out the text. Click on the TopScore < OneScore.Text event then press the letter X to create an Else connection. For the action of the Else condition, add OneScore->Set Text then click Done to clear the text out.
On Layout 1, insert a new object and pick "Local storage" and named it StoreBest. The new object will be in the Objects window but not on the Layout.
On Event sheet 1, Add event and pick SaveBest->On clicked. Add action, pick StoreBest then "Set item" and put in the Key of "Best" and the Value of TopScore then click Done.
Add event and pick LoadBest->On clicked. Add action, pick StoreBest->Get item. Use the Key of "Best"
Add event, pick StoreBest->On item get, click Next, put in the Key "Best", click Done. Add action, System->Set value then the Variable of TopScore and the Value of StoreBest.ItemValue
Run layout and let's do some testing. The top score is 0. Type in a number and click Save Score, the top score should change to that number. Type in other numbers, some bigger and some smaller while clicking Save Score after each number. The top score should only change when the new number is bigger than the current top score. Click on the Save Best button. Add a few more scores and Save Score raising the top score. Click on the "Load Best" button ... the saved value should replace the top score. Close the web browser. Click on Run layout then immediately click on the Load Best button. Even though the browser was closed and a new browser started, the vaule that was last saved was loaded up and shown as the current top score.
Save and close the StoreItLocal.capx project.
Arrays are storage objects that in Construct2 can be configured in one, two, or three dimensions. Arrays store similar types of information and are referenced by numeric indexes.
Three dimensional arrays are not used often so we are not going to cover them here. A one dimensional array is similar to the Dictionary object with a numeric value as the key instead of a name. We will look at a representation of a one-dimensional array then work through a two dimensional array example.
Create a new project called Array-Display.capx using the default layout and window sizes.
Insert a new object, select Array, change the name to Colors, then click on Insert. Notice that it appears in the Objects window but not on the Layout 1. Click on the Colors object and look at the Properties. The default values are Width of 10 and then Height and Depth both of 1. That means that this is a one dimensional array (width) that can hold 10 values. The 1 in the Height and Depth mean that they are not used, this value must be a 1, do not use a 0 for these values.
Let's say that we want to store 5 colors into our Colors array. We would set the Width to 5. The array would look like the example below. Notice that the indexes are 0 to 4 (5 items).
0 | red |
1 | green |
2 | blue |
3 | yellow |
4 | orange |
We are going to do a small Spanish color tutorial. Our tutorial is going to show the English word, the Spanish word, and change the background color to matching the color word. We want to do this for 6 colors. So our array will have a width of 6 (the 6 colors) and the height of 3 for the three types of information that we want to store (English, Spanish, color value).
Change the Colors array properties to ...
The Colors array will look like ...
0 1 2
0 | red | rojo | 255 |
1 | blue | azul | 16711680 |
2 | green | verde | 65280 |
3 | orange | anaranjado | 33023 |
4 | pink | rosado | 8983278 |
5 | purple | violeta | 15736992 |
Note: The color values were calculated using the RGB values of the color. RGB is Red Green Blue. 0 is none of that color while 255 is all of that color. To find the numbers above, take the red value of a color then add in the result of green value times 256 then add in the result of the blue value times 256 times 256. More explanation can be found researching RGB or ask your instructor if any questions.
We need to be able to store values into our array and retrieve values from it. In order to do that, it is helpful to know how to reference the values. Read the top to bottom index first then the left to right index second.
The text red is at position 0,0. Then rojo is at 0,1 and 255 is at 0,2. Verde is at 2,1 while 33023 is at 3,2.
There are a number of different ways to put information into the arry and retrieve information from the array. You can download and load information in the JSON format, you can insert/delete or push/pop data, or you can place/retrieve information from specific locations in the array. There are also options to sort and reverse the order of information.
For this activity, we are going to use the Set action to place the data so it matches the table shown above then use it to display the information.
On Event sheet 1, click Add event then pick System->On start of layout. Add action and pick Colors, click Next, pick "Set at XY", leave X and Y as 0 then put in "red" (with the quotes) for Value, then click on Done. Add action, Colors->Set at XY then 0 for X, 1 for Y, and "rojo" for Value. Add action again, , Colors->Set at XY then 0 for X, 2 for Y, and 255 for Value. You now have the first row put into the array.
The second row will be ...
X=1, Y=0, Value = "blue"
X=1, Y=1, Value = "azul"
X=1, Y=2, Value = 16711680
Add action for the items above using the Colors->SetXY and then also do the third row (where X = 2). You should have nine set value actions starting at 0,0 and going to 2,2 (red, green, blue).
Now that the first three rows of data are available, we can add the events/actions to display the English/Spanish words along with the corresponding background color.
On Layout 1, add a Text object and name it English then add a Text object and name it Spanish. Be sure each of the Text objects are in the viewable window area and that they are sized large enough to display the entire word. You can change the font and font size of the Text object if you want the color words to be bigger or display in a different font.
Back on the Event sheet 1, right click in the empty portion and pick add a new Global Variable of type Number with the name CurrentColor and the Initial Value of 0.
Add event, System->Compare Variable then pick CurrentColor as the Variable, "> Greater than" as the Comparison, and 2 as the Value. Add action for that event and pick System then "Set Value" then 0 for the value. Anytime the CurrentColor goes bigger than 2, it gets changed to 0.
Add event, System->Every X seconds then change 1.0 to 5 and click Done for every 5.0 seconds. Add action, pick English, click Next, pick "Set text", click Next, for the text type in the following exactly as shown on the next line ...
Then click on Done. Click on Add action for the Every 5 seconds event and pick Spanish->Set text then the same line as above except a 1 where the 0 is. Add action for the same event then pick System, click Next, pick "Set layer background color", click Next, leave Layer set to 0 then put in the Colors.At line above with a 2 in place of the 0 and then click Done. Finally, we need to Add action then pick System->Add to, click Next, pick CurrentColor for the Variable and 1 for the Value, then click Done.
Run layout. After 5 seconds, the background should change to red with the words red/rojo displayed, then 5 seconds later blue, then 5 seconds later green, and back to red.
The XML Data & Storage option is a more complicated than the other three items we have looked at and will not be covered in this activity.
In Construct2, click on File then New and type XML into the search box for an example of using the XML object.
Additional and More Permanent Storage
Construct2 offers ways to read and store more permanent data. Most of those methods involve communication over the Internet or network to a web site that will do the actual permanent storage and retrieval of that information. This is more involved and will not be covered in this activity.
Copyright © 2021 Eric Schumm. Permission granted to freely use this in your classroom.