From 774ba036b1eab45acc8197e718a2a02fb4c733ca Mon Sep 17 00:00:00 2001 From: omckeon Date: Tue, 9 Jul 2024 08:45:15 +0000 Subject: [PATCH] Update JSON guides --- src/content/docs/guides/json/0-json_intro.mdx | 142 +++++++++++ .../docs/guides/json/1-json_reading.mdx | 108 ++++++++ .../docs/guides/json/2-json_writing.mdx | 232 ++++++++++++++++++ 3 files changed, 482 insertions(+) create mode 100644 src/content/docs/guides/json/0-json_intro.mdx create mode 100644 src/content/docs/guides/json/1-json_reading.mdx create mode 100644 src/content/docs/guides/json/2-json_writing.mdx diff --git a/src/content/docs/guides/json/0-json_intro.mdx b/src/content/docs/guides/json/0-json_intro.mdx new file mode 100644 index 00000000..be59e2d6 --- /dev/null +++ b/src/content/docs/guides/json/0-json_intro.mdx @@ -0,0 +1,142 @@ +--- +title: Introduction to JSON in SplashKit +description: JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write, and for machines to parse and generate. +category: Guides +author: Jonathan Tynan +lastupdated: May 11 2024 +sidebar: + label: "Introduction to JSON" +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components"; + +**{frontmatter.description}** +Written by: {frontmatter.author} +_Last updated: {frontmatter.lastupdated}_ + +--- + +### What is JSON? + +[JSON](/api/json/) is often used in various programming environments, including game development, for data storage and configuration. In SplashKit, JSON functionality allows developers to efficiently manage game settings, level data, and more. This part of the tutorial introduces JSON and its basic structure, with an overview of its application in SplashKit. + +### Basic Structure of a JSON File + +A basic JSON file might look like this: + +```json +{ + "gameTitle": "My New Game", + "screenSize": { + "width": 800, + "height": 600 + }, + "levels": ["level1", "level2", "level3"] +} +``` + +JSON objects are made up of values associated with keys. In this example, `gameTitle` is the key associated with the string `"My New Game"`, `screenSize` is the key for an object with two numeric values (width and height), and an array of strings is assigned as the value for the key `levels`. + +### Overview of JSON in SplashKit + +SplashKit simplifies the process of working with JSON files in your games. Functions are provided for reading JSON files, so that we can easily read values and load configurations or game data. Additional functions are provided for writing JSON files, so that we can save configurations and game data. + +### Getting Started with JSON in SplashKit + +To begin using JSON in SplashKit, we must have our files in the correct locations. Run the following command in your project directory to generate the resources folder. + +```shell +skm resources +``` + +This command creates sub-folders for each type of resource. One of these is named `json` and that is where we place our JSON files. To begin lets take the example JSON file above and place it into the `json` folder with the name `game_data.json`. To access the values in this file we can now do the following: + + + + + ```cpp + #include "splashkit.h" + int main() + { + json game_data; + game_data = json_from_file("game_data.json"); + string game_title = json_read_string(game_data, "gameTitle"); + + write("Game Title: "); + write_line(game_title); + + free_json(game_data); + + return 0; + } + ``` + + + + +In this code example, we're first using [Json From File](/api/json/#json-from-file) to load a JSON object with the details from the `game_data.json` file. +Then we are getting the value of the key that matches `gameTitle` using [Json Read String](/api/json/#json-read-string). We write this to the console and free the JSON object using [Free Json](/api/json/#free-json) as we exit. By freeing the JSON object we are deallocating any memory that has been assigned to it, preventing any memory-related errors such as a `Segmentation Fault`. We can build this program with the following command. + + + + + ```shell + g++ program.cpp -l SplashKit -o json_program + ``` + + + + +And run it with: + + + + + ```shell + ./json_program + ``` + + + + +When we run this program it should output the following to the console: + +```plaintext +Game Title: My New Game +``` + +### Checking Keys + +But what if we didn't have a `gameTitle` key in our JSON? Well, error messages will be produced indicating that this key is `null`. To prevent this, we can use the [Json Has Key](/api/json/#json-has-key) function to check if the key is present and then do actions based on whether it has been found or not. We could then turn the previous example into the following code: + + + + + ```cpp + #include "splashkit.h" + int main() + { + json game_data; + game_data = json_from_file("game_data.json"); + + if(json_has_key(game_data, "gameTitle")) + { + string game_title = json_read_string(game_data, "gameTitle"); + write("Game Title: "); + write_line(game_title); + } + else + { + write_line("Key \"gameTitle\" not found."); + } + + free_json(game_data); + + return 0; + } + ``` + + + + +We have now loaded up our JSON file and retrieved the value stored with the `gameTitle` key. In the next tutorial we explore further how we can retrieve values stored in a JSON object. diff --git a/src/content/docs/guides/json/1-json_reading.mdx b/src/content/docs/guides/json/1-json_reading.mdx new file mode 100644 index 00000000..d6ee1c95 --- /dev/null +++ b/src/content/docs/guides/json/1-json_reading.mdx @@ -0,0 +1,108 @@ +--- +title: Reading JSON Data in SplashKit +description: After understanding the basics of JSON in SplashKit, this part of the tutorial focuses on how to read and parse JSON data. Reading JSON data is essential for game development tasks such as loading game settings, level configurations, or player data. +category: Guides +author: Jonathan Tynan +lastupdated: May 11 2024 +sidebar: + label: "Reading JSON Data" +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components"; + +**{frontmatter.description}** +Written by: {frontmatter.author} +_Last updated: {frontmatter.lastupdated}_ + +--- + +## Reading JSON Objects + +In the previous tutorial we loaded the following [JSON](/api/json/) file and read the game title from it. Lets extend this a little, and dive a further into extracting values from this structure. + +```json +{ + "gameTitle": "My New Game", + "fullScreenMode": false, + "numPlayers": 1, + "screenSize": { + "width": 800, + "height": 600 + }, + "levels": ["level1", "level2", "level3"] +} +``` + +### Accessing Values + +To access values in JSON objects like strings, numbers, or booleans, you can use functions like [Json Read String](/api/json/#json-read-string), [Json Read Number As Int](/api/json/#json-read-number-as-int), or [Json Read Bool](/api/json/#json-read-bool). We use these functions like the following code snippet. + + + + + ```cpp + string title = json_read_string(game_data, "gameTitle"); + int numPlayers = json_read_number_as_int(game_data, "numPlayers"); + bool isFullScreen = json_read_bool(game_data, "fullScreenMode"); + ``` + + + + +### Working with JSON Arrays + +If the data is an array, like the value stored for the `levels` key, we can obtain the data through [Json Read Array](/api/json/#json-read-array) and store it into a dynamic string array variable (such as `vector`in C++, or `List` in C#). Then we can loop through the entries in the array, and do some actions with the stored data. + +Below is an example of this: + + + + + ```cpp + vector levels; + + json_read_array(game_data, "levels", levels); + + int num_levels = levels.size(); + + for(int i = 0; i < num_levels; i++) + { + write("Got level: "); + write_line(levels[i]); + } + ``` + + + + +Running this prints the following to the terminal: + +```plaintext +Got level: level1 +Got level: level2 +Got level: level3 +``` + +### Extracting Nested JSON Objects + +SplashKit's JSON functionality allows you to extract various types of data, including basic types mentioned previously, but also even nested JSON objects. In our example file the value for the `screenSize` key is a JSON object. The following code demonstrates how to extract this object: + + + + + ```cpp + json game_screen_size = json_read_object(game_data, "screenSize"); + int width = json_read_number_as_int(game_screen_size, "width"); + int height = json_read_number_as_int(game_screen_size, "height"); + ``` + + + + +In this example, [Json Read Object](/api/json/#json-read-object) is used to extract the nested JSON object, and then the values are read from this nested object. These variables can then be used to define the window size for this game. + +### Conclusion + +Reading JSON data with SplashKit is a straightforward process that can greatly enhance the flexibility and functionality of your game. It enables dynamic loading of game content and configurations, making your game more adaptable and easier to manage. + +In the next part of this tutorial, we explore how to write and modify JSON data, allowing you to save game states, configurations, and player preferences. diff --git a/src/content/docs/guides/json/2-json_writing.mdx b/src/content/docs/guides/json/2-json_writing.mdx new file mode 100644 index 00000000..e3833293 --- /dev/null +++ b/src/content/docs/guides/json/2-json_writing.mdx @@ -0,0 +1,232 @@ +--- +title: Writing JSON Data in SplashKit +description: Having covered how to read JSON data in SplashKit, this part of the tutorial focuses on creating and writing data to JSON files. This functionality is crucial for features like saving game settings or player progress and information. +category: Guides +author: Jonathan Tynan +lastupdated: May 11 2024 +sidebar: + label: "Writing JSON Data" +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components"; + +**{frontmatter.description}** +_Written by {frontmatter.author} on {frontmatter.lastupdated}_ + +--- + +### Creating JSON Objects and Arrays + +In SplashKit, you can programmatically create JSON objects and arrays, which then can be populated with data. Lets see how we can create the example JSON file from previous tutorials with this method. + + + + + ```cpp + json new_game_data = create_json(); + json_set_string(new_game_data, "gameTitle", "My New Game"); + json_set_bool(new_game_data, "fullScreenMode", false); + json_set_number(new_game_data, "numPlayers", 1); + ``` + + + + +First we create the new JSON object using [Create Json](/api/json/#create-json), then we add basic data to **gameTitle**, **fullScreenMode**, and **numPlayers** using [Json Set String](/api/json/#json-set-string), [Json Set Bool](/api/json/#json-set-bool) and [Json Set Number](/api/json#json-set-number). + + + + + ```cpp + vector levels_array; + + levels_array.push_back("level1"); + levels_array.push_back("level2"); + levels_array.push_back("level3"); + + json_set_array(new_game_data, "levels", levels_array); + ``` + + + + +Next we add the levels array to the JSON object. We create a vector to store the strings, and push back each string that we want. Finally we use [Json Set Array](/api/json/#json-set-array) to store this data in JSON format. + + + + + ```cpp + json screen_size_data = create_json(); + + json_set_number(screen_size_data, "width", 800); + json_set_number(screen_size_data, "height", 600); + + json_set_object(new_game_data, "screenSize", screen_size_data); + ``` + + + + +Then we tackle the nested JSON object, the screen size object. We use [Create Json](/api/json/#create-json) to create a new object for this data, and then we add the width and the height to the object using [Json Set Number](/api/json/#json-set-number). Now that we have this JSON object filled with the data we want, we add it to the `new_game_data` object with [Json Set Object](/api/json/#json-set-object). + +### Writing JSON Data to a File + +Now that we have the `new_game_data` object that stores the same values as the JSON file used previously. Now, we can save this using [Json To File](/api/json/#json-to-file) like in the code below. + + + + + ```cpp + json_to_file(new_game_data, "new_game_data.json"); + ``` + + + + +By combining all these examples we can create the full program shown below. + + + + + ```cpp + #include "splashkit.h" + + int main() + { + json new_game_data = create_json(); + + json_set_string(new_game_data, "gameTitle", "My New Game"); + json_set_bool(new_game_data, "fullScreenMode", false); + json_set_number(new_game_data, "numPlayers", 1); + + json screen_size_data = create_json(); + + json_set_number(screen_size_data, "width", 800); + json_set_number(screen_size_data, "height", 600); + + json_set_object(new_game_data, "screenSize", screen_size_data); + + vector levels_array; + + levels_array.push_back("level1"); + levels_array.push_back("level2"); + levels_array.push_back("level3"); + + json_set_array(new_game_data, "levels", levels_array); + + json_to_file(new_game_data, "new_game_data.json"); + + free_all_json(); + } + ``` + + + + +Running this program results in a file named `new_game_data.json` being written to the `Resources/json/` folder. Open this up and you'll see something very similar or identical to the example JSON file we've been using previously. It should look something like this: + +```json +{ + "numPlayers": 1, + "fullScreenMode": false, + "gameTitle": "My New Game", + "levels": [ + "level1", + "level2", + "level3" + ], + "screenSize": { + "height": 600, + "width": 800 + } +} +``` + +Some of the keys can be in different positions, but this does not affect how we use it as we look for the key when retrieving values, not a particular data position in the JSON file. This new file is effectively the same JSON that we've used in previous JSON tutorials. + +### Modifying Existing JSON Data + +You can also load an existing JSON file, modify its contents, and save the changes back to the file. To demonstrate this, lets add the details of a player character to our game data. + + + + + ```cpp + json player_data = create_json(); + json_set_string(player_data, "name", "Hero"); + + json stats_data = create_json(); + json_set_number(stats_data, "health", 100); + json_set_number(stats_data, "mana", 50); + json_set_number(stats_data, "strength", 75); + + json_set_object(player_data, "stats", stats_data); + ``` + + + + +First we create the player JSON object to store the data for an entire character, then we create an individual object to hold the stats for the character. After this we add the stats object and nest it in the `player_data` object we created earlier. + + + + + ```cpp + json existing_data = json_from_file("new_game_data.json") + json_set_object(existing_data, "character", player_data); + + json_to_file(existing_data, "modified_game_data.json"); + ``` + + + + +Next we load the game data we saved previously, add our `player_data` object to the existing data and save it. If we add this code to our previous program and run it a file is created in the `Resources/json/` folder named `modified_game_data.json`. Open it, and you should see something like the following: + +```json +{ + "character": { + "name": "Hero", + "stats": { + "health": 100, + "mana": 50, + "strength": 75 + } + }, + "fullScreenMode": false, + "numPlayers": 1, + "gameTitle": "My New Game", + "levels": [ + "levels1", + "levels2", + "levels3" + ], + "screenSize": { + "height": 600, + "width": 800 + } +} +``` + +Now we have a character object stored with this JSON file. We also now have multiple levels of nesting. When this is the case and we want to access the innermost key we must get these JSON objects. So, to access the health stat we can use the following code: + + + + + ```cpp + // Load our JSON + json modified_game_data = json_from_file("modified_game_data.json"); + // Retrieve Character JSON object from the file. + json character = json_read_object(modified_game_data, "character"); + // Retrieve the Stats JSON object from the Character JSON + json stats = json_read_object(character, "stats"); + // Retrieve the value of health from the stats JSON object + int hp = json_read_number_as_int(stats, "health"); + ``` + + + + +### Conclusion + +By following this tutorial, you're now equipped with the foundational skills necessary to create, read and write JSON data objects with SplashKit. These examples have been focused around game development, but the JSON skills you've learnt extends beyond this as JSON is a versatile tool for any software development project.