From 9dc6f7e58d7194d3dbabf4d9f029b1ac45104ffb Mon Sep 17 00:00:00 2001 From: s223126445 <162955558+s223126445@users.noreply.github.com> Date: Wed, 11 Sep 2024 11:49:47 +0000 Subject: [PATCH 01/30] c# update --- .../Audio/0-getting-started-with-audio.mdx | 138 +++++++++++++++++- 1 file changed, 137 insertions(+), 1 deletion(-) diff --git a/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx b/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx index 0e178ad0..aaf420d5 100644 --- a/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx +++ b/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx @@ -2,7 +2,7 @@ title: Get Started with SplashKit Audio description: Adding sound effects and music can really help bring an application to life. In this article see how to get started with Audio in SplashKit. author: Various Authors -lastupdated: July 2024 +lastupdated: september 2024 category: Guides --- @@ -186,6 +186,8 @@ int main() + + ```csharp using SplashKitSDK; @@ -289,6 +291,140 @@ do CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace SoundDemoOOP +{ + public class SoundPlayer + { + private SoundEffect _sndEffect; + private Window _window; + + public SoundPlayer() + { + _window = new Window("Sound Demo", 640, 320); + LoadSounds(); + } + + public void LoadSounds() + { + _sndEffect = SplashKit.LoadSoundEffect("chipmunk", "chipmunk.ogg"); + SplashKit.LoadSoundEffect("bells", "bells.ogg"); + SplashKit.LoadSoundEffect("camera", "camera.ogg"); + SplashKit.LoadSoundEffect("boing", "comedy_boing.ogg"); + SplashKit.LoadSoundEffect("dinosaur", "dinosaur.ogg"); + SplashKit.LoadSoundEffect("bark", "dog_bark.ogg"); + } + + public void HandleInput() + { + SplashKit.ProcessEvents(); + + if (SplashKit.KeyDown(KeyCode.RightCtrlKey) || SplashKit.KeyDown(KeyCode.LeftCtrlKey)) + { + if (SplashKit.KeyTyped(KeyCode.Num1Key)) + _sndEffect = SplashKit.SoundEffectNamed("chipmunk"); + if (SplashKit.KeyTyped(KeyCode.Num2Key)) + _sndEffect = SplashKit.SoundEffectNamed("bells"); + if (SplashKit.KeyTyped(KeyCode.Num3Key)) + _sndEffect = SplashKit.SoundEffectNamed("camera"); + if (SplashKit.KeyTyped(KeyCode.Num4Key)) + _sndEffect = SplashKit.SoundEffectNamed("boing"); + if (SplashKit.KeyTyped(KeyCode.Num5Key)) + _sndEffect = SplashKit.SoundEffectNamed("dinosaur"); + if (SplashKit.KeyTyped(KeyCode.Num6Key)) + _sndEffect = SplashKit.SoundEffectNamed("bark"); + } + else + { + if (SplashKit.KeyTyped(KeyCode.Num1Key)) + _sndEffect.Play(); + if (SplashKit.KeyTyped(KeyCode.Num2Key)) + _sndEffect.Play(0.5f); + if (SplashKit.KeyTyped(KeyCode.Num3Key)) + _sndEffect.Play(3, 0.25f); + if (SplashKit.KeyTyped(KeyCode.Num4Key)) + _sndEffect.Play(-1, 0.1f); + if (SplashKit.KeyTyped(KeyCode.Num5Key)) + { + if (_sndEffect.IsPlaying) + _sndEffect.Stop(); + } + } + } + + public void DrawInterface() + { + // Clear the screen with SplashKit Orange background + SplashKit.ClearScreen(SplashKit.RGBColor(245, 166, 35)); + + // Draw heading + SplashKit.SetFontStyle("arial", FontStyle.BoldFont); + SplashKit.DrawText("Keyboard Controls", Color.Black, "arial", 20, (_window.Width - SplashKit.TextWidth("Keyboard Controls", "arial", 20)) / 2, 10); + SplashKit.SetFontStyle("arial", FontStyle.NormalFont); + + // Draw left box with SplashKit Cyan/Teal border + SplashKit.FillRectangle(SplashKit.RGBColor(5, 172, 193), 10, 45, _window.Width / 2 + 10, _window.Height - 85); + SplashKit.FillRectangle(Color.PapayaWhip, 20, 55, _window.Width / 2 - 10, _window.Height - 105); + SplashKit.DrawLine(Color.LightGray, 30, 105, _window.Width / 2, 105); + + // Playing sound effect controls text + SplashKit.DrawText("Playing Sound Controls", Color.Red, "arial", 18, 80, 70); + SplashKit.DrawText("[1] Play Sound At Full Volume", Color.Blue, "arial", 14, 30, 120); + SplashKit.DrawText("[2] Play Sound At 50% Volume", Color.Blue, "arial", 14, 30, 150); + SplashKit.DrawText("[3] Play Sound 3 Times At 25% Volume", Color.Blue, "arial", 14, 30, 180); + SplashKit.DrawText("[4] Play Sound Continuously at 10% Volume", Color.Blue, "arial", 14, 30, 210); + SplashKit.DrawText("[5] Stop Playing Current Sound", Color.Blue, "arial", 14, 30, 240); + + // Exit text + SplashKit.SetFontStyle("arial", FontStyle.ItalicFont); + SplashKit.DrawText("Press [Escape] or [Q] to quit", Color.Black, "arial", 16, 65, 290); + SplashKit.SetFontStyle("arial", FontStyle.NormalFont); + + // Draw right box with SplashKit Cyan/Teal border + SplashKit.FillRectangle(SplashKit.RGBColor(5, 172, 193), _window.Width / 2 + 30, 45, _window.Width / 2 - 40, _window.Height - 55); + SplashKit.FillRectangle(Color.PapayaWhip, _window.Width / 2 + 40, 55, _window.Width / 2 - 60, _window.Height - 75); + SplashKit.DrawLine(Color.LightGray, _window.Width / 2 + 50, 105, _window.Width - 30, 105); + + // Switching to sound effect controls text + SplashKit.DrawText("Switching Sound Controls", Color.OrangeRed, "arial", 18, _window.Width / 2 + 65, 70); + SplashKit.DrawText("[CTRL + 1] Chipmunk Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 120); + SplashKit.DrawText("[CTRL + 2] Bells Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 150); + SplashKit.DrawText("[CTRL + 3] Camera Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 180); + SplashKit.DrawText("[CTRL + 4] Boing Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 210); + SplashKit.DrawText("[CTRL + 5] Dinosaur Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 240); + SplashKit.DrawText("[CTRL + 6] Bark Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 270); + } + + public void Run() + { + do + { + HandleInput(); + DrawInterface(); + SplashKit.RefreshScreen(60); + } while (!(SplashKit.QuitRequested() || SplashKit.KeyTyped(KeyCode.EscapeKey) || SplashKit.KeyTyped(KeyCode.QKey))); + + SplashKit.CloseAllWindows(); + } + } + + public class Program + { + public static void Main() + { + SoundPlayer player = new SoundPlayer(); + player.Run(); + } + } +} +``` + + From d2f06f0956809c7576787a892210d430a3ed2b18 Mon Sep 17 00:00:00 2001 From: Breezy <114720008+breezy-codes@users.noreply.github.com> Date: Tue, 1 Oct 2024 14:24:02 +1000 Subject: [PATCH 02/30] Tutorial Review of getting started with servers guide (#145) --- .../guides/Networking/0-getting-started-with-servers.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx b/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx index 79e17478..74b471d8 100644 --- a/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx +++ b/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx @@ -3,7 +3,7 @@ title: Getting Started With Servers description: This guide is an introduction to using web servers category: Guides author: Andrew Cain and Isaac Wallis -lastupdated: Jul 14 2018 +lastupdated: Aug 10 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -91,7 +91,7 @@ We need to pair the [Start Web Server](/api/networking/#start-web-server) with a write_line("About to start the server...") # Start a web server - defaults to listening to port 8080 - server = start_web_server() + server = start_web_server_with_default_port() # For now we are done... so lets shutdown... stop_web_server(server) @@ -119,7 +119,7 @@ The following code shows an appropriate `"Hello World"` web server program. write_line("About to start the server..."); // Start a web server - defaults to listening to port 8080 - web_server server = web_server(); + web_server server = start_web_server(); write_line("Waiting for a request - navigate to http://localhost:8080"); @@ -208,7 +208,7 @@ The follow code replaces the "Hello World" response with the details from the in write_line("About to start the server..."); // Start a web server - defaults to listening to port 8080 - web_server server = web_server(); + web_server server = start_web_server(); write_line("Waiting for a request - navigate to http://localhost:8080"); From d2e0f4d09853ff2a145b44abd014e0c9a96a797e Mon Sep 17 00:00:00 2001 From: Breezy <114720008+breezy-codes@users.noreply.github.com> Date: Tue, 1 Oct 2024 14:34:34 +1000 Subject: [PATCH 03/30] review of routing with servers (#146) --- .../Networking/1-routing-with-servers.mdx | 53 ++++++++----------- 1 file changed, 23 insertions(+), 30 deletions(-) diff --git a/src/content/docs/guides/Networking/1-routing-with-servers.mdx b/src/content/docs/guides/Networking/1-routing-with-servers.mdx index b026afde..884c3fff 100644 --- a/src/content/docs/guides/Networking/1-routing-with-servers.mdx +++ b/src/content/docs/guides/Networking/1-routing-with-servers.mdx @@ -3,7 +3,7 @@ title: Routing With Servers description: This guide is an intruduction to delivering different content based on route requested category: Guides author: Isaac Wallis -lastupdated: Aug 10 2018 +lastupdated: Aug 10 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -35,7 +35,7 @@ Start with this code, which we built in the introduction guide write_line("About to start the server..."); // Start a web server - defaults to listening to port 8080 - web_server server = web_server(); + web_server server = start_web_server(); write_line("Waiting for a request - navigate to http://localhost:8080"); @@ -170,41 +170,34 @@ The following code shows the use of an if statement to serve some login text or ```csharp - using SplashKitSDK; +using SplashKitSDK; - class Program - { - static void Main() - { - SplashKit.WriteLine("About to start the server..."); +SplashKit.WriteLine("About to start the server..."); - WebServer server = SplashKit.StartWebServer(); - HttpRequest request; +WebServer server = SplashKit.StartWebServer(); +HttpRequest request; - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - // Get the next request that the server has - request = SplashKit.NextWebRequest(server); +// Get the next request that the server has +request = SplashKit.NextWebRequest(server); - SplashKit.WriteLine("I got a request for " + SplashKit.RequestURI(request)); +SplashKit.WriteLine("I got a request for " + SplashKit.RequestURI(request)); - if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) - { - // Serve page for login path, e.g. - // SplashKit.SendHtmlFileResponse(request, "login.html"); +if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) +{ + // Serve page for login path + SplashKit.SendResponse(request, "login page"); +} +else +{ + // If no specified path is requested, serve index.html to the user + SplashKit.SendHtmlFileResponse(request, "index.html"); +} - SplashKit.SendResponse(request, "login page"); - } - else - { - // If no specified path is requested, serve index.html to the user - SplashKit.SendHtmlFileResponse(request, "index.html"); - } +SplashKit.WriteLine("About to stop the server..."); +SplashKit.StopWebServer(server); - SplashKit.WriteLine("About to stop the server..."); - SplashKit.StopWebServer(server); - } - } ``` @@ -471,4 +464,4 @@ Add links to contact and about to index.html in this same manner, then try playi ## What next? -With these concepts you should have enough to create a simple web server. You could make this more dynamic by reading details from the path in the URI, and then storing details within the program or in an associated database. The main thing to remember is that when you build a web server you need to wait for an incoming request, do some processing, and return a response. +With these concepts you should have enough to create a simple web server. You could make this more dynamic by reading details from the path in the URI, and then storing details within the program or in an associated database. The main thing to remember is that when you build a web server you need to wait for an incoming request, do some processing, and return a response. \ No newline at end of file From fbb7743e9286213bafbbd59c942da12c4922cf51 Mon Sep 17 00:00:00 2001 From: Breezy <114720008+breezy-codes@users.noreply.github.com> Date: Tue, 1 Oct 2024 15:17:08 +1000 Subject: [PATCH 04/30] Tutorial Review and code update of RESTful API Call Guide (#147) --- .../guides/Networking/2-restful-api-call.mdx | 332 ++++++++++++++---- 1 file changed, 259 insertions(+), 73 deletions(-) diff --git a/src/content/docs/guides/Networking/2-restful-api-call.mdx b/src/content/docs/guides/Networking/2-restful-api-call.mdx index 5bae32ea..ae8cd2ba 100644 --- a/src/content/docs/guides/Networking/2-restful-api-call.mdx +++ b/src/content/docs/guides/Networking/2-restful-api-call.mdx @@ -1,9 +1,9 @@ --- title: How to make a RESTful API call using SplashKit -description: In the world of web services and microservices many companies make their data availlable through a REST APIIn this document we want to use SplashKit to make a RESTful API call. +description: In the world of web services and microservices, many companies make their data available through a REST API in this document we want to use SplashKit to make a RESTful API call. category: Guides -author: Cyrill Illi -lastupdated: Oct 3 2018 +author: Cyrill Illi and Brianna Laird +lastupdated: Aug 10 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -38,33 +38,88 @@ In this first example we make use of a simple GET operation to retrieve a single - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" + +int main() +{ + http_response get_data; + string response; + + // Get a single JSON web resource + get_data = http_get("https://jsonplaceholder.typicode.com/posts/1", 443); + response = http_response_to_string(get_data); + free_response(get_data); + // Output the response + json json_response = json_from_string(response); + write_line("UserID => " + std::to_string(json_read_number_as_int(json_response, "userId"))); + write_line("ID => " + std::to_string(json_read_number_as_int(json_response, "id"))); + write_line("Title => " + json_read_string(json_response, "title")); + write_line("Body => " + json_read_string(json_response, "body")); + write_line("================"); + + return 0; +} +``` - int main() - { - http_response get_data; - string response; - - // Get a single JSON web resource - get_data = http_get("https://jsonplaceholder.typicode.com/posts/1", 443); - response = http_response_to_string(get_data); - free_response(get_data); - // Output the response - json json_response = json_from_string(response); - write_line("UserID => " + to_string(json_read_number_as_int(json_response, "userId"))); - write_line("ID => " + to_string(json_read_number_as_int(json_response, "id"))); - write_line("Title => " + json_read_string(json_response, "title")); - write_line("Body => " + json_read_string(json_response, "body")); - write_line("================"); - - return 0; - } - ``` + + + +```csharp +using SplashKitSDK; + +// Get a single JSON web resource +HttpResponse getData = SplashKit.HttpGet("https://jsonplaceholder.typicode.com/posts/1", 443); +string response = SplashKit.HttpResponseToString(getData); +SplashKit.FreeResponse(getData); + +// Output the response +Json jsonResponse = SplashKit.JsonFromString(response); +SplashKit.WriteLine("UserID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "userId")); +SplashKit.WriteLine("ID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "id")); +SplashKit.WriteLine("Title => " + SplashKit.JsonReadString(jsonResponse, "title")); +SplashKit.WriteLine("Body => " + SplashKit.JsonReadString(jsonResponse, "body")); +SplashKit.WriteLine("================"); +``` + + + + +```python +from splashkit import * + +# Get a single JSON web resource +get_data = http_get("https://jsonplaceholder.typicode.com/posts/1", 443) +response = http_response_to_string(get_data) +free_response(get_data) + +# Parse the response as JSON +json_response = json_from_string(response) + +# Output the response +write_line("UserID => " + str(json_read_number_as_int(json_response, "userId"))) +write_line("ID => " + str(json_read_number_as_int(json_response, "id"))) +write_line("Title => " + json_read_string(json_response, "title")) +write_line("Body => " + json_read_string(json_response, "body")) +write_line("================") +``` +After running this example, you'll get an output like this to the terminal: + +```bash +UserID => 1 +ID => 1 +Title => sunt aut facere repellat provident occaecati excepturi optio reprehenderit +Body => quia et suscipit +suscipit recusandae consequuntur expedita et cum +reprehenderit molestiae ut ut quas totam +nostrum rerum est autem sunt rem eveniet architecto +================ +``` + ## Example 2: GET Resources Once more we use the GET operator, but this time we request all the post. The response string now contains 100 posts. In order to convert them we would need to split the string into a vector and convert each response to a JSON object. This is not done in the example since the SplashKit has no split function instead we output the string. @@ -72,29 +127,84 @@ Once more we use the GET operator, but this time we request all the post. The re - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - http_response get_data; - string response; +int main() +{ + http_response get_data; + string response; + + // Get a list of a JSON web resource + get_data = http_get("https://jsonplaceholder.typicode.com/posts/", 443); + response = http_response_to_string(get_data); + free_response(get_data); + // To access each JSON key value pair the string should be split to an vector + // objects for simplicity sake we output just the string here. + write_line(response); + + return 0; +} +``` + + + - // Get a list of a JSON web resource - get_data = http_get("https://jsonplaceholder.typicode.com/posts/", 443); - response = http_response_to_string(get_data); - free_response(get_data); - // To access each JSON key value pair the string should be split to an vector - // objects for simplicity sake we output just the string here. - write_line(response); +```csharp +using SplashKitSDK; - return 0; - } - ``` +// Get a list of a JSON web resource +HttpResponse getData = SplashKit.HttpGet("https://jsonplaceholder.typicode.com/posts/", 443); +string response = SplashKit.HttpResponseToString(getData); +SplashKit.FreeResponse(getData); + +// To access each JSON key value pair the string should be split to an vector +// objects for simplicity sake we output just the string here. +SplashKit.WriteLine(response); +``` + + + + +```python +from splashkit import * + +# Get a list of a JSON web resource +get_data = http_get("https://jsonplaceholder.typicode.com/posts/", 443) +response = http_response_to_string(get_data) +free_response(get_data) + +# To access each JSON key value pair the string should be split to an vector +# objects for simplicity sake we output just the string here. +write_line(response) + +``` +After running this example, you'll get an output like this to the terminal: + +```bash +[ + { + "userId": 1, + "id": 1, + "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", + "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" + }, + { + "userId": 1, + "id": 2, + "title": "qui est esse", + "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" + }, + ... +] +``` + +Although, your output will include all 100 posts. + ## Example 3: POST Resource In this example we create a resource on the remote server by using the POST operation. This request requires the header definition specified the content type and the charset. This header must be within a vector as specified in the SplashKit documentation. The data is formed as a JSON object that is converted to a string for the purpose of the HTTP request. Note that the body only contains three parameters as the id is generated on the server. @@ -102,39 +212,115 @@ In this example we create a resource on the remote server by using the POST oper - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" + +int main() +{ + http_response get_data; + string response; + + // Create a JSON Web resource + // Create the JSON body for the http post call + json body = create_json(); + json_set_string(body, "title", "foo"); + json_set_string(body, "body", "test entry"); + json_set_number(body, "userId", 1); + // Create the header for the http post call + vector headers; + headers.push_back("Content-type: application/json; charset=UTF-8"); + // Send the request + get_data = http_post("https://jsonplaceholder.typicode.com/posts", 443, json_to_string(body), headers); + response = http_response_to_string(get_data); + free_response(get_data); + // Output the response + json json_response = json_from_string(response); + write_line("Following resource has been created"); + write_line("UserID => " + std::to_string(json_read_number_as_int(json_response, "userId"))); + write_line("ID => " + std::to_string(json_read_number_as_int(json_response, "id"))); + write_line("Title => " + json_read_string(json_response, "title")); + write_line("Body => " + json_read_string(json_response, "body")); + write_line("================"); + + return 0; +} +``` - int main() - { - http_response get_data; - string response; - - // Create a JSON Web resource - // Create the JSON body for the http post call - json body = create_json(); - json_set_string(body, "title", "foo"); - json_set_string(body, "body", "test entry"); - json_set_number(body, "userId", 1); - // Create the header for the http post call - vector headers; - headers.push_back("Content-type: application/json; charset=UTF-8"); - // Send the request - get_data = http_post("https://jsonplaceholder.typicode.com/posts", 443, json_to_string(body), headers); - response = http_response_to_string(get_data); - free_response(get_data); - // Output the response - json json_response = json_from_string(response); - write_line("Following resource has been created"); - write_line("UserID => " + to_string(json_read_number_as_int(json_response, "userId"))); - write_line("ID => " + to_string(json_read_number_as_int(json_response, "id"))); - write_line("Title => " + json_read_string(json_response, "title")); - write_line("Body => " + json_read_string(json_response, "body")); - write_line("================"); - - return 0; - } - ``` + + + +```csharp +using SplashKitSDK; + +// Create a JSON Web resource +// Create the JSON body for the http post call +Json body = SplashKit.CreateJson(); +SplashKit.JsonSetString(body, "title", "foo"); +SplashKit.JsonSetString(body, "body", "test entry"); +SplashKit.JsonSetNumber(body, "userId", 1); + +// Create the headers for the HTTP POST call +List headers = new List +{ + "Content-type: application/json; charset=UTF-8" +}; + +// Send the request +HttpResponse getData = SplashKit.HttpPost("https://jsonplaceholder.typicode.com/posts", 443, SplashKit.JsonToString(body), headers); +string response = SplashKit.HttpResponseToString(getData); +SplashKit.FreeResponse(getData); + +// Output the response +Json jsonResponse = SplashKit.JsonFromString(response); +SplashKit.WriteLine("Following resource has been created"); +SplashKit.WriteLine("UserID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "userId")); +SplashKit.WriteLine("ID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "id")); +SplashKit.WriteLine("Title => " + SplashKit.JsonReadString(jsonResponse, "title")); +SplashKit.WriteLine("Body => " + SplashKit.JsonReadString(jsonResponse, "body")); +SplashKit.WriteLine("================"); +``` + + + + +```python +from splashkit import * + +# Create a JSON Web resource +# Create the JSON body for the HTTP POST call +body = create_json() +json_set_string(body, "title", "foo") +json_set_string(body, "body", "test entry") +json_set_number_integer(body, "userId", 1) + +# Create the header for the HTTP POST call +headers = ["Content-type: application/json; charset=UTF-8"] + +# Send the request +get_data = http_post_with_headers("https://jsonplaceholder.typicode.com/posts", 443, json_to_string(body), headers) +response = http_response_to_string(get_data) +free_response(get_data) + +# Output the response +json_response = json_from_string(response) +write_line("Following resource has been created") +write_line("UserID => " + str(json_read_number_as_int(json_response, "userId"))) +write_line("ID => " + str(json_read_number_as_int(json_response, "id"))) +write_line("Title => " + json_read_string(json_response, "title")) +write_line("Body => " + json_read_string(json_response, "body")) +write_line("================") +``` + +After running this example, you'll get an output like this to the terminal: + +```bash +Following resource has been created +UserID => 1 +ID => 101 +Title => foo +Body => test entry +================ +``` From 9b8a754805fa8714f906ced78889118e33fd344e Mon Sep 17 00:00:00 2001 From: s223126445 <162955558+s223126445@users.noreply.github.com> Date: Tue, 1 Oct 2024 16:10:55 +1000 Subject: [PATCH 05/30] Mouse Inputs -C#Language-update (#179) --- .../guides/Input/1-mouse-button-inputs.mdx | 480 +++++++++++++++++- 1 file changed, 478 insertions(+), 2 deletions(-) diff --git a/src/content/docs/guides/Input/1-mouse-button-inputs.mdx b/src/content/docs/guides/Input/1-mouse-button-inputs.mdx index d44ebbe0..bb90efab 100644 --- a/src/content/docs/guides/Input/1-mouse-button-inputs.mdx +++ b/src/content/docs/guides/Input/1-mouse-button-inputs.mdx @@ -3,7 +3,7 @@ title: Using Mouse Inputs description: Introductory Mouse Input functionality guide category: Guides author: Various Authors -lastupdated: July 2024 +lastupdated: September 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -105,6 +105,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -133,11 +136,53 @@ while (!WindowCloseRequested("Mouse Inputs")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseInputs +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Inputs", 800, 600); + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + if (SplashKit.MouseClicked(MouseButton.LeftButton)) + { + SplashKit.ClearScreen(Color.Red); + } + else if (SplashKit.MouseClicked(MouseButton.RightButton)) + { + SplashKit.ClearScreen(Color.Yellow); + } + + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + - + ```python + from splashkit import * + COLOR_RED = color_red() COLOR_YELLOW = color_yellow() COLOR_WHITE = color_white() @@ -225,6 +270,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -258,6 +306,50 @@ while (!WindowCloseRequested("Mouse Inputs")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseInputs +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Inputs", 800, 600); + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + if (SplashKit.MouseDown(MouseButton.LeftButton)) + { + SplashKit.ClearScreen(Color.Red); + } + else if (SplashKit.MouseDown(MouseButton.RightButton)) + { + SplashKit.ClearScreen(Color.Yellow); + } + else + { + SplashKit.ClearScreen(Color.White); + } + + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + @@ -350,6 +442,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -378,6 +473,46 @@ while (!WindowCloseRequested("Mouse Inputs")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseInputs +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Inputs", 800, 600); + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + if (SplashKit.MouseUp(MouseButton.LeftButton)) + { + SplashKit.ClearScreen(Color.Red); + } + else + { + SplashKit.ClearScreen(Color.White); + } + + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + @@ -479,6 +614,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -522,6 +660,54 @@ while (!WindowCloseRequested("Mouse Movement")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseMovement +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Movement", 800, 600); + double hue = 0.8; + double saturation = 0.8; + double brightness = 0.8; + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + Vector2D movement = SplashKit.MouseMovement(); + + if (SplashKit.MouseDown(MouseButton.LeftButton)) + { + hue += movement.X / SplashKit.ScreenWidth(); + } + + if (SplashKit.MouseDown(MouseButton.RightButton)) + { + saturation += movement.Y / SplashKit.ScreenHeight(); + } + + SplashKit.ClearScreen(SplashKit.HSBColor(hue, saturation, brightness)); + + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + @@ -621,6 +807,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -654,6 +843,45 @@ while (!WindowCloseRequested("Mouse Scrolling")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseScrolling +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Scrolling", 800, 600); + double hue = 0.6; + double saturation = 0.6; + double brightness = 0.6; + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + Vector2D scroll = SplashKit.MouseWheelScroll(); + + hue += scroll.Y / 100.0; + + SplashKit.ClearScreen(SplashKit.HSBColor(hue, saturation, brightness)); + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + @@ -737,6 +965,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -757,6 +988,42 @@ while (!WindowCloseRequested("Mouse Location")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseLocation +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Location", 800, 600); + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + SplashKit.ClearScreen(Color.White); + + Point2D mousePosition = SplashKit.MousePosition(); + SplashKit.FillCircle(Color.LightBlue, mousePosition.X, mousePosition.Y, 20); + + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + @@ -829,6 +1096,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -849,6 +1119,39 @@ while (!WindowCloseRequested("Mouse Location")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseLocation +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Location", 800, 600); + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + SplashKit.ClearScreen(Color.White); + SplashKit.DrawLine(Color.Blue, SplashKit.LineFrom(SplashKit.MousePositionVector())); + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + @@ -929,8 +1232,12 @@ int main() + + + ```csharp using SplashKitSDK; +using static SplashKitSDK.SplashKit; float x = 0; @@ -956,6 +1263,46 @@ while (!WindowCloseRequested("Mouse Location")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseLocation +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Location", 800, 600); + float x = 0; + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + if (SplashKit.MouseDown(MouseButton.LeftButton)) + { + x = SplashKit.MouseX(); + } + + SplashKit.ClearScreen(Color.White); + SplashKit.FillCircle(Color.Blue, 400, 300, 100); + SplashKit.FillRectangle(Color.Purple, 0, 0, x, SplashKit.ScreenHeight()); + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + @@ -1041,6 +1388,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -1069,6 +1419,46 @@ while (!WindowCloseRequested("Mouse Location")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseLocation +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Location", 800, 600); + float y = 0; + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + if (SplashKit.MouseDown(MouseButton.LeftButton)) + { + y = SplashKit.MouseY(); + } + + SplashKit.ClearScreen(Color.White); + SplashKit.FillCircle(Color.Blue, 400, 300, 100); + SplashKit.FillRectangle(Color.Purple, 0, 0, SplashKit.ScreenWidth(), y); + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + @@ -1165,6 +1555,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -1202,6 +1595,49 @@ while (!WindowCloseRequested("Mouse Visibility")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseVisibility +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Visibility", 800, 600); + Circle blackHole = SplashKit.CircleAt(SplashKit.ScreenCenter(), 50); + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + if (SplashKit.PointInCircle(SplashKit.MousePosition(), blackHole)) + { + SplashKit.HideMouse(); + } + else + { + SplashKit.ShowMouse(); + } + + SplashKit.ClearScreen(Color.White); + SplashKit.FillCircle(Color.Black, blackHole); + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + @@ -1296,6 +1732,9 @@ int main() + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -1325,6 +1764,43 @@ while (!WindowCloseRequested("Mouse Visibility")) CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace MouseVisibility +{ + public class Program + { + public static void Main() + { + Window window = SplashKit.OpenWindow("Mouse Visibility", 800, 600); + Circle spotLight = SplashKit.CircleAt(SplashKit.ScreenCenter(), 100); + + while (!SplashKit.WindowCloseRequested(window)) + { + SplashKit.ProcessEvents(); + + bool isMouseInSpotLight = SplashKit.PointInCircle(SplashKit.MousePosition(), spotLight); + SplashKit.ShowMouse(isMouseInSpotLight); + + SplashKit.ClearScreen(Color.Black); + SplashKit.FillCircle(Color.White, spotLight); + SplashKit.RefreshScreen(60); + } + + SplashKit.CloseAllWindows(); + } + } +} + +``` + + + + From 73a087e7b90296a9e258c7c4147f4ef6a838ab8c Mon Sep 17 00:00:00 2001 From: Srainyyyy <163366419+Srainyyyy@users.noreply.github.com> Date: Tue, 1 Oct 2024 16:31:13 +1000 Subject: [PATCH 06/30] Reading JSON data Tutorial - C# Language Update (#186) --- .../docs/guides/JSON/1-json_reading.mdx | 79 ++++++++++++++++++- 1 file changed, 75 insertions(+), 4 deletions(-) diff --git a/src/content/docs/guides/JSON/1-json_reading.mdx b/src/content/docs/guides/JSON/1-json_reading.mdx index c0f8f734..e56cb6de 100644 --- a/src/content/docs/guides/JSON/1-json_reading.mdx +++ b/src/content/docs/guides/JSON/1-json_reading.mdx @@ -2,8 +2,8 @@ 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 +author: Jonathan Tynan and Yuyang Yang +lastupdated: Sep 14 2024 sidebar: label: "Reading JSON Data" --- @@ -18,7 +18,7 @@ _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. +In the previous tutorial we loaded the following 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 { @@ -50,18 +50,33 @@ bool isFullScreen = json_read_bool(game_data, "fullScreenMode"); + + + ```csharp string title = JsonReadString(gameData, "gameTitle"); int numPlayers = JsonReadNumberAsInt(gameData, "numPlayers"); bool isFullScreen = JsonReadBool(gameData, "fullScreenMode"); ``` + + + +```csharp +string title = SplashKit.JsonReadString(gameData, "gameTitle"); +int numPlayers = SplashKit.JsonReadNumberAsInt(gameData, "numPlayers"); +bool isFullScreen = SplashKit.JsonReadBool(gameData, "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. +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: @@ -86,6 +101,9 @@ for(int i = 0; i < num_levels; i++) + + + ```csharp using SplashKitSDK; @@ -106,6 +124,44 @@ for (int i = 0; i < numLevels; i++) } ``` + + + +```csharp + +using SplashKitSDK; +using System.Collections.Generic; + +namespace ReadingJsonData +{ + public class Program + { + public static void Main() + { + string filePath = "game_data.json"; + + Json gameData = SplashKit.JsonFromFile(filePath); + + List levels = new List(); + + SplashKit.JsonReadArray(gameData, "levels", ref levels); + + int numLevels = levels.Count; + + for (int i = 0; i < numLevels; i++) + { + SplashKit.WriteLine($"Got level: {levels[i]}"); + } + + SplashKit.FreeJson(gameData); + } + } +} +``` + + + + @@ -134,12 +190,27 @@ int height = json_read_number_as_int(game_screen_size, "height"); + + + ```csharp Json gameScreenSize = JsonReadObject(gamedata, "screenSize"); int width = JsonReadNumberAsInt(gameScreenSize, "width"); int height = JsonReadNumberAsInt(gameScreenSize, "height"); ``` + + + +```csharp +Json gameScreenSize = SplashKit.JsonReadObject(gamedata, "screenSize"); +int width = SplashKit.JsonReadNumberAsInt(gameScreenSize, "width"); +int height = SplashKit.JsonReadNumberAsInt(gameScreenSize, "height"); +``` + + + + From 6b8688c571c2a39163c717293053d30a4f62a08d Mon Sep 17 00:00:00 2001 From: Srainyyyy <163366419+Srainyyyy@users.noreply.github.com> Date: Tue, 1 Oct 2024 16:47:55 +1000 Subject: [PATCH 07/30] Writing JSON data Tutorial - C# Language Update (#190) --- .../docs/guides/JSON/2-json_writing.mdx | 185 ++++++++++++++++-- 1 file changed, 174 insertions(+), 11 deletions(-) diff --git a/src/content/docs/guides/JSON/2-json_writing.mdx b/src/content/docs/guides/JSON/2-json_writing.mdx index 60c0514e..c233ca65 100644 --- a/src/content/docs/guides/JSON/2-json_writing.mdx +++ b/src/content/docs/guides/JSON/2-json_writing.mdx @@ -2,8 +2,8 @@ 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 +author: Jonathan Tynan and Yuyang Yang +lastupdated: Sep 20 2024 sidebar: label: "Writing JSON Data" --- @@ -31,9 +31,11 @@ json_set_number(new_game_data, "numPlayers", 1); ``` - + + + ```csharp Json newGameData = CreateJson(); JsonSetString(newGameData, "gameTitle", "My New Game"); @@ -41,6 +43,19 @@ JsonSetBool(newGameData, "fullScreenMode", false); JsonSetNumber(newGameData, "numPlayers", 1); ``` + + + +```csharp +Json newGameData = SplashKit.CreateJson(); +SplashKit.JsonSetString(newGameData, "gameTitle", "My New Game"); +SplashKit.JsonSetBool(newGameData, "fullScreenMode", false); +SplashKit.JsonSetNumber(newGameData, "numPlayers", 1); +``` + + + + @@ -60,12 +75,13 @@ json_set_array(new_game_data, "levels", levels_array); ``` - + + + ```csharp List levelsArray = new List - { "level1", "level2", @@ -75,6 +91,24 @@ List levelsArray = new List JsonSetArray(newGameData, "levels", levelsArray); ``` + + + +```csharp +List levelsArray = new List +{ + "level1", + "level2", + "level3" +}; + +SplashKit.JsonSetArray(newGameData, "levels", levelsArray); + +``` + + + + @@ -93,9 +127,11 @@ json_set_object(new_game_data, "screenSize", screen_size_data); ``` - + + + ```csharp Json screenSizeData = CreateJson(); JsonSetNumber(screenSizeData, "width", 800); @@ -104,6 +140,20 @@ JsonSetNumber(screenSizeData, "height", 600); JsonSetObject(newGameData, "screenSize", screenSizeData); ``` + + + +```csharp +Json screenSizeData = SplashKit.CreateJson(); +SplashKit.JsonSetNumber(screenSizeData, "width", 800); +SplashKit.JsonSetNumber(screenSizeData, "height", 600); + +SplashKit.JsonSetObject(newGameData, "screenSize", screenSizeData); +``` + + + + @@ -121,14 +171,26 @@ json_to_file(new_game_data, "new_game_data.json"); ``` - + + + ```csharp JsonToFile(newGameData, "new_game_data.json"); ``` + + + +```csharp +SplashKit.JsonToFile(newGameData, "new_game_data.json"); +``` + + + + @@ -170,9 +232,11 @@ int main() ``` - + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -205,6 +269,52 @@ FreeJson(newGameData); FreeJson(screenSizeData); ``` + + + +```csharp +using SplashKitSDK; +using System.Collections.Generic; + +namespace WritingJsonData +{ + public class Program + { + public static void Main() + { + Json newGameData = SplashKit.CreateJson(); + + SplashKit.JsonSetString(newGameData, "gameTitle", "My New Game"); + SplashKit.JsonSetBool(newGameData, "fullScreenMode", false); + SplashKit.JsonSetNumber(newGameData, "numPlayers", 1); + + Json screenSizeData = SplashKit.CreateJson(); + SplashKit.JsonSetNumber(screenSizeData, "width", 800); + SplashKit.JsonSetNumber(screenSizeData, "height", 600); + + SplashKit.JsonSetObject(newGameData, "screenSize", screenSizeData); + + List levelsArray = new List + { + "level1", + "level2", + "level3" + }; + + SplashKit.JsonSetArray(newGameData, "levels", levelsArray); + + SplashKit.JsonToFile(newGameData, "new_game_data.json"); + + SplashKit.FreeJson(newGameData); + SplashKit.FreeJson(screenSizeData); + } + } +} +``` + + + + @@ -249,9 +359,11 @@ json_set_object(player_data, "stats", stats_data); ``` - + + + ```csharp Json playerData = CreateJson(); JsonSetString(playerData, "name", "Hero"); @@ -264,6 +376,24 @@ JsonSetNumber(statsData, "strength", 75); JsonSetObject(playerData, "stats", statsData); ``` + + + +```csharp +Json playerData = SplashKit.CreateJson(); +SplashKit.JsonSetString(playerData, "name", "Hero"); + +Json statsData = SplashKit.CreateJson(); +SplashKit.JsonSetNumber(statsData, "health", 100); +SplashKit.JsonSetNumber(statsData, "mana", 50); +SplashKit.JsonSetNumber(statsData, "strength", 75); + +SplashKit.JsonSetObject(playerData, "stats", statsData); +``` + + + + @@ -280,15 +410,29 @@ json_to_file(existing_data, "modified_game_data.json"); ``` - + + + ```csharp Json existingData = JsonFromFile("new_game_data.json"); JsonSetObject(existingData, "character", playerData); JsonToFile(existingData, "modified_game_data.json"); ``` + + + +```csharp +Json existingData = SplashKit.JsonFromFile("new_game_data.json"); +SplashKit.JsonSetObject(existingData, "character", playerData); +SplashKit.JsonToFile(existingData, "modified_game_data.json"); +``` + + + + @@ -336,9 +480,11 @@ int hp = json_read_number_as_int(stats, "health"); ``` - + + + ```csharp // Load our JSON Json modifiedGameData = JsonFromFile("modified_game_data.json"); @@ -350,6 +496,23 @@ Json stats = JsonReadObject(character, "stats"); int hp = JsonReadNumberAsInt(stats, "health"); ``` + + + +```csharp +// Load our JSON +Json modifiedGameData = SplashKit.JsonFromFile("modified_game_data.json"); +// Retrieve Character JSON object from the file. +Json character = SplashKit.JsonReadObject(modifiedGameData, "character"); +// Retrieve the Stats JSON object from the Character JSON +Json stats = SplashKit.JsonReadObject(character, "stats"); +// Retrieve the value of health from the stats JSON object +int hp = SplashKit.JsonReadNumberAsInt(stats, "health"); +``` + + + + From 4855ae0242b915418bfe456ad3f2b4a0cc4e1f9a Mon Sep 17 00:00:00 2001 From: Srainyyyy <163366419+Srainyyyy@users.noreply.github.com> Date: Tue, 1 Oct 2024 17:04:25 +1000 Subject: [PATCH 08/30] Introduction to json tutorial c# language update (#175) --- src/content/docs/guides/JSON/0-json_intro.mdx | 125 +++++++++++++----- 1 file changed, 91 insertions(+), 34 deletions(-) diff --git a/src/content/docs/guides/JSON/0-json_intro.mdx b/src/content/docs/guides/JSON/0-json_intro.mdx index d858428c..e3a45f99 100644 --- a/src/content/docs/guides/JSON/0-json_intro.mdx +++ b/src/content/docs/guides/JSON/0-json_intro.mdx @@ -2,8 +2,8 @@ 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 +author: Jonathan Tynan and Yuyang Yang +lastupdated: Sep 10 2024 sidebar: label: "Introduction to JSON" --- @@ -54,41 +54,66 @@ This command creates sub-folders for each type of resource. One of these is name - ```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"); +```cpp +#include "splashkit.h" +int main() +{ + json game_data = json_from_file("game_data.json"); + string game_title = json_read_string(game_data, "gameTitle"); + + write_line("Game Title: " + game_title); + + free_json(game_data); + + return 0; +} +``` + + + + + + + +```csharp +using SplashKitSDK; +using static SplashKitSDK.SplashKit; - write("Game Title: "); - write_line(game_title); +Json gameData = JsonFromFile("game_data.json"); +string gameTitle = JsonReadString(gameData, "gameTitle"); - free_json(game_data); +WriteLine("Game Title: " + gameTitle); - return 0; - } - ``` +FreeJson(gameData); +``` - - - + + - ```csharp - using SplashKitSDK; - using static SplashKitSDK.SplashKit; +```csharp +using SplashKitSDK; - Json gameData = JsonFromFile("game_data.json"); +namespace GameDataManagement +{ + public class Program + { + public static void Main() + { + Json gameData = SplashKit.JsonFromFile(game_data.json); + string gameTitle = SplashKit.JsonReadString(gameData, "gameTitle"); - string gameTitle = JsonReadString(gameData, "gameTitle"); + SplashKit.WriteLine("Game Title: " + gameTitle); - WriteLine("Game Title: " + gameTitle); + SplashKit.FreeJson(gameData); + } + } +} +``` - FreeJson(gameData); - ``` + + - + 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. @@ -121,7 +146,6 @@ And run it with: ``` - ```shell @@ -129,7 +153,6 @@ dotnet run ``` - When we run this program it should output the following to the console: @@ -149,8 +172,7 @@ But what if we didn't have a `gameTitle` key in our JSON? Well, error messages w #include "splashkit.h" int main() { - json game_data; - game_data = json_from_file("game_data.json"); + json game_data = json_from_file("game_data.json"); if(json_has_key(game_data, "gameTitle")) { @@ -170,14 +192,16 @@ int main() ``` - + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; -Json gameData =JsonFromFile("game_data.json"); +Json gameData = JsonFromFile("game_data.json"); if (JsonHasKey(gameData, "gameTitle")) { @@ -189,10 +213,43 @@ else WriteLine("Key \"gameTitle\" not found."); } - FreeJson(gameData); +FreeJson(gameData); +``` + + + + +```csharp +using SplashKitSDK; + +namespace GameDataManagement +{ + public class Program + { + public static void Main() + { + Json gameData = SplashKit.JsonFromFile("game_data.json"); + + if (SplashKit.JsonHasKey(gameData, "gameTitle")) + { + string gameTitle = SplashKit.JsonReadString(gameData, "gameTitle"); + SplashKit.WriteLine("Game Title: " + gameTitle); + } + else + { + SplashKit.WriteLine("Key \"gameTitle\" not found."); + } + + SplashKit.FreeJson(gameData); + } + } +} ``` + + + 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. From 031ecfda941ad86d13fa74e175f15aa16ba50f9f Mon Sep 17 00:00:00 2001 From: s223126445 <162955558+s223126445@users.noreply.github.com> Date: Tue, 1 Oct 2024 17:34:52 +1000 Subject: [PATCH 09/30] Splashkit camera - C# Language update (#183) --- .../Camera/0-using-splashkit-camera.mdx | 550 +++++++++++------- 1 file changed, 326 insertions(+), 224 deletions(-) diff --git a/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx b/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx index b241a784..41953f87 100644 --- a/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx +++ b/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx @@ -1,8 +1,8 @@ --- title: SplashKit Camera description: See how the camera works, and how to draw to the different coordinate systems in your program. -author: Andrew Cain -lastupdated: 16 Aug 2018 +author: Andrew Cain and Mounika Angadipeta +lastupdated: September 2024 category: Guides --- @@ -62,236 +62,338 @@ The following program code demonstrates the use of some of these camera operatio - ```cpp - #include "splashkit.h" - - #define SCREEN_BORDER 100 - - void update_camera_position(double player_x, double player_y) - { - // Test edge of screen boundaries to adjust the camera - double left_edge = camera_x() + SCREEN_BORDER; - double right_edge = left_edge + screen_width() - 2 * SCREEN_BORDER; - double top_edge = camera_y() + SCREEN_BORDER; - double bottom_edge = top_edge + screen_height() - 2 * SCREEN_BORDER; - - // Test if the player is outside the area and move the camera - // the player will appear to stay still and everything else - // will appear to move :) - - // Test top/bottom of screen - if (player_y < top_edge) - { - move_camera_by(0, player_y - top_edge); - } - else if (player_y > bottom_edge) - { - move_camera_by(0, player_y - bottom_edge); - } - - // Test left/right of screen - if (player_x < left_edge) - { - move_camera_by(player_x - left_edge, 0); - } - else if (player_x > right_edge) - { - move_camera_by(player_x - right_edge, 0); - } - } - - int main() - { - open_window("Camera Test", 800, 800); - - double player_x = 400, player_y = 400; - - while (not quit_requested()) - { - // Handle input to adjust player movement - process_events(); - - if (key_down(LEFT_KEY)) - player_x -= 3; - if (key_down(RIGHT_KEY)) - player_x += 3; - if (key_down(DOWN_KEY)) - player_y += 3; - if (key_down(UP_KEY)) - player_y -= 3; - - update_camera_position(player_x, player_y); - - // Redraw everything - clear_screen(COLOR_BLACK); - - // Draw to the screen - fill_rectangle(COLOR_DIM_GRAY, 0, 0, screen_width(), 50, option_to_screen()); - draw_text("HUD", COLOR_WHITE, 10, 10, option_to_screen()); - draw_text("Camera Position: " + point_to_string(camera_position()), COLOR_WHITE, 10, 30, option_to_screen()); - - // as well as the player who can move - fill_circle(COLOR_YELLOW, player_x, player_y, 20); - - // including something stationary - it doesn't move - fill_rectangle(COLOR_WHITE, 400, 200, 10, 10); - - refresh_screen(60); - } - - close_all_windows(); - return 0; - } - ``` +```cpp +#include "splashkit.h" + +void update_camera_position(double player_x, double player_y) +{ + const int SCREEN_BORDER = 100; + + // Test edge of screen boundaries to adjust the camera + double left_edge = camera_x() + SCREEN_BORDER; + double right_edge = left_edge + screen_width() - 2 * SCREEN_BORDER; + double top_edge = camera_y() + SCREEN_BORDER; + double bottom_edge = top_edge + screen_height() - 2 * SCREEN_BORDER; + + // Test if the player is outside the area and move the camera + // the player will appear to stay still and everything else + // will appear to move :) + + // Test top/bottom of screen + if (player_y < top_edge) + { + move_camera_by(0, player_y - top_edge); + } + else if (player_y > bottom_edge) + { + move_camera_by(0, player_y - bottom_edge); + } + + // Test left/right of screen + if (player_x < left_edge) + { + move_camera_by(player_x - left_edge, 0); + } + else if (player_x > right_edge) + { + move_camera_by(player_x - right_edge, 0); + } +} + +int main() +{ + open_window("Camera Test", 800, 800); + + double player_x = 400, player_y = 400; + + while (not quit_requested()) + { + // Handle input to adjust player movement + process_events(); + + if (key_down(LEFT_KEY)) + player_x -= 3; + if (key_down(RIGHT_KEY)) + player_x += 3; + if (key_down(DOWN_KEY)) + player_y += 3; + if (key_down(UP_KEY)) + player_y -= 3; + + update_camera_position(player_x, player_y); + + // Redraw everything + clear_screen(COLOR_BLACK); + + // Draw to the screen + fill_rectangle(COLOR_DIM_GRAY, 0, 0, screen_width(), 50, option_to_screen()); + draw_text("HUD", COLOR_WHITE, 10, 10, option_to_screen()); + draw_text("Camera Position: " + point_to_string(camera_position()), COLOR_WHITE, 10, 30, option_to_screen()); + + // as well as the player who can move + fill_circle(COLOR_YELLOW, player_x, player_y, 20); + + // including something stationary - it doesn't move + fill_rectangle(COLOR_WHITE, 400, 200, 10, 10); + + refresh_screen(60); + } + + close_all_windows(); + return 0; +} +``` - ```csharp - using SplashKitSDK; - using static SplashKitSDK.SplashKit; - - const int SCREEN_BORDER = 100; - - static void UpdateCameraPosition(double playerX, double playerY) - { - // Test edge of screen boundaries to adjust the camera - double leftEdge = Camera.X + SCREEN_BORDER; - double rightEdge = leftEdge + ScreenWidth() - 2 * SCREEN_BORDER; - double topEdge = Camera.Y + SCREEN_BORDER; - double bottomEdge = topEdge + ScreenHeight() - 2 * SCREEN_BORDER; - - // Test if the player is outside the area and move the camera - // the player will appear to stay still and everything else - // will appear to move :) - - // Test top/bottom of screen - if (playerY < topEdge) - { - MoveCameraBy(0, playerY - topEdge); - } - else if (playerY > bottomEdge) - { - MoveCameraBy(0, playerY - bottomEdge); - } - - // Test left/right of screen - if (playerX < leftEdge) - { - MoveCameraBy(playerX - leftEdge, 0); - } - else if (playerX > rightEdge) - { - MoveCameraBy(playerX - rightEdge, 0); - } - } - - // Start of "main" code - OpenWindow("Camera Test", 800, 800); - - double playerX = 400, playerY = 400; - - while (!QuitRequested()) - { - // Handle input to adjust player movement - ProcessEvents(); - - if (KeyDown(KeyCode.LeftKey)) - playerX -= 3; - if (KeyDown(KeyCode.RightKey)) - playerX += 3; - if (KeyDown(KeyCode.DownKey)) - playerY += 3; - if (KeyDown(KeyCode.UpKey)) - playerY -= 3; - - UpdateCameraPosition(playerX, playerY); - - // Redraw everything - ClearScreen(ColorBlack()); - - // Draw to the screen - FillRectangle(ColorDimGray(), 0, 0, ScreenWidth(), 50, OptionToScreen()); - DrawText("HUD", ColorWhite(), 10, 10, OptionToScreen()); - DrawText("Camera Position: " + PointToString(Camera.Position), Color.White, 10, 30, OptionToScreen()); - - // as well as the player who can move - FillCircle(ColorYellow(), playerX, playerY, 20); - - // including something stationary - it doesn't move - FillRectangle(ColorWhite(), 400, 200, 10, 10); - - RefreshScreen(60); - } - CloseAllWindows(); - ``` + + + +```csharp +using SplashKitSDK; +using static SplashKitSDK.SplashKit; + + +static void UpdateCameraPosition(double playerX, double playerY) +{ + const int SCREEN_BORDER = 100; + + // Test edge of screen boundaries to adjust the camera + double leftEdge = CameraX() + SCREEN_BORDER; + double rightEdge = leftEdge + ScreenWidth() - 2 * SCREEN_BORDER; + double topEdge = CameraY() + SCREEN_BORDER; + double bottomEdge = topEdge + ScreenHeight() - 2 * SCREEN_BORDER; + + // Test if the player is outside the area and move the camera + // the player will appear to stay still and everything else + // will appear to move :) + + // Test top/bottom of screen + if (playerY < topEdge) + { + MoveCameraBy(0, playerY - topEdge); + } + else if (playerY > bottomEdge) + { + MoveCameraBy(0, playerY - bottomEdge); + } + + // Test left/right of screen + if (playerX < leftEdge) + { + MoveCameraBy(playerX - leftEdge, 0); + } + else if (playerX > rightEdge) + { + MoveCameraBy(playerX - rightEdge, 0); + } +} + +// Start of "main" code +OpenWindow("Camera Test", 800, 800); + +double playerX = 400, playerY = 400; + +while (!QuitRequested()) +{ + // Handle input to adjust player movement + ProcessEvents(); + + if (KeyDown(KeyCode.LeftKey)) + playerX -= 3; + if (KeyDown(KeyCode.RightKey)) + playerX += 3; + if (KeyDown(KeyCode.DownKey)) + playerY += 3; + if (KeyDown(KeyCode.UpKey)) + playerY -= 3; + + UpdateCameraPosition(playerX, playerY); + + // Redraw everything + ClearScreen(ColorBlack()); + + // Draw to the screen + FillRectangle(ColorDimGray(), 0, 0, ScreenWidth(), 50, OptionToScreen()); + DrawText("HUD", ColorWhite(), 10, 10, OptionToScreen()); + DrawText("Camera Position: " + PointToString(CameraPosition()), ColorWhite(), 10, 30, OptionToScreen()); + + // as well as the player who can move + FillCircle(ColorYellow(), playerX, playerY, 20); + + // including something stationary - it doesn't move + FillRectangle(ColorWhite(), 400, 200, 10, 10); + + RefreshScreen(60); +} + +CloseAllWindows(); +``` + + + + +```csharp +using SplashKitSDK; + +namespace SplashKitCamera +{ + public class Program + { + public static void UpdateCameraPosition(double playerX, double playerY) + { + const int SCREEN_BORDER = 100; + + // Test edge of screen boundaries to adjust the camera + double leftEdge = Camera.X + SCREEN_BORDER; + double rightEdge = leftEdge + SplashKit.ScreenWidth() - 2 * SCREEN_BORDER; + double topEdge = Camera.Y + SCREEN_BORDER; + double bottomEdge = topEdge + SplashKit.ScreenHeight() - 2 * SCREEN_BORDER; + + // Test if the player is outside the area and move the camera + // the player will appear to stay still and everything else + // will appear to move :) + + // Test top/bottom of screen + if (playerY < topEdge) + { + SplashKit.MoveCameraBy(0, playerY - topEdge); + } + else if (playerY > bottomEdge) + { + SplashKit.MoveCameraBy(0, playerY - bottomEdge); + } + + // Test left/right of screen + if (playerX < leftEdge) + { + SplashKit.MoveCameraBy(playerX - leftEdge, 0); + } + else if (playerX > rightEdge) + { + SplashKit.MoveCameraBy(playerX - rightEdge, 0); + } + } + + public static void Main() + { + Window window = SplashKit.OpenWindow("Camera Test", 800, 800); + + double playerX = 400, playerY = 400; + + while (!window.CloseRequested) + { + SplashKit.ProcessEvents(); + + // Handle input + if (SplashKit.KeyDown(KeyCode.LeftKey)) + playerX -= 3; + if (SplashKit.KeyDown(KeyCode.RightKey)) + playerX += 3; + if (SplashKit.KeyDown(KeyCode.DownKey)) + playerY += 3; + if (SplashKit.KeyDown(KeyCode.UpKey)) + playerY -= 3; + + UpdateCameraPosition(playerX, playerY); + + // Redraw everything + window.Clear(Color.Black); + + // Draw to the screen + window.FillRectangle(Color.DimGray, 0, 0, SplashKit.ScreenWidth(), 50, SplashKit.OptionToScreen()); + window.DrawText("HUD", Color.White, 10, 10, SplashKit.OptionToScreen()); + window.DrawText("Camera Position: " + SplashKit.PointToString(Camera.Position), Color.White, 10, 30, SplashKit.OptionToScreen()); + + // as well as the player who can move + window.FillCircle(Color.Yellow, playerX, playerY, 20); + + // including something stationary - it doesn't move + window.FillRectangle(Color.White, 400, 200, 10, 10); + + window.Refresh(60); + } + + SplashKit.CloseAllWindows(); + } + } +} +``` + + + - ```python - from splashkit import * - - SCREEN_BORDER = 100 - - def update_camera_position(player_x, player_y): - - # Test edge of screen boundaries to adjust the camera - left_edge = camera_x() + SCREEN_BORDER - right_edge = left_edge + screen_width() - 2 * SCREEN_BORDER - top_edge = camera_y() + SCREEN_BORDER - bottom_edge = top_edge + screen_height() - 2 * SCREEN_BORDER - - # Test if the player is outside the area and move the camera - # the player will appear to stay still and everything else - # will appear to move :) - - # Test top/bottom of screen - if player_y < top_edge: - move_camera_by(0, player_y - top_edge) - elif player_y > bottom_edge: - move_camera_by(0, player_y - bottom_edge) - - # Test left/right of screen - if player_x < left_edge: - move_camera_by(player_x - left_edge, 0) - elif player_x > right_edge: - move_camera_by(player_x - right_edge, 0) - - # Start of "main" code - open_window("Camera Test", 800, 800) - - player_x, player_y = 400, 400 - - while not quit_requested(): - # Handle input to adjust player movement - process_events() - - if key_down(KeyCode.left_key): player_x -= 3 - if key_down(KeyCode.right_key): player_x += 3 - if key_down(KeyCode.down_key): player_y += 3 - if key_down(KeyCode.up_key): player_y -= 3 - - update_camera_position(player_x, player_y) - - # Redraw everything - clear_screen(color_black()) - - # Draw to the screen - fill_rectangle(color_white(), 0, 0, screen_width(), 50, option_to_screen()) - draw_text_no_font_no_size_with_options("HUD", color_white(), 10, 10, option_to_screen()) - draw_text_no_font_no_size_with_options(f"Camera Position: {point_to_string(camera_position())}", color_white(), 10, 30, option_to_screen()) - - # as well as the player who can move - fill_circle(color_yellow(), player_x, player_y, 20) - - # including something stationary - it doesn't move - fill_rectangle(color_white(), 400, 200, 10, 10) - - refresh_screen_with_target_fps(60) - - close_all_windows() - ``` +```python +from splashkit import * + +SCREEN_BORDER = 100 + +def update_camera_position(player_x, player_y): + + # Test edge of screen boundaries to adjust the camera + left_edge = camera_x() + SCREEN_BORDER + right_edge = left_edge + screen_width() - 2 * SCREEN_BORDER + top_edge = camera_y() + SCREEN_BORDER + bottom_edge = top_edge + screen_height() - 2 * SCREEN_BORDER + + # Test if the player is outside the area and move the camera + # the player will appear to stay still and everything else + # will appear to move :) + + # Test top/bottom of screen + if player_y < top_edge: + move_camera_by(0, player_y - top_edge) + elif player_y > bottom_edge: + move_camera_by(0, player_y - bottom_edge) + + # Test left/right of screen + if player_x < left_edge: + move_camera_by(player_x - left_edge, 0) + elif player_x > right_edge: + move_camera_by(player_x - right_edge, 0) + +# Start of "main" code +open_window("Camera Test", 800, 800) + +player_x, player_y = 400, 400 + +while not quit_requested(): + # Handle input to adjust player movement + process_events() + + if key_down(KeyCode.left_key): + player_x -= 3 + if key_down(KeyCode.right_key): + player_x += 3 + if key_down(KeyCode.down_key): + player_y += 3 + if key_down(KeyCode.up_key): + player_y -= 3 + + update_camera_position(player_x, player_y) + + # Redraw everything + clear_screen(color_black()) + + # Draw to the screen + fill_rectangle(color_white(), 0, 0, screen_width(), 50, option_to_screen()) + draw_text_no_font_no_size_with_options("HUD", color_white(), 10, 10, option_to_screen()) + draw_text_no_font_no_size_with_options(f"Camera Position: {point_to_string(camera_position())}", color_white(), 10, 30, option_to_screen()) + + # as well as the player who can move + fill_circle(color_yellow(), player_x, player_y, 20) + + # including something stationary - it doesn't move + fill_rectangle(color_white(), 400, 200, 10, 10) + + refresh_screen_with_target_fps(60) + +close_all_windows() +``` From 47c597093cc8c4e99847a05179c06edf57bc3ad7 Mon Sep 17 00:00:00 2001 From: Oliver Exell-Bruce <87453519+oliverexell-bruce@users.noreply.github.com> Date: Tue, 1 Oct 2024 17:45:31 +1000 Subject: [PATCH 10/30] Add C# OOP to "Using Animations in SplashKit" tutorial (#194) --- .../guides/Animations/0-using-animations.mdx | 193 ++++++++++++++++++ 1 file changed, 193 insertions(+) diff --git a/src/content/docs/guides/Animations/0-using-animations.mdx b/src/content/docs/guides/Animations/0-using-animations.mdx index 4d25bcb3..d042593d 100644 --- a/src/content/docs/guides/Animations/0-using-animations.mdx +++ b/src/content/docs/guides/Animations/0-using-animations.mdx @@ -231,6 +231,9 @@ This includes sample animation scripts, images, and sounds. + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -299,6 +302,91 @@ This includes sample animation scripts, images, and sounds. CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace UsingAnimations +{ + public class Program + { + public static void Main() + { + Window window = new Window("Animation Test", 120, 120); + + // // We could load all of the resources in a bundle + // LoadResourceBundle("dance bundle", "dance_bundle.txt"); + + // // Then access by name + // AnimationScript danceScript = AnimationScriptNamed("WalkingScript"); + // Bitmap frog = BitmapNamed("FrogBmp"); + + // Loading them separately + + // Load image and set its cell details + + Bitmap frog = new Bitmap("FrogBmp", "frog.png"); + frog.SetCellDetails(73, 105, 4, 4, 16); // cell width, height, cols, rows, count + + // Load the animation script + + AnimationScript danceScript = new AnimationScript("WalkingScript", "kermit.txt"); + + // Create the animation + Animation frogAnimation = danceScript.CreateAnimation("WalkFront"); + + // Create a drawing option + DrawingOptions opt = SplashKit.OptionWithAnimation(frogAnimation); + + + // Basic event loop + while (!window.CloseRequested) + { + SplashKit.ProcessEvents(); + + // Draw the bitmap - using opt to link to animation + window.Clear(Color.White); + frog.Draw(20, 20, opt); + window.DrawText(frogAnimation.Name, Color.Black, 0, 0); + window.Refresh(60); + + // Update the animation + frogAnimation.Update(); + + // Switch animations + if (SplashKit.KeyTyped(KeyCode.UpKey)) + { + frogAnimation.Assign("WalkBack"); + } + else if (SplashKit.KeyTyped(KeyCode.DownKey)) + { + frogAnimation.Assign("WalkFront"); + } + else if (SplashKit.KeyTyped(KeyCode.LeftKey)) + { + frogAnimation.Assign("WalkLeft"); + } + else if (SplashKit.KeyTyped(KeyCode.RightKey)) + { + frogAnimation.Assign("WalkRight"); + } + else if (SplashKit.KeyTyped(KeyCode.DKey)) + { + frogAnimation.Assign("Dance"); + } + } + + SplashKit.CloseAllWindows(); + } + } +} +``` + + + + @@ -410,6 +498,9 @@ Here is a another example, where the **Left Shift Key** can be **held down** to + + + ```csharp using SplashKitSDK; using static SplashKitSDK.SplashKit; @@ -497,6 +588,108 @@ Here is a another example, where the **Left Shift Key** can be **held down** to CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace UsingAnimations +{ + public class Program + { + public static void Main() + { + Window window = new Window("Animation Test", 120, 120); + + // We could load all of the resources in a bundle + SplashKit.LoadResourceBundle("dance bundle", "dance_bundle.txt"); + + // Then access by name + AnimationScript danceScript = SplashKit.AnimationScriptNamed("WalkingScript"); + Bitmap frog = SplashKit.BitmapNamed("FrogBmp"); + + // Create the animation + Animation frogAnimation = danceScript.CreateAnimation("WalkFront"); + + // Create a drawing option + DrawingOptions opt = SplashKit.OptionWithAnimation(frogAnimation); + + + // Basic event loop + while (!window.CloseRequested) + { + SplashKit.ProcessEvents(); + + // Draw the bitmap - using opt to link to animation + window.Clear(Color.White); + frog.Draw(20, 20, opt); + window.DrawText(frogAnimation.Name, Color.Black, 0, 0); + window.Refresh(60); + + // Update the animation + frogAnimation.Update(); + + // Switch animations + if (SplashKit.KeyTyped(KeyCode.UpKey)) + { + if (SplashKit.KeyDown(KeyCode.LeftShiftKey)) + { + frogAnimation.Assign("MoonWalkBack"); + } + else + { + frogAnimation.Assign("WalkBack"); + } + } + else if (SplashKit.KeyTyped(KeyCode.DownKey)) + { + if (SplashKit.KeyDown(KeyCode.LeftShiftKey)) + { + frogAnimation.Assign("MoonWalkFront"); + } + else + { + frogAnimation.Assign("WalkFront"); + } + } + else if (SplashKit.KeyTyped(KeyCode.LeftKey)) + { + if (SplashKit.KeyDown(KeyCode.LeftShiftKey)) + { + frogAnimation.Assign("MoonWalkLeft"); + } + else + { + frogAnimation.Assign("WalkLeft"); + } + } + else if (SplashKit.KeyTyped(KeyCode.RightKey)) + { + if (SplashKit.KeyDown(KeyCode.LeftShiftKey)) + { + frogAnimation.Assign("MoonWalkRight"); + } + else + { + frogAnimation.Assign("WalkRight"); + } + } + else if (SplashKit.KeyTyped(KeyCode.DKey)) + { + frogAnimation.Assign("Dance"); + } + } + + SplashKit.CloseAllWindows(); + } + } +} +``` + + + + From 2276e351c233d9177d842d5bd7673866a5d3f5d4 Mon Sep 17 00:00:00 2001 From: omckeon Date: Tue, 1 Oct 2024 08:17:50 +0000 Subject: [PATCH 11/30] Improved audio guide code formatting --- .../Audio/0-getting-started-with-audio.mdx | 444 +++++++++--------- 1 file changed, 222 insertions(+), 222 deletions(-) diff --git a/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx b/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx index aaf420d5..1622d12e 100644 --- a/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx +++ b/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx @@ -82,6 +82,51 @@ This includes sample sounds, and a font ("arial"). ```cpp #include "splashkit.h" +void draw_instructions() +{ + // SplashKit Orange background + clear_screen(rgb_color(245, 166, 35)); + + // Draw heading + set_font_style("arial", BOLD_FONT); + draw_text("Keyboard Controls", COLOR_BLACK, "arial", 20, (screen_width() - text_width("Keyboard Controls", "arial", 20)) / 2, 10); + set_font_style("arial", NORMAL_FONT); + + // Draw left box with SplashKit Cyan/Teal bo + fill_rectangle(rgb_color(5, 172, 193), 10, 45, screen_width() / 2 + 10, screen_height() - 85); + fill_rectangle(COLOR_PAPAYA_WHIP, 20, 55, screen_width() / 2 - 10, screen_height() - 105); + draw_line(COLOR_LIGHT_GRAY, 30, 105, screen_width() / 2, 105); + + // Playing sound effect controls text + draw_text("Playing Sound Controls", COLOR_BLACK, "arial", 18, 80, 70); + draw_text("[1] Play Sound At Full Volume", COLOR_BLACK, "arial", 14, 30, 120); + draw_text("[2] Play Sound At 50% Volume", COLOR_BLACK, "arial", 14, 30, 150); + draw_text("[3] Play Sound 3 Times At 25% Volume", COLOR_BLACK, "arial", 14, 30, 180); + draw_text("[4] Play Sound Continuously at 10% Volume", COLOR_BLACK, "arial", 14, 30, 210); + draw_text("[5] Stop Playing Current Sound", COLOR_BLACK, "arial", 14, 30, 240); + + // Exit text + set_font_style("arial", ITALIC_FONT); + draw_text("Press [Escape] or [Q] to quit", COLOR_BLACK, "arial", 16, 65, 290); + set_font_style("arial", NORMAL_FONT); + + // Draw left box with SplashKit Cyan/Teal bo + fill_rectangle(rgb_color(5, 172, 193), screen_width() / 2 + 30, 45, screen_width() / 2 - 40, screen_height() - 55); + fill_rectangle(COLOR_PAPAYA_WHIP, screen_width() / 2 + 40, 55, screen_width() / 2 - 60, screen_height() - 75); + draw_line(COLOR_LIGHT_GRAY, screen_width() / 2 + 50, 105, screen_width() - 30, 105); + + // Switching to sound effect controls text + draw_text("Switching Sound Controls", COLOR_BLACK, "arial", 18, screen_width() / 2 + 65, 70); + draw_text("[CTRL + 1] Chipmunk Sound", COLOR_BLACK, "arial", 14, screen_width() / 2 + 50, 120); + draw_text("[CTRL + 2] Bells Sound", COLOR_BLACK, "arial", 14, screen_width() / 2 + 50, 150); + draw_text("[CTRL + 3] Camera Sound", COLOR_BLACK, "arial", 14, screen_width() / 2 + 50, 180); + draw_text("[CTRL + 4] Boing Sound", COLOR_BLACK, "arial", 14, screen_width() / 2 + 50, 210); + draw_text("[CTRL + 5] Dinasaur Sound", COLOR_BLACK, "arial", 14, screen_width() / 2 + 50, 240); + draw_text("[CTRL + 6] Bark Sound", COLOR_BLACK, "arial", 14, screen_width() / 2 + 50, 270); + + refresh_screen(60); +} + int main() { sound_effect snd_effect; @@ -135,48 +180,8 @@ int main() } // Drawing Keyboard Controls information in window (focus on sound effect code above) + draw_instructions(); - // SplashKit Orange background - clear_screen(rgb_color(245, 166, 35)); - - // Draw heading - set_font_style("arial", BOLD_FONT); - draw_text("Keyboard Controls", COLOR_BLACK, "arial", 20, (screen_width() - text_width("Keyboard Controls", "arial", 20)) / 2, 10); - set_font_style("arial", NORMAL_FONT); - - // Draw left box with SplashKit Cyan/Teal bo - fill_rectangle(rgb_color(5, 172, 193), 10, 45, screen_width() / 2 + 10, screen_height() - 85); - fill_rectangle(COLOR_PAPAYA_WHIP, 20, 55, screen_width() / 2 - 10, screen_height() - 105); - draw_line(COLOR_LIGHT_GRAY, 30, 105, screen_width() / 2, 105); - - // Playing sound effect controls text - draw_text("Playing Sound Controls", COLOR_RED, "arial", 18, 80, 70); - draw_text("[1] Play Sound At Full Volume", COLOR_BLUE, "arial", 14, 30, 120); - draw_text("[2] Play Sound At 50% Volume", COLOR_BLUE, "arial", 14, 30, 150); - draw_text("[3] Play Sound 3 Times At 25% Volume", COLOR_BLUE, "arial", 14, 30, 180); - draw_text("[4] Play Sound Continuously at 10% Volume", COLOR_BLUE, "arial", 14, 30, 210); - draw_text("[5] Stop Playing Current Sound", COLOR_BLUE, "arial", 14, 30, 240); - - // Exit text - set_font_style("arial", ITALIC_FONT); - draw_text("Press [Escape] or [Q] to quit", COLOR_BLACK, "arial", 16, 65, 290); - set_font_style("arial", NORMAL_FONT); - - // Draw left box with SplashKit Cyan/Teal bo - fill_rectangle(rgb_color(5, 172, 193), screen_width() / 2 + 30, 45, screen_width() / 2 - 40, screen_height() - 55); - fill_rectangle(COLOR_PAPAYA_WHIP, screen_width() / 2 + 40, 55, screen_width() / 2 - 60, screen_height() - 75); - draw_line(COLOR_LIGHT_GRAY, screen_width() / 2 + 50, 105, screen_width() - 30, 105); - - // Switching to sound effect controls text - draw_text("Switching Sound Controls", COLOR_ORANGE_RED, "arial", 18, screen_width() / 2 + 65, 70); - draw_text("[CTRL + 1] Chipmunk Sound", COLOR_DARK_GREEN, "arial", 14, screen_width() / 2 + 50, 120); - draw_text("[CTRL + 2] Bells Sound", COLOR_DARK_GREEN, "arial", 14, screen_width() / 2 + 50, 150); - draw_text("[CTRL + 3] Camera Sound", COLOR_DARK_GREEN, "arial", 14, screen_width() / 2 + 50, 180); - draw_text("[CTRL + 4] Boing Sound", COLOR_DARK_GREEN, "arial", 14, screen_width() / 2 + 50, 210); - draw_text("[CTRL + 5] Dinasaur Sound", COLOR_DARK_GREEN, "arial", 14, screen_width() / 2 + 50, 240); - draw_text("[CTRL + 6] Bark Sound", COLOR_DARK_GREEN, "arial", 14, screen_width() / 2 + 50, 270); - - refresh_screen(60); } while (!(quit_requested() || key_typed(ESCAPE_KEY) || key_typed(Q_KEY))); close_all_windows(); @@ -186,6 +191,7 @@ int main() + @@ -193,6 +199,51 @@ int main() using SplashKitSDK; using static SplashKitSDK.SplashKit; +static void DrawInstructions() +{ + // SplashKit Orange background + ClearScreen(RGBColor(245, 166, 35)); + + // Draw heading + SetFontStyle("arial", FontStyle.BoldFont); + DrawText("Keyboard Controls", ColorBlack(), "arial", 20, (ScreenWidth() - TextWidth("Keyboard Controls", "arial", 20)) / 2, 10); + SetFontStyle("arial", FontStyle.NormalFont); + + // Draw left box with SplashKit Cyan/Teal bo + FillRectangle(RGBColor(5, 172, 193), 10, 45, ScreenWidth() / 2 + 10, ScreenHeight() - 85); + FillRectangle(ColorPapayaWhip(), 20, 55, ScreenWidth() / 2 - 10, ScreenHeight() - 105); + DrawLine(ColorLightGray(), 30, 105, ScreenWidth() / 2, 105); + + // Playing sound effect controls text + DrawText("Playing Sound Controls", ColorBlack(), "arial", 18, 80, 70); + DrawText("[1] Play Sound At Full Volume", ColorBlack(), "arial", 14, 30, 120); + DrawText("[2] Play Sound At 50% Volume", ColorBlack(), "arial", 14, 30, 150); + DrawText("[3] Play Sound 3 Times At 25% Volume", ColorBlack(), "arial", 14, 30, 180); + DrawText("[4] Play Sound Continuously at 10% Volume", ColorBlack(), "arial", 14, 30, 210); + DrawText("[5] Stop Playing Current Sound", ColorBlack(), "arial", 14, 30, 240); + + // Exit text + SetFontStyle("arial", FontStyle.ItalicFont); + DrawText("Press [Escape] or [Q] to quit", ColorBlack(), "arial", 16, 65, 290); + SetFontStyle("arial", FontStyle.NormalFont); + + // Draw left box with SplashKit Cyan/Teal bo + FillRectangle(RGBColor(5, 172, 193), ScreenWidth() / 2 + 30, 45, ScreenWidth() / 2 - 40, ScreenHeight() - 55); + FillRectangle(ColorPapayaWhip(), ScreenWidth() / 2 + 40, 55, ScreenWidth() / 2 - 60, ScreenHeight() - 75); + DrawLine(ColorLightGray(), ScreenWidth() / 2 + 50, 105, ScreenWidth() - 30, 105); + + // Switching to sound effect controls text + DrawText("Switching Sound Controls", ColorBlack(), "arial", 18, ScreenWidth() / 2 + 65, 70); + DrawText("[CTRL + 1] Chipmunk Sound", ColorBlack(), "arial", 14, ScreenWidth() / 2 + 50, 120); + DrawText("[CTRL + 2] Bells Sound", ColorBlack(), "arial", 14, ScreenWidth() / 2 + 50, 150); + DrawText("[CTRL + 3] Camera Sound", ColorBlack(), "arial", 14, ScreenWidth() / 2 + 50, 180); + DrawText("[CTRL + 4] Boing Sound", ColorBlack(), "arial", 14, ScreenWidth() / 2 + 50, 210); + DrawText("[CTRL + 5] Dinasaur Sound", ColorBlack(), "arial", 14, ScreenWidth() / 2 + 50, 240); + DrawText("[CTRL + 6] Bark Sound", ColorBlack(), "arial", 14, ScreenWidth() / 2 + 50, 270); + + RefreshScreen(60); +} + SoundEffect sndEffect; OpenWindow("Sound Demo", 640, 320); @@ -244,48 +295,8 @@ do } // Drawing Keyboard Controls information in window (focus on sound effect code above) + DrawInstructions(); - // SplashKit Orange background - ClearScreen(RGBColor(245, 166, 35)); - - // Draw heading - SetFontStyle("arial", FontStyle.BoldFont); - DrawText("Keyboard Controls", Color.Black, "arial", 20, (ScreenWidth() - TextWidth("Keyboard Controls", "arial", 20)) / 2, 10); - SetFontStyle("arial", FontStyle.NormalFont); - - // Draw left box with SplashKit Cyan/Teal bo - FillRectangle(RGBColor(5, 172, 193), 10, 45, ScreenWidth() / 2 + 10, ScreenHeight() - 85); - FillRectangle(Color.PapayaWhip, 20, 55, ScreenWidth() / 2 - 10, ScreenHeight() - 105); - DrawLine(Color.LightGray, 30, 105, ScreenWidth() / 2, 105); - - // Playing sound effect controls text - DrawText("Playing Sound Controls", Color.Red, "arial", 18, 80, 70); - DrawText("[1] Play Sound At Full Volume", Color.Blue, "arial", 14, 30, 120); - DrawText("[2] Play Sound At 50% Volume", Color.Blue, "arial", 14, 30, 150); - DrawText("[3] Play Sound 3 Times At 25% Volume", Color.Blue, "arial", 14, 30, 180); - DrawText("[4] Play Sound Continuously at 10% Volume", Color.Blue, "arial", 14, 30, 210); - DrawText("[5] Stop Playing Current Sound", Color.Blue, "arial", 14, 30, 240); - - // Exit text - SetFontStyle("arial", FontStyle.ItalicFont); - DrawText("Press [Escape] or [Q] to quit", Color.Black, "arial", 16, 65, 290); - SetFontStyle("arial", FontStyle.NormalFont); - - // Draw left box with SplashKit Cyan/Teal bo - FillRectangle(RGBColor(5, 172, 193), ScreenWidth() / 2 + 30, 45, ScreenWidth() / 2 - 40, ScreenHeight() - 55); - FillRectangle(Color.PapayaWhip, ScreenWidth() / 2 + 40, 55, ScreenWidth() / 2 - 60, ScreenHeight() - 75); - DrawLine(Color.LightGray, ScreenWidth() / 2 + 50, 105, ScreenWidth() - 30, 105); - - // Switching to sound effect controls text - DrawText("Switching Sound Controls", Color.OrangeRed, "arial", 18, ScreenWidth() / 2 + 65, 70); - DrawText("[CTRL + 1] Chipmunk Sound", Color.DarkGreen, "arial", 14, ScreenWidth() / 2 + 50, 120); - DrawText("[CTRL + 2] Bells Sound", Color.DarkGreen, "arial", 14, ScreenWidth() / 2 + 50, 150); - DrawText("[CTRL + 3] Camera Sound", Color.DarkGreen, "arial", 14, ScreenWidth() / 2 + 50, 180); - DrawText("[CTRL + 4] Boing Sound", Color.DarkGreen, "arial", 14, ScreenWidth() / 2 + 50, 210); - DrawText("[CTRL + 5] Dinasaur Sound", Color.DarkGreen, "arial", 14, ScreenWidth() / 2 + 50, 240); - DrawText("[CTRL + 6] Bark Sound", Color.DarkGreen, "arial", 14, ScreenWidth() / 2 + 50, 270); - - RefreshScreen(60); } while (!(QuitRequested() || KeyTyped(KeyCode.EscapeKey) || KeyTyped(KeyCode.QKey))); CloseAllWindows(); @@ -297,140 +308,171 @@ CloseAllWindows(); ```csharp using SplashKitSDK; -namespace SoundDemoOOP +namespace SoundPlayer { - public class SoundPlayer + public class Program { - private SoundEffect _sndEffect; - private Window _window; - - public SoundPlayer() - { - _window = new Window("Sound Demo", 640, 320); - LoadSounds(); - } - - public void LoadSounds() - { - _sndEffect = SplashKit.LoadSoundEffect("chipmunk", "chipmunk.ogg"); - SplashKit.LoadSoundEffect("bells", "bells.ogg"); - SplashKit.LoadSoundEffect("camera", "camera.ogg"); - SplashKit.LoadSoundEffect("boing", "comedy_boing.ogg"); - SplashKit.LoadSoundEffect("dinosaur", "dinosaur.ogg"); - SplashKit.LoadSoundEffect("bark", "dog_bark.ogg"); - } - - public void HandleInput() - { - SplashKit.ProcessEvents(); - - if (SplashKit.KeyDown(KeyCode.RightCtrlKey) || SplashKit.KeyDown(KeyCode.LeftCtrlKey)) - { - if (SplashKit.KeyTyped(KeyCode.Num1Key)) - _sndEffect = SplashKit.SoundEffectNamed("chipmunk"); - if (SplashKit.KeyTyped(KeyCode.Num2Key)) - _sndEffect = SplashKit.SoundEffectNamed("bells"); - if (SplashKit.KeyTyped(KeyCode.Num3Key)) - _sndEffect = SplashKit.SoundEffectNamed("camera"); - if (SplashKit.KeyTyped(KeyCode.Num4Key)) - _sndEffect = SplashKit.SoundEffectNamed("boing"); - if (SplashKit.KeyTyped(KeyCode.Num5Key)) - _sndEffect = SplashKit.SoundEffectNamed("dinosaur"); - if (SplashKit.KeyTyped(KeyCode.Num6Key)) - _sndEffect = SplashKit.SoundEffectNamed("bark"); - } - else - { - if (SplashKit.KeyTyped(KeyCode.Num1Key)) - _sndEffect.Play(); - if (SplashKit.KeyTyped(KeyCode.Num2Key)) - _sndEffect.Play(0.5f); - if (SplashKit.KeyTyped(KeyCode.Num3Key)) - _sndEffect.Play(3, 0.25f); - if (SplashKit.KeyTyped(KeyCode.Num4Key)) - _sndEffect.Play(-1, 0.1f); - if (SplashKit.KeyTyped(KeyCode.Num5Key)) - { - if (_sndEffect.IsPlaying) - _sndEffect.Stop(); - } - } - } - - public void DrawInterface() + public static void DrawInstructions() { - // Clear the screen with SplashKit Orange background - SplashKit.ClearScreen(SplashKit.RGBColor(245, 166, 35)); + // SplashKit Orange background + SplashKit.ClearScreen(Color.RGBColor(245, 166, 35)); // Draw heading SplashKit.SetFontStyle("arial", FontStyle.BoldFont); - SplashKit.DrawText("Keyboard Controls", Color.Black, "arial", 20, (_window.Width - SplashKit.TextWidth("Keyboard Controls", "arial", 20)) / 2, 10); + SplashKit.DrawText("Keyboard Controls", Color.Black, "arial", 20, (SplashKit.ScreenWidth() - SplashKit.TextWidth("Keyboard Controls", "arial", 20)) / 2, 10); SplashKit.SetFontStyle("arial", FontStyle.NormalFont); - // Draw left box with SplashKit Cyan/Teal border - SplashKit.FillRectangle(SplashKit.RGBColor(5, 172, 193), 10, 45, _window.Width / 2 + 10, _window.Height - 85); - SplashKit.FillRectangle(Color.PapayaWhip, 20, 55, _window.Width / 2 - 10, _window.Height - 105); - SplashKit.DrawLine(Color.LightGray, 30, 105, _window.Width / 2, 105); + // Draw left box with SplashKit Cyan/Teal bo + SplashKit.FillRectangle(Color.RGBColor(5, 172, 193), 10, 45, SplashKit.ScreenWidth() / 2 + 10, SplashKit.ScreenHeight() - 85); + SplashKit.FillRectangle(Color.PapayaWhip, 20, 55, SplashKit.ScreenWidth() / 2 - 10, SplashKit.ScreenHeight() - 105); + SplashKit.DrawLine(Color.LightGray, 30, 105, SplashKit.ScreenWidth() / 2, 105); // Playing sound effect controls text - SplashKit.DrawText("Playing Sound Controls", Color.Red, "arial", 18, 80, 70); - SplashKit.DrawText("[1] Play Sound At Full Volume", Color.Blue, "arial", 14, 30, 120); - SplashKit.DrawText("[2] Play Sound At 50% Volume", Color.Blue, "arial", 14, 30, 150); - SplashKit.DrawText("[3] Play Sound 3 Times At 25% Volume", Color.Blue, "arial", 14, 30, 180); - SplashKit.DrawText("[4] Play Sound Continuously at 10% Volume", Color.Blue, "arial", 14, 30, 210); - SplashKit.DrawText("[5] Stop Playing Current Sound", Color.Blue, "arial", 14, 30, 240); + SplashKit.DrawText("Playing Sound Controls", Color.Black, "arial", 18, 80, 70); + SplashKit.DrawText("[1] Play Sound At Full Volume", Color.Black, "arial", 14, 30, 120); + SplashKit.DrawText("[2] Play Sound At 50% Volume", Color.Black, "arial", 14, 30, 150); + SplashKit.DrawText("[3] Play Sound 3 Times At 25% Volume", Color.Black, "arial", 14, 30, 180); + SplashKit.DrawText("[4] Play Sound Continuously at 10% Volume", Color.Black, "arial", 14, 30, 210); + SplashKit.DrawText("[5] Stop Playing Current Sound", Color.Black, "arial", 14, 30, 240); // Exit text SplashKit.SetFontStyle("arial", FontStyle.ItalicFont); SplashKit.DrawText("Press [Escape] or [Q] to quit", Color.Black, "arial", 16, 65, 290); SplashKit.SetFontStyle("arial", FontStyle.NormalFont); - // Draw right box with SplashKit Cyan/Teal border - SplashKit.FillRectangle(SplashKit.RGBColor(5, 172, 193), _window.Width / 2 + 30, 45, _window.Width / 2 - 40, _window.Height - 55); - SplashKit.FillRectangle(Color.PapayaWhip, _window.Width / 2 + 40, 55, _window.Width / 2 - 60, _window.Height - 75); - SplashKit.DrawLine(Color.LightGray, _window.Width / 2 + 50, 105, _window.Width - 30, 105); + // Draw left box with SplashKit Cyan/Teal bo + SplashKit.FillRectangle(Color.RGBColor(5, 172, 193), SplashKit.ScreenWidth() / 2 + 30, 45, SplashKit.ScreenWidth() / 2 - 40, SplashKit.ScreenHeight() - 55); + SplashKit.FillRectangle(Color.PapayaWhip, SplashKit.ScreenWidth() / 2 + 40, 55, SplashKit.ScreenWidth() / 2 - 60, SplashKit.ScreenHeight() - 75); + SplashKit.DrawLine(Color.LightGray, SplashKit.ScreenWidth() / 2 + 50, 105, SplashKit.ScreenWidth() - 30, 105); // Switching to sound effect controls text - SplashKit.DrawText("Switching Sound Controls", Color.OrangeRed, "arial", 18, _window.Width / 2 + 65, 70); - SplashKit.DrawText("[CTRL + 1] Chipmunk Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 120); - SplashKit.DrawText("[CTRL + 2] Bells Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 150); - SplashKit.DrawText("[CTRL + 3] Camera Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 180); - SplashKit.DrawText("[CTRL + 4] Boing Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 210); - SplashKit.DrawText("[CTRL + 5] Dinosaur Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 240); - SplashKit.DrawText("[CTRL + 6] Bark Sound", Color.DarkGreen, "arial", 14, _window.Width / 2 + 50, 270); + SplashKit.DrawText("Switching Sound Controls", Color.Black, "arial", 18, SplashKit.ScreenWidth() / 2 + 65, 70); + SplashKit.DrawText("[CTRL + 1] Chipmunk Sound", Color.Black, "arial", 14, SplashKit.ScreenWidth() / 2 + 50, 120); + SplashKit.DrawText("[CTRL + 2] Bells Sound", Color.Black, "arial", 14, SplashKit.ScreenWidth() / 2 + 50, 150); + SplashKit.DrawText("[CTRL + 3] Camera Sound", Color.Black, "arial", 14, SplashKit.ScreenWidth() / 2 + 50, 180); + SplashKit.DrawText("[CTRL + 4] Boing Sound", Color.Black, "arial", 14, SplashKit.ScreenWidth() / 2 + 50, 210); + SplashKit.DrawText("[CTRL + 5] Dinasaur Sound", Color.Black, "arial", 14, SplashKit.ScreenWidth() / 2 + 50, 240); + SplashKit.DrawText("[CTRL + 6] Bark Sound", Color.Black, "arial", 14, SplashKit.ScreenWidth() / 2 + 50, 270); + + SplashKit.RefreshScreen(60); } - public void Run() + public static void Main() { + SoundEffect sndEffect; + + Window window = new Window("Sound Demo", 640, 320); + + sndEffect = SplashKit.LoadSoundEffect("chipmunk", "chipmunk.ogg"); + + SplashKit.LoadSoundEffect("bells", "bells.ogg"); + SplashKit.LoadSoundEffect("camera", "camera.ogg"); + SplashKit.LoadSoundEffect("boing", "comedy_boing.ogg"); + SplashKit.LoadSoundEffect("dinosaur", "dinosaur.ogg"); + SplashKit.LoadSoundEffect("bark", "dog_bark.ogg"); + + SplashKit.LoadFont("arial", "arial.ttf"); + do { - HandleInput(); - DrawInterface(); - SplashKit.RefreshScreen(60); - } while (!(SplashKit.QuitRequested() || SplashKit.KeyTyped(KeyCode.EscapeKey) || SplashKit.KeyTyped(KeyCode.QKey))); + SplashKit.ProcessEvents(); - SplashKit.CloseAllWindows(); - } - } + if (SplashKit.KeyDown(KeyCode.RightCtrlKey) || SplashKit.KeyDown(KeyCode.LeftCtrlKey)) + { + if (SplashKit.KeyTyped(KeyCode.Num1Key)) + sndEffect = SplashKit.SoundEffectNamed("chipmunk"); + if (SplashKit.KeyTyped(KeyCode.Num2Key)) + sndEffect = SplashKit.SoundEffectNamed("bells"); + if (SplashKit.KeyTyped(KeyCode.Num3Key)) + sndEffect = SplashKit.SoundEffectNamed("camera"); + if (SplashKit.KeyTyped(KeyCode.Num4Key)) + sndEffect = SplashKit.SoundEffectNamed("boing"); + if (SplashKit.KeyTyped(KeyCode.Num5Key)) + sndEffect = SplashKit.SoundEffectNamed("dinosaur"); + if (SplashKit.KeyTyped(KeyCode.Num6Key)) + sndEffect = SplashKit.SoundEffectNamed("bark"); + } + else + { + if (SplashKit.KeyTyped(KeyCode.Num1Key)) + sndEffect.Play(); + if (SplashKit.KeyTyped(KeyCode.Num2Key)) + sndEffect.Play(0.5f); + if (SplashKit.KeyTyped(KeyCode.Num3Key)) + sndEffect.Play(3, 0.25f); + if (SplashKit.KeyTyped(KeyCode.Num4Key)) + sndEffect.Play(-1, 0.1f); + if (SplashKit.KeyTyped(KeyCode.Num5Key)) + { + if (sndEffect.IsPlaying) + sndEffect.Stop(); + } + } - public class Program - { - public static void Main() - { - SoundPlayer player = new SoundPlayer(); - player.Run(); + // Drawing Keyboard Controls information in window (focus on sound effect code above) + DrawInstructions(); + + } while (!(window.CloseRequested || SplashKit.KeyTyped(KeyCode.EscapeKey) || SplashKit.KeyTyped(KeyCode.QKey))); + + SplashKit.CloseAllWindows(); } } } ``` + + ```python from splashkit import * +def draw_instructions(): + # SplashKit Orange background + clear_screen(rgb_color(245, 166, 35)) + + # Draw heading + set_font_style_name_as_string("arial", FontStyle.bold_font) + draw_text_font_as_string("Keyboard Controls", color_black(), "arial", 20, (screen_width() - text_width_font_named("Keyboard Controls", "arial", 20)) / 2, 10) + set_font_style_name_as_string("arial", FontStyle.normal_font) + + # Draw left box with SplashKit Cyan/Teal bo + fill_rectangle(rgb_color(5, 172, 193), 10, 45, screen_width() / 2 + 10, screen_height() - 85) + fill_rectangle(color_papaya_whip(), 20, 55, screen_width() / 2 - 10, screen_height() - 105) + draw_line(color_light_gray(), 30, 105, screen_width() / 2, 105) + + # Playing sound effect controls text + draw_text_font_as_string("Playing Sound Controls", color_black(), "arial", 18, 80, 70) + draw_text_font_as_string("[1] Play Sound At Full Volume", color_black(), "arial", 14, 30, 120) + draw_text_font_as_string("[2] Play Sound At 50% Volume", color_black(), "arial", 14, 30, 150) + draw_text_font_as_string("[3] Play Sound 3 Times At 25% Volume", color_black(), "arial", 14, 30, 180) + draw_text_font_as_string("[4] Play Sound Continuously at 10% Volume", color_black(), "arial", 14, 30, 210) + draw_text_font_as_string("[5] Stop Playing Current Sound", color_black(), "arial", 14, 30, 240) + + # Exit text + set_font_style_name_as_string("arial", FontStyle.italic_font) + draw_text_font_as_string("Press [Escape] or [Q] to quit", color_black(), "arial", 16, 65, 290) + set_font_style_name_as_string("arial", FontStyle.normal_font) + + # Draw left box with SplashKit Cyan/Teal bo + fill_rectangle(rgb_color(5, 172, 193), screen_width() / 2 + 30, 45, screen_width() / 2 - 40, screen_height() - 55) + fill_rectangle(color_papaya_whip(), screen_width() / 2 + 40, 55, screen_width() / 2 - 60, screen_height() - 75) + draw_line(color_light_gray(), screen_width() / 2 + 50, 105, screen_width() - 30, 105) + + # Switching to sound effect controls text + draw_text_font_as_string("Switching Sound Controls", color_black(), "arial", 18, screen_width() / 2 + 65, 70) + draw_text_font_as_string("[CTRL + 1] Chipmunk Sound", color_black(), "arial", 14, screen_width() / 2 + 50, 120) + draw_text_font_as_string("[CTRL + 2] Bells Sound", color_black(), "arial", 14, screen_width() / 2 + 50, 150) + draw_text_font_as_string("[CTRL + 3] Camera Sound", color_black(), "arial", 14, screen_width() / 2 + 50, 180) + draw_text_font_as_string("[CTRL + 4] Boing Sound", color_black(), "arial", 14, screen_width() / 2 + 50, 210) + draw_text_font_as_string("[CTRL + 5] Dinasaur Sound", color_black(), "arial", 14, screen_width() / 2 + 50, 240) + draw_text_font_as_string("[CTRL + 6] Bark Sound", color_black(), "arial", 14, screen_width() / 2 + 50, 270) + + refresh_screen_with_target_fps(60) + +# Start of "main" code open_window("Sound, Demo", 640, 320) snd_effect = load_sound_effect("chipmunk", "chipmunk.ogg") @@ -472,50 +514,8 @@ while not (quit_requested() or key_typed(KeyCode.escape_key or key_typed(KeyCode if sound_effect_playing(snd_effect): stop_sound_effect(snd_effect) - # Drawing Keyboard Controls information in window (focus on sound effect code above) - - # SplashKit Orange background - clear_screen(rgb_color(245, 166, 35)) - - # Draw heading - set_font_style_name_as_string("arial", FontStyle.bold_font) - draw_text_font_as_string("Keyboard Controls", color_black(), "arial", 20, (screen_width() - text_width_font_named("Keyboard Controls", "arial", 20)) / 2, 10) - set_font_style_name_as_string("arial", FontStyle.normal_font) - - # Draw left box with SplashKit Cyan/Teal bo - fill_rectangle(rgb_color(5, 172, 193), 10, 45, screen_width() / 2 + 10, screen_height() - 85) - fill_rectangle(color_papaya_whip(), 20, 55, screen_width() / 2 - 10, screen_height() - 105) - draw_line(color_light_gray(), 30, 105, screen_width() / 2, 105) - - # Playing sound effect controls text - draw_text_font_as_string("Playing Sound Controls", color_red(), "arial", 18, 80, 70) - draw_text_font_as_string("[1] Play Sound At Full Volume", color_blue(), "arial", 14, 30, 120) - draw_text_font_as_string("[2] Play Sound At 50% Volume", color_blue(), "arial", 14, 30, 150) - draw_text_font_as_string("[3] Play Sound 3 Times At 25% Volume", color_blue(), "arial", 14, 30, 180) - draw_text_font_as_string("[4] Play Sound Continuously at 10% Volume", color_blue(), "arial", 14, 30, 210) - draw_text_font_as_string("[5] Stop Playing Current Sound", color_blue(), "arial", 14, 30, 240) - - # Exit text - set_font_style_name_as_string("arial", FontStyle.italic_font) - draw_text_font_as_string("Press [Escape] or [Q] to quit", color_black(), "arial", 16, 65, 290) - set_font_style_name_as_string("arial", FontStyle.normal_font) - - # Draw left box with SplashKit Cyan/Teal bo - fill_rectangle(rgb_color(5, 172, 193), screen_width() / 2 + 30, 45, screen_width() / 2 - 40, screen_height() - 55) - fill_rectangle(color_papaya_whip(), screen_width() / 2 + 40, 55, screen_width() / 2 - 60, screen_height() - 75) - draw_line(color_light_gray(), screen_width() / 2 + 50, 105, screen_width() - 30, 105) - - # Switching to sound effect controls text - draw_text_font_as_string("Switching Sound Controls", color_orange_red(), "arial", 18, screen_width() / 2 + 65, 70) - draw_text_font_as_string("[CTRL + 1] Chipmunk Sound", color_dark_green(), "arial", 14, screen_width() / 2 + 50, 120) - draw_text_font_as_string("[CTRL + 2] Bells Sound", color_dark_green(), "arial", 14, screen_width() / 2 + 50, 150) - draw_text_font_as_string("[CTRL + 3] Camera Sound", color_dark_green(), "arial", 14, screen_width() / 2 + 50, 180) - draw_text_font_as_string("[CTRL + 4] Boing Sound", color_dark_green(), "arial", 14, screen_width() / 2 + 50, 210) - draw_text_font_as_string("[CTRL + 5] Dinasaur Sound", color_dark_green(), "arial", 14, screen_width() / 2 + 50, 240) - draw_text_font_as_string("[CTRL + 6] Bark Sound", color_dark_green(), "arial", 14, screen_width() / 2 + 50, 270) - - refresh_screen_with_target_fps(60) + draw_instructions() close_all_windows() ``` From c06b2930b7e0abde4b416944b26e84ed0e137a7c Mon Sep 17 00:00:00 2001 From: NidhishaPahade <101486006+NidhishaPahade@users.noreply.github.com> Date: Wed, 2 Oct 2024 16:36:45 +1000 Subject: [PATCH 12/30] Add C# Language Tabs to "Getting Started Creating User Interfaces" Guide (#196) --- .../docs/guides/Interface/00-interface.mdx | 890 +++++++++++++++--- 1 file changed, 746 insertions(+), 144 deletions(-) diff --git a/src/content/docs/guides/Interface/00-interface.mdx b/src/content/docs/guides/Interface/00-interface.mdx index 8b7293ef..c05e7437 100644 --- a/src/content/docs/guides/Interface/00-interface.mdx +++ b/src/content/docs/guides/Interface/00-interface.mdx @@ -24,28 +24,86 @@ Let's see how we can create a simple button. We'll start in an empty project, an 4. and finally _delayed_ for 5 seconds (so the program doesn't end immediately) Make sure to have a look at the code, and see where we'll put our interface code! - + + - ```cpp - #include "splashkit.h" + ```cpp + #include "splashkit.h" - int main() - { - // open a window and clear it to white - open_window("My Interface!", 800, 600); - clear_screen(COLOR_WHITE); + int main() + { + // open a window and clear it to white + open_window("My Interface!", 800, 600); + clear_screen(COLOR_WHITE); - // ...we'll put our interface code here!... + // ...we'll put our interface code here!... - // refresh the screen, then wait 5 seconds - refresh_screen(); - delay(5000); + // refresh the screen, then wait 5 seconds + refresh_screen(); + delay(5000); - // program ends, and the window closes - return 0; - } - ``` + // close all open windows + close_all_windows(); + + return 0; + } + ``` + + + + + + + + ```csharp + using static SplashKitSDK.SplashKit; + + // open a window and clear it to white + OpenWindow("My Interface!", 800, 600); + ClearScreen(ColorWhite()); + + // ...we'll put our interface code here!... + + // refresh the screen, then wait for 5 seconds + RefreshScreen(); + Delay(5000); + + // close all open windows + CloseAllWindows(); + ``` + + + + + ```csharp + using SplashKitSDK; + + namespace CreatingUserInterfaces + { + public class Program + { + public static void Main() + { + // open a window and clear it to white + Window window = new Window("My Interface!", 800, 600); + window.Clear(Color.White); + + // ...we'll put our interface code here!... + + // refresh the screen, then wait for 5 seconds + window.Refresh(); + SplashKit.Delay(5000); + + // close all open windows + SplashKit.CloseAllWindows(); + } + } + } + ``` + + + @@ -56,11 +114,16 @@ Let's see how we can create a simple button. We'll start in an empty project, an 3. We also need to _draw_ the interface - we can do this with [Draw Interface](/api/interface/#draw-interface) - Making those changes, we get the following inside `main`: - + Making those changes, we get the following: + + - ```cpp ins={5-9} + ```cpp ins={9-13} + #include "splashkit.h" + + int main() + { // open a window and clear it to white open_window("My Interface!", 800, 600); clear_screen(COLOR_WHITE); @@ -74,11 +137,80 @@ Let's see how we can create a simple button. We'll start in an empty project, an // refresh the screen, then wait 5 seconds refresh_screen(); delay(5000); + + // close all open windows + close_all_windows(); + + return 0; + } + ``` + + + + + + + + ```csharp ins={7-11} + using static SplashKitSDK.SplashKit; + + // open a window and clear it to white + OpenWindow("My Interface!", 800, 600); + ClearScreen(ColorWhite()); + + // show button + Button("My Button!", RectangleFrom(300, 260, 200, 24)); + + // draw the interface! + DrawInterface(); + + // refresh the screen, then wait 5 seconds + RefreshScreen(); + Delay(5000); + + // close all open windows + CloseAllWindows(); + ``` + + + + + ```csharp ins={13-17} + using SplashKitSDK; + + namespace CreatingUserInterfaces + { + public class Program + { + public static void Main() + { + // open a window and clear it to white + Window window = new Window("My Interface!", 800, 600); + window.Clear(Color.White); + + // show button + SplashKit.Button("My Button!", SplashKit.RectangleFrom(300, 260, 200, 24)); + + // draw the interface! + SplashKit.DrawInterface(); + + // refresh the screen, then wait 5 seconds + window.Refresh(); + SplashKit.Delay(5000); + + // close all open windows + SplashKit.CloseAllWindows(); + } + } + } ``` + + + Which if you run, will show you this! ![A single button on a white window](./images/first_button.png) @@ -99,30 +231,105 @@ Let's see how we can create a simple button. We'll start in an empty project, an SplashKit will try to give helpful messages when things aren't quite right, so make sure to pay attention to them! - Putting this all together, we get this inside `main`: - + Putting this all together, we get this: + + - ```cpp ins={4-6, 15} - // open a window - open_window("My Interface!", 800, 600); + ```cpp ins={8-10, 19} + #include "splashkit.h" + + int main() + { + // open a window + open_window("My Interface!", 800, 600); + + while (!quit_requested()) + { + process_events(); - while (!quit_requested()) - { - process_events(); + clear_screen(COLOR_WHITE); - clear_screen(COLOR_WHITE); + button("My Button!", rectangle_from(300, 260, 200, 24)); - button("My Button!", rectangle_from(300, 260, 200, 24)); + draw_interface(); - draw_interface(); + refresh_screen(); + } - refresh_screen(); - } + // close all open windows + close_all_windows(); - // program ends, and the window closes - return 0; - ``` + return 0; + } + ``` + + + + + + + + ```csharp ins={6-8, 17} + using static SplashKitSDK.SplashKit; + + // open a window + OpenWindow("My Interface!", 800, 600); + + while (!QuitRequested()) + { + ProcessEvents(); + + ClearScreen(ColorWhite()); + + Button("My Button!", RectangleFrom(300, 260, 200, 24)); + + DrawInterface(); + + RefreshScreen(); + } + + // close all open windows + CloseAllWindows(); + ``` + + + + + ```csharp ins={12-14, 23} + using SplashKitSDK; + + namespace CreatingUserInterfaces + { + public class Program + { + public static void Main() + { + // open a window + Window window = new Window("My Interface!", 800, 600); + + while (!window.CloseRequested) + { + SplashKit.ProcessEvents(); + + window.Clear(Color.White); + + SplashKit.Button("My Button!", SplashKit.RectangleFrom(300, 260, 200, 24)); + + SplashKit.DrawInterface(); + + window.Refresh(); + } + + // close all open windows + SplashKit.CloseAllWindows(); + } + } + } + ``` + + + @@ -160,15 +367,41 @@ Let's try it out: We should also give the button some more descriptive text inside it, like "Write To Terminal!" - + - ```cpp ins="Write To Terminal!" ins="if (" ins=/24\\)\\)(\\))/ ins={2-4} - if (button("Write To Terminal!", rectangle_from(300, 260, 200, 24))) - { - write_line("The button was clicked!"); - } - ``` +```cpp ins="Write To Terminal!" ins="if (" ins=/24\\)\\)(\\))/ ins={2-4} + if (button("Write To Terminal!", rectangle_from(300, 260, 200, 24))) + { + write_line("The button was clicked!"); + } +``` + + + + + + + +```csharp ins="Write To Terminal!" ins="if (" ins=/24\\)\\)(\\))/ ins={2-4} +if (Button("Write To Terminal!", RectangleFrom(300, 260, 200, 24))) +{ + WriteLine("The button was clicked!"); +} +``` + + + + +```csharp ins="Write To Terminal!" ins="if (" ins=/24\\)\\)(\\))/ ins={2-4} + if (SplashKit.Button("Write To Terminal!", SplashKit.RectangleFrom(300, 260, 200, 24))) + { + SplashKit.WriteLine("The button was clicked!"); + } +``` + + + @@ -183,18 +416,51 @@ Now when we click on the button, our text gets printed in the terminal! You can Now let's try out some more interesting elements - let's add a text box, so we can customize the message written to the terminal! 1. First let's start by adding a variable to store the user's text in - make sure to do this _outside_ the main loop, or else the user's text will be forgotten each iteration! - + + - ```cpp ins={3} - open_window("My Interface!", 800, 600); + ```cpp ins={3} + open_window("My Interface!", 800, 600); + + string user_message = "Default message!"; + + while (!quit_requested()) + { + process_events(); + ``` + + + + + + - string user_message = "Default message!"; + ```csharp ins={3} + OpenWindow("My Interface!", 800, 600); - while (!quit_requested()) - { - process_events(); - ``` + string userMessage = "Default message!"; + + while (!QuitRequested()) + { + ProcessEvents(); + ``` + + + + + ```csharp ins={3} + Window window = new Window("My Interface!", 800, 600); + + string userMessage = "Default message!"; + + while (!window.CloseRequested) + { + SplashKit.ProcessEvents(); + ``` + + + @@ -208,17 +474,49 @@ Now let's try out some more interesting elements - let's add a text box, so we c Finally, we can use this variable in our [Write Line](/api/terminal/#write-line), to write the user's text to the console. Remember - this all needs to go inside the main `while` loop. Otherwise the text box will only exist for a split second before vanishing - we need to keep it alive! - + + - ```cpp ins={1} ins="write_line(user_message);" - user_message = text_box(user_message, rectangle_from(300, 220, 200, 24)); + ```cpp ins={1} ins="write_line(user_message);" + user_message = text_box(user_message, rectangle_from(300, 220, 200, 24)); + + if (button("Write To Terminal!", rectangle_from(300, 260, 200, 24))) + { + write_line(user_message); + } + ``` + + + + + + + + ```csharp ins={1} ins="WriteLine(userMessage);" + userMessage = TextBox(userMessage, RectangleFrom(300, 220, 200, 24)); + + if (Button("Write To Terminal!", RectangleFrom(300, 260, 200, 24))) + { + WriteLine(userMessage); + } + ``` + + + + + ```csharp ins={1} ins="SplashKit.WriteLine(userMessage);" + userMessage = SplashKit.TextBox(userMessage, SplashKit.RectangleFrom(300, 220, 200, 24)); + + // Check if the button is clicked + if (SplashKit.Button("Write To Terminal!", SplashKit.RectangleFrom(300, 260, 200, 24))) + { + SplashKit.WriteLine(userMessage); + } + ``` - if (button("Write To Terminal!", rectangle_from(300, 260, 200, 24))) - { - write_line(user_message); - } - ``` + + @@ -239,47 +537,141 @@ Now let's try out some more interesting elements - let's add a text box, so we c ![A button and a text box. When the button is clicked, the contents of the text box is printed in the terminal.](/gifs/guides/interface/text_box_to_terminal.gif) Here's the complete code up until this point: - + + - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" + +int main() +{ + // open a window + open_window("My Interface!", 800, 600); - int main() - { - // open a window - open_window("My Interface!", 800, 600); + // define variables + string user_message = "Default message!"; - // define variables - string user_message = "Default message!"; + // main loop + while (!quit_requested()) + { + // get user events + process_events(); - // main loop - while (!quit_requested()) - { - // get user events - process_events(); + // clear screen + clear_screen(COLOR_WHITE); - // clear screen - clear_screen(COLOR_WHITE); + // interface! + user_message = text_box(user_message, rectangle_from(300, 220, 200, 24)); - // interface! - user_message = text_box(user_message, rectangle_from(300, 220, 200, 24)); + if (button("Write To Terminal!", rectangle_from(300, 260, 200, 24))) + { + write_line(user_message); + } - if (button("Write To Terminal!", rectangle_from(300, 260, 200, 24))) - { - write_line(user_message); - } + // finally draw interface, then refresh screen + draw_interface(); - // finally draw interface, then refresh screen - draw_interface(); + refresh_screen(); + } - refresh_screen(); - } + // close all open windows + close_all_windows(); - // program ends, and the window closes - return 0; - } - ``` + return 0; +} +``` + + + + + + + +```csharp +using static SplashKitSDK.SplashKit; + +// open a window +OpenWindow("My Interface!", 800, 600); + +// define variables +string userMessage = "Default message!"; + +// main loop +while (!QuitRequested()) +{ + // get user events + ProcessEvents(); + + // clear screen + ClearScreen(ColorWhite()); + + // interface! + userMessage = TextBox(userMessage, RectangleFrom(300, 220, 200, 24)); + + if (Button("Write To Terminal!", RectangleFrom(300, 260, 200, 24))) + { + WriteLine(userMessage); + } + + // finally draw interface, then refresh screen + DrawInterface(); + RefreshScreen(); +} + +// close all open windows +CloseAllWindows(); +``` + + + + +```csharp +using SplashKitSDK; + +namespace CreatingUserInterfaces +{ + public class Program + { + public static void Main() + { + // open a window + Window window = new Window("My Interface!", 800, 600); + + // define variables + string userMessage = "Default message!"; + + // main loop + while (!window.CloseRequested) + { + // get user events + SplashKit.ProcessEvents(); + + // clear screen + window.Clear(Color.White); + + // interface! + userMessage = SplashKit.TextBox(userMessage, SplashKit.RectangleFrom(300, 220, 200, 24)); + + if (SplashKit.Button("Write To Terminal!", SplashKit.RectangleFrom(300, 260, 200, 24))) + { + SplashKit.WriteLine(userMessage); + } + + // finally draw interface, then refresh screen + SplashKit.DrawInterface(); + window.Refresh(); + } + + // close all open windows + SplashKit.CloseAllWindows(); + } + } +} +``` + + + @@ -293,43 +685,154 @@ Let's try adding one more element - this time we can try adding a slider! For fu 3. To make the elements actually change width, we just need to update the calls to [Rectangle From](/api/geometry/#rectangle-from), changing the width to our variable `width` instead! You can also try _centering_ the elements, by adjusting their x coordinate as well.
-Here is _one_ way to do write this, but don't peek until you've tried it yourself! - +Here is _one_ way to write this, but don't peek until you've tried it yourself! + + - ```cpp ins={3} ins={22} ins=/(width), 2/ ins="400 - width/2" - // define variables - string user_message = "Default message!"; - float width = 200; +```cpp ins={10} ins={29} ins=/(width), 2/ ins="400 - width/2" +#include "splashkit.h" - // main loop - while (!quit_requested()) - { - // get user events - process_events(); +int main() +{ + // open a window + open_window("My Interface!", 800, 600); - // clear screen - clear_screen(COLOR_WHITE); + // define variables + string user_message = "Default message!"; + float width = 200; - // interface! - user_message = text_box(user_message, rectangle_from(400 - width/2, 220, width, 24)); + // main loop + while (!quit_requested()) + { + // get user events + process_events(); - if (button("Write To Terminal!", rectangle_from(400 - width/2, 260, width, 24))) - { - write_line(user_message); - } + // clear screen + clear_screen(COLOR_WHITE); - width = slider(width, 10, 400, rectangle_from(300, 300, 200, 24)); + // interface! + user_message = text_box(user_message, rectangle_from(400 - width/2, 220, width, 24)); - // finally draw interface, then refresh screen - draw_interface(); + if (button("Write To Terminal!", rectangle_from(400 - width/2, 260, width, 24))) + { + write_line(user_message); + } - refresh_screen(); - } - ``` + width = slider(width, 10, 400, rectangle_from(300, 300, 200, 24)); + + // finally draw interface, then refresh screen + draw_interface(); + refresh_screen(); + } + + // close all open windows + close_all_windows(); + + return 0; +} +``` + + + + + + + +```csharp ins={8} ins={27} ins=/(width), 2/ ins="400 - width/2" +using static SplashKitSDK.SplashKit; + +// open a window +OpenWindow("My Interface!", 800, 600); + +// define variables +string userMessage = "Default message!"; +float width = 200; + +// main loop +while (!QuitRequested()) +{ + // get user events + ProcessEvents(); + + // clear screen + ClearScreen(ColorWhite()); + + // interface! + userMessage = TextBox(userMessage, RectangleFrom(400 - width/2, 220, width, 24)); + + if (Button("Write To Terminal!", RectangleFrom(400 - width/2, 260, width, 24))) + { + WriteLine(userMessage); + } + + width = Slider(width, 10, 400, RectangleFrom(300, 300, 200, 24)); + + // finally draw interface, then refresh screen + DrawInterface(); + RefreshScreen(); +} + +// close all open windows +CloseAllWindows(); +``` + + + + +```csharp ins={14} ins={33} ins=/(width), 2/ ins="400 - width/2" +using SplashKitSDK; + +namespace CreatingUserInterfaces +{ + public class Program + { + public static void Main() + { + // open a window + Window window = new Window("My Interface!", 800, 600); + + // define variables + string userMessage = "Default message!"; + float width = 200; + + // main loop + while (!window.CloseRequested) + { + // get user events + SplashKit.ProcessEvents(); + + // clear screen + window.Clear(Color.White); + + // interface! + userMessage = SplashKit.TextBox(userMessage, SplashKit.RectangleFrom(400 - width / 2, 220, width, 24)); + + if (SplashKit.Button("Write To Terminal!", SplashKit.RectangleFrom(400 - width / 2, 260, width, 24))) + { + SplashKit.WriteLine(userMessage); + } + + width = SplashKit.Slider(width, 10, 400, SplashKit.RectangleFrom(300, 300, 200, 24)); + + // finally draw interface, then refresh screen + SplashKit.DrawInterface(); + window.Refresh(); + } + + // close all open windows + SplashKit.CloseAllWindows(); + } + } +} +``` + + + +
## Wrap up @@ -340,50 +843,149 @@ Hopefully now you understand how easy it is to make a dynamic interface in Splas ![A button, text box, and slider. Adjusting the value of the slider changes the width of the other controls.](/gifs/guides/interface/slider.gif) - + - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - // open a window - open_window("My Interface!", 800, 600); +int main() +{ + // open a window + open_window("My Interface!", 800, 600); - // define variables - string user_message = "Default message!"; - float width = 200; + // define variables + string user_message = "Default message!"; + float width = 200; - // main loop - while (!quit_requested()) - { - // get user events - process_events(); + // main loop + while (!quit_requested()) + { + // get user events + process_events(); - // clear screen - clear_screen(COLOR_WHITE); + // clear screen + clear_screen(COLOR_WHITE); - // interface! - user_message = text_box(user_message, rectangle_from(400 - width/2, 220, width, 24)); + // interface! + user_message = text_box(user_message, rectangle_from(400 - width/2, 220, width, 24)); - if (button("Write To Terminal!", rectangle_from(400 - width/2, 260, width, 24))) - { - write_line(user_message); - } + if (button("Write To Terminal!", rectangle_from(400 - width/2, 260, width, 24))) + { + write_line(user_message); + } - width = slider(width, 10, 400, rectangle_from(300, 300, 200, 24)); + width = slider(width, 10, 400, rectangle_from(300, 300, 200, 24)); - // finally draw interface, then refresh screen - draw_interface(); + // finally draw interface, then refresh screen + draw_interface(); + refresh_screen(); + } - refresh_screen(); - } + // close all open windows + close_all_windows(); - // program ends, and the window closes - return 0; - } + return 0; +} ``` + + + + + + + +```csharp +using static SplashKitSDK.SplashKit; + +// open a window +OpenWindow("My Interface!", 800, 600); + +// define variables +string userMessage = "Default message!"; +float width = 200; + +// main loop +while (!QuitRequested()) +{ + // get user events + ProcessEvents(); + + // clear screen + ClearScreen(ColorWhite()); + + // interface! + userMessage = TextBox(userMessage, RectangleFrom(400 - width/2, 220, width, 24)); + + if (Button("Write To Terminal!", RectangleFrom(400 - width/2, 260, width, 24))) + { + WriteLine(userMessage); + } + + width = Slider(width, 10, 400, RectangleFrom(300, 300, 200, 24)); + + // finally draw interface, then refresh screen + DrawInterface(); + RefreshScreen(); +} + +// close all open windows +CloseAllWindows(); +``` + + + + +```csharp +using SplashKitSDK; + +namespace CreatingUserInterfaces +{ + public class Program + { + public static void Main() + { + // open a window + Window window = new Window("My Interface!", 800, 600); + + // define variables + string userMessage = "Default message!"; + float width = 200; + + // main loop + while (!window.CloseRequested) + { + // get user events + SplashKit.ProcessEvents(); + + // clear screen + window.Clear(Color.White); + + // interface! + userMessage = SplashKit.TextBox(userMessage, SplashKit.RectangleFrom(400 - width / 2, 220, width, 24)); + + if (SplashKit.Button("Write To Terminal!", SplashKit.RectangleFrom(400 - width / 2, 260, width, 24))) + { + SplashKit.WriteLine(userMessage); + } + + width = SplashKit.Slider(width, 10, 400, SplashKit.RectangleFrom(300, 300, 200, 24)); + + // finally draw interface, then refresh screen + SplashKit.DrawInterface(); + window.Refresh(); + } + + // close all open windows + SplashKit.CloseAllWindows(); + } + } +} +``` + + + + From 4cbf0fc5e537b824fe03875b84eb99380da834a4 Mon Sep 17 00:00:00 2001 From: NidhishaPahade <101486006+NidhishaPahade@users.noreply.github.com> Date: Wed, 2 Oct 2024 16:47:59 +1000 Subject: [PATCH 13/30] Add C# Language Tabs to "Drawing using Procedures" Guide (#198) --- .../Graphics/0-drawing-using-procedures.mdx | 111 ++++++++++++++---- 1 file changed, 88 insertions(+), 23 deletions(-) diff --git a/src/content/docs/guides/Graphics/0-drawing-using-procedures.mdx b/src/content/docs/guides/Graphics/0-drawing-using-procedures.mdx index 4853fa00..771d3cd2 100644 --- a/src/content/docs/guides/Graphics/0-drawing-using-procedures.mdx +++ b/src/content/docs/guides/Graphics/0-drawing-using-procedures.mdx @@ -25,7 +25,7 @@ In SplashKit you can open a Window to draw on and interact with. To open the win Lets get this started by opening a new Window, and using SplashKit to delay us for a few seconds. Give the following code a try: - + ```cpp #include "splashkit.h" @@ -42,14 +42,40 @@ int main() + + + ```csharp using static SplashKitSDK.SplashKit; -OpenWindow("Window Title... to change", 800, 600); +OpenWindow("Window Title... to change ", 800, 600); Delay(5000); CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace DrawingUsingProcedures +{ + public class Program + { + public static void Main() + { + Window window = new Window("Shapes by ...", 800, 600); + SplashKit.Delay(5000); + SplashKit.CloseAllWindows(); + } + } +} +``` + + + + @@ -69,24 +95,24 @@ Compile and run the program from the terminal. - ```shell - clang++ program.cpp -l SplashKit -o ShapeDrawing - ./ShapeDrawing - ``` +```shell +clang++ program.cpp -l SplashKit -o ShapeDrawing +./ShapeDrawing +``` - ```shell - dotnet run - ``` +```shell +dotnet run +``` - ```shell - skm python3 program.cpp - ``` +```shell +skm python3 program.cpp +``` @@ -116,8 +142,11 @@ int main() fill_rectangle(COLOR_GRAY, 300, 300, 200, 200); fill_triangle(COLOR_RED, 250, 300, 400, 150, 550, 300); refresh_screen(); + delay(5000); + close_all_windows(); + return 0; } ``` @@ -125,6 +154,9 @@ int main() + + + ```csharp using static SplashKitSDK.SplashKit; @@ -135,11 +167,43 @@ FillEllipse(ColorBrightGreen(), 0, 400, 800, 400); FillRectangle(ColorGray(), 300, 300, 200, 200); FillTriangle(ColorRed(), 250, 300, 400, 150, 550, 300); RefreshScreen(); + Delay(5000); CloseAllWindows(); ``` + + + +```csharp +using SplashKitSDK; + +namespace DrawingUsingProcedures +{ + public class Program + { + public static void Main() + { + Window window = new Window("Shapes by ...", 800, 600); + + window.Clear(Color.White); + window.FillEllipse(Color.BrightGreen, 0, 400, 800, 400); + window.FillRectangle(Color.Gray, 300, 300, 200, 200); + window.FillTriangle(Color.Red, 250, 300, 400, 150, 550, 300); + window.Refresh(); + + SplashKit.Delay(5000); + + SplashKit.CloseAllWindows(); + } + } +} +``` + + + + @@ -153,6 +217,7 @@ fill_ellipse(color_bright_green(), 0, 400, 800, 400) fill_rectangle(color_gray(), 300, 300, 200, 200) fill_triangle(color_red(), 250, 300, 400, 150, 550, 300) refresh_screen() + delay(5000) close_all_windows() @@ -161,29 +226,29 @@ close_all_windows() -Build and run the program. +Compile and run the program again: - ```shell - clang++ program.cpp -l SplashKit -o ShapeDrawing - ./ShapeDrawing - ``` +```shell +clang++ program.cpp -l SplashKit -o ShapeDrawing +./ShapeDrawing +``` - ```shell - dotnet run - ``` +```shell +dotnet run +``` - ```shell - skm python3 program.cpp - ``` +```shell +skm python3 program.cpp +``` From 67e80120430fd8b5282e4ae5b27d372eaf682006 Mon Sep 17 00:00:00 2001 From: Breezy <114720008+breezy-codes@users.noreply.github.com> Date: Wed, 2 Oct 2024 17:17:19 +1000 Subject: [PATCH 14/30] Adding OOP to Starting with Servers (#204) --- .../0-getting-started-with-servers.mdx | 348 ++++++++++++------ 1 file changed, 230 insertions(+), 118 deletions(-) diff --git a/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx b/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx index 74b471d8..6438d5fe 100644 --- a/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx +++ b/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx @@ -3,7 +3,7 @@ title: Getting Started With Servers description: This guide is an introduction to using web servers category: Guides author: Andrew Cain and Isaac Wallis -lastupdated: Aug 10 2024 +lastupdated: Oct 1 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -50,52 +50,82 @@ We need to pair the [Start Web Server](/api/networking/#start-web-server) with a - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - write_line("About to start the server..."); +int main() +{ + write_line("About to start the server..."); - // Start a web server - defaults to listening to port 8080 - web_server server = start_web_server(); + // Start a web server - defaults to listening to port 8080 + web_server server = start_web_server(); - // For now we are done... so lets shutdown... - stop_web_server(server); + // For now we are done... so lets shutdown... + stop_web_server(server); - return 0; - } - ``` + return 0; +} +``` - ```csharp - using SplashKitSDK; + + - Console.WriteLine("About to start the server..."); +```csharp +using SplashKitSDK; - // Start a web server - defaults to listening to port 8080 - WebServer server = SplashKit.StartWebServer(); +Console.WriteLine("About to start the server..."); - // For now, we are done... so let's shutdown... - SplashKit.StopWebServer(server); +// Start a web server - defaults to listening to port 8080 +WebServer server = SplashKit.StartWebServer(); + +// For now, we are done... so let's shutdown... +SplashKit.StopWebServer(server); ``` + + + +```csharp +using SplashKitSDK; + +namespace WebServerApp +{ + public class Program + { + public static void Main() + { + SplashKit.WriteLine("About to start the server..."); + + // Start the web server (defaults to listening to port 8080) + WebServer server = SplashKit.StartWebServer(); + + // Stop the web server + SplashKit.StopWebServer(server); + } + } +} +``` + + + + - ```python - from splashkit import * +```python +from splashkit import * - write_line("About to start the server...") +write_line("About to start the server...") - # Start a web server - defaults to listening to port 8080 - server = start_web_server_with_default_port() +# Start a web server - defaults to listening to port 8080 +server = start_web_server_with_default_port() - # For now we are done... so lets shutdown... - stop_web_server(server) - ``` +# For now we are done... so lets shutdown... +stop_web_server(server) +``` @@ -111,80 +141,121 @@ The following code shows an appropriate `"Hello World"` web server program. - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - write_line("About to start the server..."); +int main() +{ + write_line("About to start the server..."); - // Start a web server - defaults to listening to port 8080 - web_server server = start_web_server(); + // Start a web server - defaults to listening to port 8080 + web_server server = start_web_server(); - write_line("Waiting for a request - navigate to http://localhost:8080"); + write_line("Waiting for a request - navigate to http://localhost:8080"); - // Wait and get the first request that comes in - http_request request = next_web_request(server); + // Wait and get the first request that comes in + http_request request = next_web_request(server); - // Send back the index.html file - send_html_file_response(request, "index.html"); + // Send back the index.html file + send_html_file_response(request, "index.html"); - // For now we are done... so lets shutdown... - stop_web_server(server); + // For now we are done... so lets shutdown... + stop_web_server(server); - return 0; - } - ``` + return 0; +} +``` - ```csharp - using SplashKitSDK; + + - SplashKit.WriteLine("About to start the server..."); +```csharp +using SplashKitSDK; - // Start a web server - defaults to listening to port 8080 - WebServer server = SplashKit.StartWebServer(); +SplashKit.WriteLine("About to start the server..."); - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +// Start a web server - defaults to listening to port 8080 +WebServer server = SplashKit.StartWebServer(); - // Wait and get the first request that comes in - HttpRequest request = SplashKit.NextWebRequest(server); +SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - // Send back the index.html file - SplashKit.SendResponse(request, "Hello World"); +// Wait and get the first request that comes in +HttpRequest request = SplashKit.NextWebRequest(server); - // For now, we are done, so let's shutdown - SplashKit.StopWebServer(server); +// Send back the index.html file +SplashKit.SendResponse(request, "Hello World"); - SplashKit.ReadLine(); // Pause to keep the console window open - ``` +// For now, we are done, so let's shutdown +SplashKit.StopWebServer(server); + +SplashKit.ReadLine(); // Pause to keep the console window open +``` + + + + +```csharp + +using SplashKitSDK; + +namespace WebServerApp +{ + public class Program + { + public static void Main() + { + SplashKit.WriteLine("About to start the server..."); + + // Start a web server - defaults to listening to port 8080 + WebServer server = SplashKit.StartWebServer(); + + SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); + + // Wait and get the first request that comes in + HttpRequest request = SplashKit.NextWebRequest(server); + + // Send back the index.html file + SplashKit.SendResponse(request, "Hello World"); + + // For now, we are done, so let's shutdown + SplashKit.StopWebServer(server); + + SplashKit.ReadLine(); // Pause to keep the console window open + } + } +} +``` + + + - ```python - from splashkit import * +```python +from splashkit import * - write_line("About to start the server...") +write_line("About to start the server...") - # Start a web server - defaults to listening to port 8080 - server = start_web_server_with_default_port() +# Start a web server - defaults to listening to port 8080 +server = start_web_server_with_default_port() - write_line("Waiting for a request - navigate to http://localhost:8080") +write_line("Waiting for a request - navigate to http://localhost:8080") - # Wait and get the first request that comes in - request = next_web_request(server) +# Wait and get the first request that comes in +request = next_web_request(server) - # Send back the index.html file - send_response(request, "Hello World") +# Send back the index.html file +send_response(request, "Hello World") - # For now, we are done, so let's shutdown - stop_web_server(server) +# For now, we are done, so let's shutdown +stop_web_server(server) - read_line() # Pause to keep the console window open - ``` +read_line() # Pause to keep the console window open +``` @@ -200,80 +271,121 @@ The follow code replaces the "Hello World" response with the details from the in - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - write_line("About to start the server..."); +int main() +{ + write_line("About to start the server..."); - // Start a web server - defaults to listening to port 8080 - web_server server = start_web_server(); + // Start a web server - defaults to listening to port 8080 + web_server server = start_web_server(); - write_line("Waiting for a request - navigate to http://localhost:8080"); + write_line("Waiting for a request - navigate to http://localhost:8080"); - // Wait and get the first request that comes in - http_request request = next_web_request(server); + // Wait and get the first request that comes in + http_request request = next_web_request(server); - // Send back the index.html file - send_html_file_response(request, "index.html"); + // Send back the index.html file + send_html_file_response(request, "index.html"); - // For now we are done... so lets shutdown... - stop_web_server(server); + // For now we are done... so lets shutdown... + stop_web_server(server); - return 0; - } - ``` + return 0; +} +``` - ```csharp - using SplashKitSDK; + + - SplashKit.WriteLine("About to start the server..."); +```csharp +using SplashKitSDK; - // Start a web server - defaults to listening to port 8080 - WebServer server = SplashKit.StartWebServer(); +SplashKit.WriteLine("About to start the server..."); - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +// Start a web server - defaults to listening to port 8080 +WebServer server = SplashKit.StartWebServer(); - // Wait and get the first request that comes in - HttpRequest request = SplashKit.NextWebRequest(server); +SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - // Send back the index.html file - SplashKit.SendHtmlFileResponse(request, "index.html"); +// Wait and get the first request that comes in +HttpRequest request = SplashKit.NextWebRequest(server); - // For now, we are done, so let's shutdown - SplashKit.StopWebServer(server); +// Send back the index.html file +SplashKit.SendHtmlFileResponse(request, "index.html"); - SplashKit.ReadLine(); // Pause to keep the console window open - ``` +// For now, we are done, so let's shutdown +SplashKit.StopWebServer(server); + +SplashKit.ReadLine(); // Pause to keep the console window open +``` + + + + +```csharp + +using SplashKitSDK; + +namespace WebServerApp +{ + public class Program + { + public static void Main() + { + SplashKit.WriteLine("About to start the server..."); + + // Start a web server - defaults to listening to port 8080 + WebServer server = SplashKit.StartWebServer(); + + SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); + + // Wait and get the first request that comes in + HttpRequest request = SplashKit.NextWebRequest(server); + + // Send back the index.html file + SplashKit.SendHtmlFileResponse(request, "index.html"); + + // For now, we are done, so let's shutdown + SplashKit.StopWebServer(server); + + SplashKit.ReadLine(); // Pause to keep the console window open + } + } +} +``` + + + - ```python - from splashkit import * +```python +from splashkit import * - write_line("About to start the server...") +write_line("About to start the server...") - # Start a web server - defaults to listening to port 8080 - server = start_web_server_with_default_port() +# Start a web server - defaults to listening to port 8080 +server = start_web_server_with_default_port() - write_line("Waiting for a request - navigate to http://localhost:8080") +write_line("Waiting for a request - navigate to http://localhost:8080") - # Wait and get the first request that comes in - request = next_web_request(server) +# Wait and get the first request that comes in +request = next_web_request(server) - # Send back the index.html file - send_html_file_response(request, "index.html") +# Send back the index.html file +send_html_file_response(request, "index.html") - # For now, we are done, so let's shutdown - stop_web_server(server) +# For now, we are done, so let's shutdown +stop_web_server(server) - read_line() # Pause to keep the console window open - ``` +read_line() # Pause to keep the console window open +``` From 10cc2cdc63cd777beb967be7d5faa3d7b4ddbf36 Mon Sep 17 00:00:00 2001 From: Breezy <114720008+breezy-codes@users.noreply.github.com> Date: Wed, 2 Oct 2024 17:24:11 +1000 Subject: [PATCH 15/30] Adding OOP to Routing with Servers Guide (#203) --- .../Networking/1-routing-with-servers.mdx | 617 +++++++++++------- 1 file changed, 384 insertions(+), 233 deletions(-) diff --git a/src/content/docs/guides/Networking/1-routing-with-servers.mdx b/src/content/docs/guides/Networking/1-routing-with-servers.mdx index 884c3fff..f9e3ab0f 100644 --- a/src/content/docs/guides/Networking/1-routing-with-servers.mdx +++ b/src/content/docs/guides/Networking/1-routing-with-servers.mdx @@ -3,7 +3,7 @@ title: Routing With Servers description: This guide is an intruduction to delivering different content based on route requested category: Guides author: Isaac Wallis -lastupdated: Aug 10 2024 +lastupdated: Oct 1 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -27,81 +27,114 @@ Start with this code, which we built in the introduction guide - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - write_line("About to start the server..."); - - // Start a web server - defaults to listening to port 8080 - web_server server = start_web_server(); +int main() +{ + write_line("About to start the server..."); - write_line("Waiting for a request - navigate to http://localhost:8080"); + // Start a web server - defaults to listening to port 8080 + web_server server = start_web_server(); - // Wait and get the first request that comes in - http_request request = next_web_request(server); + write_line("Waiting for a request - navigate to http://localhost:8080"); - // Send back the index.html file - send_html_file_response(request, "index.html"); + // Wait and get the first request that comes in + http_request request = next_web_request(server); - // For now we are done... so lets shutdown... - stop_web_server(server); + // Send back the index.html file + send_html_file_response(request, "index.html"); - return 0; - } + // For now we are done... so lets shutdown... + stop_web_server(server); - ``` + return 0; +} +``` - ```csharp - using SplashKitSDK; + + - SplashKit.WriteLine("About to start the server..."); +```csharp +using SplashKitSDK; - // Start a web server - defaults to listening to port 8080 - WebServer server = SplashKit.StartWebServer(); +SplashKit.WriteLine("About to start the server..."); - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +// Start a web server - defaults to listening to port 8080 +WebServer server = SplashKit.StartWebServer(); - // Wait and get the first request that comes in - HttpRequest request = SplashKit.NextWebRequest(server); +SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - // Send back the index.html file - SplashKit.SendHtmlFileResponse(request, "index.html"); +// Wait and get the first request that comes in +HttpRequest request = SplashKit.NextWebRequest(server); - // For now, we are done, so let's shutdown - SplashKit.StopWebServer(server); +// Send back the index.html file +SplashKit.SendHtmlFileResponse(request, "index.html"); - SplashKit.ReadLine(); // Pause to keep the console window open - ``` +// For now, we are done, so let's shutdown +SplashKit.StopWebServer(server); +``` - + - ```python - from splashkit import * +```csharp +using SplashKitSDK; - write_line("About to start the server...") +namespace WebServerApp +{ + public class Program + { + public static void Main() + { + SplashKit.WriteLine("About to start the server..."); - # Start a web server - defaults to listening to port 8080 - server = start_web_server_with_default_port() + // Start a web server - defaults to listening to port 8080 + WebServer server = SplashKit.StartWebServer(); - write_line("Waiting for a request - navigate to http://localhost:8080") + SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - # Wait and get the first request that comes in - request = next_web_request(server) + // Wait and get the first request that comes in + HttpRequest request = SplashKit.NextWebRequest(server); - # Send back the index.html file - send_html_file_response(request, "index.html") + // Send back the index.html file + SplashKit.SendHtmlFileResponse(request, "index.html"); - # For now, we are done, so let's shutdown - stop_web_server(server) + // For now, we are done, so let's shutdown + SplashKit.StopWebServer(server); + } + } +} +``` - read_line() # Pause to keep the console window open - ``` + + + + + + +```python +from splashkit import * + +write_line("About to start the server...") + +# Start a web server - defaults to listening to port 8080 +server = start_web_server_with_default_port() + +write_line("Waiting for a request - navigate to http://localhost:8080") + +# Wait and get the first request that comes in +request = next_web_request(server) + +# Send back the index.html file +send_html_file_response(request, "index.html") + +# For now, we are done, so let's shutdown +stop_web_server(server) +``` @@ -129,47 +162,48 @@ The following code shows the use of an if statement to serve some login text or - ```cpp - #include "splashkit.h" - - int main() - { - write_line("About to start the server..."); +```cpp +#include "splashkit.h" - web_server server = start_web_server(); - http_request request; +int main() +{ + write_line("About to start the server..."); - write_line("Waiting for a request - navigate to http://localhost:8080"); + web_server server = start_web_server(); + http_request request; - //Get the next request that the server has - request = next_web_request(server); + write_line("Waiting for a request - navigate to http://localhost:8080"); - write_line("I got a request for " + request_uri(request)); + //Get the next request that the server has + request = next_web_request(server); - if (is_get_request_for(request, "/login") or is_get_request_for(request, "/login.html")) - { - // Serve page for login path, e.g. - // send_html_file_response(request, "login.html"); + write_line("I got a request for " + request_uri(request)); - send_response(request, "login page"); - } - else - { - //If no specified path is requested, serve index.html to the user - send_html_file_response(request, "index.html"); - } + if (is_get_request_for(request, "/login") or is_get_request_for(request, "/login.html")) + { + // Serve page for login path + send_response(request, "login page"); + } + else + { + //If no specified path is requested, serve index.html to the user + send_html_file_response(request, "index.html"); + } - write_line("About to stop the server..."); - stop_web_server(server); + write_line("About to stop the server..."); + stop_web_server(server); - return 0; - } - ``` + return 0; +} +``` - ```csharp + + + +```csharp using SplashKitSDK; SplashKit.WriteLine("About to start the server..."); @@ -197,39 +231,81 @@ else SplashKit.WriteLine("About to stop the server..."); SplashKit.StopWebServer(server); +``` + + + - ``` +```csharp +using SplashKitSDK; + +namespace WebServerApp +{ + public class Program + { + public static void Main() + { + SplashKit.WriteLine("About to start the server..."); + + WebServer server = SplashKit.StartWebServer(); + HttpRequest request; + + SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); + + // Get the next request that the server has + request = SplashKit.NextWebRequest(server); + + SplashKit.WriteLine("I got a request for " + SplashKit.RequestURI(request)); + + if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) + { + // Serve page for login path + SplashKit.SendResponse(request, "login page"); + } + else + { + // If no specified path is requested, serve index.html to the user + SplashKit.SendHtmlFileResponse(request, "index.html"); + } + + SplashKit.WriteLine("About to stop the server..."); + SplashKit.StopWebServer(server); + } + } +} +``` - + - ```python - from splashkit import * + + - write_line("About to start the server...") +```python +from splashkit import * - server = start_web_server_with_default_port() +write_line("About to start the server...") - write_line("Waiting for a request - navigate to http://localhost:8080") +server = start_web_server_with_default_port() - # Get the next request that the server has - request = next_web_request(server) +write_line("Waiting for a request - navigate to http://localhost:8080") - write_line("I got a request for " + request_uri(request)) +# Get the next request that the server has +request = next_web_request(server) +write_line("I got a request for " + request_uri(request)) - if is_get_request_for(request, "/login") or is_get_request_for(request, "/login.html"): - # Serve page for login path, e.g. - # send_html_file_response(request, "login.html") - send_response(request, "login page") - else: - # If no specified path is requested, serve index.html to the user - send_html_file_response(request, "index.html") +if is_get_request_for(request, "/login") or is_get_request_for(request, "/login.html"): + # Serve page for login path + send_response(request, "login page") +else: + # If no specified path is requested, serve index.html to the user + send_html_file_response(request, "index.html") - write_line("About to stop the server...") - stop_web_server(server) - ``` +write_line("About to stop the server...") +stop_web_server(server) +``` @@ -249,176 +325,251 @@ The following code illustrates the use of the concepts covered so far. You can n - ```cpp - #include "splashkit.h" - - int main() - { - write_line("About to start the server..."); - - web_server server = start_web_server(); - http_request request; - - write_line("Waiting for a request - navigate to http://localhost:8080"); - write_line("To end - navigate to http://localhost:8080/quit"); - - //Get the next request that the server has - request = next_web_request(server); - - while ( ! is_get_request_for(request, "/quit") ) - { - write_line("I got a request for " + request_uri(request)); +```cpp +#include "splashkit.h" - if (is_get_request_for(request, "/login") or is_get_request_for(request, "/login.html")) - { - // Serve page for login path, e.g. - // send_html_file_response(request, "login.html"); - - send_response(request, "login page"); - } - else if (is_get_request_for(request, "/contact") or is_get_request_for(request, "/contact.html")) - { - // Serve page for contact path, e.g. - // send_html_file_response(request, "contact.html"); - - send_response(request, "contact page"); - } - else if (is_get_request_for(request, "/about") or is_get_request_for(request, "/about.html")) - { - // Server page for about path, e.g. - // send_html_file_response(request, "about.html"); - - send_response(request, "about page"); - } - else - { - //If no specified path is requested, serve index.html to the user - send_html_file_response(request, "index.html"); - } - - write_line("Waiting for a request - navigate to http://localhost:8080"); - write_line("To end - navigate to http://localhost:8080/quit"); - - //Get the next request that the server has - request = next_web_request(server); - } - - write_line("About to stop the server..."); - stop_web_server(server); - - return 0; - } - ``` +int main() +{ + write_line("About to start the server..."); + + web_server server = start_web_server(); + http_request request; + + write_line("Waiting for a request - navigate to http://localhost:8080"); + write_line("To end - navigate to http://localhost:8080/quit"); + + //Get the next request that the server has + request = next_web_request(server); + + while ( ! is_get_request_for(request, "/quit") ) + { + write_line("I got a request for " + request_uri(request)); + + if (is_get_request_for(request, "/login") or is_get_request_for(request, "/login.html")) + { + // Serve page for login path, e.g. + // send_html_file_response(request, "login.html"); + + send_response(request, "login page"); + } + else if (is_get_request_for(request, "/contact") or is_get_request_for(request, "/contact.html")) + { + // Serve page for contact path, e.g. + // send_html_file_response(request, "contact.html"); + + send_response(request, "contact page"); + } + else if (is_get_request_for(request, "/about") or is_get_request_for(request, "/about.html")) + { + // Server page for about path, e.g. + // send_html_file_response(request, "about.html"); + + send_response(request, "about page"); + } + else + { + //If no specified path is requested, serve index.html to the user + send_html_file_response(request, "index.html"); + } + + write_line("Waiting for a request - navigate to http://localhost:8080"); + write_line("To end - navigate to http://localhost:8080/quit"); + + //Get the next request that the server has + request = next_web_request(server); + } + + write_line("About to stop the server..."); + stop_web_server(server); + + return 0; +} +``` - ```csharp - using SplashKitSDK; + + - SplashKit.WriteLine("About to start the server..."); +```csharp +using SplashKitSDK; - WebServer server = SplashKit.StartWebServer(); - HttpRequest request; +SplashKit.WriteLine("About to start the server..."); - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); +WebServer server = SplashKit.StartWebServer(); +HttpRequest request; - // Get the next request that the server has - request = SplashKit.NextWebRequest(server); +SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); - while (!SplashKit.IsGetRequestFor(request, "/quit")) - { - SplashKit.WriteLine("I got a request for " + SplashKit.RequestURI(request)); +// Get the next request that the server has +request = SplashKit.NextWebRequest(server); - if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) - { - // Serve page for login path, e.g. - // SendHtmlFileResponse(request, "login.html"); +while (!SplashKit.IsGetRequestFor(request, "/quit")) +{ + SplashKit.WriteLine("I got a request for " + SplashKit.RequestURI(request)); + + if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) + { + // Serve page for login path, e.g. + // SendHtmlFileResponse(request, "login.html"); + + SplashKit.SendResponse(request, "login page"); + } + else if (SplashKit.IsGetRequestFor(request, "/contact") || SplashKit.IsGetRequestFor(request, "/contact.html")) + { + // Serve page for contact path, e.g. + // SendHtmlFileResponse(request, "contact.html"); + + SplashKit.SendResponse(request, "contact page"); + } + else if (SplashKit.IsGetRequestFor(request, "/about") || SplashKit.IsGetRequestFor(request, "/about.html")) + { + // Serve page for about path, e.g. + // SendHtmlFileResponse(request, "about.html"); + + SplashKit.SendResponse(request, "about page"); + } + else + { + // If no specified path is requested, serve index.html to the user + SplashKit.SendHtmlFileResponse(request, "index.html"); + } + + SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); + SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); + + // Get the next request that the server has + request = SplashKit.NextWebRequest(server); +} - SplashKit.SendResponse(request, "login page"); - } - else if (SplashKit.IsGetRequestFor(request, "/contact") || SplashKit.IsGetRequestFor(request, "/contact.html")) - { - // Serve page for contact path, e.g. - // SendHtmlFileResponse(request, "contact.html"); +SplashKit.WriteLine("About to stop the server..."); +SplashKit.StopWebServer(server); +``` - SplashKit.SendResponse(request, "contact page"); - } - else if (SplashKit.IsGetRequestFor(request, "/about") || SplashKit.IsGetRequestFor(request, "/about.html")) - { - // Serve page for about path, e.g. - // SendHtmlFileResponse(request, "about.html"); + + - SplashKit.SendResponse(request, "about page"); - } - else - { - // If no specified path is requested, serve index.html to the user - SplashKit.SendHtmlFileResponse(request, "index.html"); - } +```csharp - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); +using SplashKitSDK; - // Get the next request that the server has - request = SplashKit.NextWebRequest(server); - } +namespace WebServerApp +{ + public class Program + { + public static void Main() + { + SplashKit.WriteLine("About to start the server..."); + + WebServer server = SplashKit.StartWebServer(); + HttpRequest request; + + SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); + SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); + + // Get the next request that the server has + request = SplashKit.NextWebRequest(server); + + while (!SplashKit.IsGetRequestFor(request, "/quit")) + { + SplashKit.WriteLine("I got a request for " + SplashKit.RequestURI(request)); + + if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) + { + // Serve page for login path, e.g. + // SendHtmlFileResponse(request, "login.html"); + + SplashKit.SendResponse(request, "login page"); + } + else if (SplashKit.IsGetRequestFor(request, "/contact") || SplashKit.IsGetRequestFor(request, "/contact.html")) + { + // Serve page for contact path, e.g. + // SendHtmlFileResponse(request, "contact.html"); + + SplashKit.SendResponse(request, "contact page"); + } + else if (SplashKit.IsGetRequestFor(request, "/about") || SplashKit.IsGetRequestFor(request, "/about.html")) + { + // Serve page for about path, e.g. + // SendHtmlFileResponse(request, "about.html"); + + SplashKit.SendResponse(request, "about page"); + } + else + { + // If no specified path is requested, serve index.html to the user + SplashKit.SendHtmlFileResponse(request, "index.html"); + } + + SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); + SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); + + // Get the next request that the server has + request = SplashKit.NextWebRequest(server); + } + + SplashKit.WriteLine("About to stop the server..."); + SplashKit.StopWebServer(server); + } + } +} +``` - SplashKit.WriteLine("About to stop the server..."); - SplashKit.StopWebServer(server); - ``` + + - ```python - from splashkit import * +```python +from splashkit import * - write_line("About to start the server...") +write_line("About to start the server...") - server = start_web_server_with_default_port() +server = start_web_server_with_default_port() - write_line("Waiting for a request - navigate to http://localhost:8080") - write_line("To end - navigate to http://localhost:8080/quit") +write_line("Waiting for a request - navigate to http://localhost:8080") +write_line("To end - navigate to http://localhost:8080/quit") - # Get the next request that the server has - request = next_web_request(server) +# Get the next request that the server has +request = next_web_request(server) - while not is_get_request_for(request, "/quit"): - write_line("I got a request for " + request_uri(request)) +while not is_get_request_for(request, "/quit"): + write_line("I got a request for " + request_uri(request)) - if is_get_request_for(request, "/login") or is_get_request_for(request, "/login.html"): - # Serve page for login path, e.g. - # send_html_file_response(request, "login.html") + if is_get_request_for(request, "/login") or is_get_request_for(request, "/login.html"): + # Serve page for login path, e.g. + # send_html_file_response(request, "login.html") - send_response(request, "login page") - elif is_get_request_for(request, "/contact") or is_get_request_for(request, "/contact.html"): - # Serve page for contact path, e.g. - # send_html_file_response(request, "contact.html") + send_response(request, "login page") + elif is_get_request_for(request, "/contact") or is_get_request_for(request, "/contact.html"): + # Serve page for contact path, e.g. + # send_html_file_response(request, "contact.html") - send_response(request, "contact page") - - elif is_get_request_for(request, "/about") or is_get_request_for(request, "/about.html"): - # Server page for about path, e.g. - # send_html_file_response(request, "about.html") + send_response(request, "contact page") + + elif is_get_request_for(request, "/about") or is_get_request_for(request, "/about.html"): + # Server page for about path, e.g. + # send_html_file_response(request, "about.html") - send_response(request, "about page") + send_response(request, "about page") - else: - # If no specified path is requested, serve index.html to the user - send_html_file_response(request, "index.html") + else: + # If no specified path is requested, serve index.html to the user + send_html_file_response(request, "index.html") - write_line("Waiting for a request - navigate to http://localhost:8080") - write_line("To end - navigate to http://localhost:8080/quit") + write_line("Waiting for a request - navigate to http://localhost:8080") + write_line("To end - navigate to http://localhost:8080/quit") - # Get the next request that the server has - request = next_web_request(server) + # Get the next request that the server has + request = next_web_request(server) - write_line("About to stop the server...") - stop_web_server(server) - ``` +write_line("About to stop the server...") +stop_web_server(server) +``` @@ -464,4 +615,4 @@ Add links to contact and about to index.html in this same manner, then try playi ## What next? -With these concepts you should have enough to create a simple web server. You could make this more dynamic by reading details from the path in the URI, and then storing details within the program or in an associated database. The main thing to remember is that when you build a web server you need to wait for an incoming request, do some processing, and return a response. \ No newline at end of file +With these concepts you should have enough to create a simple web server. You could make this more dynamic by reading details from the path in the URI, and then storing details within the program or in an associated database. The main thing to remember is that when you build a web server you need to wait for an incoming request, do some processing, and return a response. From 0c0813f9d08d511be94f6767e8e8ebeb36a7a5d9 Mon Sep 17 00:00:00 2001 From: Breezy <114720008+breezy-codes@users.noreply.github.com> Date: Wed, 2 Oct 2024 17:39:32 +1000 Subject: [PATCH 16/30] Adding OOP to RESTful API Calls (#202) --- .../0-getting-started-with-servers.mdx | 46 ++--- .../Networking/1-routing-with-servers.mdx | 73 +++---- .../guides/Networking/2-restful-api-call.mdx | 178 +++++++++++++++--- 3 files changed, 203 insertions(+), 94 deletions(-) diff --git a/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx b/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx index 6438d5fe..17bb18d1 100644 --- a/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx +++ b/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx @@ -74,16 +74,17 @@ int main() ```csharp +using static SplashKitSDK.SplashKit; using SplashKitSDK; Console.WriteLine("About to start the server..."); // Start a web server - defaults to listening to port 8080 -WebServer server = SplashKit.StartWebServer(); +WebServer server = StartWebServer(); // For now, we are done... so let's shutdown... -SplashKit.StopWebServer(server); - ``` +StopWebServer(server); +``` @@ -173,25 +174,24 @@ int main() ```csharp +using static SplashKitSDK.SplashKit; using SplashKitSDK; -SplashKit.WriteLine("About to start the server..."); +WriteLine("About to start the server..."); // Start a web server - defaults to listening to port 8080 -WebServer server = SplashKit.StartWebServer(); +WebServer server = StartWebServer(); -SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +WriteLine("Waiting for a request - navigate to http://localhost:8080"); // Wait and get the first request that comes in -HttpRequest request = SplashKit.NextWebRequest(server); +HttpRequest request = NextWebRequest(server); // Send back the index.html file -SplashKit.SendResponse(request, "Hello World"); +SendResponse(request, "Hello World"); // For now, we are done, so let's shutdown -SplashKit.StopWebServer(server); - -SplashKit.ReadLine(); // Pause to keep the console window open +StopWebServer(server); ``` @@ -222,8 +222,6 @@ namespace WebServerApp // For now, we are done, so let's shutdown SplashKit.StopWebServer(server); - - SplashKit.ReadLine(); // Pause to keep the console window open } } } @@ -253,8 +251,6 @@ send_response(request, "Hello World") # For now, we are done, so let's shutdown stop_web_server(server) - -read_line() # Pause to keep the console window open ``` @@ -303,32 +299,30 @@ int main() ```csharp +using static SplashKitSDK.SplashKit; using SplashKitSDK; -SplashKit.WriteLine("About to start the server..."); +WriteLine("About to start the server..."); // Start a web server - defaults to listening to port 8080 -WebServer server = SplashKit.StartWebServer(); +WebServer server = StartWebServer(); -SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +WriteLine("Waiting for a request - navigate to http://localhost:8080"); // Wait and get the first request that comes in -HttpRequest request = SplashKit.NextWebRequest(server); +HttpRequest request = NextWebRequest(server); // Send back the index.html file -SplashKit.SendHtmlFileResponse(request, "index.html"); +SendHtmlFileResponse(request, "index.html"); // For now, we are done, so let's shutdown -SplashKit.StopWebServer(server); - -SplashKit.ReadLine(); // Pause to keep the console window open +StopWebServer(server); ``` ```csharp - using SplashKitSDK; namespace WebServerApp @@ -352,8 +346,6 @@ namespace WebServerApp // For now, we are done, so let's shutdown SplashKit.StopWebServer(server); - - SplashKit.ReadLine(); // Pause to keep the console window open } } } @@ -383,8 +375,6 @@ send_html_file_response(request, "index.html") # For now, we are done, so let's shutdown stop_web_server(server) - -read_line() # Pause to keep the console window open ``` diff --git a/src/content/docs/guides/Networking/1-routing-with-servers.mdx b/src/content/docs/guides/Networking/1-routing-with-servers.mdx index f9e3ab0f..87555960 100644 --- a/src/content/docs/guides/Networking/1-routing-with-servers.mdx +++ b/src/content/docs/guides/Networking/1-routing-with-servers.mdx @@ -59,23 +59,24 @@ int main() ```csharp +using static SplashKitSDK.SplashKit; using SplashKitSDK; -SplashKit.WriteLine("About to start the server..."); +WriteLine("About to start the server..."); // Start a web server - defaults to listening to port 8080 -WebServer server = SplashKit.StartWebServer(); +WebServer server = StartWebServer(); -SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +WriteLine("Waiting for a request - navigate to http://localhost:8080"); // Wait and get the first request that comes in -HttpRequest request = SplashKit.NextWebRequest(server); +HttpRequest request = NextWebRequest(server); // Send back the index.html file -SplashKit.SendHtmlFileResponse(request, "index.html"); +SendHtmlFileResponse(request, "index.html"); // For now, we are done, so let's shutdown -SplashKit.StopWebServer(server); +StopWebServer(server); ``` @@ -204,33 +205,34 @@ int main() ```csharp +using static SplashKitSDK.SplashKit; using SplashKitSDK; -SplashKit.WriteLine("About to start the server..."); +WriteLine("About to start the server..."); -WebServer server = SplashKit.StartWebServer(); +WebServer server = StartWebServer(); HttpRequest request; -SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +WriteLine("Waiting for a request - navigate to http://localhost:8080"); // Get the next request that the server has -request = SplashKit.NextWebRequest(server); +request = NextWebRequest(server); -SplashKit.WriteLine("I got a request for " + SplashKit.RequestURI(request)); +WriteLine("I got a request for " + RequestURI(request)); -if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) +if (IsGetRequestFor(request, "/login") || IsGetRequestFor(request, "/login.html")) { // Serve page for login path - SplashKit.SendResponse(request, "login page"); + SendResponse(request, "login page"); } else { // If no specified path is requested, serve index.html to the user - SplashKit.SendHtmlFileResponse(request, "index.html"); + SendHtmlFileResponse(request, "index.html"); } -SplashKit.WriteLine("About to stop the server..."); -SplashKit.StopWebServer(server); +WriteLine("About to stop the server..."); +StopWebServer(server); ``` @@ -393,59 +395,60 @@ int main() ```csharp +using static SplashKitSDK.SplashKit; using SplashKitSDK; -SplashKit.WriteLine("About to start the server..."); +WriteLine("About to start the server..."); -WebServer server = SplashKit.StartWebServer(); +WebServer server = StartWebServer(); HttpRequest request; -SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); -SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); +WriteLine("Waiting for a request - navigate to http://localhost:8080"); +WriteLine("To end - navigate to http://localhost:8080/quit"); // Get the next request that the server has -request = SplashKit.NextWebRequest(server); +request = NextWebRequest(server); -while (!SplashKit.IsGetRequestFor(request, "/quit")) +while (!IsGetRequestFor(request, "/quit")) { - SplashKit.WriteLine("I got a request for " + SplashKit.RequestURI(request)); + WriteLine("I got a request for " + RequestURI(request)); - if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) + if (IsGetRequestFor(request, "/login") || IsGetRequestFor(request, "/login.html")) { // Serve page for login path, e.g. // SendHtmlFileResponse(request, "login.html"); - SplashKit.SendResponse(request, "login page"); + SendResponse(request, "login page"); } - else if (SplashKit.IsGetRequestFor(request, "/contact") || SplashKit.IsGetRequestFor(request, "/contact.html")) + else if (IsGetRequestFor(request, "/contact") || IsGetRequestFor(request, "/contact.html")) { // Serve page for contact path, e.g. // SendHtmlFileResponse(request, "contact.html"); - SplashKit.SendResponse(request, "contact page"); + SendResponse(request, "contact page"); } - else if (SplashKit.IsGetRequestFor(request, "/about") || SplashKit.IsGetRequestFor(request, "/about.html")) + else if (IsGetRequestFor(request, "/about") || IsGetRequestFor(request, "/about.html")) { // Serve page for about path, e.g. // SendHtmlFileResponse(request, "about.html"); - SplashKit.SendResponse(request, "about page"); + SendResponse(request, "about page"); } else { // If no specified path is requested, serve index.html to the user - SplashKit.SendHtmlFileResponse(request, "index.html"); + SendHtmlFileResponse(request, "index.html"); } - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); + WriteLine("Waiting for a request - navigate to http://localhost:8080"); + WriteLine("To end - navigate to http://localhost:8080/quit"); // Get the next request that the server has - request = SplashKit.NextWebRequest(server); + request = NextWebRequest(server); } -SplashKit.WriteLine("About to stop the server..."); -SplashKit.StopWebServer(server); +WriteLine("About to stop the server..."); +StopWebServer(server); ``` diff --git a/src/content/docs/guides/Networking/2-restful-api-call.mdx b/src/content/docs/guides/Networking/2-restful-api-call.mdx index ae8cd2ba..cb83af1b 100644 --- a/src/content/docs/guides/Networking/2-restful-api-call.mdx +++ b/src/content/docs/guides/Networking/2-restful-api-call.mdx @@ -3,7 +3,7 @@ title: How to make a RESTful API call using SplashKit description: In the world of web services and microservices, many companies make their data available through a REST API in this document we want to use SplashKit to make a RESTful API call. category: Guides author: Cyrill Illi and Brianna Laird -lastupdated: Aug 10 2024 +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -65,23 +65,59 @@ int main()
+ + + ```csharp +using static SplashKitSDK.SplashKit; using SplashKitSDK; // Get a single JSON web resource -HttpResponse getData = SplashKit.HttpGet("https://jsonplaceholder.typicode.com/posts/1", 443); -string response = SplashKit.HttpResponseToString(getData); -SplashKit.FreeResponse(getData); +HttpResponse getData = HttpGet("https://jsonplaceholder.typicode.com/posts/1", 443); +string response = HttpResponseToString(getData); +FreeResponse(getData); // Output the response -Json jsonResponse = SplashKit.JsonFromString(response); -SplashKit.WriteLine("UserID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "userId")); -SplashKit.WriteLine("ID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "id")); -SplashKit.WriteLine("Title => " + SplashKit.JsonReadString(jsonResponse, "title")); -SplashKit.WriteLine("Body => " + SplashKit.JsonReadString(jsonResponse, "body")); -SplashKit.WriteLine("================"); +Json jsonResponse = JsonFromString(response); +WriteLine("UserID => " + JsonReadNumberAsInt(jsonResponse, "userId")); +WriteLine("ID => " + JsonReadNumberAsInt(jsonResponse, "id")); +WriteLine("Title => " + JsonReadString(jsonResponse, "title")); +WriteLine("Body => " + JsonReadString(jsonResponse, "body")); +WriteLine("================"); +``` + + + + +```csharp +using SplashKitSDK; + +namespace RESTfulAPIApp +{ + public class Program + { + public static void Main() + { + // Get a single JSON web resource + HttpResponse getData = SplashKit.HttpGet("https://jsonplaceholder.typicode.com/posts/1", 443); + string response = SplashKit.HttpResponseToString(getData); + SplashKit.FreeResponse(getData); + + // Output the response + Json jsonResponse = SplashKit.JsonFromString(response); + SplashKit.WriteLine("UserID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "userId")); + SplashKit.WriteLine("ID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "id")); + SplashKit.WriteLine("Title => " + SplashKit.JsonReadString(jsonResponse, "title")); + SplashKit.WriteLine("Body => " + SplashKit.JsonReadString(jsonResponse, "body")); + SplashKit.WriteLine("================"); + } + } +} ``` + + + @@ -109,7 +145,7 @@ write_line("================") After running this example, you'll get an output like this to the terminal: -```bash +```shell UserID => 1 ID => 1 Title => sunt aut facere repellat provident occaecati excepturi optio reprehenderit @@ -149,20 +185,51 @@ int main() + + ```csharp +using static SplashKitSDK.SplashKit; using SplashKitSDK; // Get a list of a JSON web resource -HttpResponse getData = SplashKit.HttpGet("https://jsonplaceholder.typicode.com/posts/", 443); -string response = SplashKit.HttpResponseToString(getData); -SplashKit.FreeResponse(getData); +HttpResponse getData = HttpGet("https://jsonplaceholder.typicode.com/posts/", 443); +string response = HttpResponseToString(getData); +FreeResponse(getData); // To access each JSON key value pair the string should be split to an vector // objects for simplicity sake we output just the string here. -SplashKit.WriteLine(response); +WriteLine(response); ``` + + + +```csharp +using SplashKitSDK; + +namespace RESTfulAPIApp +{ + public class Program + { + public static void Main() + { + // Get a list of a JSON web resource + HttpResponse getData = SplashKit.HttpGet("https://jsonplaceholder.typicode.com/posts/", 443); + string response = SplashKit.HttpResponseToString(getData); + SplashKit.FreeResponse(getData); + + // To access each JSON key value pair the string should be split to an vector + // objects for simplicity sake we output just the string here. + SplashKit.WriteLine(response); + } + } +} +``` + + + + @@ -185,7 +252,7 @@ write_line(response) After running this example, you'll get an output like this to the terminal: -```bash +```shell [ { "userId": 1, @@ -248,16 +315,19 @@ int main() + + ```csharp +using static SplashKitSDK.SplashKit; using SplashKitSDK; // Create a JSON Web resource // Create the JSON body for the http post call -Json body = SplashKit.CreateJson(); -SplashKit.JsonSetString(body, "title", "foo"); -SplashKit.JsonSetString(body, "body", "test entry"); -SplashKit.JsonSetNumber(body, "userId", 1); +Json body = CreateJson(); +JsonSetString(body, "title", "foo"); +JsonSetString(body, "body", "test entry"); +JsonSetNumber(body, "userId", 1); // Create the headers for the HTTP POST call List headers = new List @@ -266,20 +336,66 @@ List headers = new List }; // Send the request -HttpResponse getData = SplashKit.HttpPost("https://jsonplaceholder.typicode.com/posts", 443, SplashKit.JsonToString(body), headers); -string response = SplashKit.HttpResponseToString(getData); -SplashKit.FreeResponse(getData); +HttpResponse getData = HttpPost("https://jsonplaceholder.typicode.com/posts", 443, JsonToString(body), headers); +string response = HttpResponseToString(getData); +FreeResponse(getData); // Output the response -Json jsonResponse = SplashKit.JsonFromString(response); -SplashKit.WriteLine("Following resource has been created"); -SplashKit.WriteLine("UserID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "userId")); -SplashKit.WriteLine("ID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "id")); -SplashKit.WriteLine("Title => " + SplashKit.JsonReadString(jsonResponse, "title")); -SplashKit.WriteLine("Body => " + SplashKit.JsonReadString(jsonResponse, "body")); -SplashKit.WriteLine("================"); +Json jsonResponse = JsonFromString(response); +WriteLine("Following resource has been created"); +WriteLine("UserID => " + JsonReadNumberAsInt(jsonResponse, "userId")); +WriteLine("ID => " + JsonReadNumberAsInt(jsonResponse, "id")); +WriteLine("Title => " + JsonReadString(jsonResponse, "title")); +WriteLine("Body => " + JsonReadString(jsonResponse, "body")); +WriteLine("================"); +``` + + + + +```csharp +using SplashKitSDK; + +namespace RESTfulAPIApp +{ + public class Program + { + public static void Main() + { + // Create a JSON Web resource + // Create the JSON body for the http post call + Json body = SplashKit.CreateJson(); + SplashKit.JsonSetString(body, "title", "foo"); + SplashKit.JsonSetString(body, "body", "test entry"); + SplashKit.JsonSetNumber(body, "userId", 1); + + // Create the headers for the HTTP POST call + List headers = new List + { + "Content-type: application/json; charset=UTF-8" + }; + + // Send the request + HttpResponse getData = SplashKit.HttpPost("https://jsonplaceholder.typicode.com/posts", 443, SplashKit.JsonToString(body), headers); + string response = SplashKit.HttpResponseToString(getData); + SplashKit.FreeResponse(getData); + + // Output the response + Json jsonResponse = SplashKit.JsonFromString(response); + SplashKit.WriteLine("Following resource has been created"); + SplashKit.WriteLine("UserID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "userId")); + SplashKit.WriteLine("ID => " + SplashKit.JsonReadNumberAsInt(jsonResponse, "id")); + SplashKit.WriteLine("Title => " + SplashKit.JsonReadString(jsonResponse, "title")); + SplashKit.WriteLine("Body => " + SplashKit.JsonReadString(jsonResponse, "body")); + SplashKit.WriteLine("================"); + } + } +} ``` + + + @@ -316,7 +432,7 @@ write_line("================") After running this example, you'll get an output like this to the terminal: -```bash +```shell Following resource has been created UserID => 1 ID => 101 From b79ccbedfe3f061abd07242e501cbd143b95b8bb Mon Sep 17 00:00:00 2001 From: Oliver Exell-Bruce <87453519+oliverexell-bruce@users.noreply.github.com> Date: Wed, 2 Oct 2024 18:13:30 +1000 Subject: [PATCH 17/30] Useful utilities review (#176) --- .../guides/Utilities/0-useful-utilities.mdx | 872 +++++++++++------- 1 file changed, 550 insertions(+), 322 deletions(-) diff --git a/src/content/docs/guides/Utilities/0-useful-utilities.mdx b/src/content/docs/guides/Utilities/0-useful-utilities.mdx index f64346f8..60f4afd9 100644 --- a/src/content/docs/guides/Utilities/0-useful-utilities.mdx +++ b/src/content/docs/guides/Utilities/0-useful-utilities.mdx @@ -3,7 +3,7 @@ title: Useful Utilities description: In this article, we discuss useful utilities that you can use to convert, check and manipulate common data types in SplashKit programs. category: Guides author: Richard Denton -lastupdated: July 2024 +lastupdated: 09 September 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -14,7 +14,7 @@ _Last updated: {frontmatter.lastupdated}_ --- -SplashKit's [Utilities library](/api/utilities) provides a range of useful functions that can assist you with converting, checking and manipulating common data types in your SplashKit program. +SplashKit's [Utilities library](/api/utilities) provides a range of useful functions that can assist you with converting, checking, and manipulating common data types in your SplashKit program. These functions are useful in many areas of programming. @@ -31,71 +31,106 @@ SplashKit provides two useful functions for handling the conversion of a `string - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - // Convert the string "2017" to an integer 2017 - string some_string = "2017"; - int some_number = convert_to_integer(some_string); +int main() +{ + // Convert the string "2017" to an integer 2017 + string some_string = "2017"; + int some_number = convert_to_integer(some_string); - write("The value of some_number is: "); - write_line(some_number); + write("The value of some_number is: "); + write_line(some_number); - // Convert the string "3.14159265358979" to a double ~3.141593 - string pi_string = "3.14159265358979"; - double pi = convert_to_double(pi_string); + // Convert the string "3.14159265358979" to a double ~3.141593 + string pi_string = "3.14159265358979"; + double pi = convert_to_double(pi_string); - write("The value of pi is: "); - write_line(pi); + write("The value of pi is: "); + write_line(pi); - return 0; - } - ``` + return 0; +} +``` - ```csharp - using static SplashKitSDK.SplashKit; + + - //Convert the string "2017" to an integer 2017 - string some_string = "2017"; - int some_number = ConvertToInteger(some_string); +```csharp +using static SplashKitSDK.SplashKit; - Write("The value of some_number is: "); - WriteLine(some_number); +//Convert the string "2017" to an integer 2017 +string some_string = "2017"; +int some_number = ConvertToInteger(some_string); - //Convert the string "3.14159265358979" to a double ~3.141593 - string pi_string = "3.14159265358979"; - double pi = ConvertToDouble(pi_string); +Write("The value of some_number is: "); +WriteLine(some_number); - Write("The value of pi is: "); - WriteLine(pi); - ``` +//Convert the string "3.14159265358979" to a double ~3.141593 +string pi_string = "3.14159265358979"; +double pi = ConvertToDouble(pi_string); + +Write("The value of pi is: "); +WriteLine(pi); +``` - + - ```python - from splashkit import * +```csharp +using SplashKitSDK; - ## Convert the string "2017" to an integer 2017 - some_string = "2017" - some_number = convert_to_integer(some_string) +namespace UsefulUtilities +{ + public class Program + { + public static void Main() + { + //Convert the string "2017" to an integer 2017 + string some_string = "2017"; + int some_number = SplashKit.ConvertToInteger(some_string); + + SplashKit.Write("The value of some_number is: "); + SplashKit.WriteLine(some_number); + + //Convert the string "3.14159265358979" to a double ~3.141593 + string pi_string = "3.14159265358979"; + double pi = SplashKit.ConvertToDouble(pi_string); + + SplashKit.Write("The value of pi is: "); + SplashKit.WriteLine(pi); + } + } +} +``` - write("The value of some_number is: ") - write_line_int(some_number) + + - ## Convert the string "3.14159265358979" to a double ~3.141593 - pi_string = "3.14159265358979" - pi = convert_to_double(pi_string) + + - write("The value of pi is: ") - write_line_double(pi) +```python +from splashkit import * - ``` +## Convert the string "2017" to an integer 2017 +some_string = "2017" +some_number = convert_to_integer(some_string) + +write("The value of some_number is: ") +write_line_int(some_number) + +## Convert the string "3.14159265358979" to a double ~3.141593 +pi_string = "3.14159265358979" +pi = convert_to_double(pi_string) + +write("The value of pi is: ") +write_line_double(pi) +``` @@ -107,136 +142,197 @@ Consider you want to write a program that accepts two numbers as input from a us - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - // User input will initially be stored in these two strings. - string snum_1, snum_2; +int main() +{ + // User input will initially be stored in these two strings. + string snum_1, snum_2; - // And then it will be converted and stored in these integers. - int inum_1, inum_2, result; + // And then it will be converted and stored in these integers. + int inum_1, inum_2, result; - // Read user input - write("Enter first number: "); - snum_1 = read_line(); - write("Enter second number: "); - snum_2 = read_line(); + // Read user input + write("Enter first number: "); + snum_1 = read_line(); + write("Enter second number: "); + snum_2 = read_line(); - // Convert user input to integers - inum_1 = convert_to_integer(snum_1); - inum_2 = convert_to_integer(snum_2); + // Convert user input to integers + inum_1 = convert_to_integer(snum_1); + inum_2 = convert_to_integer(snum_2); - // Compute the result - result = inum_1 * inum_2; + // Compute the result + result = inum_1 * inum_2; - // Output the results - write(snum_1 + " multiplied by " + snum_2 + " equals "); - write_line(result); + // Output the results + write(snum_1 + " multiplied by " + snum_2 + " equals "); + write_line(result); - return 0; - } - ``` + return 0; +} +``` - The same can be achieved for decimal numbers, simply by swapping `convert_to_integer` with `convert_to_double`, and using the appropriate data types. +The same can be achieved for decimal numbers, simply by swapping `convert_to_integer` with `convert_to_double`, and using the appropriate data types. - ```cpp - //... +```cpp +//... - //Don't use integers, instead use doubles - double inum_1, inum_2, result; +//Don't use integers, instead use doubles +double inum_1, inum_2, result; - //... +//... - inum_1 = convert_to_double(snum_1); - inum_2 = convert_to_double(snum_2); +inum_1 = convert_to_double(snum_1); +inum_2 = convert_to_double(snum_2); - //... - ``` +//... +``` - ```csharp - using static SplashKitSDK.SplashKit; + + - //User input will initially be stored in these two strings. - string snum_1, snum_2; +```csharp +using static SplashKitSDK.SplashKit; - // And then it will be converted and stored in these integers. - int inum_1, inum_2, result; +//User input will initially be stored in these two strings. +string snum_1, snum_2; - //Read user input - Write("Enter first number: "); - snum_1 = ReadLine(); - Write("Enter second number: "); - snum_2 = ReadLine(); +// And then it will be converted and stored in these integers. +int inum_1, inum_2, result; - //Convert user input to integers - inum_1 = ConvertToInteger(snum_1); - inum_2 = ConvertToInteger(snum_2); +//Read user input +Write("Enter first number: "); +snum_1 = ReadLine(); +Write("Enter second number: "); +snum_2 = ReadLine(); - //Compute the result - result = inum_1 * inum_2; +//Convert user input to integers +inum_1 = ConvertToInteger(snum_1); +inum_2 = ConvertToInteger(snum_2); - //Output the results - Write(snum_1 + " multiplied by " + snum_2 + " equals "); - WriteLine(result); - ``` +//Compute the result +result = inum_1 * inum_2; - The same can be achieved for decimal numbers, simply by swapping `ConvertToInteger`with `ConvertToDouble`, and using the appropriate data types. +//Output the results +Write(snum_1 + " multiplied by " + snum_2 + " equals "); +WriteLine(result); +``` - ```csharp - //... +The same can be achieved for decimal numbers, simply by swapping `ConvertToInteger`with `ConvertToDouble`, and using the appropriate data types. - // Don't use integers, instead use doubles - double inum_1, inum_2, result; +```csharp +//... - //... +// Don't use integers, instead use doubles +double inum_1, inum_2, result; - inum_1 = SplashKit.ConvertToDouble(snum_1); - inum_2 = SplashKit.ConvertToDouble(snum_2); +//... - //... - ``` +inum_1 = ConvertToDouble(snum_1); +inum_2 = ConvertToDouble(snum_2); + +//... +``` + + + + +```csharp +using SplashKitSDK; + +namespace UsefulUtilities +{ + public class Program + { + public static void Main() + { + //User input will initially be stored in these two strings. + string snum_1, snum_2; + + // And then it will be converted and stored in these integers. + int inum_1, inum_2, result; + + //Read user input + SplashKit.Write("Enter first number: "); + snum_1 = SplashKit.ReadLine(); + SplashKit.Write("Enter second number: "); + snum_2 = SplashKit.ReadLine(); + + //Convert user input to integers + inum_1 = SplashKit.ConvertToInteger(snum_1); + inum_2 = SplashKit.ConvertToInteger(snum_2); + + //Compute the result + result = inum_1 * inum_2; + + //Output the results + SplashKit.Write(snum_1 + " multiplied by " + snum_2 + " equals "); + SplashKit.WriteLine(result); + } + } +} +``` + +The same can be achieved for decimal numbers, simply by swapping `SplashKit.ConvertToInteger`with `SplashKit.ConvertToDouble`, and using the appropriate data types. + +```csharp +//... + +// Don't use integers, instead use doubles +double inum_1, inum_2, result; + +//... + +inum_1 = SplashKit.ConvertToDouble(snum_1); +inum_2 = SplashKit.ConvertToDouble(snum_2); + +//... +``` + + + - ```python - from splashkit import * +```python +from splashkit import * - # Read user input - write("Enter first number: ") - snum_1 = read_line() - write("Enter second number: ") - snum_2 = read_line() +# Read user input +write("Enter first number: ") +snum_1 = read_line() +write("Enter second number: ") +snum_2 = read_line() - # Convert user inputs to integers - inum_1 = convert_to_integer(snum_1) - inum_2 = convert_to_integer(snum_2) +# Convert user inputs to integers +inum_1 = convert_to_integer(snum_1) +inum_2 = convert_to_integer(snum_2) - # Compute the result - result = inum_1 * inum_2 +# Compute the result +result = inum_1 * inum_2 - # Output the result - write(snum_1 + " multiplied by " + snum_2 + " equals ") - write_line_int(result) - ``` +# Output the result +write(snum_1 + " multiplied by " + snum_2 + " equals ") +write_line_int(result) +``` - The same can be achieved for decimal numbers, simply by swapping `convert_to_integer` with `convert_to_double`, and using the appropriate data types. +The same can be achieved for decimal numbers, simply by swapping `convert_to_integer` with `convert_to_double`, and using the appropriate data types. - ```python - #... +```python +#... - # Don't uses integers, instead use doubles - inum_1 = convert_to_double(snum_1) - inum_2 = convert_to_double(snum_2) +# Don't uses integers, instead use doubles +inum_1 = convert_to_double(snum_1) +inum_2 = convert_to_double(snum_2) - #... - ``` +#... +``` @@ -250,95 +346,139 @@ Consider the following. - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - string message_1 = "9781273"; - string message_2 = "23129739.13"; - string message_3 = "Hello world."; +int main() +{ + string message_1 = "9781273"; + string message_2 = "23129739.13"; + string message_3 = "Hello world."; - if (is_integer(message_1)) - write_line("Message 1 contains an integer!"); + if (is_integer(message_1)) + write_line("Message 1 contains an integer!"); - if (is_number(message_1)) - write_line("Message 1 contains a number!"); + if (is_number(message_1)) + write_line("Message 1 contains a number!"); - if (not is_integer(message_2)) - write_line("Message 2 is not an integer!"); + if (not is_integer(message_2)) + write_line("Message 2 is not an integer!"); - if (is_number(message_2)) - write_line("Message 2 contains a number!"); + if (is_number(message_2)) + write_line("Message 2 contains a number!"); - if (not is_integer(message_3)) - write_line("Message 3 is not an integer!"); + if (not is_integer(message_3)) + write_line("Message 3 is not an integer!"); - if (not is_number(message_3)) - write_line("Message 3 is not a number!"); + if (not is_number(message_3)) + write_line("Message 3 is not a number!"); - return 0; - } - ``` + return 0; +} +``` - ```csharp - using static SplashKitSDK.SplashKit; + + - string message_1 = "9781273"; - string message_2 = "23129739.13"; - string message_3 = "Hello world."; +```csharp +using static SplashKitSDK.SplashKit; - if (IsInteger(message_1)) - WriteLine("Message 1 contains an integer!"); +string message_1 = "9781273"; +string message_2 = "23129739.13"; +string message_3 = "Hello world."; - if (IsNumber(message_1)) - WriteLine("Message 1 contains a number!"); +if (IsInteger(message_1)) + WriteLine("Message 1 contains an integer!"); - if (!IsInteger(message_2)) - WriteLine("Message 2 is not an integer!"); +if (IsNumber(message_1)) + WriteLine("Message 1 contains a number!"); - if (IsNumber(message_2)) - WriteLine("Message 2 contains a number!"); +if (!IsInteger(message_2)) + WriteLine("Message 2 is not an integer!"); - if (!IsInteger(message_3)) - WriteLine("Message 3 is not an integer!"); +if (IsNumber(message_2)) + WriteLine("Message 2 contains a number!"); - if (!IsNumber(message_3)) - WriteLine("Message 3 is not a number!"); - ``` +if (!IsInteger(message_3)) + WriteLine("Message 3 is not an integer!"); + +if (!IsNumber(message_3)) + WriteLine("Message 3 is not a number!"); +``` + + + + +```csharp +using SplashKitSDK; + +namespace UsefulUtilities +{ + public class Program + { + public static void Main() + { + string message_1 = "9781273"; + string message_2 = "23129739.13"; + string message_3 = "Hello world."; + + if (SplashKit.IsInteger(message_1)) + SplashKit.WriteLine("Message 1 contains an integer!"); + + if (SplashKit.IsNumber(message_1)) + SplashKit.WriteLine("Message 1 contains a number!"); + + if (!SplashKit.IsInteger(message_2)) + SplashKit.WriteLine("Message 2 is not an integer!"); + + if (SplashKit.IsNumber(message_2)) + SplashKit.WriteLine("Message 2 contains a number!"); + + if (!SplashKit.IsInteger(message_3)) + SplashKit.WriteLine("Message 3 is not an integer!"); + + if (!SplashKit.IsNumber(message_3)) + SplashKit.WriteLine("Message 3 is not a number!"); + } + } +} +``` + + + - ```python - from splashkit import * +```python +from splashkit import * - message_1 = "9781273" - message_2 = "23129739.13" - message_3 = "Hello world." +message_1 = "9781273" +message_2 = "23129739.13" +message_3 = "Hello world." - if is_integer(message_1): - write_line("Message 1 contains an integer!") +if is_integer(message_1): + write_line("Message 1 contains an integer!") - if is_number(message_1): - write_line("Message 1 contains a number!") +if is_number(message_1): + write_line("Message 1 contains a number!") - if not is_integer(message_2): - write_line("Message 2 is not an integer!") +if not is_integer(message_2): + write_line("Message 2 is not an integer!") - if is_number(message_2): - write_line("Message 2 contains a number!") +if is_number(message_2): + write_line("Message 2 contains a number!") - if not is_integer(message_3): - write_line("Message 3 is not an integer!") +if not is_integer(message_3): + write_line("Message 3 is not an integer!") - if not is_number(message_3): - write_line("Message 3 is not a number!") +if not is_number(message_3): + write_line("Message 3 is not a number!") - ``` +``` @@ -361,40 +501,41 @@ SplashKit's [Is Integer](/api/utilities/#is-integer) and [Is Number](/api/utilit - ```cpp - #include "splashkit.h" - #include +```cpp +#include "splashkit.h" +#include - using namespace std; +using namespace std; - /** - * Reads input from a user, only allowing whole numbers. - * @prompt string - The string to display to the user. - * @return int - */ - int read_integer(string prompt) - { - string buffer; +/** + * Reads input from a user, only allowing whole numbers. + * @prompt string - The string to display to the user. + * @return int + */ +int read_integer(string prompt) +{ - //Continue requesting user input until a valid whole number is entered. - while (1) + // Prompt the user with the message + write(prompt); + + // Read the user input as a string. + string line = read_line(); + + // Check if user input is a valid whole number, loop until it is. + while (!is_integer(line)) { - //Prompt the user with the message - write(prompt); - //Read the user input as a string. - buffer = read_line(); - //If the user input is a valid whole number, leave the loop. - if ( is_integer(buffer) ) - break; - //If the user input was not a valid whole number, ask them to enter a whole number. - write_line("Please enter a valid whole number."); + write_line("Please enter a whole number."); + + write(prompt); + line = read_line(); } - //Convert the user input to an integer before returning it. - return convert_to_integer(buffer); - } - int main() - { + // Convert the user input to an integer before returning it. + return convert_to_integer(line); +} + +int main() +{ int height; height = read_integer("Enter your height in centimetres: "); @@ -403,75 +544,124 @@ SplashKit's [Is Integer](/api/utilities/#is-integer) and [Is Number](/api/utilit write_line("CM tall!"); return 0; - } +} ``` - ```csharp - using static SplashKitSDK.SplashKit; - - static int ReadInteger(string prompt) - { - // Prompt the user with the message - Write(prompt); - - // Read the user input as a string. - string line = ReadLine(); - - // Loop while the user's input is NOT a valid whole number. - while (!IsInteger(line)) - { - // If the user input was not a valid whole number, ask them to enter a whole number. - WriteLine("Please enter a whole number."); - Write(prompt); - line = ReadLine(); - } - // Convert the user input to an integer before returning it. - return ConvertToInteger(line); - } - - // Start of "main" code - int height; - - height = ReadInteger("Enter your height in centimetres: "); - Write("You are "); - Write(height); - WriteLine("cm tall!"); - ``` + + + +```csharp +using static SplashKitSDK.SplashKit; + +static int ReadInteger(string prompt) +{ + // Prompt the user with the message + Write(prompt); + + // Read the user input as a string. + string line = ReadLine(); + + // Loop while the user's input is NOT a valid whole number. + while (!IsInteger(line)) + { + // If the user input was not a valid whole number, ask them to enter a whole number. + WriteLine("Please enter a whole number."); + Write(prompt); + line = ReadLine(); + } + // Convert the user input to an integer before returning it. + return ConvertToInteger(line); +} + +// Start of "main" code +int height; + +height = ReadInteger("Enter your height in centimetres: "); +Write("You are "); +Write(height); +WriteLine("cm tall!"); +``` + + + + +```csharp +using SplashKitSDK; + +namespace UsefulUtilities +{ + public class Program + { + public static int ReadInteger(string prompt) + { + // Prompt the user with the message + SplashKit.Write(prompt); + + // Read the user input as a string. + string line = SplashKit.ReadLine(); + + // Loop while the user's input is NOT a valid whole number. + while (!SplashKit.IsInteger(line)) + { + // If the user input was not a valid whole number, ask them to enter a whole number. + SplashKit.WriteLine("Please enter a whole number."); + SplashKit.Write(prompt); + line = SplashKit.ReadLine(); + } + // Convert the user input to an integer before returning it. + return SplashKit.ConvertToInteger(line); + } + + public static void Main() + { + int height; + + height = ReadInteger("Enter your height in centimetres: "); + SplashKit.Write("You are "); + SplashKit.Write(height); + SplashKit.WriteLine("cm tall!"); + } + } +} +``` + + + - ```python - from splashkit import * +```python +from splashkit import * - def read_integer(prompt): - # Prompt the user with the message - write(prompt) +def read_integer(prompt): + # Prompt the user with the message + write(prompt) - # Read the user input as a string. - line = read_line() + # Read the user input as a string. + line = read_line() - # Loop while the user's input is NOT a valid whole number. - while not is_integer(line): + # Loop while the user's input is NOT a valid whole number. + while not is_integer(line): - # If the user input was not a valid whole number, ask them to enter a whole number. - write_line("Please enter a valid whole number.") - write(prompt) - line = read_line() + # If the user input was not a valid whole number, ask them to enter a whole number. + write_line("Please enter a valid whole number.") + write(prompt) + line = read_line() - # Convert the user input to an integer before returning it. - return convert_to_integer(buffer) + # Convert the user input to an integer before returning it. + return convert_to_integer(line) - // Start of "main" code - height = read_integer("Enter your height in centimetres: ") +# Start of "main" code +height = read_integer("Enter your height in centimetres: ") - write("You are ") - write_int(height) - write_line("cm tall!") - ``` +write("You are ") +write_int(height) +write_line("cm tall!") +``` @@ -483,76 +673,114 @@ In addition to the functionality provided by each language's standard library (T - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" - int main() - { - string name = "Richard"; - string location = " Burwood"; +int main() +{ + string name = "Richard"; + string location = " Burwood"; - // Convert "Richard" to "RICHARD" - name = to_uppercase(name); - write_line(name); + // Convert "Richard" to "RICHARD" + name = to_uppercase(name); + write_line(name); - // Convert "RICHARD" to "richard" - name = to_lowercase(name); - write_line(name); + // Convert "RICHARD" to "richard" + name = to_lowercase(name); + write_line(name); - // Remove all of the empty spaces at the start of " Burwood". - write_line("Before: " + location); - location = trim(location); - write_line("After: " + location); + // Remove all of the empty spaces at the start of " Burwood". + write_line("Before: " + location); + location = trim(location); + write_line("After: " + location); - return 0; - } - ``` + return 0; +} +``` - ```csharp - using static SplashKitSDK.SplashKit; + + - string name = "Richard"; - string location = " Burwood"; +```csharp +using static SplashKitSDK.SplashKit; - //Convert "Richard" to "RICHARD" - name = ToUppercase(name); - WriteLine(name); +string name = "Richard"; +string location = " Burwood"; - //Convert "RICHARD" to "richard" - name = ToLowercase(name); - WriteLine(name); +//Convert "Richard" to "RICHARD" +name = ToUppercase(name); +WriteLine(name); - //Remove all of the empty spaces at the start of " Burwood". - WriteLine("Before: " + location); - location = Trim(location); - WriteLine("After: " + location); - ``` +//Convert "RICHARD" to "richard" +name = ToLowercase(name); +WriteLine(name); + +//Remove all of the empty spaces at the start of " Burwood". +WriteLine("Before: " + location); +location = Trim(location); +WriteLine("After: " + location); +``` + + + + +```csharp +using SplashKitSDK; + +namespace UsefulUtilities +{ + public class Program + { + public static void Main() + { + string name = "Richard"; + string location = " Burwood"; + + //Convert "Richard" to "RICHARD" + name = SplashKit.ToUppercase(name); + SplashKit.WriteLine(name); + + //Convert "RICHARD" to "richard" + name = SplashKit.ToLowercase(name); + SplashKit.WriteLine(name); + + //Remove all of the empty spaces at the start of " Burwood". + SplashKit.WriteLine("Before: " + location); + location = SplashKit.Trim(location); + SplashKit.WriteLine("After: " + location); + } + } +} +``` + + + - ```python - from splashkit import * +```python +from splashkit import * - name = "Richard" - location = " Burwood" +name = "Richard" +location = " Burwood" - # Convert "Richard" to "RICHARD" - name = to_uppercase(name) - write_line(name) +# Convert "Richard" to "RICHARD" +name = to_uppercase(name) +write_line(name) - # Convert "RICHARD" to "richard" - name = to_lowercase(name) - write_line(name) +# Convert "RICHARD" to "richard" +name = to_lowercase(name) +write_line(name) - # Remove all of the empty spaces at the start of " Burwood". - write_line("Before: " + location) - location = trim(location) - write_line("After: " + location) - ``` +# Remove all of the empty spaces at the start of " Burwood". +write_line("Before: " + location) +location = trim(location) +write_line("After: " + location) +``` From 4f15a1d8ff3fa426b078848d0cb64675cc3fbc6c Mon Sep 17 00:00:00 2001 From: Jinx-means-jinx <113697592+Jinx-means-jinx@users.noreply.github.com> Date: Wed, 9 Oct 2024 13:46:09 +1100 Subject: [PATCH 18/30] Reveiw reading text (#188) --- src/content/docs/guides/Input/0-reading-text.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/content/docs/guides/Input/0-reading-text.mdx b/src/content/docs/guides/Input/0-reading-text.mdx index 1f28a3e4..95e60128 100644 --- a/src/content/docs/guides/Input/0-reading-text.mdx +++ b/src/content/docs/guides/Input/0-reading-text.mdx @@ -3,7 +3,7 @@ title: Reading Text description: See how to read text from the user, both from command line and graphical applications. category: Tutorials author: Andrew Cain and others -lastupdated: Oct 2 2018 +lastupdated: Sep 20, 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -18,7 +18,7 @@ This article shows you how to get started reading text from the user. This inclu ## Reading Text from the Command Line -Reading text input from the user is straightforward for command line applications. In this context, [Read Line](/api/terminal/#read-line) gives you the ability to read a line of text entered at the Terminal. This is a **blocking** function call, meaning it waits for the user to input the line before it returns. For command line applications, this is fine; you want it to wait for the input. +Reading text input from the user is straightforward for command line applications. In this context, [Read Line](/api/terminal/#read-line) allows you to read a line of text entered at the Terminal. This is a **blocking** function call, meaning it waits for the user to input the line before it returns. For command line applications, this is fine; you want it to wait for the input. The following code demonstrates the use of [Read Line](/api/terminal/#read-line) in order to read in and display the user's name. @@ -120,7 +120,7 @@ write_line(name + "'s quest is: " + quest) ## Reading Text in Graphical Applications -Reading input from users in graphical applications is more complex, as blocking operations will cause the entire graphical interface to freeze. With a graphical application you need to keep redrawing, processing events, updating elements, and refreshing the screen. If you stop doing this to wait for user input, then any dynamic visuals will stop! +Reading input from users in graphical applications is more complex, as blocking operations will cause the entire graphical interface to freeze. With a graphical application, you need to keep redrawing, processing events, updating elements, and refreshing the screen. If you stop doing this to wait for user input, then any dynamic visuals will stop! Let's see how to read input from the user using some example code. We can then talk through the different parts to understand how they come together to give you a dynamic application with user input. @@ -430,7 +430,7 @@ close_all_windows() -In the above program we want to read in the user's name and store it in the `name` variable. To get started with this we need to open a window, and load a font to draw the text and input. There is also the standard event loop that is repeating the basic actions of checking user input and drawing the screen until the program is closed. +In the above program we want to read in the user's name and store it in the `name` variable. To get started with this we need to open a window and load a font to draw the text and input. There is also the standard event loop that repeats the basic actions of checking user input and drawing the screen until the program is closed. The logic for reading input starts with the call to [Start Reading Text](/api/input/#start-reading-text). This tells SplashKit that you want it to collect text input by the user, and that you want it drawn into the passed-in [Rectangle](/api/types/#rectangle) (in this case `rect`). SplashKit is now listening for input from, and collecting this text for you when you call [Process Events](/api/input/#process-events). From ad957853a5ca5c5f6533e3570fd504219e5e3311 Mon Sep 17 00:00:00 2001 From: s223126445 <162955558+s223126445@users.noreply.github.com> Date: Wed, 9 Oct 2024 16:12:03 +1100 Subject: [PATCH 19/30] Tutorial Review of Mouse Inputs Functionality Guide (#161) From 3e9aaf32a4c0bb0203d103e93c05b19bd726848e Mon Sep 17 00:00:00 2001 From: s223126445 <162955558+s223126445@users.noreply.github.com> Date: Wed, 9 Oct 2024 16:38:10 +1100 Subject: [PATCH 20/30] Adding Python Code Blocks to Json Intro Guide (#173) --- src/content/docs/guides/JSON/0-json_intro.mdx | 55 ++++++++++++++++++- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/src/content/docs/guides/JSON/0-json_intro.mdx b/src/content/docs/guides/JSON/0-json_intro.mdx index e3a45f99..2bd1822c 100644 --- a/src/content/docs/guides/JSON/0-json_intro.mdx +++ b/src/content/docs/guides/JSON/0-json_intro.mdx @@ -2,8 +2,8 @@ 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 and Yuyang Yang -lastupdated: Sep 10 2024 +author: Jonathan Tynan +lastupdated: September 2024 sidebar: label: "Introduction to JSON" --- @@ -99,7 +99,7 @@ namespace GameDataManagement { public static void Main() { - Json gameData = SplashKit.JsonFromFile(game_data.json); + Json gameData = SplashKit.JsonFromFile("game_data.json"); string gameTitle = SplashKit.JsonReadString(gameData, "gameTitle"); SplashKit.WriteLine("Game Title: " + gameTitle); @@ -113,6 +113,27 @@ namespace GameDataManagement + + + +```python +from splashkit import * + +def main(): + game_data = json_from_file("game_data.json") + game_title = json_read_string(game_data, "gameTitle") + + if not game_title: + write_line("Error retrieving gameTitle.") + else: + write_line(f"Game Title: {game_title}") + + free_json(game_data) + +if __name__ == "__main__": + main() +``` + @@ -152,6 +173,13 @@ And run it with: dotnet run ``` + + + +```shell +skm python3 program.py +``` + @@ -249,6 +277,27 @@ namespace GameDataManagement + + + +```python +from splashkit import * + +def main(): + game_data = json_from_file("game_data.json") + + if json_has_key(game_data, "gameTitle"): + game_title = json_read_string(game_data, "gameTitle") + write_line(f"Game Title: {game_title}") + else: + write_line('Key "gameTitle" not found.') + + free_json(game_data) + +if __name__ == "__main__": + main() +``` + From 280d81d4c7527a9b1a6e503fc95ab985c2e0ac65 Mon Sep 17 00:00:00 2001 From: NidhishaPahade <101486006+NidhishaPahade@users.noreply.github.com> Date: Wed, 9 Oct 2024 18:00:20 +1100 Subject: [PATCH 21/30] Add C# Language Tabs to "Layouts in User Interfaces" Guide (#199) --- .../Interface/01-interface-layouting.mdx | 812 +++++++++++++++--- 1 file changed, 674 insertions(+), 138 deletions(-) diff --git a/src/content/docs/guides/Interface/01-interface-layouting.mdx b/src/content/docs/guides/Interface/01-interface-layouting.mdx index 8641bc87..a7a1009b 100644 --- a/src/content/docs/guides/Interface/01-interface-layouting.mdx +++ b/src/content/docs/guides/Interface/01-interface-layouting.mdx @@ -20,41 +20,117 @@ The last few sections of this article will be closer to an API _reference_ than All the automatic layouting functionality in SplashKit starts by creating a container, and the most useful container is a 'panel'. A panel is like a mini window inside your program, that can be dragged around and resized. We'll be placing our elements _inside_ these panels. Here's just a basic example from the previous tutorial that we can get started from: + :::tip[SplashKit Interfaces] Remember that SplashKit uses an immediate mode GUI paradigm. This means we need to place _all_ of our interface code _inside_ the main `while` loop, between [Process Events](/api/input/#process-events) and [Draw Interface](/api/interface/#draw-interface)! ::: - + + - ```cpp - #include "splashkit.h" +```cpp +#include "splashkit.h" + +int main() +{ + // open a window + open_window("My Interface!", 800, 600); + + // main loop + while (!quit_requested()) + { + // get user events + process_events(); + + // clear screen + clear_screen(COLOR_WHITE); - int main() - { - // open a window - open_window("My Interface!", 800, 600); + // ...we'll put our interface code here...! - // main loop - while (!quit_requested()) - { - // get user events - process_events(); + // finally draw interface, then refresh screen + draw_interface(); + refresh_screen(); + } - // clear screen - clear_screen(COLOR_WHITE); + // close all open windows + close_all_windows(); + + return 0; +} +``` + + + - // ...we'll put out interface code here...! + + - // finally draw interface, then refresh screen - draw_interface(); +```csharp +using static SplashKitSDK.SplashKit; - refresh_screen(); - } +// open a window +OpenWindow("My Interface!", 800, 600); + +// main loop +while (!QuitRequested()) +{ + // get user events + ProcessEvents(); + + // clear screen + ClearScreen(ColorWhite()); + + // ...we'll put our interface code here...! + + // finally draw interface, then refresh screen + DrawInterface(); + RefreshScreen(); +} + +// close all open windows +CloseAllWindows(); +``` + + + + +```csharp +using SplashKitSDK; + +namespace InterfaceLayouts +{ + public class Program + { + public static void Main() + { + // open a window + Window window = new Window("My Interface!", 800, 600); + + // main loop + while (!window.CloseRequested) + { + // get user events + SplashKit.ProcessEvents(); + + // clear screen + window.Clear(Color.White); + + // ...we'll put our interface code here...! + + // finally draw interface, then refresh screen + SplashKit.DrawInterface(); + window.Refresh(); + } + + // close all open windows + SplashKit.CloseAllWindows(); + } + } +} +``` - // program ends, and the window closes - return 0; - } - ``` + + @@ -68,19 +144,54 @@ Let's add a panel now! Adding a panel takes two lines of code: 2. Then once we're done, we need to end the panel with [End Panel](/api/interface/#end-panel), where we just give it the same name (so for example `end_panel("My panel")`). One **really important** thing to note here is that [Start Panel](/api/interface/#start-panel) _returns_ whether the panel is visible or not, so we need to make sure to check this as well, and only create elements and end the panel `if` the panel is open, like so: - + + - ```cpp - // start the panel and check if it's open/visible - if (start_panel("My panel", rectangle_from(50,50,200,100))) - { - // ...here we'll create all the UI elements, inside the braces { ... } +```cpp +// start the panel and check if it's open/visible +if (start_panel("My panel", rectangle_from(50,50,200,100))) +{ + // ...here we'll create all the UI elements, inside the braces { ... } - // end the panel - end_panel("My panel"); - } - ``` + // end the panel + end_panel("My panel"); +} +``` + + + + + + + +```csharp +// start the panel and check if it's open/visible +if (StartPanel("My panel", RectangleFrom(50, 50, 200, 100))) +{ + // ...here we'll create all the UI elements, inside the braces { ... } + + // end the panel + EndPanel("My panel"); +} +``` + + + + +```csharp +// start the panel and check if it's open/visible +if (SplashKit.StartPanel("My panel", SplashKit.RectangleFrom(50, 50, 200, 100))) +{ + // ...here we'll create all the UI elements, inside the braces { ... } + + // end the panel + SplashKit.EndPanel("My panel"); +} +``` + + + @@ -113,54 +224,161 @@ Similarly, we can add a [Text Box](/api/interface/#text-box) by declaring a `str ![A panel with a button and a text box in it.](/gifs/guides/interface/panel_w_button_and_textbox.gif) Here's the full code recreating what we had last tutorial, while creating a panel and adding the elements inside it. - + + - ```cpp ins={20-22, 31-33} {8-9, 23-30} - #include "splashkit.h" +```cpp ins={20-22, 31-33} +#include "splashkit.h" + +int main() +{ + // open a window + open_window("My Interface!", 800, 600); + + // setup a variable to store the user's string - same as last tutorial + string user_message = "Default message"; + + // main loop + while (!quit_requested()) + { + // get user events + process_events(); + + // clear screen + clear_screen(COLOR_WHITE); + + // here we start the panel + if (start_panel("My panel", rectangle_from(50,50,200,100))) + { + // create the elements, just like last tutorial! + if (button("Write To Terminal!")) + { + write_line(user_message); + } + + user_message = text_box(user_message); + + // end the panel + end_panel("My panel"); + } + + // finally draw interface, then refresh screen + draw_interface(); + refresh_screen(); + } + + // close all open windows + close_all_windows(); + + return 0; +} +``` - int main() - { - // open a window - open_window("My Interface!", 800, 600); + + - // setup a variable to store the user's string - same as last tutorial - string user_message = "Default message"; + + - // main loop - while (!quit_requested()) - { - // get user events - process_events(); +```csharp ins={18-20, 29-31} +using static SplashKitSDK.SplashKit; - // clear screen - clear_screen(COLOR_WHITE); +// open a window +OpenWindow("My Interface!", 800, 600); - // here we start the panel - if (start_panel("My panel", rectangle_from(50,50,200,100))) - { - // create the elements, just like last tutorial! - if (button("Write To Terminal!")) - { - write_line(user_message); - } +// setup a variable to store the user's string - same as last tutorial +string userMessage = "Default message"; - user_message = text_box(user_message); +// main loop +while (!QuitRequested()) +{ + // get user events + ProcessEvents(); - // end the panel - end_panel("My panel"); - } + // clear screen + ClearScreen(ColorWhite()); - // finally draw interface, then refresh screen - draw_interface(); + // here we start the panel + if (StartPanel("My panel", RectangleFrom(50, 50, 200, 100))) + { + // create the elements, just like last tutorial! + if (Button("Write To Terminal!")) + { + WriteLine(userMessage); + } - refresh_screen(); - } + userMessage = TextBox(userMessage); - // program ends, and the window closes - return 0; - } - ``` + // end the panel + EndPanel("My panel"); + } + + // finally draw interface, then refresh screen + DrawInterface(); + RefreshScreen(); +} + +// close all open windows +CloseAllWindows(); +``` + + + + +```csharp ins={24-26, 35-37} +using SplashKitSDK; + +namespace InterfaceLayouts +{ + public class Program + { + public static void Main() + { + // open a window + Window window = new Window("My Interface!", 800, 600); + + // setup a variable to store the user's string - same as last tutorial + string userMessage = "Default message"; + + // main loop + while (!window.CloseRequested) + { + // get user events + SplashKit.ProcessEvents(); + + // clear screen + window.Clear(Color.White); + + // here we start the panel + if (SplashKit.StartPanel("My panel", SplashKit.RectangleFrom(50, 50, 200, 100))) + { + // create the elements, just like last tutorial! + if (SplashKit.Button("Write To Terminal!")) + { + SplashKit.WriteLine(userMessage); + } + + userMessage = SplashKit.TextBox(userMessage); + + // end the panel + SplashKit.EndPanel("My panel"); + } + + // finally draw interface, then refresh screen + SplashKit.DrawInterface(); + window.Refresh(); + } + + // close all open windows + SplashKit.CloseAllWindows(); + } + } +} +``` + + + @@ -193,7 +411,8 @@ See the [API](/api/interface/) for more functions! Now that we can create panels and place UI elements on those panels, let's see how we can use extra elements to help lay them out! This section will focus on mainly demonstrating each concept. -Make sure to try each of these snippets out - you can just copy paste them into anywhere between your start/end panel calls. + +Make sure to try each of these snippets out - you can just copy paste them into anywhere **between your start/end panel** calls. Some of the easiest ways to group our elements together, is to place them under headers and inside 'insets'. @@ -201,16 +420,42 @@ Some of the easiest ways to group our elements together, is to place them under Headers are really easy to add - we can use the [Header](/api/interface/#header) function, which takes a name for the heading, and returns if the header is open (like the panels!): - + - ```cpp - if (header("Edit Message!")) - { - user_message = text_box(user_message); - } +```cpp +if (header("Edit Message!")) +{ + user_message = text_box(user_message); +} ``` + + + + + + +```csharp +if (Header("Edit Message!")) +{ + userMessage = TextBox(userMessage); +} +``` + + + + +```csharp +if (SplashKit.Header("Edit Message!")) +{ + userMessage = SplashKit.TextBox(userMessage); +} +``` + + + + @@ -224,20 +469,80 @@ Insets let you group a bunch of elements inside a fixed-size region! They can be Here's a code example - an inset is started, and six buttons are created inside it. Finally, the inset is ended. - + - ```cpp - paragraph("This text is outside the inset area!"); - start_inset("Inset area", 60); - if (button("Button 1!")) write_line("Button 1 clicked!"); - if (button("Button 2!")) write_line("Button 2 clicked!"); - if (button("Button 3!")) write_line("Button 3 clicked!"); - if (button("Button 4!")) write_line("Button 4 clicked!"); - if (button("Button 5!")) write_line("Button 5 clicked!"); - if (button("Button 6!")) write_line("Button 6 clicked!"); - end_inset("Inset area"); - ``` +```cpp +paragraph("This text is outside the inset area!"); +start_inset("Inset area", 60); + +if (button("Button 1!")) + write_line("Button 1 clicked!"); +if (button("Button 2!")) + write_line("Button 2 clicked!"); +if (button("Button 3!")) + write_line("Button 3 clicked!"); +if (button("Button 4!")) + write_line("Button 4 clicked!"); +if (button("Button 5!")) + write_line("Button 5 clicked!"); +if (button("Button 6!")) + write_line("Button 6 clicked!"); + +end_inset("Inset area"); +``` + + + + + + + +```csharp +Paragraph("This text is outside the inset area!"); +StartInset("Inset area", 60); + +if (Button("Button 1!")) + WriteLine("Button 1 clicked!"); +if (Button("Button 2!")) + WriteLine("Button 2 clicked!"); +if (Button("Button 3!")) + WriteLine("Button 3 clicked!"); +if (Button("Button 4!")) + WriteLine("Button 4 clicked!"); +if (Button("Button 5!")) + WriteLine("Button 5 clicked!"); +if (Button("Button 6!")) + WriteLine("Button 6 clicked!"); + +EndInset("Inset area"); +``` + + + + +```csharp +SplashKit.Paragraph("This text is outside the inset area!"); +SplashKit.StartInset("Inset area", 60); + +if (SplashKit.Button("Button 1!")) + SplashKit.WriteLine("Button 1 clicked!"); +if (SplashKit.Button("Button 2!")) + SplashKit.WriteLine("Button 2 clicked!"); +if (SplashKit.Button("Button 3!")) + SplashKit.WriteLine("Button 3 clicked!"); +if (SplashKit.Button("Button 4!")) + SplashKit.WriteLine("Button 4 clicked!"); +if (SplashKit.Button("Button 5!")) + SplashKit.WriteLine("Button 5 clicked!"); +if (SplashKit.Button("Button 6!")) + SplashKit.WriteLine("Button 6 clicked!"); + +SplashKit.EndInset("Inset area"); +``` + + + @@ -251,30 +556,108 @@ Another powerful feature of `insets`, is that you can use them as a container di Tree nodes allow you to organize your elements as a tree - like a file system! You can collapse and expand the nodes individually, so this is a great way to organize data. Here's a code example - various _nested_ tree nodes are started and ended with, buttons placed in between - this creates a hierarchy. - - - ```cpp - if (start_treenode("Some buttons!")){ - if (button("Button 1!")) write_line("Button 1 clicked!"); - if (button("Button 2!")) write_line("Button 2 clicked!"); - if (button("Button 3!")) write_line("Button 3 clicked!"); - end_treenode("Some buttons!"); - } + + - if (start_treenode("Some more buttons!")){ - if (button("Button 4!")) write_line("Button 4 clicked!"); - if (button("Button 5!")) write_line("Button 5 clicked!"); +```cpp +if (start_treenode("Some buttons!")) +{ + if (button("Button 1!")) + write_line("Button 1 clicked!"); + if (button("Button 2!")) + write_line("Button 2 clicked!"); + if (button("Button 3!")) + write_line("Button 3 clicked!"); + end_treenode("Some buttons!"); +} + +if (start_treenode("Some more buttons!")) +{ + if (button("Button 4!")) + write_line("Button 4 clicked!"); + if (button("Button 5!")) + write_line("Button 5 clicked!"); + + if (start_treenode("Buttons in buttons!!")) + { + if (button("Button 6!")) + write_line("Button 6 clicked!"); + end_treenode("Buttons in buttons!!"); + } + end_treenode("Some more buttons!"); +} +``` - if (start_treenode("Buttons in buttons!!")){ - if (button("Button 6!")) write_line("Button 6 clicked!"); + + + + + + +```csharp +if (StartTreenode("Some buttons!")) +{ + if (Button("Button 1!")) + WriteLine("Button 1 clicked!"); + if (Button("Button 2!")) + WriteLine("Button 2 clicked!"); + if (Button("Button 3!")) + WriteLine("Button 3 clicked!"); + EndTreenode("Some buttons!"); +} + +if (StartTreenode("Some more buttons!")) +{ + if (Button("Button 4!")) + WriteLine("Button 4 clicked!"); + if (Button("Button 5!")) + WriteLine("Button 5 clicked!"); + + if (StartTreenode("Buttons in buttons!!")) + { + if (Button("Button 6!")) + WriteLine("Button 6 clicked!"); + EndTreenode("Buttons in buttons!!"); + } + EndTreenode("Some more buttons!"); +} +``` - end_treenode("Buttons in buttons!!"); - } + + + +```csharp +if (SplashKit.StartTreenode("Some buttons!")) +{ + if (SplashKit.Button("Button 1!")) + SplashKit.WriteLine("Button 1 clicked!"); + if (SplashKit.Button("Button 2!")) + SplashKit.WriteLine("Button 2 clicked!"); + if (SplashKit.Button("Button 3!")) + SplashKit.WriteLine("Button 3 clicked!"); + SplashKit.EndTreenode("Some buttons!"); +} + +if (SplashKit.StartTreenode("Some more buttons!")) +{ + if (SplashKit.Button("Button 4!")) + SplashKit.WriteLine("Button 4 clicked!"); + if (SplashKit.Button("Button 5!")) + SplashKit.WriteLine("Button 5 clicked!"); + + if (SplashKit.StartTreenode("Buttons in buttons!!")) + { + if (SplashKit.Button("Button 6!")) + SplashKit.WriteLine("Button 6 clicked!"); + SplashKit.EndTreenode("Buttons in buttons!!"); + } + SplashKit.EndTreenode("Some more buttons!"); +} +``` - end_treenode("Some more buttons!"); - } - ``` + + @@ -291,12 +674,14 @@ allowing us to group our elements together on single rows! To start, we need to call [Start Custom Layout](/api/interface/#start-custom-layout) - this removes the default layouting. Now we can use the following functions to adjust how many elements we can place on the row: :::note[SplashKit Interfaces] Here's a rundown of common layout functions: + | Name | Description| |---------------|-----------| |[Split Into Columns](/api/interface/#split-into-columns)(count) | Splits the current row into equal sized columns - this is how many elements you can place on the one row | |[Single Line Layout](/api/interface/#single-line-layout)() | Just place _all_ elements on a single row with their default size | |[Add Column](/api/interface/#add-column)(width) | Adds a single column of a specific width in pixels | |[Add Column Relative](/api/interface/#add-column-relative)(width) | Adds a single column of a specific width _relative_ to the total width (a value between 0 and 1)| + ------------------------------------------- You'll usually want to use the first two, while the bottom two can be used for more custom layouts. @@ -320,24 +705,92 @@ You can also adjust the height of a row, using [Set Layout Height](/api/interfac Here's an example, where we create six buttons - three on each row, with the top row being taller. - + - ```cpp - start_custom_layout(); - split_into_columns(3); - set_layout_height(64); - if (button("Button 1!")) write_line("Button 1 clicked!"); - if (button("Button 2!")) write_line("Button 2 clicked!"); - if (button("Button 3!")) write_line("Button 3 clicked!"); +```cpp +start_custom_layout(); +split_into_columns(3); +set_layout_height(64); + +if (button("Button 1!")) + write_line("Button 1 clicked!"); +if (button("Button 2!")) + write_line("Button 2 clicked!"); +if (button("Button 3!")) + write_line("Button 3 clicked!"); + +set_layout_height(0); // 0 resets to default - set_layout_height(0); // 0 resets to default - if (button("Button 4!")) write_line("Button 4 clicked!"); - if (button("Button 5!")) write_line("Button 5 clicked!"); - if (button("Button 6!")) write_line("Button 6 clicked!"); - reset_layout(); +if (button("Button 4!")) + write_line("Button 4 clicked!"); +if (button("Button 5!")) + write_line("Button 5 clicked!"); +if (button("Button 6!")) + write_line("Button 6 clicked!"); - ``` +reset_layout(); +``` + + + + + + + +```csharp +StartCustomLayout(); +SplitIntoColumns(3); +SetLayoutHeight(64); + +if (Button("Button 1!")) + WriteLine("Button 1 clicked!"); +if (Button("Button 2!")) + WriteLine("Button 2 clicked!"); +if (Button("Button 3!")) + WriteLine("Button 3 clicked!"); + +SetLayoutHeight(0); // 0 resets to default + +if (Button("Button 4!")) + WriteLine("Button 4 clicked!"); +if (Button("Button 5!")) + WriteLine("Button 5 clicked!"); +if (Button("Button 6!")) + WriteLine("Button 6 clicked!"); + +ResetLayout(); +``` + + + + +```csharp +SplashKit.StartCustomLayout(); +SplashKit.SplitIntoColumns(3); +SplashKit.SetLayoutHeight(64); + +if (SplashKit.Button("Button 1!")) + SplashKit.WriteLine("Button 1 clicked!"); +if (SplashKit.Button("Button 2!")) + SplashKit.WriteLine("Button 2 clicked!"); +if (SplashKit.Button("Button 3!")) + SplashKit.WriteLine("Button 3 clicked!"); + +SplashKit.SetLayoutHeight(0); // 0 resets to default + +if (SplashKit.Button("Button 4!")) + SplashKit.WriteLine("Button 4 clicked!"); +if (SplashKit.Button("Button 5!")) + SplashKit.WriteLine("Button 5 clicked!"); +if (SplashKit.Button("Button 6!")) + SplashKit.WriteLine("Button 6 clicked!"); + +SplashKit.ResetLayout(); +``` + + + @@ -354,25 +807,108 @@ Once you're done, you can leave it with [Leave Column](/api/interface/#leave-col Here's an example: - + - ```cpp - start_custom_layout(); - split_into_columns(2); - enter_column(); - set_layout_height(64); - if (button("Button 1!")) write_line("Button 1 clicked!"); - if (button("Button 2!")) write_line("Button 2 clicked!"); - leave_column(); - enter_column(); - set_layout_height(0); // 0 resets to default - if (button("Button 4!")) write_line("Button 4 clicked!"); - if (button("Button 5!")) write_line("Button 5 clicked!"); - if (button("Button 6!")) write_line("Button 6 clicked!"); - leave_column(); - reset_layout(); - ``` +```cpp +start_custom_layout(); +split_into_columns(2); + +enter_column(); +set_layout_height(64); + +if (button("Button 1!")) + write_line("Button 1 clicked!"); +if (button("Button 2!")) + write_line("Button 2 clicked!"); + +leave_column(); + +enter_column(); +set_layout_height(0); // 0 resets to default + +if (button("Button 4!")) + write_line("Button 4 clicked!"); +if (button("Button 5!")) + write_line("Button 5 clicked!"); +if (button("Button 6!")) + write_line("Button 6 clicked!"); + +leave_column(); + +reset_layout(); +``` + + + + + + + +```csharp +// Start custom layout +StartCustomLayout(); +SplitIntoColumns(2); + +EnterColumn(); +SetLayoutHeight(64); + +if (Button("Button 1!")) + WriteLine("Button 1 clicked!"); +if (Button("Button 2!")) + WriteLine("Button 2 clicked!"); + +LeaveColumn(); + +EnterColumn(); +SetLayoutHeight(0); // 0 resets to default + +if (Button("Button 4!")) + WriteLine("Button 4 clicked!"); +if (Button("Button 5!")) + WriteLine("Button 5 clicked!"); +if (Button("Button 6!")) + WriteLine("Button 6 clicked!"); + +LeaveColumn(); + +ResetLayout(); +``` + + + + +```csharp +SplashKit.StartCustomLayout(); +SplashKit.SplitIntoColumns(2); + +SplashKit.EnterColumn(); +SplashKit.SetLayoutHeight(64); + +if (SplashKit.Button("Button 1!")) + SplashKit.WriteLine("Button 1 clicked!"); +if (SplashKit.Button("Button 2!")) + SplashKit.WriteLine("Button 2 clicked!"); + +SplashKit.LeaveColumn(); + +SplashKit.EnterColumn(); +SplashKit.SetLayoutHeight(0); // 0 resets to default + +if (SplashKit.Button("Button 4!")) + SplashKit.WriteLine("Button 4 clicked!"); +if (SplashKit.Button("Button 5!")) + SplashKit.WriteLine("Button 5 clicked!"); +if (SplashKit.Button("Button 6!")) + SplashKit.WriteLine("Button 6 clicked!"); + +SplashKit.LeaveColumn(); + +SplashKit.ResetLayout(); +``` + + + From bd14e579f81a4caae7bf1e727a5d42d801649a15 Mon Sep 17 00:00:00 2001 From: NidhishaPahade <101486006+NidhishaPahade@users.noreply.github.com> Date: Wed, 9 Oct 2024 18:05:47 +1100 Subject: [PATCH 22/30] Add C# Language Tabs to "Styling User Interfaces" Guide (#200) --- package.json | 11 +- scripts/components.cjs | 2 +- scripts/generate-groups.cjs | 19 --- src/components/Guides.astro | 134 +++++++-------- src/components/guides-groups.json | 14 -- .../guides/Interface/02-interface-styling.mdx | 155 +++++++++++++++--- 6 files changed, 194 insertions(+), 141 deletions(-) delete mode 100644 scripts/generate-groups.cjs delete mode 100644 src/components/guides-groups.json diff --git a/package.json b/package.json index 6cb0ce8d..2134f510 100644 --- a/package.json +++ b/package.json @@ -3,15 +3,14 @@ "type": "module", "version": "0.9", "scripts": { - "dev": "npm run generate-mdx && npm run generate-usage-examples-pages && npm run generate-groups && astro dev", - "start": "npm run generate-mdx && npm run generate-usage-examples-pages && npm run generate-groups && astro dev", - "build": "npm run generate-mdx && npm run generate-usage-examples-pages && npm run generate-groups && astro build", + "dev": "npm run generate-mdx && npm run generate-usage-examples-pages && astro dev", + "start": "npm run generate-mdx && npm run generate-usage-examples-pages && astro dev", + "build": "npm run generate-mdx && npm run generate-usage-examples-pages && astro build", "preview": "astro preview", "astro": "astro", "generate-mdx": "node ./scripts/components.cjs", "generate-usage-examples-pages": "node ./scripts/usage-example-page-generation.cjs", - "check-links": "SET CHECK_LINKS=true && npm run build && SET CHECK_LINKS=false", - "generate-groups": "node ./scripts/generate-groups.cjs" + "check-links": "SET CHECK_LINKS=true && npm run build && SET CHECK_LINKS=false" }, "dependencies": { "@astrojs/netlify": "^5.4.0", @@ -47,4 +46,4 @@ "devDependencies": { "accessible-astro-components": "2.3.6" } -} \ No newline at end of file +} diff --git a/scripts/components.cjs b/scripts/components.cjs index 5e6e1964..164cd630 100644 --- a/scripts/components.cjs +++ b/scripts/components.cjs @@ -443,7 +443,7 @@ fs.readFile(`${__dirname}/api.json`, "utf8", async (err, data) => { // Write the MDX file - fs.writeFileSync(`./src/content/docs/api/${name}.mdx`, mdxContent, (err) => { + fs.writeFile(`./src/content/docs/api/${name}.mdx`, mdxContent, (err) => { if (err) { console.log(kleur.red(`Error writing ${input} MDX file: ${err.message}`)); } else { diff --git a/scripts/generate-groups.cjs b/scripts/generate-groups.cjs deleted file mode 100644 index 07c8d0de..00000000 --- a/scripts/generate-groups.cjs +++ /dev/null @@ -1,19 +0,0 @@ -const fs = require('fs'); // Import the file system module to interact with the file system -const path = require('path'); // Import the path module to handle and transform file paths - -// Define the path to the directory containing the guide groups -const guidesDir = './src/content/docs/guides'; -// Define the path where the output JSON file will be saved -const outputFile = './src/components/guides-groups.json'; - -// Read the contents of the guides directory -const groupNames = fs.readdirSync(guidesDir, { withFileTypes: true }) - // Filter out only the directories from the list of files and directories - .filter(dirent => dirent.isDirectory()) - // Map the directory names to lowercase to standardise them - .map(dirent => dirent.name); - -// Write the list of group names to the output JSON file -fs.writeFileSync(outputFile, JSON.stringify(groupNames, null, 2)); -// Log a message to the console indicating that the JSON file has been created -console.log('Group names have been written to', outputFile); \ No newline at end of file diff --git a/src/components/Guides.astro b/src/components/Guides.astro index 07f4f7a2..9be4553f 100644 --- a/src/components/Guides.astro +++ b/src/components/Guides.astro @@ -1,9 +1,6 @@ --- import { LinkCard, CardGrid } from "@astrojs/starlight/components"; -import fs from "fs"; -import path from "path"; -// Define the type for frontmatter interface Frontmatter { title: string; description?: string; @@ -12,84 +9,73 @@ interface Frontmatter { category?: string; } -// Define paths -const jsonFilePath = path.resolve("./src/components/guides-groups.json"); - -// Define the type for the group names -type GroupName = string; - -// Helper function to capitalize and format group names -function formatGroupName(groupName: GroupName): string { - // Replace dashes with spaces and capitalize each word - return groupName - .replace(/-/g, " ") - .split(" ") - .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) - .join(" "); -} - -// Read and parse the JSON file -const groupNames: GroupName[] = JSON.parse( - fs.readFileSync(jsonFilePath, "utf-8"), -); - -// Load and filter posts let posts = await Astro.glob("../content/docs/guides/*/*.mdx"); posts = posts.filter((post) => !post.file.endsWith("index.mdx")); -// Function to check if URL contains the group name -function urlContainsGroup(url: string, groupName: string): boolean { - return url.toLowerCase().includes(groupName.toLowerCase()); -} +let guides = posts.filter( + (post) => post.frontmatter.category?.toLowerCase() == "guides", +); +// sort guides on the basis of simplifyed File Path +guides = guides.sort((a, b) => + simplifyFilePath(a.url?.toString() || "").localeCompare( + simplifyFilePath(b.url?.toString() || ""), + ), +); +let tutorials = posts.filter( + (post) => post.frontmatter.category?.toLowerCase() == "tutorials", +); +tutorials = tutorials.sort((a, b) => + simplifyFilePath(a.url?.toString() || "").localeCompare( + simplifyFilePath(b.url?.toString() || ""), + ), +); -// Function to simplify file path -function simplifyFilePath(filePath: string): string { +function simplifyFilePath(filePath: string) { + // Remove leading and trailing slashes filePath = filePath.replace(/^\/|\/$/g, ""); + + // Split the path into parts using '/' const pathParts = filePath.split("/"); - const fileFolder = pathParts[pathParts.length - 2]; - const lastPart = pathParts[pathParts.length - 1]; - const simplifiedName = - fileFolder + "/" + lastPart.split(".").slice(0, -1).join("."); - return simplifiedName.toLowerCase(); -} ---- -{ - groupNames.map((groupName: GroupName) => { - // Filter posts by the current group name and check for "guides" or "tutorials" category - const filteredPosts = posts - .filter( - (post) => - (post.frontmatter.category?.toLowerCase() === "guides" || - post.frontmatter.category?.toLowerCase() === "tutorials") && - urlContainsGroup(post.url?.toString() || "", groupName), - ) - .sort((a, b) => - simplifyFilePath(a.url?.toString() || "").localeCompare( - simplifyFilePath(b.url?.toString() || ""), - ), - ); + // Get the last part of the path (including directory name) + const folderPath = pathParts[4] + "/" + pathParts[pathParts.length - 1]; - // Capitalize and format the group name - const formattedGroupName = formatGroupName(groupName); + // Remove file extension (assuming it's after the last dot in the last part) + const simplifiedName = folderPath.split(".").slice(0, -1).join("."); - return ( - <> -

{formattedGroupName}

- - {filteredPosts.map((post) => ( - - ))} - - - ); - }) + return simplifiedName.toLowerCase(); // Convert to lowercase for consistency } +--- + +

Tutorials

+ + { + tutorials.map((post) => ( + + )) + } + +

Guides

+ + { + guides.map((post) => ( + + )) + } + diff --git a/src/components/guides-groups.json b/src/components/guides-groups.json deleted file mode 100644 index f1788396..00000000 --- a/src/components/guides-groups.json +++ /dev/null @@ -1,14 +0,0 @@ -[ - "Animations", - "Audio", - "Camera", - "Graphics", - "Input", - "Interface", - "JSON", - "Networking", - "Raspberry-GPIO", - "Resource-Bundles", - "Using-SplashKit", - "Utilities" -] \ No newline at end of file diff --git a/src/content/docs/guides/Interface/02-interface-styling.mdx b/src/content/docs/guides/Interface/02-interface-styling.mdx index 1577049f..5e86c6af 100644 --- a/src/content/docs/guides/Interface/02-interface-styling.mdx +++ b/src/content/docs/guides/Interface/02-interface-styling.mdx @@ -3,7 +3,7 @@ title: Styling User Interfaces description: This article will explain how we can style our SplashKit interfaces to match our projects. category: Tutorials author: Sean Boettger -lastupdated: May 17 2024 +lastupdated: October 2024 --- **{frontmatter.description}** @@ -19,37 +19,114 @@ In this article we'll see how we can customize the _style_ of our interfaces, to SplashKit comes with a few preset styles that make it easy to start customizing the interface. To use them, just call [Set Interface Style](/api/interface/#set-interface-style) with the style you want - any elements created after this will use the new style! Here's an example: - + - ```cpp ins={8} - # include "splashkit.h" +```cpp ins={8} +# include "splashkit.h" - int main() - { - // open a window - open_window("My Interface!", 800, 600); +int main() +{ + // open a window + open_window("My Interface!", 800, 600); - set_interface_style(SHADED_LIGHT_STYLE); + // set the interface style + set_interface_style(SHADED_LIGHT_STYLE); - while (!quit_requested()) - { - process_events(); + while (!quit_requested()) + { + process_events(); - clear_screen(COLOR_WHITE); + clear_screen(COLOR_WHITE); - button("My Button!", rectangle_from(300, 260, 200, 24)); + button("My Button!", rectangle_from(300, 260, 200, 24)); - draw_interface(); + draw_interface(); - refresh_screen(); - } + refresh_screen(); + } - // program ends, and the window closes - return 0; - } + // close all open windows + close_all_windows(); + + return 0; +} - ``` +``` + + + + + + + +```csharp +using SplashKitSDK; +using static SplashKitSDK.SplashKit; + +// open a window +OpenWindow("My Interface!", 800, 600); + +// set the interface style +SetInterfaceStyle(InterfaceStyle.ShadedLightStyle); + +while (!QuitRequested()) +{ + ProcessEvents(); + + ClearScreen(ColorWhite()); + + Button("My Button!", RectangleFrom(300, 260, 200, 24)); + + DrawInterface(); + + RefreshScreen(); +} + +// close all open windows +CloseAllWindows(); +``` + + + + +```csharp +using SplashKitSDK; + +namespace InterfaceStyling +{ + public class Program + { + public static void Main() + { + // open a window + Window window = new Window("My Interface!", 800, 600); + + // set the interface style + SplashKit.SetInterfaceStyle(InterfaceStyle.ShadedLightStyle); + + while (!window.CloseRequested) + { + SplashKit.ProcessEvents(); + + window.Clear(Color.White); + + SplashKit.Button("My Button!", SplashKit.RectangleFrom(300, 260, 200, 24)); + + SplashKit.DrawInterface(); + + window.Refresh(); + } + + // close all open windows + SplashKit.CloseAllWindows(); + } + } +} +``` + + + @@ -162,14 +239,38 @@ By default, the interface will try and use a font available in your system. You - [Set Interface Font](/api/interface/#set-interface-font), lets you change the current font, loaded with [Load Font](/api/graphics/#load-font) - [Set Interface Font Size](/api/interface/#set-interface-font-size), lets you change the current font size - + - ```cpp - font myFont = load_font("Custom Font", "arial.ttf"); - set_interface_font(myFont); - set_interface_font_size(12); - ``` +```cpp +font myFont = load_font("Custom Font", "arial.ttf"); +set_interface_font(myFont); +set_interface_font_size(12); +``` + + + + + + + +```csharp +Font myFont = LoadFont("Custom Font", "arial.ttf"); +SetInterfaceFont(myFont); +SetInterfaceFontSize(12); +``` + + + + +```csharp +Font myFont = SplashKit.LoadFont("Custom Font", "arial.ttf"); +SplashKit.SetInterfaceFont(myFont); +SplashKit.SetInterfaceFontSize(12); +``` + + + From dcd36a7ff90a1c1c33074b4918b9f8009b4b7316 Mon Sep 17 00:00:00 2001 From: Srainyyyy <163366419+Srainyyyy@users.noreply.github.com> Date: Wed, 9 Oct 2024 19:13:45 +1100 Subject: [PATCH 23/30] Review "splashkit camera" guide (#164) --- .../Camera/0-using-splashkit-camera.mdx | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx b/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx index 41953f87..5ed763c4 100644 --- a/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx +++ b/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx @@ -1,7 +1,7 @@ --- title: SplashKit Camera description: See how the camera works, and how to draw to the different coordinate systems in your program. -author: Andrew Cain and Mounika Angadipeta +author: Andrew Cain lastupdated: September 2024 category: Guides --- @@ -18,15 +18,15 @@ This article provides information on how to use the camera in SplashKit to creat ## Coordinates and the Camera -The camera provides an easy way to move around a game world. It is set to 0,0 by default, however the offset can be changed using the different camera procedures in order to explore a larger game world. When the camera position changes it moves the window to another part of the game world, as you can see in the image below. +The camera provides an easy way to move around a game world. The camera is set to 0,0 by default, however the offset can be changed using the different camera procedures in order to explore a larger game world. When you change the camera position, it shifts the view of the game window to a different part of the game world, as you can see in the image below. ![Illustration of the camera and game coordinates](./images/camera.png) -When drawing use 'game coordinates' for each of your entities, which describe where an entity is in relation to other entities in the game. Some of these may be on the screen or off the screen, but we can let SplashKit take care of that. In the above image the dancing frog is at 250,300 in the game world. +When drawing, use 'game coordinates' for each entity, which represent the entity's position relative to other entities in the game world. These coordinates help in positioning entities correctly in the larger game world context. Some of these may be on the screen or off the screen, but we can let SplashKit take care of that. In the above image the dancing frog is at 250,300 in the game world. -When you draw to the screen SplashKit adjusts the screen position based on the current camera offset. So the dancing frog in the above image is at 200,200 on the screen as the camera is at 50,100. The camera defines the coordinate of the top left of the window. +When drawing to the screen, SplashKit adjusts the rendering position based on the current camera offset. This means the game world coordinates are translated into screen coordinates considering the camera’s position. So the dancing frog in the above image is at 200,200 on the screen as the camera is at 50,100. The camera defines the coordinate of the top left of the window. -With the camera you can create the effect of moving past stationary background objects by moving the player and the camera at the same time. As you move the camera, stationary objects drawn to the screen will appear in different locations on the Window. +By moving both the player and the camera simultaneously, you can create the effect of moving past stationary background objects. This creates the illusion of movement through a larger world, while the background objects remain in their relative positions.As you move the camera, stationary objects drawn to the screen will appear in different locations on the Window. - [Set Camera X](/api/camera/#set-camera-x) - adjust the x value for the camera - [Set Camera Y](/api/camera/#set-camera-y) - adjust the y value for the camera @@ -154,7 +154,6 @@ int main() using SplashKitSDK; using static SplashKitSDK.SplashKit; - static void UpdateCameraPosition(double playerX, double playerY) { const int SCREEN_BORDER = 100; @@ -379,10 +378,10 @@ while not quit_requested(): # Redraw everything clear_screen(color_black()) - # Draw to the screen - fill_rectangle(color_white(), 0, 0, screen_width(), 50, option_to_screen()) - draw_text_no_font_no_size_with_options("HUD", color_white(), 10, 10, option_to_screen()) - draw_text_no_font_no_size_with_options(f"Camera Position: {point_to_string(camera_position())}", color_white(), 10, 30, option_to_screen()) + # Draw to the screen + fill_rectangle(color_dim_gray(), 0, 0, screen_width(), 50,option_to_screen()) + draw_text_no_font_no_size_with_options("HUD", color_white(), 10, 10, option_to_screen()) + draw_text_no_font_no_size_with_options(f"Camera Position: {point_to_string(camera_position())}", color_white(), 10, 30, option_to_screen()) # as well as the player who can move fill_circle(color_yellow(), player_x, player_y, 20) From 20cc0f1f0453e89a3021156f8eeff838fe801aba Mon Sep 17 00:00:00 2001 From: Srainyyyy <163366419+Srainyyyy@users.noreply.github.com> Date: Wed, 9 Oct 2024 19:17:13 +1100 Subject: [PATCH 24/30] Tutorial Review of Introduction to JSON in SplashKit (#156) --- src/content/docs/guides/JSON/0-json_intro.mdx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/content/docs/guides/JSON/0-json_intro.mdx b/src/content/docs/guides/JSON/0-json_intro.mdx index 2bd1822c..6e4b0248 100644 --- a/src/content/docs/guides/JSON/0-json_intro.mdx +++ b/src/content/docs/guides/JSON/0-json_intro.mdx @@ -18,7 +18,7 @@ _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. +[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 section of the tutorial introduces JSON, its basic structure, and provides an overview of its application in SplashKit. ### Basic Structure of a JSON File @@ -39,7 +39,7 @@ JSON objects are made up of values associated with keys. In this example, `gameT ### 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. +SplashKit simplifies the process of working with JSON files in your games. It provides functions for reading JSON files, allowing us to easily retrieve values and load configurations or game data. Additionally, it offers functions for writing JSON files, enabling us to save configurations and game data. ### Getting Started with JSON in SplashKit @@ -137,8 +137,8 @@ if __name__ == "__main__":
-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. +In this code example, we first use [Json From File](/api/json/#json-from-file) to load a JSON object containing details from the `game_data.json` file. +Next, we retrieve the value associated with the `gameTitle` key using [Json Read String](/api/json/#json-read-string)and output it to the console. Finally, we free the JSON object using [Free Json](/api/json/#free-json) before exiting the program. This deallocates any memory that was allocated to the JSON object, helping to prevent memory-related errors such as `Segmentation Fault`. We can build this program using the following command. @@ -183,7 +183,7 @@ skm python3 program.py -When we run this program it should output the following to the console: +When we run this program, it should display the following output in the console: ```plaintext Game Title: My New Game @@ -301,4 +301,4 @@ if __name__ == "__main__":
-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. +We have successfully loaded our JSON file and retrieved the value associated with the `gameTitle` key. In the next tutorial, we'll delve deeper into retrieving other values stored within a JSON object. From e46dc6036a8902310a5df7acae89194dd49a9886 Mon Sep 17 00:00:00 2001 From: Oliver Exell-Bruce <87453519+oliverexell-bruce@users.noreply.github.com> Date: Wed, 9 Oct 2024 19:54:55 +1100 Subject: [PATCH 25/30] Add Python code to "Getting Started Creating User Interfaces" tutorial (#189) --- .../docs/guides/Interface/00-interface.mdx | 205 +++++++++++++++++- 1 file changed, 203 insertions(+), 2 deletions(-) diff --git a/src/content/docs/guides/Interface/00-interface.mdx b/src/content/docs/guides/Interface/00-interface.mdx index c05e7437..230242ef 100644 --- a/src/content/docs/guides/Interface/00-interface.mdx +++ b/src/content/docs/guides/Interface/00-interface.mdx @@ -3,7 +3,7 @@ title: Getting Started Creating User Interfaces description: This article will help you get started creating interfaces in SplashKit. In this one we'll see how to create and use basic elements, like buttons and sliders. In later the next ones, we'll move on to advanced layouting, and finally we'll see how we can style the interface to match our project. category: Tutorials author: Sean Boettger -lastupdated: April 29 2024 +lastupdated: September 19 2024 --- **{frontmatter.description}** @@ -105,6 +105,26 @@ Let's see how we can create a simple button. We'll start in an empty project, an
+ + + + ```python + from splashkit import * + + # open a window and clear it to white + open_window("My Interface!", 800, 600) + clear_screen_to_white() + + # ... we'll put our interface code here!... + + # refresh the screen, then wait 5 seconds + refresh_screen() + delay(5000) + + # close all open windows + close_all_windows() + ``` +
@@ -208,6 +228,28 @@ Let's see how we can create a simple button. We'll start in an empty project, an
+ + + + ```python ins={5-9} + # open a window and clear it to white + open_window("My Interface!", 800, 600) + clear_screen_to_white() + + # show button + button_at_position("My Button!", rectangle_from(300, 260, 200, 24)) + + # draw the interface! + draw_interface() + + # refresh the screen, then wait 5 seconds + refresh_screen() + delay(5000) + + # close all open windows + close_all_windows() + ``` +
@@ -331,6 +373,28 @@ Let's see how we can create a simple button. We'll start in an empty project, an + + + + ```python ins={4-5} + # open a window + open_window("My Interface!", 800, 600) + + while (not quit_requested()): + process_events() + + clear_screen_to_white() + + button_at_position("My Button!", rectangle_from(300, 260, 200, 24)) + + draw_interface() + + refresh_screen() + + # close all open windows + close_all_windows() + ``` + @@ -403,6 +467,14 @@ if (Button("Write To Terminal!", RectangleFrom(300, 260, 200, 24))) + + + +```python ins="Write To Terminal!" ins="if " ins=":" ins={2} +if button_at_position("Write To Terminal!", rectangle_from(300, 260, 200, 24)): + write_line("The button was clicked!") +``` + @@ -462,6 +534,18 @@ Now let's try out some more interesting elements - let's add a text box, so we c + + + + ```python ins={3} + open_window("My Interface!", 800, 600) + + user_message = "Default message!" + + while (not quit_requested()): + process_events() + ``` + @@ -518,6 +602,16 @@ Now let's try out some more interesting elements - let's add a text box, so we c + + + + ```python ins={1} ins="write_line(user_message)" + user_message = text_box_at_position(user_message, rectangle_from(300, 220, 200, 24)) + + if button_at_position("Write To Terminal!", rectangle_from(300, 260, 200, 24)): + write_line(user_message) + ``` + @@ -673,6 +767,40 @@ namespace CreatingUserInterfaces + + + +```python +from splashkit import * + +# open a window +open_window("My Interface!", 800, 600) + +# define variables +user_message = "Default message!" + +# main loop +while (not quit_requested()): + # get user events + process_events() + + # clear screen + clear_screen_to_white() + + # interface! + user_message = text_box_at_position(user_message, rectangle_from(300, 220, 200, 24)) + + if button_at_position("Write To Terminal!", rectangle_from(300, 260, 200, 24)): + write_line(user_message) + + # finally draw interface, then refresh screen + draw_interface() + refresh_screen() + +# close all open windows +close_all_windows() +``` + @@ -830,6 +958,43 @@ namespace CreatingUserInterfaces + + + +```python ins={8, 24} ins=/(width), 2/ ins="400 - width/2" +from splashkit import * + +# open a window +open_window("My Interface!", 800, 600) + +# define variables +user_message = "Default message!" +width = 200 + +# main loop +while (not quit_requested()): + # get user events + process_events() + + # clear screen + clear_screen_to_white() + + # interface + user_message = text_box_at_position(user_message, rectangle_from(400 - width/2, 220, width, 24)) + + if button_at_position("Write To Terminal!", rectangle_from(400 - width/2, 260, width, 24)): + write_line(user_message) + + width = slider_at_position(width, 10, 400, rectangle_from(300, 300, 200, 24)) + + # finally draw interface, then refresh screen + draw_interface() + refresh_screen() + +# close all open windows +close_all_windows() +``` + @@ -890,7 +1055,6 @@ int main() ``` - @@ -987,5 +1151,42 @@ namespace CreatingUserInterfaces + + + +```python +from splashkit import * + +# open a window +open_window("My Interface!", 800, 600) + +# define variables +user_message = "Default message!" +width = 200 + +# main loop +while (not quit_requested()): + # get user events + process_events() + + # clear screen + clear_screen_to_white() + + # interface + user_message = text_box_at_position(user_message, rectangle_from(400 - width/2, 220, width, 24)) + + if button_at_position("Write To Terminal!", rectangle_from(400 - width/2, 260, width, 24)): + write_line(user_message) + + width = slider_at_position(width, 10, 400, rectangle_from(300, 300, 200, 24)) + + # finally draw interface, then refresh screen + draw_interface() + refresh_screen() + +# close all open windows +close_all_windows() +``` + From 57c327610f4add339926e91967fc13250664ff7a Mon Sep 17 00:00:00 2001 From: Oliver Exell-Bruce <87453519+oliverexell-bruce@users.noreply.github.com> Date: Wed, 9 Oct 2024 20:21:05 +1100 Subject: [PATCH 26/30] Add Python code to "Layouts in User Interfaces" tutorial (#191) --- .../Interface/01-interface-layouting.mdx | 219 +++++++++++++++++- 1 file changed, 207 insertions(+), 12 deletions(-) diff --git a/src/content/docs/guides/Interface/01-interface-layouting.mdx b/src/content/docs/guides/Interface/01-interface-layouting.mdx index a7a1009b..1e8f482b 100644 --- a/src/content/docs/guides/Interface/01-interface-layouting.mdx +++ b/src/content/docs/guides/Interface/01-interface-layouting.mdx @@ -3,7 +3,7 @@ title: Layouts in User Interfaces description: This article will help you understand how to customize the layouts of your interfaces in SplashKit. category: Tutorials author: Sean Boettger -lastupdated: May 5 2024 +lastupdated: September 20 2024 --- **{frontmatter.description}** @@ -132,6 +132,34 @@ namespace InterfaceLayouts + + + +```python +from splashkit import * + +# open a window +open_window("My Interface!", 800, 600) + +# main loop +while (not quit_requested()): + # get user events + process_events() + + # clear screen + clear_screen_to_white() + + # ...we'll put our interface code here...! + + # finally draw interface, then refresh screen + draw_interface() + + refresh_screen() + +# close all open windows +close_all_windows() +``` + @@ -193,6 +221,18 @@ if (SplashKit.StartPanel("My panel", SplashKit.RectangleFrom(50, 50, 200, 100))) + + + +```python +# start the panel and check if it's open/visible +if (start_panel("My panel", rectangle_from(50,50,200,100))): + # ...here we'll create all the UI elements + + # end the panel + end_panel("My panel") +``` + @@ -270,7 +310,7 @@ int main() // close all open windows close_all_windows(); - + return 0; } ``` @@ -380,6 +420,46 @@ namespace InterfaceLayouts + + + +```python ins={17-18, 25-26} {6-7, 19-24} +from splashkit import * + +# open a window +open_window("My Interface!", 800, 600) + +# setup a variable to store the user's string - same as last tutorial +user_message = "Default message!" + +# main loop +while (not quit_requested()): + # get user events + process_events() + + # clear screen + clear_screen_to_white() + + # here we start the panel + if (start_panel("My panel", rectangle_from(50,50,200,100))): + # create the elements, just like last tutorial! + if button("Write To Terminal!"): + write_line(user_message) + + user_message = text_box(user_message) + + # end the panel + end_panel("My panel") + + + # finally draw interface, then refresh screen + draw_interface() + refresh_screen() + +# close all open windows +close_all_windows() +``` + @@ -456,6 +536,14 @@ if (SplashKit.Header("Edit Message!")) + + + +```python +if header("Edit Message!"): + user_message = text_box(user_message) +``` + @@ -544,6 +632,29 @@ SplashKit.EndInset("Inset area"); + + + +```python +paragraph("This text is outside the inset area!") +start_inset("Inset area", 60) + +if (button("Button 1!")): + write_line("Button 1 clicked!") +if (button("Button 2!")): + write_line("Button 2 clicked!") +if (button("Button 3!")): + write_line("Button 3 clicked!") +if (button("Button 4!")): + write_line("Button 4 clicked!") +if (button("Button 5!")): + write_line("Button 5 clicked!") +if (button("Button 6!")): + write_line("Button 6 clicked!") + +end_inset("Inset area") +``` + @@ -579,15 +690,15 @@ if (start_treenode("Some more buttons!")) if (button("Button 5!")) write_line("Button 5 clicked!"); - if (start_treenode("Buttons in buttons!!")) - { - if (button("Button 6!")) - write_line("Button 6 clicked!"); - end_treenode("Buttons in buttons!!"); - } - end_treenode("Some more buttons!"); -} -``` + if (start_treenode("Buttons in buttons!!")){ + if (button("Button 6!")) write_line("Button 6 clicked!"); + + end_treenode("Buttons in buttons!!"); + } + + end_treenode("Some more buttons!"); + } + ``` @@ -659,6 +770,32 @@ if (SplashKit.StartTreenode("Some more buttons!")) + + + +```python +if start_treenode("Some buttons!"): + if (button("Button 1!")): + write_line("Button 1 clicked!") + if (button("Button 2!")): + write_line("Button 2 clicked!") + if (button("Button 3!")): + write_line("Button 3 clicked!") + end_treenode("Some buttons!") + +if start_treenode("Some more buttons!"): + if (button("Button 4!")): + write_line("Button 4 clicked!") + if (button("Button 5!")): + write_line("Button 5 clicked!") + + if start_treenode("Buttons in buttons!!"): + if (button("Button 6!")): + write_line("Button 6 clicked!") + end_treenode("Buttons in buttons!!") + end_treenode("Some more buttons!") +``` + @@ -792,6 +929,33 @@ SplashKit.ResetLayout(); + + + +```python +start_custom_layout() +split_into_columns(3) +set_layout_height(64) + +if (button("Button 1!")): + write_line("Button 1 clicked!") +if (button("Button 2!")): + write_line("Button 2 clicked!") +if (button("Button 3!")): + write_line("Button 3 clicked!") + +set_layout_height(0); # 0 resets to default + +if (button("Button 4!")): + write_line("Button 4 clicked!") +if (button("Button 5!")): + write_line("Button 5 clicked!") +if (button("Button 6!")): + write_line("Button 6 clicked!") + +reset_layout() +``` + @@ -846,7 +1010,6 @@ reset_layout(); ```csharp -// Start custom layout StartCustomLayout(); SplitIntoColumns(2); @@ -910,6 +1073,38 @@ SplashKit.ResetLayout(); + + + +```python +start_custom_layout() +split_into_columns(2) + +enter_column() +set_layout_height(64) + +if (button("Button 1!")): + write_line("Button 1 clicked!") +if (button("Button 2!")): + write_line("Button 2 clicked!") + +leave_column() + +enter_column() +set_layout_height(0); # 0 resets to default + +if (button("Button 4!")): + write_line("Button 4 clicked!") +if (button("Button 5!")): + write_line("Button 5 clicked!") +if (button("Button 6!")): + write_line("Button 6 clicked!") + +leave_column() + +reset_layout() +``` + From f754f8b0f6e0878d35921be8ebab1e462fcc1de1 Mon Sep 17 00:00:00 2001 From: Oliver Exell-Bruce <87453519+oliverexell-bruce@users.noreply.github.com> Date: Wed, 9 Oct 2024 20:28:57 +1100 Subject: [PATCH 27/30] Add Python code to "Styling User Interfaces" tutorial (#192) --- .../guides/Interface/02-interface-styling.mdx | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/content/docs/guides/Interface/02-interface-styling.mdx b/src/content/docs/guides/Interface/02-interface-styling.mdx index 5e86c6af..37ab9e5d 100644 --- a/src/content/docs/guides/Interface/02-interface-styling.mdx +++ b/src/content/docs/guides/Interface/02-interface-styling.mdx @@ -51,7 +51,6 @@ int main() return 0; } - ``` @@ -128,6 +127,33 @@ namespace InterfaceStyling + + + +```python ins={6} +from splashkit import * + +# open a window +open_window("My Interface!", 800, 600) + +# set the interface style +set_interface_style(InterfaceStyle.shaded_light_style) + +while (not quit_requested()): + process_events() + + clear_screen_to_white() + + button_at_position("My Button!", rectangle_from(300, 260, 200, 24)) + + draw_interface() + + refresh_screen() + +# close all open windows +close_all_windows() +``` + @@ -272,6 +298,15 @@ SplashKit.SetInterfaceFontSize(12); + + + +```python +my_font = load_font("Custom Font", "arial.ttf") +set_interface_font(my_font) +set_interface_font_size(12) +``` + From d6f22ea593657d54a1766425dc14d3c21dbf3462 Mon Sep 17 00:00:00 2001 From: omckeon Date: Fri, 11 Oct 2024 02:46:11 +0000 Subject: [PATCH 28/30] Add in missing files from upstream --- package.json | 11 +-- scripts/components.cjs | 2 +- scripts/generate-groups.cjs | 19 +++++ src/components/Guides.astro | 134 +++++++++++++++++------------- src/components/guides-groups.json | 14 ++++ 5 files changed, 114 insertions(+), 66 deletions(-) create mode 100644 scripts/generate-groups.cjs create mode 100644 src/components/guides-groups.json diff --git a/package.json b/package.json index 5ffe85bf..14d14c47 100644 --- a/package.json +++ b/package.json @@ -3,14 +3,15 @@ "type": "module", "version": "0.9", "scripts": { - "dev": "npm run generate-mdx && npm run generate-usage-examples-pages && astro dev", - "start": "npm run generate-mdx && npm run generate-usage-examples-pages && astro dev", - "build": "npm run generate-mdx && npm run generate-usage-examples-pages && astro build", + "dev": "npm run generate-mdx && npm run generate-usage-examples-pages && npm run generate-groups && astro dev", + "start": "npm run generate-mdx && npm run generate-usage-examples-pages && npm run generate-groups && astro dev", + "build": "npm run generate-mdx && npm run generate-usage-examples-pages && npm run generate-groups && astro build", "preview": "astro preview", "astro": "astro", "generate-mdx": "node ./scripts/components.cjs", "generate-usage-examples-pages": "node ./scripts/usage-example-page-generation.cjs", - "check-links": "SET CHECK_LINKS=true && npm run build && SET CHECK_LINKS=false" + "check-links": "SET CHECK_LINKS=true && npm run build && SET CHECK_LINKS=false", + "generate-groups": "node ./scripts/generate-groups.cjs" }, "dependencies": { "@astrojs/netlify": "^5.4.0", @@ -46,4 +47,4 @@ "devDependencies": { "accessible-astro-components": "2.3.6" } -} +} \ No newline at end of file diff --git a/scripts/components.cjs b/scripts/components.cjs index 164cd630..5e6e1964 100644 --- a/scripts/components.cjs +++ b/scripts/components.cjs @@ -443,7 +443,7 @@ fs.readFile(`${__dirname}/api.json`, "utf8", async (err, data) => { // Write the MDX file - fs.writeFile(`./src/content/docs/api/${name}.mdx`, mdxContent, (err) => { + fs.writeFileSync(`./src/content/docs/api/${name}.mdx`, mdxContent, (err) => { if (err) { console.log(kleur.red(`Error writing ${input} MDX file: ${err.message}`)); } else { diff --git a/scripts/generate-groups.cjs b/scripts/generate-groups.cjs new file mode 100644 index 00000000..07c8d0de --- /dev/null +++ b/scripts/generate-groups.cjs @@ -0,0 +1,19 @@ +const fs = require('fs'); // Import the file system module to interact with the file system +const path = require('path'); // Import the path module to handle and transform file paths + +// Define the path to the directory containing the guide groups +const guidesDir = './src/content/docs/guides'; +// Define the path where the output JSON file will be saved +const outputFile = './src/components/guides-groups.json'; + +// Read the contents of the guides directory +const groupNames = fs.readdirSync(guidesDir, { withFileTypes: true }) + // Filter out only the directories from the list of files and directories + .filter(dirent => dirent.isDirectory()) + // Map the directory names to lowercase to standardise them + .map(dirent => dirent.name); + +// Write the list of group names to the output JSON file +fs.writeFileSync(outputFile, JSON.stringify(groupNames, null, 2)); +// Log a message to the console indicating that the JSON file has been created +console.log('Group names have been written to', outputFile); \ No newline at end of file diff --git a/src/components/Guides.astro b/src/components/Guides.astro index 9be4553f..07f4f7a2 100644 --- a/src/components/Guides.astro +++ b/src/components/Guides.astro @@ -1,6 +1,9 @@ --- import { LinkCard, CardGrid } from "@astrojs/starlight/components"; +import fs from "fs"; +import path from "path"; +// Define the type for frontmatter interface Frontmatter { title: string; description?: string; @@ -9,73 +12,84 @@ interface Frontmatter { category?: string; } +// Define paths +const jsonFilePath = path.resolve("./src/components/guides-groups.json"); + +// Define the type for the group names +type GroupName = string; + +// Helper function to capitalize and format group names +function formatGroupName(groupName: GroupName): string { + // Replace dashes with spaces and capitalize each word + return groupName + .replace(/-/g, " ") + .split(" ") + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(" "); +} + +// Read and parse the JSON file +const groupNames: GroupName[] = JSON.parse( + fs.readFileSync(jsonFilePath, "utf-8"), +); + +// Load and filter posts let posts = await Astro.glob("../content/docs/guides/*/*.mdx"); posts = posts.filter((post) => !post.file.endsWith("index.mdx")); -let guides = posts.filter( - (post) => post.frontmatter.category?.toLowerCase() == "guides", -); -// sort guides on the basis of simplifyed File Path -guides = guides.sort((a, b) => - simplifyFilePath(a.url?.toString() || "").localeCompare( - simplifyFilePath(b.url?.toString() || ""), - ), -); -let tutorials = posts.filter( - (post) => post.frontmatter.category?.toLowerCase() == "tutorials", -); -tutorials = tutorials.sort((a, b) => - simplifyFilePath(a.url?.toString() || "").localeCompare( - simplifyFilePath(b.url?.toString() || ""), - ), -); +// Function to check if URL contains the group name +function urlContainsGroup(url: string, groupName: string): boolean { + return url.toLowerCase().includes(groupName.toLowerCase()); +} -function simplifyFilePath(filePath: string) { - // Remove leading and trailing slashes +// Function to simplify file path +function simplifyFilePath(filePath: string): string { filePath = filePath.replace(/^\/|\/$/g, ""); - - // Split the path into parts using '/' const pathParts = filePath.split("/"); + const fileFolder = pathParts[pathParts.length - 2]; + const lastPart = pathParts[pathParts.length - 1]; + const simplifiedName = + fileFolder + "/" + lastPart.split(".").slice(0, -1).join("."); + return simplifiedName.toLowerCase(); +} +--- - // Get the last part of the path (including directory name) - const folderPath = pathParts[4] + "/" + pathParts[pathParts.length - 1]; +{ + groupNames.map((groupName: GroupName) => { + // Filter posts by the current group name and check for "guides" or "tutorials" category + const filteredPosts = posts + .filter( + (post) => + (post.frontmatter.category?.toLowerCase() === "guides" || + post.frontmatter.category?.toLowerCase() === "tutorials") && + urlContainsGroup(post.url?.toString() || "", groupName), + ) + .sort((a, b) => + simplifyFilePath(a.url?.toString() || "").localeCompare( + simplifyFilePath(b.url?.toString() || ""), + ), + ); - // Remove file extension (assuming it's after the last dot in the last part) - const simplifiedName = folderPath.split(".").slice(0, -1).join("."); + // Capitalize and format the group name + const formattedGroupName = formatGroupName(groupName); - return simplifiedName.toLowerCase(); // Convert to lowercase for consistency + return ( + <> +

{formattedGroupName}

+ + {filteredPosts.map((post) => ( + + ))} + + + ); + }) } ---- - -

Tutorials

- - { - tutorials.map((post) => ( - - )) - } - -

Guides

- - { - guides.map((post) => ( - - )) - } - diff --git a/src/components/guides-groups.json b/src/components/guides-groups.json new file mode 100644 index 00000000..f1788396 --- /dev/null +++ b/src/components/guides-groups.json @@ -0,0 +1,14 @@ +[ + "Animations", + "Audio", + "Camera", + "Graphics", + "Input", + "Interface", + "JSON", + "Networking", + "Raspberry-GPIO", + "Resource-Bundles", + "Using-SplashKit", + "Utilities" +] \ No newline at end of file From f5601bf90303da1fe729b9ad6cf4515a47e72d97 Mon Sep 17 00:00:00 2001 From: omckeon Date: Fri, 11 Oct 2024 03:03:02 +0000 Subject: [PATCH 29/30] Add extra line at eof --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 14d14c47..ae960a2a 100644 --- a/package.json +++ b/package.json @@ -47,4 +47,4 @@ "devDependencies": { "accessible-astro-components": "2.3.6" } -} \ No newline at end of file +} From 1adf02ee3f99563aa43946a3d4ce388d46f52080 Mon Sep 17 00:00:00 2001 From: omckeon Date: Fri, 11 Oct 2024 03:15:35 +0000 Subject: [PATCH 30/30] Update guides frontmatter info --- src/content/docs/guides/Animations/0-using-animations.mdx | 2 +- .../docs/guides/Audio/0-getting-started-with-audio.mdx | 2 +- src/content/docs/guides/Camera/0-using-splashkit-camera.mdx | 4 ++-- .../docs/guides/Graphics/0-drawing-using-procedures.mdx | 4 ++-- src/content/docs/guides/Input/0-reading-text.mdx | 2 +- src/content/docs/guides/Input/1-mouse-button-inputs.mdx | 2 +- src/content/docs/guides/Interface/00-interface.mdx | 4 ++-- .../docs/guides/Interface/01-interface-layouting.mdx | 4 ++-- src/content/docs/guides/Interface/02-interface-styling.mdx | 2 +- src/content/docs/guides/JSON/0-json_intro.mdx | 6 +++--- src/content/docs/guides/JSON/1-json_reading.mdx | 4 ++-- src/content/docs/guides/JSON/2-json_writing.mdx | 4 ++-- .../guides/Networking/0-getting-started-with-servers.mdx | 4 ++-- .../docs/guides/Networking/1-routing-with-servers.mdx | 4 ++-- src/content/docs/guides/Networking/2-restful-api-call.mdx | 2 +- src/content/docs/guides/Utilities/0-useful-utilities.mdx | 4 ++-- 16 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/content/docs/guides/Animations/0-using-animations.mdx b/src/content/docs/guides/Animations/0-using-animations.mdx index d042593d..73e7ab4b 100644 --- a/src/content/docs/guides/Animations/0-using-animations.mdx +++ b/src/content/docs/guides/Animations/0-using-animations.mdx @@ -3,7 +3,7 @@ title: Using Animations in SplashKit description: Animations allow you to switch between different images to make a more visually dynamic entity on the screen. SplashKit allows you to create animations and use these together with sprite sheets to create these animations. category: Guides author: Various Authors -lastupdated: July 2024 +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; diff --git a/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx b/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx index 1622d12e..cb9bc218 100644 --- a/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx +++ b/src/content/docs/guides/Audio/0-getting-started-with-audio.mdx @@ -2,7 +2,7 @@ title: Get Started with SplashKit Audio description: Adding sound effects and music can really help bring an application to life. In this article see how to get started with Audio in SplashKit. author: Various Authors -lastupdated: september 2024 +lastupdated: October 2024 category: Guides --- diff --git a/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx b/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx index 5ed763c4..fd8a60c5 100644 --- a/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx +++ b/src/content/docs/guides/Camera/0-using-splashkit-camera.mdx @@ -1,8 +1,8 @@ --- title: SplashKit Camera description: See how the camera works, and how to draw to the different coordinate systems in your program. -author: Andrew Cain -lastupdated: September 2024 +author: Andrew Cain and others +lastupdated: October 2024 category: Guides --- diff --git a/src/content/docs/guides/Graphics/0-drawing-using-procedures.mdx b/src/content/docs/guides/Graphics/0-drawing-using-procedures.mdx index 771d3cd2..1c6df8be 100644 --- a/src/content/docs/guides/Graphics/0-drawing-using-procedures.mdx +++ b/src/content/docs/guides/Graphics/0-drawing-using-procedures.mdx @@ -2,8 +2,8 @@ title: Drawing using Procedures description: This article provide a quick overview of getting started with SplashKit. It includes how to create a window and do some basic drawing in order to create a small animation. This is a great place to start with SplashKit. category: Tutorials -author: Andrew Cain -lastupdated: May 10 2024 +author: Andrew Cain and others +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; diff --git a/src/content/docs/guides/Input/0-reading-text.mdx b/src/content/docs/guides/Input/0-reading-text.mdx index 95e60128..8228a0b8 100644 --- a/src/content/docs/guides/Input/0-reading-text.mdx +++ b/src/content/docs/guides/Input/0-reading-text.mdx @@ -3,7 +3,7 @@ title: Reading Text description: See how to read text from the user, both from command line and graphical applications. category: Tutorials author: Andrew Cain and others -lastupdated: Sep 20, 2024 +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; diff --git a/src/content/docs/guides/Input/1-mouse-button-inputs.mdx b/src/content/docs/guides/Input/1-mouse-button-inputs.mdx index bb90efab..e8fbadaa 100644 --- a/src/content/docs/guides/Input/1-mouse-button-inputs.mdx +++ b/src/content/docs/guides/Input/1-mouse-button-inputs.mdx @@ -3,7 +3,7 @@ title: Using Mouse Inputs description: Introductory Mouse Input functionality guide category: Guides author: Various Authors -lastupdated: September 2024 +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; diff --git a/src/content/docs/guides/Interface/00-interface.mdx b/src/content/docs/guides/Interface/00-interface.mdx index 230242ef..43deacd7 100644 --- a/src/content/docs/guides/Interface/00-interface.mdx +++ b/src/content/docs/guides/Interface/00-interface.mdx @@ -2,8 +2,8 @@ title: Getting Started Creating User Interfaces description: This article will help you get started creating interfaces in SplashKit. In this one we'll see how to create and use basic elements, like buttons and sliders. In later the next ones, we'll move on to advanced layouting, and finally we'll see how we can style the interface to match our project. category: Tutorials -author: Sean Boettger -lastupdated: September 19 2024 +author: Sean Boettger and others +lastupdated: October 2024 --- **{frontmatter.description}** diff --git a/src/content/docs/guides/Interface/01-interface-layouting.mdx b/src/content/docs/guides/Interface/01-interface-layouting.mdx index 1e8f482b..b94316af 100644 --- a/src/content/docs/guides/Interface/01-interface-layouting.mdx +++ b/src/content/docs/guides/Interface/01-interface-layouting.mdx @@ -2,8 +2,8 @@ title: Layouts in User Interfaces description: This article will help you understand how to customize the layouts of your interfaces in SplashKit. category: Tutorials -author: Sean Boettger -lastupdated: September 20 2024 +author: Sean Boettger and others +lastupdated: October 2024 --- **{frontmatter.description}** diff --git a/src/content/docs/guides/Interface/02-interface-styling.mdx b/src/content/docs/guides/Interface/02-interface-styling.mdx index 37ab9e5d..4ce9f80c 100644 --- a/src/content/docs/guides/Interface/02-interface-styling.mdx +++ b/src/content/docs/guides/Interface/02-interface-styling.mdx @@ -2,7 +2,7 @@ title: Styling User Interfaces description: This article will explain how we can style our SplashKit interfaces to match our projects. category: Tutorials -author: Sean Boettger +author: Sean Boettger and others lastupdated: October 2024 --- diff --git a/src/content/docs/guides/JSON/0-json_intro.mdx b/src/content/docs/guides/JSON/0-json_intro.mdx index 6e4b0248..f6ef2486 100644 --- a/src/content/docs/guides/JSON/0-json_intro.mdx +++ b/src/content/docs/guides/JSON/0-json_intro.mdx @@ -2,8 +2,8 @@ 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: September 2024 +author: Jonathan Tynan and others +lastupdated: October 2024 sidebar: label: "Introduction to JSON" --- @@ -183,7 +183,7 @@ skm python3 program.py -When we run this program, it should display the following output in the console: +When we run this program, it should display the following output in the console: ```plaintext Game Title: My New Game diff --git a/src/content/docs/guides/JSON/1-json_reading.mdx b/src/content/docs/guides/JSON/1-json_reading.mdx index e56cb6de..e0a2e8fa 100644 --- a/src/content/docs/guides/JSON/1-json_reading.mdx +++ b/src/content/docs/guides/JSON/1-json_reading.mdx @@ -2,8 +2,8 @@ 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 and Yuyang Yang -lastupdated: Sep 14 2024 +author: Jonathan Tynan and others +lastupdated: October 2024 sidebar: label: "Reading JSON Data" --- diff --git a/src/content/docs/guides/JSON/2-json_writing.mdx b/src/content/docs/guides/JSON/2-json_writing.mdx index c233ca65..63d8e55c 100644 --- a/src/content/docs/guides/JSON/2-json_writing.mdx +++ b/src/content/docs/guides/JSON/2-json_writing.mdx @@ -2,8 +2,8 @@ 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 and Yuyang Yang -lastupdated: Sep 20 2024 +author: Jonathan Tynan and others +lastupdated: October 2024 sidebar: label: "Writing JSON Data" --- diff --git a/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx b/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx index 17bb18d1..7167270e 100644 --- a/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx +++ b/src/content/docs/guides/Networking/0-getting-started-with-servers.mdx @@ -2,8 +2,8 @@ title: Getting Started With Servers description: This guide is an introduction to using web servers category: Guides -author: Andrew Cain and Isaac Wallis -lastupdated: Oct 1 2024 +author: Andrew Cain, Isaac Wallis and others +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; diff --git a/src/content/docs/guides/Networking/1-routing-with-servers.mdx b/src/content/docs/guides/Networking/1-routing-with-servers.mdx index 87555960..00ee8823 100644 --- a/src/content/docs/guides/Networking/1-routing-with-servers.mdx +++ b/src/content/docs/guides/Networking/1-routing-with-servers.mdx @@ -2,8 +2,8 @@ title: Routing With Servers description: This guide is an intruduction to delivering different content based on route requested category: Guides -author: Isaac Wallis -lastupdated: Oct 1 2024 +author: Isaac Wallis and others +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; diff --git a/src/content/docs/guides/Networking/2-restful-api-call.mdx b/src/content/docs/guides/Networking/2-restful-api-call.mdx index cb83af1b..7c26f2a0 100644 --- a/src/content/docs/guides/Networking/2-restful-api-call.mdx +++ b/src/content/docs/guides/Networking/2-restful-api-call.mdx @@ -2,7 +2,7 @@ title: How to make a RESTful API call using SplashKit description: In the world of web services and microservices, many companies make their data available through a REST API in this document we want to use SplashKit to make a RESTful API call. category: Guides -author: Cyrill Illi and Brianna Laird +author: Cyrill Illi and others lastupdated: October 2024 --- diff --git a/src/content/docs/guides/Utilities/0-useful-utilities.mdx b/src/content/docs/guides/Utilities/0-useful-utilities.mdx index 60f4afd9..c80acdf2 100644 --- a/src/content/docs/guides/Utilities/0-useful-utilities.mdx +++ b/src/content/docs/guides/Utilities/0-useful-utilities.mdx @@ -2,8 +2,8 @@ title: Useful Utilities description: In this article, we discuss useful utilities that you can use to convert, check and manipulate common data types in SplashKit programs. category: Guides -author: Richard Denton -lastupdated: 09 September 2024 +author: Richard Denton and others +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components";