diff --git a/src/content/docs/guides/Animations/0-using-animations.mdx b/src/content/docs/guides/Animations/0-using-animations.mdx index 4d25bcb3..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"; @@ -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(); + } + } +} +``` + + + + 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..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: July 2024 +lastupdated: October 2024 category: Guides --- @@ -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(); @@ -187,10 +192,58 @@ int main() + + + ```csharp 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); @@ -242,59 +295,184 @@ do } // Drawing Keyboard Controls information in window (focus on sound effect code above) + DrawInstructions(); - // SplashKit Orange background - ClearScreen(RGBColor(245, 166, 35)); +} while (!(QuitRequested() || KeyTyped(KeyCode.EscapeKey) || KeyTyped(KeyCode.QKey))); - // 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); +CloseAllWindows(); +``` - // 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); +```csharp +using SplashKitSDK; - // Exit text - SetFontStyle("arial", FontStyle.ItalicFont); - DrawText("Press [Escape] or [Q] to quit", Color.Black, "arial", 16, 65, 290); - SetFontStyle("arial", FontStyle.NormalFont); +namespace SoundPlayer +{ + public class Program + { + public static void DrawInstructions() + { + // 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, (SplashKit.ScreenWidth() - SplashKit.TextWidth("Keyboard Controls", "arial", 20)) / 2, 10); + SplashKit.SetFontStyle("arial", FontStyle.NormalFont); + + // 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.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 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.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); + } - // 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); + public static void Main() + { + SoundEffect sndEffect; - // 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); + Window window = new Window("Sound Demo", 640, 320); - RefreshScreen(60); -} while (!(QuitRequested() || KeyTyped(KeyCode.EscapeKey) || KeyTyped(KeyCode.QKey))); + sndEffect = SplashKit.LoadSoundEffect("chipmunk", "chipmunk.ogg"); -CloseAllWindows(); + 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 + { + 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(); + } + } + + // 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") @@ -336,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() ``` 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..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: 16 Aug 2018 +author: Andrew Cain and others +lastupdated: October 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 @@ -62,236 +62,337 @@ 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(); +``` - - - ```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) + + +```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(); + } + } +} +``` - 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()) +```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()) + 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) + # 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) + # including something stationary - it doesn't move + fill_rectangle(color_white(), 400, 200, 10, 10) - refresh_screen_with_target_fps(60) - - close_all_windows() - ``` + refresh_screen_with_target_fps(60) + +close_all_windows() +``` 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..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"; @@ -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 +``` diff --git a/src/content/docs/guides/Input/0-reading-text.mdx b/src/content/docs/guides/Input/0-reading-text.mdx index 1f28a3e4..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: Oct 2 2018 +lastupdated: October 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). 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..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: July 2024 +lastupdated: October 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(); + } + } +} + +``` + + + + diff --git a/src/content/docs/guides/Interface/00-interface.mdx b/src/content/docs/guides/Interface/00-interface.mdx index 8b7293ef..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: April 29 2024 +author: Sean Boettger and others +lastupdated: October 2024 --- **{frontmatter.description}** @@ -24,28 +24,106 @@ 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); + // 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 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(); + } + } + } + ``` + + + + + + + + ```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() + ``` @@ -56,11 +134,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,6 +157,97 @@ 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(); + } + } + } + ``` + + + + + + + + ```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() ``` @@ -99,30 +273,127 @@ 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" - while (!quit_requested()) - { - process_events(); + int main() + { + // open a window + open_window("My Interface!", 800, 600); + + while (!quit_requested()) + { + process_events(); + + clear_screen(COLOR_WHITE); + + button("My Button!", rectangle_from(300, 260, 200, 24)); + + draw_interface(); + + refresh_screen(); + } + + // close all open windows + close_all_windows(); + + return 0; + } + ``` + + + + + + - clear_screen(COLOR_WHITE); + ```csharp ins={6-8, 17} + using static SplashKitSDK.SplashKit; - button("My Button!", rectangle_from(300, 260, 200, 24)); + // open a window + OpenWindow("My Interface!", 800, 600); - draw_interface(); + while (!QuitRequested()) + { + ProcessEvents(); - refresh_screen(); - } + ClearScreen(ColorWhite()); - // program ends, and the window closes - return 0; - ``` + 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(); + } + } + } + ``` + + + + + + + + ```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() + ``` @@ -160,15 +431,49 @@ 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!"); + } +``` + + + + + + + +```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!") +``` @@ -183,18 +488,63 @@ 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!"; + string user_message = "Default message!"; - while (!quit_requested()) - { - process_events(); - ``` + while (!quit_requested()) + { + process_events(); + ``` + + + + + + + + ```csharp ins={3} + OpenWindow("My Interface!", 800, 600); + + 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(); + ``` + + + + + + + + ```python ins={3} + open_window("My Interface!", 800, 600) + + user_message = "Default message!" + + while (not quit_requested()): + process_events() + ``` @@ -208,17 +558,59 @@ 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); - } - ``` + 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); + } + ``` + + + + + + + + ```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) + ``` @@ -239,47 +631,175 @@ 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(); + } + } +} +``` + + + + + + + +```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() +``` @@ -293,43 +813,191 @@ 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" + +int main() +{ + // open a window + open_window("My Interface!", 800, 600); - // main loop - while (!quit_requested()) - { - // get user events - process_events(); + // define variables + string user_message = "Default message!"; + float width = 200; - // clear screen - clear_screen(COLOR_WHITE); + // main loop + while (!quit_requested()) + { + // get user events + process_events(); - // interface! - user_message = text_box(user_message, rectangle_from(400 - width/2, 220, width, 24)); + // clear screen + clear_screen(COLOR_WHITE); - if (button("Write To Terminal!", rectangle_from(400 - width/2, 260, width, 24))) - { - write_line(user_message); - } + // interface! + user_message = text_box(user_message, rectangle_from(400 - width/2, 220, width, 24)); - width = slider(width, 10, 400, rectangle_from(300, 300, 200, 24)); + if (button("Write To Terminal!", rectangle_from(400 - width/2, 260, width, 24))) + { + write_line(user_message); + } - // finally draw interface, then refresh screen - draw_interface(); + width = slider(width, 10, 400, rectangle_from(300, 300, 200, 24)); - refresh_screen(); - } - ``` + // 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(); + } + } +} +``` + + + + + + + +```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() +``` +
## Wrap up @@ -340,50 +1008,185 @@ 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(); + } + } +} +``` + + + + + + + +```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() +``` + diff --git a/src/content/docs/guides/Interface/01-interface-layouting.mdx b/src/content/docs/guides/Interface/01-interface-layouting.mdx index 8641bc87..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: May 5 2024 +author: Sean Boettger and others +lastupdated: October 2024 --- **{frontmatter.description}** @@ -20,41 +20,145 @@ 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); +int main() +{ + // open a window + open_window("My Interface!", 800, 600); - // 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); - // ...we'll put out interface code here...! + // ...we'll put our interface code here...! - // 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); + +// 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(); + } + } +} +``` + + + + + + + +```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() +``` @@ -68,19 +172,66 @@ 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"); +} +``` + + + + + + + +```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") +``` @@ -113,54 +264,201 @@ 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); +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"; + // 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(); + // main loop + while (!quit_requested()) + { + // get user events + process_events(); - // clear screen - clear_screen(COLOR_WHITE); + // 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); - } + // 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); + user_message = text_box(user_message); - // end the panel - end_panel("My panel"); - } + // end the panel + end_panel("My panel"); + } - // 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 ins={18-20, 29-31} +using static SplashKitSDK.SplashKit; + +// open a window +OpenWindow("My Interface!", 800, 600); + +// setup a variable to store the user's string - same as last tutorial +string userMessage = "Default message"; + +// main loop +while (!QuitRequested()) +{ + // get user events + ProcessEvents(); + + // clear screen + ClearScreen(ColorWhite()); + + // 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); + } + + userMessage = TextBox(userMessage); + + // 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(); + } + } +} +``` + + + + + + + +```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() +``` @@ -193,7 +491,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,14 +500,48 @@ 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); +} +``` + + + + + + + +```python +if header("Edit Message!"): + user_message = text_box(user_message) ``` @@ -224,20 +557,103 @@ 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"); +``` + + + + + + + +```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") +``` @@ -251,20 +667,28 @@ 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!"); @@ -276,6 +700,102 @@ Here's a code example - various _nested_ tree nodes are started and ended with, } ``` + + + + + + +```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!"); +} +``` + + + + +```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!"); +} +``` + + + + + + + +```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!") +``` + @@ -291,12 +811,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 +842,119 @@ 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); - 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 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(); +``` + + + + + + + +```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(); +``` + + + + + + + +```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() +``` @@ -354,25 +971,139 @@ 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 +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(); +``` + + + + + + + +```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() +``` diff --git a/src/content/docs/guides/Interface/02-interface-styling.mdx b/src/content/docs/guides/Interface/02-interface-styling.mdx index 1577049f..4ce9f80c 100644 --- a/src/content/docs/guides/Interface/02-interface-styling.mdx +++ b/src/content/docs/guides/Interface/02-interface-styling.mdx @@ -2,8 +2,8 @@ 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 +author: Sean Boettger and others +lastupdated: October 2024 --- **{frontmatter.description}** @@ -19,37 +19,140 @@ 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(); + } + } +} +``` + + + + + + + +```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() +``` @@ -162,14 +265,47 @@ 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); +``` + + + + + + + +```python +my_font = load_font("Custom Font", "arial.ttf") +set_interface_font(my_font) +set_interface_font_size(12) +``` diff --git a/src/content/docs/guides/JSON/0-json_intro.mdx b/src/content/docs/guides/JSON/0-json_intro.mdx index d858428c..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: May 11 2024 +author: Jonathan Tynan and others +lastupdated: October 2024 sidebar: label: "Introduction to JSON" --- @@ -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 @@ -54,45 +54,91 @@ 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("Game Title: "); - write_line(game_title); + write_line("Game Title: " + game_title); - free_json(game_data); + free_json(game_data); + + return 0; +} +``` - return 0; - } - ``` + + - - - + + - ```csharp - using SplashKitSDK; - using static SplashKitSDK.SplashKit; +```csharp +using SplashKitSDK; +using static SplashKitSDK.SplashKit; - Json gameData = JsonFromFile("game_data.json"); +Json gameData = JsonFromFile("game_data.json"); +string gameTitle = JsonReadString(gameData, "gameTitle"); - string gameTitle = JsonReadString(gameData, "gameTitle"); +WriteLine("Game Title: " + gameTitle); - WriteLine("Game Title: " + gameTitle); +FreeJson(gameData); +``` - FreeJson(gameData); - ``` + + - +```csharp +using SplashKitSDK; + +namespace GameDataManagement +{ + public class Program + { + public static void Main() + { + Json gameData = SplashKit.JsonFromFile("game_data.json"); + string gameTitle = SplashKit.JsonReadString(gameData, "gameTitle"); + + SplashKit.WriteLine("Game Title: " + gameTitle); + + SplashKit.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. -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. + + + +```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() +``` + + + + +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. @@ -121,7 +167,6 @@ And run it with: ``` - ```shell @@ -129,10 +174,16 @@ dotnet run ``` - + + +```shell +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 @@ -149,8 +200,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 +220,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 +241,64 @@ 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); + } + } +} +``` + + + + + + + +```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() ``` -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. diff --git a/src/content/docs/guides/JSON/1-json_reading.mdx b/src/content/docs/guides/JSON/1-json_reading.mdx index c0f8f734..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 -lastupdated: May 11 2024 +author: Jonathan Tynan and others +lastupdated: October 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"); +``` + + + + diff --git a/src/content/docs/guides/JSON/2-json_writing.mdx b/src/content/docs/guides/JSON/2-json_writing.mdx index 60c0514e..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 -lastupdated: May 11 2024 +author: Jonathan Tynan and others +lastupdated: October 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"); +``` + + + + 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..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: Jul 14 2018 +author: Andrew Cain, Isaac Wallis and others +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -50,52 +50,83 @@ 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; + + + +```csharp +using static SplashKitSDK.SplashKit; +using SplashKitSDK; + +Console.WriteLine("About to start the server..."); - Console.WriteLine("About to start the server..."); +// Start a web server - defaults to listening to port 8080 +WebServer server = StartWebServer(); - // Start a web server - defaults to listening to port 8080 - WebServer server = SplashKit.StartWebServer(); +// For now, we are done... so let's shutdown... +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); + } + } +} +``` - // For now, we are done... so let's shutdown... - 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() +# 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 +142,116 @@ 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 = 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 static SplashKitSDK.SplashKit; +using SplashKitSDK; - // Start a web server - defaults to listening to port 8080 - WebServer server = SplashKit.StartWebServer(); +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 = StartWebServer(); - // Wait and get the first request that comes in - HttpRequest request = SplashKit.NextWebRequest(server); +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 = NextWebRequest(server); - // For now, we are done, so let's shutdown - SplashKit.StopWebServer(server); +// Send back the index.html file +SendResponse(request, "Hello World"); - SplashKit.ReadLine(); // Pause to keep the console window open - ``` +// For now, we are done, so let's shutdown +StopWebServer(server); +``` - + - ```python - from splashkit import * +```csharp - write_line("About to start the server...") +using SplashKitSDK; - # Start a web server - defaults to listening to port 8080 - server = start_web_server_with_default_port() +namespace WebServerApp +{ + public class Program + { + public static void Main() + { + SplashKit.WriteLine("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 + WebServer server = SplashKit.StartWebServer(); - # Wait and get the first request that comes in - request = next_web_request(server) + SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - # Send back the index.html file - send_response(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 - stop_web_server(server) + // Send back the index.html file + SplashKit.SendResponse(request, "Hello World"); - read_line() # Pause to keep the console window open - ``` + // For now, we are done, so let's shutdown + SplashKit.StopWebServer(server); + } + } +} +``` + + + + + + + +```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_response(request, "Hello World") + +# For now, we are done, so let's shutdown +stop_web_server(server) +``` @@ -200,80 +267,115 @@ 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 = 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 static SplashKitSDK.SplashKit; +using SplashKitSDK; - // Start a web server - defaults to listening to port 8080 - WebServer server = SplashKit.StartWebServer(); +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 = StartWebServer(); - // Wait and get the first request that comes in - HttpRequest request = SplashKit.NextWebRequest(server); +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 = NextWebRequest(server); - // For now, we are done, so let's shutdown - SplashKit.StopWebServer(server); +// Send back the index.html file +SendHtmlFileResponse(request, "index.html"); - SplashKit.ReadLine(); // Pause to keep the console window open - ``` +// For now, we are done, so let's shutdown +StopWebServer(server); +``` - + + +```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(); - ```python - from splashkit import * + SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - write_line("About to start the server...") + // Wait and get the first request that comes in + HttpRequest request = SplashKit.NextWebRequest(server); - # Start a web server - defaults to listening to port 8080 - server = start_web_server_with_default_port() + // Send back the index.html file + SplashKit.SendHtmlFileResponse(request, "index.html"); - write_line("Waiting for a request - navigate to http://localhost:8080") + // For now, we are done, so let's shutdown + SplashKit.StopWebServer(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") +```python +from splashkit import * - # For now, we are done, so let's shutdown - stop_web_server(server) +write_line("About to start the server...") - read_line() # Pause to keep the console window open - ``` +# 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) +``` 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..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: Aug 10 2018 +author: Isaac Wallis and others +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -27,81 +27,115 @@ 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..."); +int main() +{ + write_line("About to start the server..."); - // Start a web server - defaults to listening to port 8080 - web_server server = 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 static SplashKitSDK.SplashKit; +using SplashKitSDK; - // Start a web server - defaults to listening to port 8080 - WebServer server = SplashKit.StartWebServer(); +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 = StartWebServer(); - // Wait and get the first request that comes in - HttpRequest request = SplashKit.NextWebRequest(server); +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 = NextWebRequest(server); - // For now, we are done, so let's shutdown - SplashKit.StopWebServer(server); +// Send back the index.html file +SendHtmlFileResponse(request, "index.html"); - SplashKit.ReadLine(); // Pause to keep the console window open - ``` +// For now, we are done, so let's shutdown +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,114 +163,151 @@ 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 - using SplashKitSDK; + + - class Program - { - static void Main() - { - SplashKit.WriteLine("About to start the server..."); +```csharp +using static SplashKitSDK.SplashKit; +using SplashKitSDK; - WebServer server = SplashKit.StartWebServer(); - HttpRequest request; +WriteLine("About to start the server..."); - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); +WebServer server = StartWebServer(); +HttpRequest request; - // Get the next request that the server has - request = SplashKit.NextWebRequest(server); +WriteLine("Waiting for a request - navigate to http://localhost:8080"); - SplashKit.WriteLine("I got a request for " + SplashKit.RequestURI(request)); +// Get the next request that the server has +request = NextWebRequest(server); - if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) - { - // Serve page for login path, e.g. - // SplashKit.SendHtmlFileResponse(request, "login.html"); +WriteLine("I got a request for " + RequestURI(request)); - SplashKit.SendResponse(request, "login page"); - } - else - { - // If no specified path is requested, serve index.html to the user - SplashKit.SendHtmlFileResponse(request, "index.html"); - } +if (IsGetRequestFor(request, "/login") || IsGetRequestFor(request, "/login.html")) +{ + // Serve page for login path + SendResponse(request, "login page"); +} +else +{ + // If no specified path is requested, serve index.html to the user + SendHtmlFileResponse(request, "index.html"); +} - SplashKit.WriteLine("About to stop the server..."); - SplashKit.StopWebServer(server); - } - } - ``` +WriteLine("About to stop the server..."); +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) +``` @@ -256,176 +327,252 @@ 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)); - - 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"); +```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)); + + 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; +} +``` - //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 static SplashKitSDK.SplashKit; +using SplashKitSDK; - - +WriteLine("About to start the server..."); - ```csharp - using SplashKitSDK; +WebServer server = StartWebServer(); +HttpRequest request; - SplashKit.WriteLine("About to start the server..."); +WriteLine("Waiting for a request - navigate to http://localhost:8080"); +WriteLine("To end - navigate to http://localhost:8080/quit"); - WebServer server = SplashKit.StartWebServer(); - HttpRequest request; +// Get the next request that the server has +request = NextWebRequest(server); - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); +while (!IsGetRequestFor(request, "/quit")) +{ + WriteLine("I got a request for " + RequestURI(request)); - // Get the next request that the server has - request = SplashKit.NextWebRequest(server); + if (IsGetRequestFor(request, "/login") || 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)); + SendResponse(request, "login page"); + } + else if (IsGetRequestFor(request, "/contact") || IsGetRequestFor(request, "/contact.html")) + { + // Serve page for contact path, e.g. + // SendHtmlFileResponse(request, "contact.html"); - if (SplashKit.IsGetRequestFor(request, "/login") || SplashKit.IsGetRequestFor(request, "/login.html")) - { - // Serve page for login path, e.g. - // SendHtmlFileResponse(request, "login.html"); + SendResponse(request, "contact page"); + } + else if (IsGetRequestFor(request, "/about") || IsGetRequestFor(request, "/about.html")) + { + // Serve page for about path, e.g. + // SendHtmlFileResponse(request, "about.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"); + SendResponse(request, "about page"); + } + else + { + // If no specified path is requested, serve index.html to the user + SendHtmlFileResponse(request, "index.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"); + WriteLine("Waiting for a request - navigate to http://localhost:8080"); + WriteLine("To end - navigate to http://localhost:8080/quit"); - SplashKit.SendResponse(request, "about page"); - } - else - { - // If no specified path is requested, serve index.html to the user - SplashKit.SendHtmlFileResponse(request, "index.html"); - } + // Get the next request that the server has + request = NextWebRequest(server); +} - SplashKit.WriteLine("Waiting for a request - navigate to http://localhost:8080"); - SplashKit.WriteLine("To end - navigate to http://localhost:8080/quit"); +WriteLine("About to stop the server..."); +StopWebServer(server); +``` - // Get the next request that the server has - request = SplashKit.NextWebRequest(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"); + 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) +``` 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..7c26f2a0 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 others +lastupdated: October 2024 --- import { Tabs, TabItem } from "@astrojs/starlight/components"; @@ -38,33 +38,124 @@ 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 static SplashKitSDK.SplashKit; +using SplashKitSDK; + +// Get a single JSON web resource +HttpResponse getData = HttpGet("https://jsonplaceholder.typicode.com/posts/1", 443); +string response = HttpResponseToString(getData); +FreeResponse(getData); + +// Output the response +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("================"); + } + } +} +``` + + + + + + + +```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: + +```shell +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 +163,115 @@ 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; +} +``` + + + + + + +```csharp +using static SplashKitSDK.SplashKit; +using SplashKitSDK; + +// Get a list of a JSON web resource +HttpResponse getData = HttpGet("https://jsonplaceholder.typicode.com/posts/", 443); +string response = HttpResponseToString(getData); +FreeResponse(getData); - // 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); +// 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. +WriteLine(response); +``` - return 0; - } - ``` + + + +```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); + } + } +} +``` + + + +```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: + +```shell +[ + { + "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 +279,164 @@ 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 static SplashKitSDK.SplashKit; +using SplashKitSDK; + +// Create a JSON Web resource +// Create the JSON body for the http post call +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 +{ + "Content-type: application/json; charset=UTF-8" +}; + +// Send the request +HttpResponse getData = HttpPost("https://jsonplaceholder.typicode.com/posts", 443, JsonToString(body), headers); +string response = HttpResponseToString(getData); +FreeResponse(getData); + +// Output the response +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("================"); + } + } +} +``` + + + + +```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: + +```shell +Following resource has been created +UserID => 1 +ID => 101 +Title => foo +Body => test entry +================ +``` diff --git a/src/content/docs/guides/Utilities/0-useful-utilities.mdx b/src/content/docs/guides/Utilities/0-useful-utilities.mdx index f64346f8..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: July 2024 +author: Richard Denton and others +lastupdated: October 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) +```