<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Matthew Connelly</title>
    <description>The latest articles on DEV Community by Matthew Connelly (@mattconn).</description>
    <link>https://dev.to/mattconn</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F116431%2F94c24420-0327-46da-936d-41392dbdd801.jpg</url>
      <title>DEV Community: Matthew Connelly</title>
      <link>https://dev.to/mattconn</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mattconn"/>
    <language>en</language>
    <item>
      <title>Compiling an SDL2 Game to WASM</title>
      <dc:creator>Matthew Connelly</dc:creator>
      <pubDate>Sat, 12 Mar 2022 21:36:53 +0000</pubDate>
      <link>https://dev.to/mattconn/compiling-an-sdl2-game-to-wasm-42fj</link>
      <guid>https://dev.to/mattconn/compiling-an-sdl2-game-to-wasm-42fj</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published 7/13/20 on my personal blog.&lt;/em&gt;&lt;br&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2gxbx9uhqdvr92xj5rng.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2gxbx9uhqdvr92xj5rng.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I have a Snake clone written in C++ and SDL2, and while it's not just-add-water (yet) to compile a game to WASM with emscripten, it's pretty close. There was just some minor refactoring to be done, but it didn't affect the desktop version.&lt;/p&gt;

&lt;h1&gt;
  
  
  Infinite loop error
&lt;/h1&gt;

&lt;p&gt;My game loop spins forever or until a quit event occurs. Infinite loops don't fly in the browser however, and this is the biggest change that had to be made to my game.&lt;/p&gt;

&lt;p&gt;I had to move some code around, and what once sat in a while loop now lives in a function.&lt;/p&gt;

&lt;p&gt;Before (no good):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// main.cpp

int main()
{
    &amp;lt;init code...&amp;gt;

    while(running)
    {
        &amp;lt;game loop code...&amp;gt;
    }

    return 0;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;After (good):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// main.cpp

&amp;lt;declarations, defined later during init...&amp;gt;

void mainloop()
{
    &amp;lt;game loop code...&amp;gt;

    if(quit)
    {
        emscripten_cancel_main_loop(); 
        // ^ Add this to your close and destroy code 
        &amp;lt;close sdl subsystems and destroy...&amp;gt;
    }
}

int main()
{
    &amp;lt;init code...&amp;gt;

    emscripten_set_main_loop(mainloop, 0, 1);

    return 0;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;My main routine now ends with the &lt;code&gt;emscripten_set_main_loop&lt;/code&gt; call, whereas prior to this WASM refactor, it ended with a closing of SDL2 subsystems, meaning my game now handles quitting at the end of the game loop.&lt;/p&gt;

&lt;p&gt;Later on I'll add define guards to make sure this all still compiles for desktop.&lt;/p&gt;

&lt;h1&gt;
  
  
  Build Flags
&lt;/h1&gt;

&lt;p&gt;There were some build troubles. To be fair, I didn't read all that much on what these build flags mean, but that's alright because it builds now and that's all that matters (just kidding). It does build though.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;RuntimeError error: unreachable&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;A Google search led to a suggestion that this resulted from control flow not being able to reach code due to a missing return statement? I then tracked it down to a SDL_RenderPresent call. I'm wrapping most SDL things in my own namespace and functions so I though that might be the problem. It turns out it was the &lt;code&gt;asyncify&lt;/code&gt; flag which I thoughtlessly and needlessly added to the build flags.&lt;/p&gt;

&lt;p&gt;Bad:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

em++ *.cpp -o snake.html -g -lm --bind -s USE_SDL=2 -s USE_SDL_IMAGE=2 -s SDL2_IMAGE_FORMATS='["png"]' --preload-file assets/ --use-preload-plugins -s ASYNCIFY


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Good:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

em++ *.cpp -o snake.html -g -lm --bind -s USE_SDL=2 -s USE_SDL_IMAGE=2 -s SDL2_IMAGE_FORMATS='["png"]' --preload-file assets/ --use-preload-plugins


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;No asyncify.&lt;/p&gt;

&lt;h3&gt;
  
  
  Handling Images
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;-s SDL2_IMAGE_FORMATS='["png"]' --preload-file assets/ --use-preload-plugins&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;These flags will let SDL2_image load PNG's. Also, a trailing slash must be used to preload an entire directory with &lt;code&gt;preload-file&lt;/code&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Maintaining Interoperability
&lt;/h1&gt;

&lt;p&gt;Makefile targets look like this, snake-game being for desktop and snake.html for wasm:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

snake-game: *.cpp
        clang++ -std=c++11 -I /usr/include/SDL2/ -l SDL2 -l SDL2_image $^ -o $@

snake.html: *.cpp
        em++ $^ -o $@ -g -lm --bind -s USE_SDL=2 -s USE_SDL_IMAGE=2 -s SDL2_IMAGE_FORMATS='["png"]' --preload-file assets/ --use-preload-plugins 



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;I also added define guards around emscripten function calls and the header as well.&lt;br&gt;
At the top of main.cpp:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

.
.
.

#ifdef __EMSCRIPTEN__
#include "emscripten.h"
#endif

.
.
.


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and, towards the end of mainloop():&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

.
.
.

if(quit) {
    #ifdef __EMSCRIPTEN__
    emscripten_cancel_main_loop();
    #endif

    &amp;lt;close SDL subsystems and destroy...&amp;gt;
}

.
.
.


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and at the bottom of main():&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;.&lt;br&gt;
.&lt;br&gt;
.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    #ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(mainloop, 0, 1);
    #endif

    #ifndef __EMSCRIPTEN__
// repeatedly calling mainloop on desktop
    while(!quit) mainloop();
    #endif

    return 0;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;}&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h1&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Game Development with WASM in Mind&lt;br&gt;
&lt;/h1&gt;

&lt;p&gt;I will probably separate my code like the above in the future to keep it open for WASM compilation, much like we now develop webpages mobile-first.&lt;/p&gt;

&lt;p&gt;If you've made it this far, you'd may as well play my Snake clone here: &lt;a href="http://mattconndev.com/snake-wasm/" rel="noopener noreferrer"&gt;http://mattconndev.com/snake-wasm/&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Sources
&lt;/h1&gt;

&lt;p&gt;Code restructuring for emscripten: &lt;a href="https://medium.com/@robaboukhalil/porting-games-to-the-web-with-webassembly-70d598e1a3ec" rel="noopener noreferrer"&gt;https://medium.com/@robaboukhalil/porting-games-to-the-web-with-webassembly-70d598e1a3ec&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Define guards for interoperability: &lt;a href="https://dev.to/kibebr/i-made-a-game-in-c-run-in-a-web-browser-and-so-can-you-4deb"&gt;https://dev.to/kibebr/i-made-a-game-in-c-run-in-a-web-browser-and-so-can-you-4deb&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Comparing Array-Based Stacks in C and Go</title>
      <dc:creator>Matthew Connelly</dc:creator>
      <pubDate>Fri, 05 Feb 2021 04:40:54 +0000</pubDate>
      <link>https://dev.to/mattconn/comparing-array-based-stacks-in-c-and-go-5e83</link>
      <guid>https://dev.to/mattconn/comparing-array-based-stacks-in-c-and-go-5e83</guid>
      <description>&lt;p&gt;&lt;em&gt;This was originally published on my blog on July 5th, 2020. Now I'm publishing it here! I hope you find it interesting.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--UfrSJ8aG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/6cnihy08im420mp6f6mf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UfrSJ8aG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/6cnihy08im420mp6f6mf.png" alt="Golang Gopher playing with giant letter C" width="263" height="377"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I'll be comparing stack-based arrays in C and Go. There are many ways to implement a stack, but the aim here is for simplicity.&lt;/p&gt;

&lt;h1&gt;
  
  
  Stacks in C
&lt;/h1&gt;




&lt;h2&gt;
  
  
  Non-Functionial Approach
&lt;/h2&gt;

&lt;p&gt;Filling a stack with integers 1 through 10.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

int main()
{
        int stack[10];
        int top = -1; 

        int i = 1;
        while(top+1 &amp;lt; 10) 
        {   
                stack[++top] = i;
                i++;
        }   

    // print 
        for(int i=0; i &amp;lt; 10; i++) printf("STACK[%d]=%d\n",i,stack[i]); 


        return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In need of a stack, this will do. The big deal here is &lt;code&gt;stack[++top]=i&lt;/code&gt; which is our push functionality. Pop can be achieved similarly, and peek is &lt;code&gt;stack[top]&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Functional Approach
&lt;/h2&gt;

&lt;p&gt;Things get more interesting with functions involved. The code is more resuable, unlike the code above which is more of a one-off.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdbool.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;

bool push(int arr[], int size, int *top, int element);

int main(){
        int stack[10];
        int top = -1; 

        int i = 0;
        while(push(stack, 10, &amp;amp;top, ++i)){}

    // print 
        for(int i=0; i &amp;lt; 10; i++) printf("STACK[%d]=%d\n",i,stack[i]); 

        return 0;
}

bool push(int arr[], int size, int *top, int element)
{
        if((*top)+1 == size) return false;
        arr[++(*top)] = element;

        return true;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the function will all the work in a while loop like &lt;code&gt;while(push(stack, 10, &amp;amp;top, ++i)){}&lt;/code&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Stacks in Go
&lt;/h1&gt;




&lt;h2&gt;
  
  
  Without Functions
&lt;/h2&gt;

&lt;p&gt;Nearly identical to C:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import "fmt"

func main(){
        var stack [10]int                         
        top := -1 

        i := 1
        for top+1 &amp;lt; 10 {
                top++
                stack[top] = i
                i++
        }                     

    // print
        for i := range stack {fmt.Printf("STACK[%d]=%d\n",i,stack[i])}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are some syntax differences such as Go's lack of a prefix increment operator which would make a terse statement like &lt;code&gt;stack[++top] = i;&lt;/code&gt; possible in C.&lt;/p&gt;

&lt;p&gt;It's also worth noting that the array declared as &lt;code&gt;var stack [10]int&lt;/code&gt; is automatically zeroed-out.&lt;/p&gt;

&lt;h2&gt;
  
  
  With Functions
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import "fmt"

func push(arr []int, top *int, element int) bool {
        if *top + 1 == len(arr) {return false}
        *top++
        arr[*top] = element

        return true
}

func main(){
        var stack [10]int
        top := -1

        i := 1
        for push(stack[:],&amp;amp;top,i) != false {i++}

        // print
        for i := range stack {fmt.Printf("STACK[%d]=%d\n",i,stack[i])}

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can put what is essentially a while loop to work again but this time, in Go syntax as &lt;code&gt;for push(stack[:],&amp;amp;top,i) != false {i++}&lt;/code&gt;. We cannot increment our &lt;code&gt;i&lt;/code&gt; variable here in our function call like we can in C unfortunately, so the body of our loop gets a single line.&lt;/p&gt;

&lt;p&gt;There is a greater difference here, however. When passing the array to the &lt;code&gt;push&lt;/code&gt; function, it must be passed as a slice (a dynamic subarray pointing to the actual array). The expression &lt;code&gt;stack[:]&lt;/code&gt; creates this slice with the endpoints omitted.&lt;/p&gt;

&lt;p&gt;To not pass in a slice, the function signature would look like &lt;code&gt;func push(arr [10]int, top *int, element int) bool&lt;/code&gt;, where the size of the array must be explicitly stated and therefore only size 10 arrays would be allowed in this function.&lt;/p&gt;

&lt;h1&gt;
  
  
  Go's Built-In Dynamic Arrays
&lt;/h1&gt;

&lt;p&gt;Go will let you append to a slice with a statement like &lt;code&gt;stack = append(stack, i)&lt;/code&gt;, which would manage the top of the stack for you, the catch being that this can only be done with slices and not statically sized arrays.&lt;/p&gt;

</description>
      <category>c</category>
      <category>go</category>
      <category>datastructures</category>
    </item>
    <item>
      <title>Text-based Level Editing and Phaser JS</title>
      <dc:creator>Matthew Connelly</dc:creator>
      <pubDate>Mon, 26 Nov 2018 19:41:56 +0000</pubDate>
      <link>https://dev.to/mattconn/text-based-level-editing-and-phaser-js-124o</link>
      <guid>https://dev.to/mattconn/text-based-level-editing-and-phaser-js-124o</guid>
      <description>

&lt;p&gt;&lt;em&gt;I originally published this on my website on 4/7/17.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you are familiar with roguelikes (turn-based dungeon crawlers) such as Nethack, then you are no doubt familiar with the idea of a game's elements being displayed entirely as ASCII characters.  &lt;/p&gt;

&lt;p&gt;Here I will explain how I use a similar approach to create the layout of rooms in a game I am working on and how I use Phaser (JS game engine) to render the rooms based on my layouts.&lt;/p&gt;

&lt;p&gt;The following array of strings represents a single room: &lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   [
    //1         12             25
    'ppppppppppppppppppppppppp',//1
    'p------------------------',//2
    'p------------------------',//3
    'pppppppppp---------------',//4
    'p----------------E-------',//5
    'p--------------pppppppppp',//6
    'p------------------------',//7
    'p------E-E---------------',//8
    'pppppppppp---------------',//9
    'p------------------------',//10
    'p----------------E-E-E---',//11
    'p--------------pppppppppp',//12
    'p-----------------------p',//13
    'p-----------------------p',//14
    'p-----------ppppppppppppp',//15
    'p---------ppppppppppppppp',//16
    'p------pppppppppppppppppp',//17
    'ppppppppppppppppppppppppp',//18
    'ppppppppppppppppppppppppp' //19
    ]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;"E" represents an enemy, and "p" represents an immovable block that can be used as a platform or wall. A dash represents empty space, simply because I find it easier to read than whitespace, although I am not exactly counting dashes to find any kind of distance.  &lt;/p&gt;

&lt;p&gt;The commented-out numbers on top and on the right represent columns and rows respectively; I have divided a canvas 800 pixels wide and 600 pixels high into 25-by-19 32-pixel squares.  &lt;/p&gt;

&lt;h3&gt;
  
  
  How and when a room is rendered
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The player collides with the edge of the world (canvas)  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The player's x-position is then changed to the position of the edge opposite of the collision (right edge collision, player moved to far-left of canvas; left edge collision, player moved to far-right of canvas); this gives the appearance of entering a new room  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The room is then cleared, using Phaser's &lt;code&gt;sprite.kill()&lt;/code&gt; method  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;A variable integer is then increased or decreased by 1 depending on the edge of collision (right, +1; left, -1), and this integer is then used as our room's index in our level array.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;So if our current room's index is 0 (the first room in the level array), and the player collides with the right edge of the canvas, our integer increases to 1, and we render the room who's index is 1 (our second room in the level array)
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After getting the room we want by index, we check each string within the room array; each of these strings can be looked at as a row of things that can be rendered onto the canvas, from the top of the canvas to the bottom.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For each row (string) in the room array, we check each character by its index using &lt;code&gt;String.charAt()&lt;/code&gt;.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using a switch statement, the character can be matched to a case; if and after being matched, we will call Phaser's &lt;code&gt;group.create()&lt;/code&gt; method to render the matched sprite or image.  &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So using the room layout above, &lt;code&gt;level1[0][8].charAt(4)&lt;/code&gt; would match a case of &lt;code&gt;p&lt;/code&gt; in our switch statement:&lt;br&gt;
    - 0 is the index of the room (it is the only room shown, but typically there would be multiple rooms), 8 is the index of the row, and the 4th character of the 8th row is a &lt;code&gt;p&lt;/code&gt;.  &lt;/p&gt;

&lt;h3&gt;
  
  
  The room-rendering function (abridged)
&lt;/h3&gt;

&lt;p&gt;(To be called on collision.)&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function renderRoom(room){
    for(var row in room){
        for(var column=0; column &amp;lt;=  room[row].length; column++){
            switch (room[row].charAt(column)){
                case 'p':
                    platform = platforms.create(column*32, row*32, 'platform-image');
                    break;
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This room-rendering function currently only works with one level but should scale to accommodate multiple levels and work similarly if not identically. &lt;/p&gt;

&lt;p&gt;The room system works as detailed in pseudo-code below, with each "column" actually representing a single character in a string:  &lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;level1 [
    room1 [ 
        row1 'column1 column2 column3',
        row2 'column1 column2 column3',
        row3 'column1 column2 column3'
    ],
    room2 [ 
        row1 'column1 column2 column3',
        row2 'column1 column2 column3',
        row3 'column1 column2 column3'
    ]
]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;




</description>
      <category>webdev</category>
      <category>gamedev</category>
    </item>
  </channel>
</rss>
