<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jared Mills on Medium]]></title>
        <description><![CDATA[Stories by Jared Mills on Medium]]></description>
        <link>https://medium.com/@jaredianmills?source=rss-f7023642fb78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PI7lnZM5_35c4C9Jslk5og.jpeg</url>
            <title>Stories by Jared Mills on Medium</title>
            <link>https://medium.com/@jaredianmills?source=rss-f7023642fb78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:00:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaredianmills/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simple drag and drop for React projects with react-sortable-hoc]]></title>
            <link>https://medium.com/jared-mills/simple-drag-and-drop-for-react-projects-with-react-sortable-hoc-5364295e6c33?source=rss-f7023642fb78------2</link>
            <guid isPermaLink="false">https://medium.com/p/5364295e6c33</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[drag-and-drop]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jared Mills]]></dc:creator>
            <pubDate>Wed, 26 Sep 2018 15:26:47 GMT</pubDate>
            <atom:updated>2018-09-26T15:26:47.104Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve always enjoyed drag and drop functionality on web pages. I think it gives a fun level of interactivity that enhances the user experience. In my journey to learn web development, while not a major focus of mine, I wanted to spend a few hours to learn some basic drag and drop functionality in React.</p><p>A fellow student of mine at <a href="https://flatironschool.com/">Flatiron School</a> suggested that I check out <a href="https://github.com/clauderic/react-sortable-hoc">react-sortable-hoc</a> as an easy way to dip my toes into the subject. This library provides two <a href="https://reactjs.org/docs/higher-order-components.html">higher order React components</a>, SortableContainer and SortableElement that, along with a few functions, allow for easy drag and drop and sorting functionality. While a bit limited in its functionality, react-sortable-hoc served as a good introduction to drag and drop and I was able to integrate it into one of my projects at Flatiron School. For this blog post, I’ll walk through a very simple implementation of its functionalities.</p><p>In a React project directory, run the following command in your terminal to install the library: npm install react-sortable-hoc --save</p><p>After that installs, you’ll have access to react-sortable-hoc’s functions and higher order components. For this simple demo, in the App component in my React project, I added an images property to App’s state and set it to an array containing four image URLs that I would use for dragging and dropping.</p><p>App renders a component that I called ImgContainer that receives the images array from App’s state as props, as well as a reference to a function called onSortEnd. onSortEnd takes in as an argument an object with two keys, oldIndex and newIndex. These keys refer to an image’s index before the sorting event started, and the index of the position in which the image was dropped.</p><p>This function gets called, you guessed it, at the end of the drag and drop event. It called this.setState and sets the images property of App’s state equal to the result of a call to one of react-sortable-hoc’s built in functions, called arrayMove.</p><p>arrayMove takes in three argument: the current state of the elements being sorted, the old index, and the new index. It then handles the re-ordering of the images for you so that, when the drag and drop event ends, the elements being sorted remain in the order that you left them in.</p><p>I’ll get into how the ImgContainer component mentioned above works shortly, but for now, here’s the code for App:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJY-QkfQ9RQAI0K3A_s75A.png" /><figcaption>Code for the App component</figcaption></figure><p>Here is where react-sortable-hoc’s higher order component come into play. The first of these is called SortableContainer and, as its name implies, it is the container element for the sortable elements, or the context for the draggable and droppable components.</p><p>The ImgContainer component that is rendered in App is just a const set to the value of SortableContainer, which maps over the images array passed down as props and for each image in the array, renders a component that I called SortableImageContainer. This receives as props the image as well as the index of the image (the second argument of JavaScript’s map function. The index is what will be used in the onSortEnd function to reset the order of the images.</p><p>Here’s the code for the ImgContainer component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ih0GXvOU9EhKbBr_tsihw.png" /><figcaption>ImgContainer component code</figcaption></figure><p>SortableImageContainer is a simple component. It is just a constant set to the value of react-sortable-hoc’s SortableElement component, which I’m using just to render an Image component, which will be the image itself.</p><p>A brief note about my reasoning here: react-sortable-hoc’s SortableElement and SortableContainer components are functional, meaning they do not hold state (at least not to the best of my knowledge). For the sortable element or sortable container to hold state, SortableElement and/or SortableContainer should just render another class component that can hold state. This way, SortableElement and SortableContainer just become wrappers for your other components, giving them the ability to be dragged, dropped, and sorted, and letting your components do their own thing.</p><p>Here’s the code for my SortableImageContainer component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jwbaxqhIdHLv16caa852g.png" /></figure><p>Just to test out handling changes in state to components rendered by react-sortable-hoc’s components, I gave the Image components a red border set to hidden that, onMouseOver calls this.setState to display the border, and onMouseOut calls this.setState to hide the border again. Otherwise, it just renders the image, which can now be dragged, dropped and sorted, because it’s wrapped in react-sortable-hoc’s higher order components.</p><p>Here’s the code for the Image component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMvEoAdol1KurYEQ58MfGA.png" /></figure><p>And here’s the example in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Y5NnV8XJGBPtKPhTugWRlg.gif" /></figure><p>And that’s it! Pretty simple and quick to implement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5364295e6c33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jared-mills/simple-drag-and-drop-for-react-projects-with-react-sortable-hoc-5364295e6c33">Simple drag and drop for React projects with react-sortable-hoc</a> was originally published in <a href="https://medium.com/jared-mills">Jared Mills</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type safe JavaScript using TypeScript]]></title>
            <link>https://medium.com/@jaredianmills/type-safe-javascript-using-typescript-3181070c8183?source=rss-f7023642fb78------2</link>
            <guid isPermaLink="false">https://medium.com/p/3181070c8183</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jared Mills]]></dc:creator>
            <pubDate>Thu, 06 Sep 2018 02:32:57 GMT</pubDate>
            <atom:updated>2018-09-06T02:32:57.822Z</atom:updated>
            <content:encoded><![CDATA[<p>One of my developer friends recently asked me if I had ever worked with a type safe language. As someone relatively new to coding, I’ve thus far only leaned Ruby and JavaScript. My answer was, more or less, “what is type safety?” Obviously, the answer was no and it was time to do a bit of Googling.</p><p>After some quick searching, I learned that type safety is a feature of certain programming languages, such as Java and C#, that prevents type errors. Type errors are, according to <a href="https://en.wikipedia.org/wiki/Type_safety">Wikipedia</a>, “erroneous or undesirable program behaviour caused by a discrepancy between differing <a href="https://en.wikipedia.org/wiki/Data_type">data types</a> for the program’s constants, variables, and methods (functions).”</p><p>What this means is that type safe languages prevent data types from being changed once they have been declared. Variables, functions, etc must declare their data types at the time of definition. For example, if you have a variable named “person” that, upon declaration, you decide is going to be a string, that variable cannot ever then be assigned to the value of an integer, float, array, etc. It will always have to be a string, or the program won’t even compile. This is considered to be very useful in preventing bugs at runtime.</p><p>JavaScript, obviously, is not a type safe language. Take the code below as an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNNw5TL2FxiA_OMzsXSmyg.png" /><figcaption>JavaScript is definitely not type safe</figcaption></figure><p>Here, I am assigning a variable to the value of a string and then re-assigning it to the value of a number, array, and boolean and JavaScript just rolls with it.</p><p>Many developers prefer type safety because their programs simply won’t compile if there is an error with a data type. This helps prevent buggy code from making its way into production. With a non-type safe language like JavaScript, however, how can we prevent these types of bugs?</p><p>Enter <a href="https://www.typescriptlang.org/">TypeScript</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_Idj5hJfRKfK1KQoWwM8g.png" /></figure><p>TypeScript is an open-source superset of JavaScript, developed by Microsoft, that enforces type safety and compiles down to regular old JavaScript.</p><p>Getting started with TypeScript is simple and easy. The documentation even has a <a href="https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html">five-minute tutorial</a> to get you started. First, install TypeScript with the following command in terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*jzqUMcxheQVdmry-_FSv8A.png" /></figure><p>Then, to get going, create a new file with a .ts extension. Write some TypeScript code (make sure it’s type safe) and run the following command in terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*XhskCF_MdhFgVKlXUrSqeQ.png" /></figure><p>Running this command will create a new file of the same name with a .js file extension, allowing you to use that file as a source for a script tag in your HTML file.</p><h4>Vanilla JavaScript vs. TypeScript</h4><p>In vanilla JavaScript, the following code would be perfectly valid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*0fjwVYyqT00XXzfvmeE5KQ.png" /></figure><p>This works, but if somewhere down the line, the program is expecting a string and it receives an integer, this will cause an error.</p><p>Let’s take a look at how we could handle this in TypeScript and the error it will throw when the code is not typesafe.</p><p>Here’s an example of working TypeScript code. We’re giving the variable “person” a string type annotation. Type annotations, according to the documentation, “are lightweight ways to record the intended contract of the function or variable.” When the function is called with the variable “person”, which is set to the value of a string, the program will work as expected and the function <strong>greetUser</strong> will return the proper greeting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*cVg8Lv5Lh1VNy6709WlW2w.png" /></figure><p>However, after initially defining the data type of “person” in the <strong>greetUser</strong> function as a string, if we were to later try to call that function with a variable of a different data type, the program will not compile and will throw an error. Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*rIYGutWWulATTtoe07v5Ww.png" /></figure><p>And here’s the error that it will throw:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ss2Vf8UWxsy1Xqz3QqASNQ.png" /></figure><p>Furthermore, if we were to call <strong>greetPerson </strong>with, no arguments, TypeScript will throw another error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-siyltUj9trTLtLU1CkTw.png" /></figure><p>In vanilla JavaScript, inside of the greetUser function, the variable “person” would have been “undefined”, but with TypeScript, it won’t even compile.</p><p>While there are some other examples of what TypeScript can do, this was merely meant to be an introduction and an excuse for this coding newbie to learn a bit more about type safety, a topic that I haven’t really come across yet in my coding journey.</p><h4>Conclusion</h4><p>Most articles that I’ve read about TypeScript suggest that it’s not really worth using unless you’re dealing with a very large codebase. For smaller applications, it’s probably not necessary. But <a href="https://blog.acolyer.org/2017/09/19/to-type-or-not-to-type-quantifying-detectable-bugs-in-javascript/">one analysis</a> that I read suggested that using TypeScript can result in “a 15% reduction in bugs making it all the way through your development pipeline.” Sure, it’s a bit more typing, but if that many bugs can be prevented before they even pop up, especially in an enormous code base, that extra typing just might be worth it.</p><h4>Sources:</h4><p><a href="https://en.wikipedia.org/wiki/Type_safety)">https://en.wikipedia.org/wiki/Type_safety</a></p><p><a href="https://en.wikipedia.org/wiki/TypeScript">https://en.wikipedia.org/wiki/TypeScript</a></p><p><a href="https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html">Documentation - TypeScript for JavaScript Programmers</a></p><p><a href="https://blog.acolyer.org/2017/09/19/to-type-or-not-to-type-quantifying-detectable-bugs-in-javascript/">https://blog.acolyer.org/2017/09/19/to-type-or-not-to-type-quantifying-detectable-bugs-in-javascript/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3181070c8183" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a simple space shooter game for the browser]]></title>
            <link>https://medium.com/jared-mills/creating-a-simple-space-shooter-game-for-the-browser-401f8adde1ad?source=rss-f7023642fb78------2</link>
            <guid isPermaLink="false">https://medium.com/p/401f8adde1ad</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jared Mills]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 03:00:56 GMT</pubDate>
            <atom:updated>2018-08-25T16:26:14.947Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m currently enrolled in <a href="http://flatironschool.com/">Flatiron School’s</a> web development immersive bootcamp. We just started learning JavaScript two weeks ago, and I’ve been very much enjoying DOM manipulation.</p><p>As a fun little weekend project, I decided to have a go at making a simple space-themed shooting game for the browser. It ended up being a lot more work than I had anticipated, but in the end, I was able to successfully make a working game with a scoring mechanism and losing conditions. There are no winning conditions. You just play until you lose.</p><p>I’ll do my best in this post to explain how I got the job done. So without further ado…</p><h3>Starting Simply</h3><p>Inside of a new respository, I created three files: <strong>index.html</strong>, <strong>index.js</strong>, and <strong>style.css</strong>. All of my code went in these three files. Let’s start with the HTML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_h7TmicpkusmTa_FfkiOw.png" /><figcaption>Blank HTML canvas with links to the CSS style sheet and JavaScript file.</figcaption></figure><p>I started by just adding the links to the style sheet and JavaScript file in an otherwise empty HTML file. I then created a div with an ID of “main-play-area” and chose to make the main area a 400x400 pixel square, which I accomplished with CSS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*E4rwKiqhcy5YHkNRHsuK4A.png" /><figcaption>The main-play-area div</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*50fpHkF5IejIf34vPAELRA.png" /><figcaption>The CSS styling</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qGSknIt6A5KOTmSmWRqupQ.png" /><figcaption>The main play area in the browser</figcaption></figure><p>I decided that the enemies would appear from the right and move towards the player’s ship, which would occupy the left side of the screen. So I made another div for the player’s spaceship, initially just a white rectangle. I gave the div an id of “player-controlled-shooter”, gave it width and height properties, and a relative position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*8rpOizIQTFRm6-F6W7BmpA.png" /><figcaption>HTML</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*LT6_XjRBG9R_Mg3b9xLPSw.png" /><figcaption>CSS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*raDj8VxhYCpqEES61uPMHw.png" /><figcaption>The white rectangle is the original version of the space ship.</figcaption></figure><p>That looks ugly, though. I wanted to find some images to liven it up. I found a site called <a href="https://www.kisspng.com/">KissPNG</a>. They have millions of PNG images with transparent backgrounds that are perfect for exercises such as this. I grabbed a space ship image, a laser image, a few monster images, and an explosion images while I was there. Then I did a quick Google search for a space background image for the main play area. I then added all of these images to an <strong>images</strong> folder in my project folder.</p><p>Changing the background was as simple as removing the <strong>background-color</strong> property from the main play area’s CSS styling and adding a <strong>background-image</strong> property with a URL pointing to the image’s relative path in my respository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*K6L5QtfNxHIhkzaDQHIChw.png" /><figcaption>Adding a background image in CSS</figcaption></figure><p>For the space ship, I decided to just replace the div element with an img element in the HTML file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwlyiF8j1sviNNbXvGpYZw.png" /></figure><p>I then removed the white background from the image in my CSS file and played around with the width and height properties until I was happy with the way it looked. Here’s what I ended up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*zks7FuQxZwqIE7VsJIBCMQ.png" /><figcaption>The ship and the background, much more presentable now.</figcaption></figure><p>Much better. Okay, now let’s make the space ship fly!</p><h3>Making the ship fly</h3><p>First, I grabbed the ship element by writing a constant called <strong>shooter</strong> that pointed to the ship element.</p><p>I decided that, since the enemies would be spawning on the right side and moving towards the ship on the left, and for the sake of simplicity, the ship should only move up and down. So I wrote two functions, <strong>moveUp() </strong>and<strong> moveDown()</strong>,<strong> </strong>in the <strong>index.js</strong> file that I would later call with an event listener. These two functions, when eventually called by the event listener, will parse the integer out of the ship’s <strong>top</strong> style property, and increment or decrement that value, depending on which direction it is moving, by four pixels. Since the ship is 40 pixels in height and the play area is 400 pixels in height, incrementing or decrementing by 4 pixels at a time allows for easily calculating whether or not a call to one of these functions would move the ship out of the main play area. The <strong>moveUp()</strong> function makes sure that the ship’s top property does not go below 0px, and the <strong>moveDown()</strong> function makes sure that it the ship’s top property does not go above 360px.</p><p>The JavaScript code so far looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQ75djmsHg5PewgEyW9HqA.png" /><figcaption>JavaScript moveUp() and moveDown() functions</figcaption></figure><p>A brief note on lines 4 and 15 in the code above: I used the <strong>window.getComputedStyle</strong>… function chaining because calling shooter.style.top returned an empty string. I’m not 100% sure why, but it seemed that I could only <em>set</em> a style property with the element.style function. To actually get that value in the first place, I had to use the code in lines 4 and 15 above. <a href="https://zellwk.com/blog/css-values-in-js/">Here’s a blog post about it</a>.</p><p>Next, I wrote a function called <strong>letShipFly() </strong>that takes in an argument of an event. It calls on the <strong>event.key</strong> property of the <strong>“keydown”</strong> event, determines if the key is either <strong>ArrowUp</strong>,<strong> ArrowDown</strong>, or<strong> “ ” </strong>(which is the Spacebar). If they key is arrowUp, the function calls the MoveUp() function, and if the key is arrowDown, it calls the MoveDown() function. The Spacebar calls a function named <strong>fireLaser()</strong>, which I’ll define shortly. Before each of those functions are called, <strong>event.PreventDefault() </strong>is called, so that the browser page doesn’t try to scroll up or down.</p><p>Finally, I added an event listener on the window, listening for a keydown event and passing the event listener a reference to the <strong>letShipFly </strong>function. Here’s the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*wksZQMp9iBmqMpqJjnF9IQ.png" /></figure><p>And here’s the ship in motion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*QjqKuR5Vz2-nQyGPgq-YvQ.gif" /><figcaption>Liftoff!</figcaption></figure><p>Yes, the movement is a bit janky, and I probably should have used <strong>requestAnimationFrame()</strong>, but that’s a bit more complicated and for the purposes of this exercise, I was pretty happy with this movement. So, moving on…</p><h3>Creating and moving the laser</h3><p>Next, I focused on shooting a laser out of the ship. I wanted the laser to come out of the ship’s nose and move forward to the end of the play area. When it reached there, I wanted to remove it from the DOM. I broke this strategy down into three parts and created three functions, <strong>fireLaser()</strong>, <strong>createLaserElement()</strong>, and <strong>moveLaser()</strong>.</p><p><strong>fireLaser() </strong>is called by the <strong>letShipFly()</strong> function passed to the event listener when the spacebar is pressed. <strong>fireLaser()</strong> will then call <strong>createLaserElement()</strong>, which returns a new <strong>img</strong> element. This is saved to a variable, appended to the DOM, and then the <strong>fireLaser()</strong> function calls <strong>moveLaser() </strong>with an argument of the newly created laser. The <strong>moveLaser() </strong>function moves this newly created laser element across the game area horizontally until it reaches the edge of the play area. It is then removed from the DOM.</p><p>Since the ship will not be in a fixed position, <strong>createLaser()</strong> has grab the position of the the ship at Y-axis (since the X-axis is fixed) to set the laser’s initial position. Then it has to offset the Y-axis position by a few pixels in order to make it appear as if it’s being fired from the nose of the ship. I had to fiddle around with this for a bit to get it right.</p><p>I also wanted to add a sound effect whenever the laser was fired. I created folder in the project called “audio” and found a simple sound effect on Youtube. You can download Youtube videos with any number of Firefox add-ons, and then trim them and export just the audio using Quicktime.</p><p>I had never done audio effects in JavaScript, so this was new territory for me. Thankfully, it’s extremely simple. Once the audio clip was saved in my project file, it was just a matter of creating a new Audio object, saving it to a variable, and calling <strong>play()</strong> on the variable. Thanks, <a href="https://stackoverflow.com/questions/9419263/playing-audio-with-javascript">Stack Overflow</a>.</p><p>The syntax is in the image below on lines 56 and 57.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pv5EV78LSRpbctqIVZcOVQ.png" /><figcaption>Creating and moving the laser</figcaption></figure><p>On line 67, each laser is given a class of “laser” to give it some simple CSS styling. Really just sizing. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*hZGTG5io6CMCf6K-TSC58A.png" /></figure><p>The <strong>moveLaser() </strong>function simply moves the laser across the play area 4px at a time at an interval of 10 milliseconds. When it reaches the edge of the play area, it is removed. Again, I should probably be using <strong>requestAnimationFrame() </strong>for smoother animation, but this worked fine for my purposes.</p><p>I’ll revisit this <strong>moveLaser() </strong>function a bit later when I get to actually shooting and destroying the monsters, but for now, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*bEVw0YeMe03jshHqCvxdaQ.gif" /><figcaption>Pew! Pew! Pew!</figcaption></figure><p>Success! I’ll add a video demo at the end of this post so you can hear all of the SFX put together, but for now, let’s keep rolling.</p><h3>Monster Mash</h3><p>There’s only one ship, and all of its lasers are going to look the same, but I wanted to vary the look of the monsters a bit. As mentioned above, I chose a few monster images and saved them in the images folder. I then saved their relative paths as strings in an array called <strong>monsterImgs</strong> in my <strong>index.js</strong> file. The plan was to have the monsters created at a set interval. Each time a new monster would be created, it would have a randomly selected image and a randomly selected Y-axis placement within the boundaries of the game area on the left side. Then I wanted each monster to move menacingly towards the ship.</p><p>Because JavaScript, as far as I know, doesn’t have a built in array method to return a random element from the array like <strong>#sample</strong> in Ruby, I had to select a random monster image from my <strong>monsterImgs </strong>array the ugly way, calling <strong>Math.floor() </strong>(which rounds a float down to the nearest integer) with an argument of the results of<strong> </strong>multiplying <strong>Math.random()</strong> (which selects a random float between 0 and 1) by the length of <strong>monsterImgs </strong>minus 1. This randomly selecting image path would then be set as the monster’s <strong>src</strong> property.</p><p>I essentially used the same <strong>Math.floor() </strong>and<strong> Math.random() </strong>methodology to select a Y-axis starting position for each monster as it was created before appending it to the DOM. Each monster was also given a class of “monster” for some CSS styling. This was all handled in a function called <strong>createMonster()</strong>, which then called another function, <strong>moveMonster()</strong> with the newly created monster element as an argument. <strong>moveMonster() </strong>worked with almost the exact same logic as <strong>moveLaser()</strong>, just in the opposite direction.</p><p>Here’s what all that code looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jHu5e05Kyz8g4hUDhUdGA.png" /><figcaption>Creating and moving a monster</figcaption></figure><p>The monsters were all a little bit dark, though, and really hard to see in the darker areas of the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*N1iQOH5ylzaO925Q8lyiJw.png" /></figure><p>I wanted to add a glow effect, but I don’t know a ton of CSS. Luckily, the internet is just packed to the brim with CSS tutorials. I searched for “CSS glow effect” and found <a href="https://codersblock.com/blog/creating-glow-effects-with-css/">this useful blog post</a>. I followed his instructions for a circular, multi-colored glow effect to create a halo around each monster and, more importantly, make them stand out from the dark background. Here’s the end result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*27KYp4UlUPhi682b6Nmcrg.png" /><figcaption>Glowing monsters are, like, so scary.</figcaption></figure><p>Alright! We have monsters. They move. And they glow. This is starting to get cool.</p><h3>Shooting monsters with the laser</h3><p>This was the hardest part of this entire project. Since the monsters were constantly moving and the lasers were constantly moving, I had to detect if, at any given time, a particular laser was occupying the same space as a particular monster, and if it was, remove that particular monster from the DOM.</p><p>It took a lot of fiddling around, and I ultimately think that the hit-box I created for the monsters is just a little bit off, but I was able to get it to run to a degree that I thought was acceptable for this just-for-fun project. Here was my thought process:</p><p>If a laser’s left style <em>plus</em> the length of a laser is greater than or equal to the left style of a monster(that is, if they are in the same X-axis range), then we need to check if the laser is within the the same Y-axis range as the monster. If it is, the monster gets destroyed.</p><p>I chose to express this in code as a function called <strong>checkLaserCollision()</strong>, which has a nested <strong>if</strong> statement and returns a boolean. <em>If</em> a laser is in the same X-axis (horizontal) range as a monster, we should then check to see if the laser is in the same Y-axis (vertical) range. If both of those cases are true, then that function should return true. Otherwise, it should return false.</p><p>In other words, if <strong>checkLaserCollision() </strong>returns true, the monster has been hit by a laser and it should be destroyed. Elsewhere, I can write a function that handles the logic for actually destroying the monster.</p><p>First, let’s take a look at <strong>checkLaserCollision()</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ic7vfcv5YEsLvBDoRBwlFw.png" /></figure><p>It takes in an argument of a laser and a monster, creates variables that get the X-axis and Y-axis positions of each element and, as discussed above, checks to see if they have collided. This ended up with the hit box for the monster being a little but wonky, but it worked for the most part when I finally implemented it. (A note about line 110, when the laser’s left position reaches 340px, it is removed from the DOM and we don’t have to worry about it).</p><p>This brought me to a new problem. At any given moment, there can be many lasers and many monsters in the play area. How do I make sure that the game is always checking every laser and every monster for collision?</p><p>After some consideration, I decided to give this responsibility to each individual laser. The laser should check for collision each time it moves, so I modified my <strong>moveLaser()</strong> function to handle this logic. Here was my thought process:</p><p>Every time a laser moved forward, I needed to find all of the monsters currently within the play area. Within the <strong>moveLaser() </strong>function, I created a variable called <strong>monsters</strong> and assigned to it the results of calling <strong>document.querySelectorAll(“.monster”)</strong>. This returns a NodeList of all currently existing elements with the class of “monster”, i.e. all of the monster elements currently in the play area. NodeLists can be iterated over with forEach, map, filter, etc. For my purposes, forEach works perfectly.</p><p>The next step was to, every time the laser moved, grab a new collection of the currently existing monsters, iterate through that collection, and, for each monster, determine if <strong>checkCollision() </strong>returned true. If it returned true, the monster should be destroyed. Here’s how I added this logic to the <strong>moveLaser()</strong> function, starting at line 76:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HL-Q_oEO7ccwpZQHd0IIQ.png" /><figcaption>Code for destroying the monster, lines 76–87</figcaption></figure><p>When the monster is struck by the laser, the function first cues up and plays an explosion sound effect. Then, it changes the monster’s img src to an image of an explosion. The class “monster” is removed from the monster, and the class “dead-monster” is added. This removes the glow effect created in the CSS .monster class, but keeps the size styling. I also later used the “dead monster” class to to check for an end-game condition, but we’ll get to that in a little bit.</p><p>Finally, I wanted the explosion to fade out of view. To accomplish this, I created a new class called “monster-transition” and, revisiting my <strong>createMonster()</strong> function, added that class to each monster as it was created.</p><p>The “monster-transition” class sets the monster’s opacity to full (a value of 1), and then sets an opacity ease-out transition. The “dead-monster” class sets the opacity of the monster to 0, so when that class is added to the monster, it fades out. Here’s what the CSS for that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*WijpKzLWwDiYpGg5hiTiGA.png" /><figcaption>CSS for all monster classes</figcaption></figure><p>And here is what the explosion effect looks like in the game:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*5NQU-Z7kxtJlt-_2xtFz4A.gif" /><figcaption>BOOM!</figcaption></figure><p>The game was really starting to come together at this point. The only things I had left to add were a score tracker, a start button to begin the flow of the game, and a losing condition.</p><h3>Starting the Game</h3><p>Let’s start with the start button.</p><p>I added an H1 element with the text “START” as well as some brief instructional text above it. Here’s the HTML:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHhFPGXmv3aniz7nknGTqQ.png" /></figure><p>I set each of these elements to constants by grabbing them by their ID in my <strong>index.js</strong> file. Then, I added a “click” event listener on the start button which, when clicked, will call a function called <strong>playGame()</strong>.</p><p><strong>playGame() </strong>sets the start button and instructions displays to none, so they disappear from the play area. I then moved the event listener that controls the ship’s movement into <strong>playGame()</strong>, so that the ship would be static until <strong>playGame()</strong> was called. Then I set a new variable, <strong>justice</strong>, to a new audio track, a song that I wanted to play as background music (<a href="https://www.youtube.com/watch?v=wXp1C6Byd2E">“One Minute to Midnight”</a> by <a href="https://en.wikipedia.org/wiki/Justice_(band)">Justice</a>) and called play on it. Then I set another new variable, <strong>monsterInterval</strong>, that set an interval that calls <strong>createMonster() </strong>every 2100 milliseconds. Why 2100 specifically? It causes the first monster’s appearance to line up with the first drum hit in the Justice track, so the first monster will appear right as the beat kicks in. Just some vestiges of my editing background. Here’s the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_0dB7SSs4ViS_5uwKChjw.png" /></figure><p>Great! Now the ship can fly, the monsters will come at the ship at an interval, and the ship can destroy them with lasers.</p><h3>Score Tracker</h3><p>Next, I quickly set up a score tracker. This was a fairly easy addition. I added an <strong>h2</strong> tag at the bottom of the main play area with a <strong>span</strong> tag around the score number so that I could easily grab the number, parse it into an integer, and increment it by 100 (which was a totally arbitrary choice) each time a monster was shot. Here’s the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CN9DpfC8tUsE6sbd4BH-KQ.png" /><figcaption>HTML for the score counter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RqodHHJBac0D13L6z88fg.png" /><figcaption>Grabbing the number from the with a const</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Fnp_jEaVp-cD05zc2w-qg.png" /><figcaption>Line 93: Incrementing the score counter every time a monster is struck by a laser</figcaption></figure><p>Awesome. Almost done! Now I just had to set a game end condition. After all of the above work, I decided to make this one pretty simple. If the front of a monster reaches an X-axis plane whose value is less than that of the front of the ship, I considered it to have reached Earth, and the game is over.</p><h3>Creating game end conditions and ending the game</h3><p>Since the game would end on a monster’s movement, I had to revisit my <strong>moveMonster()</strong> function. When a monster reaches the horizontal location mentioned above, instead of simply removing it from the DOM as the function did previously, it will now end the game.</p><p>But wait! To get that nice fade out effect after the monster is shot by the ship’s laser, it’s not actually being removed from the DOM when it is shot, so destroyed monsters will eventually reach the front of the ship, even though they’ve been destroyed. However, a dead monster does have something else that can be checked for: the class “dead-monster”! So if the monster reaches the appropriate horizontal location <em>and</em> it doesn’t have the class “dead-monster”, the game should be over.</p><p>Here’s the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYr5RG1w8ChaaLrCbjjMig.png" /><figcaption>The updated moveMonster() function</figcaption></figure><p>This game is really close to being done at this point. It just needs a defined <strong>gameOver()</strong> function to get called above with some logic to end the game.</p><p>The music should stop playing. A game over sound effect should play. The game should stop creating monsters. All of the monsters and lasers should be removed. The ship should no longer be moveable. The player should be alerted that the game is over and be given their final score. Finally, the score should be reset to zero, the ship put back to its starting position, and the instructions and start game button should reappear.</p><p>This is fairly straight-forward. Grab all of the lasers and the monsters currently in the DOM with a <strong>document.querySelectorAll()</strong>, searching for their class names, then iterate through those collections and remove each element.</p><p>There were a few tricky parts to this. I had to make sure that the game over sound effect played fully before the alert popped up on screen, which I did with a <strong>setTimeout()</strong>, fiddling with the time delay a bit until I got it right.</p><p>Then, because I wanted to access the variables for both the song and the interval that creates the monsters so that I could stop playing the music and clear the monster creation interval, I had to declare those variables in the global scope, and change their declaration and assignment to just assignments in the <strong>playGame()</strong> function.</p><p>Here’s the variable assignments at the top of the <strong>index.js</strong> file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*rA0B5F7YtJ8E-SgIztsvIQ.png" /></figure><p>And here’s the code for gameOver():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_VQiZ-Y699NPTfOzLCR7g.png" /><figcaption>The gameOver() function</figcaption></figure><p>And that’s it! I built a fully-functioning (if a bit clunky) browser game. And it only took this JavaScript newbie the whole weekend!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*BBRul6z8BBdW1QmaQZqo7w.gif" /></figure><h3>Game link, video demo, and GitHub repo link</h3><p>Here’s a link to the deployed game on GitHub pages:</p><p><a href="https://jaredianmills.github.io/Space-Shooter-browser-game/">https://jaredianmills.github.io/Space-Shooter-browser-game/</a></p><p>Here’s a video demo of the game in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FC2Z1RckdnCw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DC2Z1RckdnCw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FC2Z1RckdnCw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4181c9e478ff1ae627562ea02f6d636/href">https://medium.com/media/a4181c9e478ff1ae627562ea02f6d636/href</a></iframe><p>And here’s a link to the repo on GitHub: <a href="https://github.com/jaredianmills/Space-Shooter-browser-game">https://github.com/jaredianmills/Space-Shooter-browser-game</a></p><p>This project was a lot of work and took me a lot longer than I thought it would from the outset, but I had a blast making it, learned a ton about DOM manipulation, and even learned a few CSS tricks. It was well worth the effort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=401f8adde1ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jared-mills/creating-a-simple-space-shooter-game-for-the-browser-401f8adde1ad">Creating a simple space shooter game for the browser</a> was originally published in <a href="https://medium.com/jared-mills">Jared Mills</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking Ruby Enumerables]]></title>
            <link>https://medium.com/jared-mills/benchmarking-ruby-enumerables-f93961aef6ba?source=rss-f7023642fb78------2</link>
            <guid isPermaLink="false">https://medium.com/p/f93961aef6ba</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jared Mills]]></dc:creator>
            <pubDate>Wed, 25 Jul 2018 02:08:47 GMT</pubDate>
            <atom:updated>2018-07-25T12:49:55.392Z</atom:updated>
            <content:encoded><![CDATA[<p>Probably the most wonderful thing about Ruby is the sheer number of built-in methods that is has for manipulating data. This lets developers to choose from a wide range of options as they work, allowing them to write beautiful, expressive code.</p><p>An example of this is Ruby’s <a href="https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-group_by">Enumerable Module</a>, where the documentation lists fifty-one different methods for iterating through collections of data. While some of these are aliases for one another (such as <strong>#map</strong> and <strong>#collect</strong>), there are wealths of functionality and options in this collection of methods. It can occasionally be difficult for a beginner to choose the right one, especially when handling very large collections of data.</p><p>One tool that Ruby has to help you with this in the <a href="https://ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html">Benchmark Module </a>. According to the documentation, the Benchmark Module “provides methods to measure and report the time used to execute Ruby code.”</p><h3>USING RUBY’S BENCHMARK MODULE</h3><p>Using the Ruby Benchmark tool is pretty simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJG4F2ThDmH2-fl2I1pzxg.png" /></figure><p>First, at the top of your file, you must require the Benchmark Module with the “require” keyword. Then, call the Benchmark.bm method and set a block variable. In the case above, I set that to “x”. Next, call the<strong> #report</strong> method on the block variable. <strong>#report</strong> can take an argument of a string, which will display when the benchmark stats are output to the terminal. This is useful when benchmarking more than one block at time.</p><p>Next, the <strong>#report</strong> method takes in a block, which is what will be evaluated and benchmarked. In the simple example above, I used the Benchmark module to test how long it would take for the <strong>#collect </strong>method to iterate through a range of 1 to 100, multiply each number by two, and return a new array of those multiplied numbers. Running the above code produces the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*Rxg0sG-GsoJ9oATNcanTUQ.png" /></figure><p>This output shows us, in seconds (or fractions of seconds, in the above example), how long it took for the user CPU and the system CPU to process the code, the total combined time, and the real elapsed time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*-MNElnzWzfsVQU_TJh7Glw.gif" /></figure><p>So now that we know how to use Ruby’s Benchmark Module, let’s test out some enumerables. And let’s give it some bigger numbers to play with. After all, in the real world, many of our applications will be dealing with large collections of data.</p><p>First of all, as I mentioned above, the <strong>#collect</strong> and <strong>#map </strong>methods are aliases of one another and perform the same functionality. Is there any difference in performance time? Let’s test it out with a range of 1 to 500,000,000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPncAZFuGDVX2T-5VtwBRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*n9F3djO58WYAX1cmjM9d_A.png" /></figure><p>The difference is negligible. Great. We know that the docs aren’t lying to us. Moving on…</p><p>Next, let’s test a lower-level iterator,<strong> #each</strong> against a higher-level iterator, <strong>#map</strong>. The <strong>#map</strong> method, of course, will return a new array with each element by the block to which it was passed. The <strong>#each</strong> method will return the original array, so in order to actually return those manipulated values, we’ll have to shovel each of them onto a separate array after they have been manipulated by the block. I wrote a few methods that should return the same results using these different iterators. And just for kicks, let’s kick that range up to a billion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*trCKFxux6LB-ef2noW_sOA.png" /></figure><p>Give it a spin and…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*1DrOCfaTp-huO-ezVpbTdg.png" /></figure><p>In real time that 5.4 second difference might not seem like a huge number, but that’s nearly 9% extra time processing when using the <strong>#each</strong> iterator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*ZPRJbbfdVB8ELNEMyozrhw.gif" /></figure><p>Let’s do one more, the <strong>#partition</strong> enumerable. But before we do that, a brief side note.</p><h3>SIDE NOTE</h3><p>I am very much a beginner when it comes to programming. I’m currently attending Flatiron School’s Web Development immersive bootcamp in NYC. Before I started the program, I asked a few developer friends for advice, and they all said the same thing: <em>read the documentation</em>. Read the docs for any language or framework that you wish to master. Read them front to back.</p><p>I’ll admit that I have not always read every word of every page of documentation for every language and framework that I have used thus far (dev bootcamp leaves you with little time to spare), but I have made an effort, and I truly and strongly believe that the advice my friends gave me was very valuable, and has come in handy in countless situations already, and I’m only a month into the program.</p><p>I have rarely seen the <strong>#partition</strong> enumerable in use in the wild. I found it by just reading the docs. If you’re unfamiliar with it, I think its value will become apparent:</p><p>The <strong>#partition</strong> method iterates through an array, yields each element to a block, and returns an array containing two nested arrays. The first nested array, is a collection of all of the elements from the original array for which the block evaluated as true. The second nested array contains all of the elements from the original array for which the block evaluated as false. Its return value is almost like running the <strong>#select</strong> method twice on the same collection of data. Or using the <strong>#each</strong> method and shoveling each item onto the 0th or 1st (depending on the block evaluation) index of an outside array. That second option sounds gross, but probably faster than iterating through a collection twice with <strong>#select</strong>. So let’s try it.</p><h3>BACK TO BENCHMARKING</h3><p>We’re going to test that ugly <strong>#each</strong> method I mentioned above against the much more elegant <strong>#partition</strong> method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEjjIp-EMX6zefUg8J8_XA.png" /><figcaption>How gross is that <strong>#use_each</strong> method?</figcaption></figure><p>Run the code and…</p><p>(This took a few minutes in real time)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ffzJD-RgqhvwrBm7L4joUw.gif" /></figure><p>…</p><p>…</p><p>…</p><p>Finally! Results!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*bqmw7BjG4ZSznikjmUisLg.png" /></figure><p>The <strong>#partition</strong> method only took 68 seconds, but <strong>#each </strong>took 84.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*L9ZJLqYibaFraBuqP_Seuw.gif" /></figure><p>To return the same results, the <strong>#partition</strong> method is almost 20% faster than the <strong>#each</strong> method. That’s pretty awesome, and speaks to the power of Ruby’s higher-level iterators.</p><p>There you go. If you’ve never used Ruby’s benchmarking tool, I hope that this has served as a good introduction and taught you how to use this valuable tool to test your code for speed. Also, don’t use <strong>#each</strong> unless you really need to. There is often a better option.</p><h4>SOURCES:</h4><p><a href="https://ruby-doc.org/core-2.2.3/Enumerable.html">https://ruby-doc.org/core-2.2.3/Enumerable.html</a></p><p><a href="https://ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html">https://ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html</a></p><p><a href="https://en.wikipedia.org/wiki/Benchmark_(computing)">https://en.wikipedia.org/wiki/Benchmark_(computing)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f93961aef6ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jared-mills/benchmarking-ruby-enumerables-f93961aef6ba">Benchmarking Ruby Enumerables</a> was originally published in <a href="https://medium.com/jared-mills">Jared Mills</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>