<?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 Nicolai Andersen on Medium]]></title>
        <description><![CDATA[Stories by Nicolai Andersen on Medium]]></description>
        <link>https://medium.com/@niiicolai?source=rss-188a6546660a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Nicolai Andersen on Medium</title>
            <link>https://medium.com/@niiicolai?source=rss-188a6546660a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:14:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@niiicolai/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[Deploy and Automate MySQL Server on Ubuntu Using Docker and GitHub Actions]]></title>
            <link>https://medium.com/better-programming/how-to-deploy-and-automate-mysql-server-on-ubuntu-using-docker-and-github-actions-b7cda5075eaf?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7cda5075eaf</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 03:19:40 GMT</pubDate>
            <atom:updated>2023-04-07T18:01:18.923Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn to streamline your database deployment process and ensure consistency with containerization and CI/CD workflows</h4><figure><img alt="Photo by panumas nikhomkhai: https://www.pexels.com/da-dk/foto/tilt-shift-database-taet-pa-serverpanel-1148820/" src="https://cdn-images-1.medium.com/max/1024/1*ei6vnOcvX73EByRduzTJlQ.jpeg" /><figcaption>Photo by panumas nikhomkhai: <a href="https://www.pexels.com/da-dk/foto/tilt-shift-database-taet-pa-serverpanel-1148820/">https://www.pexels.com/da-dk/foto/tilt-shift-database-taet-pa-serverpanel-1148820/</a></figcaption></figure><p>This guide will teach you how to create a custom Docker image that contains a MySQL server configured to your specifications. You’ll then learn how to use GitHub Actions to automate the deployment of your MySQL server image on an Ubuntu server, streamlining the deployment process and ensuring consistency across environments. By following this guide, you’ll be able to easily create and manage MySQL servers using Docker and GitHub Actions.</p><h3>Prerequisites</h3><p>Before you begin, you will need the following:</p><ul><li>A GitHub account. If you don’t have one yet, you can sign up for free at <a href="https://github.com/">https://github.com/</a>.</li><li>A code editor of your choice. I recommend using Visual Studio Code, but you can use any editor that you’re comfortable with.</li><li>Basic knowledge of Git. You should know how to clone a repository, commit changes, and push them to GitHub. If you’re new to Git, you can learn more from the <a href="https://git-scm.com/doc">official Git documentation</a>.</li><li>An Ubuntu server 22.04 with Docker installed.</li></ul><h3>Step 1: Set up your Repository</h3><p>To get started, create a new repository on GitHub with an appropriate name (see the image below). Then, create an empty local directory on your computer and connect it to the remote origin of the repository.</p><figure><img alt="Screenshot: Creating a new repository on GitHub. To create a new repository on GitHub, select the “+” symbol and click “New repository”." src="https://cdn-images-1.medium.com/max/286/1*HfPdHHGI9mXEdTCaw3RFjg.png" /><figcaption>Screenshot: Creating a new repository on GitHub. To create a new repository on GitHub, select the “+” symbol and click “New repository”.</figcaption></figure><h3>Step 2: Configure GitHub Actions</h3><p>We’ll be using GitHub Actions to automate the building of the Docker image and copying it to the server. Since we use GitHub Actions to build the Docker image, you don’t need to install and set up Docker on your local system. The build process will be automatically triggered whenever someone pushes code to the main branch.</p><h4>The Workflow File</h4><p>To get started, create the necessary directories for GitHub Actions. This includes a new hidden directory named “.github” with a subdirectory named “workflows” inside it. Next, add a YAML file named “deploy” (or something similar) to the “workflows” directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*6b10LHct5dbXMFhaUiuAPA.png" /><figcaption>Screenshot: The directory structure and the workflow file.</figcaption></figure><p>Open the .github/workflows/deploy.yaml file in your code editor and add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e69888f6e3532d75b9aa92ad76c0495b/href">https://medium.com/media/e69888f6e3532d75b9aa92ad76c0495b/href</a></iframe><p>name on line 1 simply specifies the name of the workflow, which in this case is &quot;Build and Deploy Docker Image&quot;.</p><p>On line 3, the on keyword specifies the events that trigger the workflow to run. In this case, we&#39;re using the push event, which triggers the workflow to run whenever code is pushed to the main branch.</p><p>The env section on line 7 specifies the environment variables used to set up the database, with ${{ secrets.DB }}, ${{ secrets.DB_USER }}, and ${{ secrets.DB_PASSWORD }} being used to access the database credentials stored as encrypted secrets.</p><p>Let’s now add the job that will build and deploy the Docker image. Paste the following code at the bottom of your workflow file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7197d6bc819ab482cea751666d8df995/href">https://medium.com/media/7197d6bc819ab482cea751666d8df995/href</a></iframe><p>On line 1, the jobs keyword specifies the list of jobs to be executed when the workflow is triggered. In this particular workflow file, the deploy keyword refers to the only job that needs to be executed.</p><p>On line 3, runs-on specifies the operating system environment in which the job will be executed, and in this case, it is Ubuntu 22.04.</p><p>The first step of the deploy job on lines 6–7 fetches the source code of the repository using the “actions/checkout” action. The second step on lines 9–16 builds the Docker image using the Dockerfile and passes three database arguments, which are defined as GitHub secrets. The built image is then saved with a name fetched from GitHub secrets.</p><p>The following step on lines 17–21 uses the “actions/upload-artifact” action to upload the Docker image as an artifact, which can later be downloaded and sent to the remote server.</p><p>In the subsequent step on lines 23–30, the workflow connects to the remote server using an SSH private key and copies the Docker image tar file to a directory located at root/containers. It’s essential to make sure that this directory exists on your Ubuntu server before running this workflow.</p><p>In the final step on lines 32–43, the workflow connects to the remote server using SSH and executes the following Docker commands:</p><ul><li>docker stop &lt;container-name&gt; — stops a running container with the specified name.</li><li>docker rm &lt;container-name&gt; — removes a container with the specified name.</li><li>docker load &lt; “/path/to/image.tar” — loads a Docker image at the specified path.</li><li>docker run -d --name &lt;container-name&gt; -p 3306:3306 -v mysql:/var/lib/mysql &lt;image-name&gt; — starts the Docker image with a specified name, port mapping, and external volume.</li><li>exit — closes the SSH connection.</li></ul><p>Note: The external volume is used to ensure that the data stored by the MySQL server remain persistent between redeployments of the Docker image. This is necessary because the Docker image is reinstalled every time a new modification is deployed by the workflow. To see the details of the volume, such as the location of its directory, you can use the command docker volume inspect mysql.</p><h4>Adding Secrets</h4><p>To add the secrets used by the workflow file, open the repository’s settings page, locate “Secrets and variables” in the menu, and click on “Actions”.</p><figure><img alt="Screenshot: Demonstrating the location where GitHub Actions secrets can be set up." src="https://cdn-images-1.medium.com/max/950/1*9Z7UVFta3Oh7w_YZlEAAMw.png" /><figcaption>Screenshot: Demonstrating the location where GitHub Actions secrets can be set up.</figcaption></figure><p>Next, add the following secrets:</p><p>SSH_HOST — This should specify the IP address or domain name of the remote server, for example, 192.168.1.2. You can usually find the public IP address of your server by logging into the service where you created the server.</p><p>SSH_USER — The Ubuntu user which connects to the server (for example, root).</p><p>SSH_PRIVATE_KEY — A private key which is created on the Ubuntu server.</p><p>To create a new SSH key on the Ubuntu server:</p><ol><li>Execute ssh-keygen -t rsa to create a new SSH key. This will generate a new private key and a corresponding public key.</li><li>Append the public key to the authorized_keys file by running cat ~/.ssh/id_rsa.pub &gt;&gt; ~/.ssh/authorized_keys.</li><li>Output the private key by executing cat ~/.ssh/id_rsa, and copy the output into the value field for SSH_PRIVATE_KEY in GitHub Actions secrets.</li></ol><p>IMAGE_NAME — The name of the Docker image (for example, mysql_server).</p><p>DB — The name of the database created upon initialization.</p><p>DB_USER — The name of the database user who has access to the database.</p><p>DB_PASSWORD — The password of the database user.</p><p>Great! We’ve completed the CI/CD part. In the next section, we will focus on creating the Dockerfile that is used to generate the Docker image.</p><h3>Step 3: Set up the Dockerfile</h3><p>Add a new file at the root of the repository called Dockerfile, and add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bbc17460f4eb91f1eb18d864f1ef1a1/href">https://medium.com/media/3bbc17460f4eb91f1eb18d864f1ef1a1/href</a></iframe><p>At line 2, we define the base operating system environment in which the MySQL server will be running.</p><p>Lines 5–7 update the package list of the Ubuntu package manager and install MySQL using the apt-get package manager.</p><p>Line 10 changes the ownership of the MySQL data directory to the mysql user and group. This is necessary because the MySQL server runs under the mysql user account, and it needs to have read and write access to this directory to store and retrieve data.</p><p>Line 13 specifies the replacement of the default MySQL configuration file with a custom configuration file named my.cnf. The my.cnf file contains the configuration parameters for the MySQL server, such as the bind-address which can be used to specify allowed incoming connections.</p><p>Lines 16–18 specify the MySQL database arguments passed when building the image using the workflow file.</p><p>Lines 21–23 execute SQL statements to create a database, a database user, and to set up the necessary privileges.</p><p>Line 26 in the Dockerfile uses the EXPOSE command to inform Docker that the container will listen on port 3306.</p><p>Line 29 changes the user to mysql, allowing the server to run with minimal privileges. Finally, line 32 starts the MySQL server, which makes the MySQL database available for remote connections via port 3306.</p><p>That’s it! The Docker file is now ready. We just need to add the custom MySQL configuration file. To do so, add a new file at the root called my.cnf and insert the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42c8997b3fdc8ee86eecd43b424d2f54/href">https://medium.com/media/42c8997b3fdc8ee86eecd43b424d2f54/href</a></iframe><p>I won’t cover everything in this configuration file, but I want to highlight that I have configured the bind-address option to accept all incoming connections. This will ensure that you can connect directly from your local computer using software like MySQL Workbench (Note: Remember to also configure your firewall on the remote Ubuntu server to allow connections on port 3306, if you want to connect using Workbench).</p><p>However, keep in mind that this may not be the most secure option for a production environment. In a production environment, you would typically want to restrict incoming connections to a specific IP range or use a VPN.</p><p>Now that all the necessary steps have been completed, it’s time to push the code to the repository. If everything has been set up correctly, the deployment flow will run under the “Actions” tab in your GitHub repository, and it should be completed within a few minutes.</p><p>You can find a complete example of the code at the following repository: <a href="https://github.com/Project-Mainframe/MySQL">https://github.com/Project-Mainframe/MySQL</a>. Feel free to fork the repository and modify the code to suit your needs.</p><p>I hope you found this guide helpful in setting up your own MySQL server. If you have any questions or feedback, feel free to reach out. Good luck with your project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7cda5075eaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-deploy-and-automate-mysql-server-on-ubuntu-using-docker-and-github-actions-b7cda5075eaf">Deploy and Automate MySQL Server on Ubuntu Using Docker and GitHub Actions</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Simple 2D Hunting Game With JavaScript and HTML]]></title>
            <link>https://medium.com/better-programming/create-a-simple-2d-hunting-game-with-javascript-and-html-1cb78e01a69e?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cb78e01a69e</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html-canvas]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 23:34:34 GMT</pubDate>
            <atom:updated>2023-01-31T14:25:27.642Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn to create a simple 2D hunting game for your website 🦆</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*zkJhWO-TR0GURxsHJ--D2Q.gif" /><figcaption>A GIF showing the game created in the article.</figcaption></figure><p>Do you want to learn to create games? Or are you looking for a way to upgrade your website with a fun activity? This article explains how to create a simple 2D hunting game with elements such as animations, particle systems, and collision checks.</p><h3>Motivation</h3><p>Developing 2D games can both be fun and educational, and the possibilities are more or less endless. So, why recreate a simple 2D hunting game? I often spent time thinking about what types of games I should write about, and what I like about this specific game is actually the simplicity of the game’s required features.</p><p>For example, all the game really needs in order to work is an enemy moving across the scene and a check that can be triggered to see if the mouse is above the enemy object. So I think it is a great game for beginners who wants to learn to develop games. Another aspect is that less mechanical complexity gives more time to be creative and implement visual effects, such as the particle system I will introduce later in the article.</p><h3>Introduction</h3><p>The game is a classic hunting game made up of two important objects, a duck, and a weapon. The duck and the cursor have a simple collider defined by a rectangle (see figure 1). When the weapon is shooting, the collision between any active duck and the cursor is checked to see if the weapon hit anything.</p><figure><img alt="Figure 1: The red rectangle represents the objects’ collider." src="https://cdn-images-1.medium.com/max/572/1*z_TgiauVrevksPu0b-ck4A.png" /><figcaption>Figure 1: The red rectangle represents the objects’ collider.</figcaption></figure><p>The game is also designed to spawn particle effects whenever the weapon is shooting to increase the visual feedback of the game. The particle effects include a particle effect showing the area where a bullet was shot, and another showing a bullet was shot from the weapon’s barrel (see figure 2).</p><figure><img alt="Figure 2: The red rectangle outlines the shooting particles, the bullet particles, and the weapon’s image." src="https://cdn-images-1.medium.com/max/563/1*cMfHTZvYLwtnVD0RtjU33A.png" /><figcaption>Figure 2: The red rectangle outlines the shooting particles, the bullet particles, and the weapon’s image.</figcaption></figure><p>The player can progress in the game by increasing a simple numerical score. Each duck gives a 1+ score if they are shot. The game’s difficulty is controlled by adding different speeds to the different ducks and allowing a limited number of ducks to leave the screen on the right side (see figure 3).</p><figure><img alt="Figure 3: Each duck gives a 1+ score, ducks have different movement speeds, and a duck leaving the screen count as a 1+ miss." src="https://cdn-images-1.medium.com/max/589/1*XWLTFpOG_tGn2RozpwFkIA.png" /><figcaption>Figure 3: Each duck gives a 1+ score, ducks have different movement speeds, and a duck leaving the screen count as a 1+ miss.</figcaption></figure><p>The game is made of four images (see figure 4). You can download the images from the following <a href="https://github.com/niiicolai/2d-hunting-game/tree/main/src/images">GitHub Repository</a>. But you can also create your own images if you want the ‘enemy’ to be something else than a duck, or to have another background.</p><figure><img alt="Figure 4: The game’s assets." src="https://cdn-images-1.medium.com/max/338/1*mhsVAI3UYmdom6W1qTwPfA.png" /><figcaption>Figure 4: The game’s assets.</figcaption></figure><h3>A Drawable Object</h3><p>The first class the game include is called Drawable (see figure 5). The purpose of the class is to have an object specifying an object’s two-dimensional position (x, y), width and height (w, h), and fill and stroke colour (fillStyle, strokeStyle).</p><p>It also defines two methods, called drawRect(ctx) and drawImage(ctx, image), designed to either draw the object as a rectangle or as an image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cca564a6dcb02a65339dfd0a07c3783/href">https://medium.com/media/2cca564a6dcb02a65339dfd0a07c3783/href</a></iframe><h3>The Duck Object</h3><p>The duck’s object is created by a class called Enemy (see figure 7). The class depends on the class Drawable described in the last section, a numerical value specifying movement speed (speed), and an array of images (images).</p><p>The enemy class contains five instance methods and two static methods. draw(ctx) is designed to draw an image within the canvas using the drawable object, and the current image of the animation. The current image is specified by a continuously increasing variable called index.</p><figure><img alt="Figure 6: The images used for the duck’s animation." src="https://cdn-images-1.medium.com/max/483/1*V7HPtPBXvL1pWZuwV--Ssg.png" /><figcaption>Figure 6: The images used for the duck’s animation.</figcaption></figure><p>update() can be used to update the object’s animation and movement behaviour. The method calls two other methods called updateAnimation() and updateMovement().</p><p>updateAnimation() is designed to increase the value of the variable index within the range of zero and the image array’s length. updateMovement() simply increases the x position of the object’s drawable by the value of the variable speed.</p><p>overlaps(x, y, w, h) is designed to check if the position and dimensions of another rectangle collide with the object’s drawable.</p><p>The methods create(x, y, w, h, speed, imageSources) and createCollection(x, y, w, h, minSpeed, maxSpeed, imageSources, noOfEnemies) can be used to create either a single enemy instance or an array of enemy instances. The idea of this method is to be able to create an enemy by only specifying the location of the animation’s images and to create a collection with a single method call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3fdf8164e83732009104fa326e92905/href">https://medium.com/media/b3fdf8164e83732009104fa326e92905/href</a></iframe><h3>The Weapon Object</h3><p>The weapon object’s class is called Weapon (see figure 9). The class also depends on the class Drawable as the Enemy class and for the same reasons.</p><p>An object of the class also requires a numerical value specifying the fire rate (firerate), and another value specifying the image used to draw the weapon.</p><figure><img alt="Figure 8: The image used for the game’s weapon." src="https://cdn-images-1.medium.com/max/73/1*6mTqZW4lxItQ__ad_ewoUQ.png" /><figcaption>Figure 8: The image used for the game’s weapon.</figcaption></figure><p>The class have a method called draw(ctx) used to draw the weapon’s image by calling its drawable’s method drawImage(ctx, image).</p><p>Shoot() can be used to check if the weapon is ready to shoot a bullet, and it is, therefore, designed to return a boolean where false means the weapon did not shoot and true means the weapon shot. The method is also designed to ‘deactivate’ the shoot functionality after executing shoot().</p><p>startShootCooldown() and endShootCooldown() is used to control the cooldown functionality of the weapon. startShootCooldown() sets the variable isCooldown to the value true to prevent the shooting method to be executed. startShootCooldown() also executes the method setTimeout to trigger endShootCooldown() when an amount of time equal to the value of the variable firerate has passed.</p><p>Lastly, endShootCooldown() sets the variable isCooldown back to the value false to allow the weapon to shoot again.</p><p>create(x, w, y, h, firerate, imageSource) is a method that can be used to create an instance of a weapon by specifying the parameters of a drawable, the fire rate, and the location of an image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82a7834703636687a2f4ab8bd0646637/href">https://medium.com/media/82a7834703636687a2f4ab8bd0646637/href</a></iframe><h3>Particle Effects</h3><p>The game’s particle effects are defined by three different classes: ParticleSystem; BulletParticleSystem; ShootParticleSystem;</p><p>Both BulletParticleSystem and ShootParticleSystem are subclasses of ParticleSystem (see figure 10). The idea is the class ParticleSystem contains the basic behaviour of a particle system, and subclasses of the method can override the method loop() to move the system’s particles differently.</p><figure><img alt="Figure 10: The UML class diagram shows that both classes BulletParticleSystem and ShootParticleSystem is subclasses of the ParticleSystem class." src="https://cdn-images-1.medium.com/max/576/1*e5WG5VydzlRBLJa5ds2rag.png" /><figcaption>Figure 10: The UML class diagram shows that both classes BulletParticleSystem and ShootParticleSystem are subclasses of the ParticleSystem class.</figcaption></figure><p>The class ParticleSystem depends on an array of drawable objects (drawables), a numerical value specifying play speed (playSpeed), and another numerical value specifying the amount of time the particle should be active after calling its play method (playTime) (see figure 11).</p><p>ParticleSystem have a method called draw(ctx) that can be used to draw the particle system’s drawable objects as rectangles.</p><p>play() can be used to start the particle system. The method sets a variable named isActive to the value true to prevent the play method to be executed again until the particle is done playing.</p><p>The method play() start a loop by calling the method setInterval and caching its return value in a variable called interval so it later can be stopped when the effect is done. The interval continuously executes the class’ method called loop().</p><p>Lastly, to stop the particle system, the method play() calls the method setTimeout to ensure the class’ method end() is executed after an amount of time equal to the value of the variable playTime.</p><p>setPosition(x, y) is used to move the particle system to a new position. This is done by moving the position of the particle system’s drawable objects to the argument’s x and y positions.</p><p>createDrawables(x, y, w, h, noOfDrawables, colors) is a static method that can be used to create an array of drawable objects with a random colour.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72cb867bc1b55dd69a60f96330f28de9/href">https://medium.com/media/72cb867bc1b55dd69a60f96330f28de9/href</a></iframe><h4>Bullet Particle System</h4><p>The class used to display the bullet particle effects is called BulletParticleSystem (see figure 12). The class is designed to move the drawable objects of a particle system outwards in a circle by utilizing sine and cosine.</p><p>The class also contains two static methods called create(x, y, w, h, playSpeed, playTime, noOfDrawables, colors) and createCollection(x, y, w, h, playSpeed, playTime, noOfDrawables, colors, noOfParticles). The idea behind the methods is to be able to create either a single or a collection of BulletParticleSystem instances.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7422e69fa4d0fa1ec53c78e7d29d0ed/href">https://medium.com/media/d7422e69fa4d0fa1ec53c78e7d29d0ed/href</a></iframe><h4>Shoot Particle System</h4><p>The class designed to display the shooting particle effects are called ShootParticleSystem (see figure 13). The class requires two extra parameters to be instantiated, which are called spread and speed.</p><p>spread determines how much the drawable objects of the particle should randomly move on the x-axis, and speed determines the speed the drawable objects should move on the y-axis.</p><p>The loop() method of ShootParticleSystem is designed to move the drawable objects of the particle system upwards, and either left or right by randomly calculated values.</p><p>The class also contains a create(...) and a createCollection(...) method as the other particle system subclass calledBulletParticleSystem. The behaviour of these methods is similar to the other subclass.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e589a358a7103a16dc1ceffc4f39a119/href">https://medium.com/media/e589a358a7103a16dc1ceffc4f39a119/href</a></iframe><h3>The Hunting Game Object</h3><p>The final class included in the game is called HuntingGame. The class is used to connect the general behaviour of the game, for example, it is designed to call draw methods, or utilize the enemy class’ overlaps(x, y, w, h) method.</p><figure><img alt="Figure 14: The game’s background image." src="https://cdn-images-1.medium.com/max/422/1*NrD_9bPrsrRNazG2IN2Kug.png" /><figcaption>Figure 14: The game’s background image.</figcaption></figure><p>The class contains the following attributes: canvas; ctx; enemies; weapon; bulletParticleSystems; shootParticleSystems; frameRate; maxActive; enemyMaxY; maxMisses; bggImage; gameOver; misses; activeEnemies; mouseX; mouseY; mouseW; mouseH; score;</p><p>canvas refers to the canvas used to display the game, and ctx refers to the canvas’ CanvasRenderingContext2D.</p><p>enemies specifies an array of Enemy objects representing all enemies available in the game, and weapon specifies the weapon used to shoot the enemies.</p><p>bulletParticleSystems and shootParticleSystems both refer to arrays of particle systems used to display the game’s particle effects.</p><p>frameRate controls how often the game’s update method should execute.</p><p>maxActive determines the max number of enemies allowed within the scene at the same time, and activeEnemies contains the current instance within the scene. enemyMaxY specifies enemies&#39; maximum y position used to avoid any ducks spawning at the weapon’s y position.</p><p>misses specifies the current number of ducks who left the screen on the right side, and maxMisses determines the number of ducks that should leave the screen before the game ends.</p><p>bggImage specifies the game’s background image, gameOver specifies whether or not the game has ended, and score specifies the player’s current score.</p><p>mouseX and mouseY are used to keep track of the mouse position, and mouseW and mouseH specifies the width and height of the cursor used to check if the cursor collides with a duck.</p><p>The class also contains a couple of methods defining the game’s overall behaviour. initialize() reset the game’s state variables to their initial value and it can be used to reset the game.</p><p>start() can be used to start the game’s continuous behaviour. The method adds two events that bind the methods mousemove() and keydown().</p><p>mousemove() is executed when the cursor moves and it is designed to keep track of the mouse&#39;s x and y position.keydown() executes whenever a key on the keyboard is pressed down, the method is designed to either restart the game if gameOver is equal to the value true or to try shooting with the weapon. If the weapon is able to shoot when keydown() is executed, the method shows the particle effects and checks if an enemy was hit.</p><p>Last, The method start() initiates an interval that executes the method update().</p><p>update() is designed to control the game’s overall behaviour. First, it clears the canvas to make space for the next frame. Then, it draws the background, and the score and misses text, by calling drawBggImage() and drawMissesAndScore().</p><p>Next, update() draws the weapon and checks whether or not the game has ended. If the game has ended, the method displays the text “GAME OVER” by calling drawGameOver(), and if it has not, it executes updateActiveEnemies() to update the active enemies, executes trySpawnEnemy() to spawn new enemies, and check if the game should end with a simple if statement.</p><p>Lastly, update() draws the reticle by using the method drawReticle(), and any active particle effects by calling drawParticles().</p><p>updateActiveEnemies() is designed to both draw and move the enemy objects, but it also removes any objects who have left the screen from the list of active enemies.</p><p>trySpawnEnemy() is designed to only spawn enemies if the length of the active list of enemies is less than the value of maxActive, and if this is the case, it finds all the inactive enemies and spawns one of them at a random position at the left side of the screen.</p><p>hitCheck() is used to check if the cursor overlaps with any of the active enemy objects and if the check evaluates to true, the active enemy is removed from the active list, and the score is increased by one. hitCheck() get the hit position by calling the method getHitPosition().</p><p>showBulletParticle() and showShootParticle() is designed to spawn a particle effect, and finally create(…) is a simple helper method that can be used to create an instance of a hunting game.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9dd8f23f8ec506aeba90aa68e531188/href">https://medium.com/media/c9dd8f23f8ec506aeba90aa68e531188/href</a></iframe><h3>Create a New Game Instance</h3><p>Finally, the game is ready to be instantiated. Create instances of the game’s weapon, enemies, and particles, so they can be passed to the HuntingGame class’ create method, and call the method start() (see figure 16).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/127701e1a7d4f48638a2ad9dd2208e87/href">https://medium.com/media/127701e1a7d4f48638a2ad9dd2208e87/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*jvDvXOK7L-6IKONLsE9l4w.png" /></figure><p>You can find a complete sample of the game in the following <a href="https://github.com/niiicolai/2d-hunting-game">GitHub Repository</a>.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cb78e01a69e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/create-a-simple-2d-hunting-game-with-javascript-and-html-1cb78e01a69e">Create a Simple 2D Hunting Game With JavaScript and HTML</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a 2D Endless Runner Game With JavaScript and HTML]]></title>
            <link>https://medium.com/better-programming/how-to-build-a-2d-endless-runner-game-with-javascript-and-html-11940ab797bf?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/11940ab797bf</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 02:45:14 GMT</pubDate>
            <atom:updated>2023-01-26T05:50:59.748Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn to build a game for your website 🏃</h4><figure><img alt="A GIF showing the game developed in the article." src="https://cdn-images-1.medium.com/max/600/1*jMotDLp0KJ1485UHB3a1wA.gif" /><figcaption>A GIF showing the game developed in the article.</figcaption></figure><p>Have you thought of starting to create games and are looking for a place to begin? Or do you want to learn how to add games to your website? Then, look no further, this article explains how to create a simple 2D endless runner game using an HTML canvas element and JavaScript.</p><h3>Introduction</h3><p>The 2D endless runner game developed in this article is based on a couple of simple concepts.</p><p>The first concept is about the movement of the player and the obstacles. You might think that because the game’s primary feature is running, the player object is both able to run and jump, however, to simulate an endless map, the obstacles are moved instead of the player (see figure 1). This means the player’s only required movement ability is to jump.</p><figure><img alt="Figure 1: Shows the directions the player and obstacles can move." src="https://cdn-images-1.medium.com/max/522/1*kKvbfGAnfv8bZFAeL4FZGA.png" /><figcaption>Figure 1: Shows the directions the player and obstacles can move.</figcaption></figure><p>The second concept is about progression and losing. The player’s score automatically increases by one for every frame execution, and the game ends if the player collides with an obstacle (see figure 2).</p><figure><img alt="Figure 2: Shows the game’s colliders, score, and the idea of the game ending if the player and an obstacle collide." src="https://cdn-images-1.medium.com/max/502/1*9H6hM9005O0PtdkKLbBmXw.png" /><figcaption>Figure 2: Shows the game’s colliders, score, and the idea of the game ending if the player and an obstacle collide.</figcaption></figure><p>The last concept is about the difficulty of the game. To avoid the game just being a monotone experience, the game’s speed, jump power, and gravity are automatically increased over time, and the time between obstacle spawn is random (see figure 3).</p><figure><img alt="Figure 3: Shows the elements used to control the difficulty of the game, such as the idea of increasing speed, jump power, and gravity over time, and how obstacles are spawned with a random time between." src="https://cdn-images-1.medium.com/max/507/1*kUSEJeWksFjzoLHr7YkGCw.png" /><figcaption>Figure 3: Shows the elements used to control the difficulty of the game, such as the idea of increasing speed, jump power, and gravity over time, and how obstacles are spawned with a random time between.</figcaption></figure><p>The development of the game is divided into three different parts. The first part focuses on creating the actual player object, such as implementing animations, and movement.</p><p>The second part focuses on creating the game’s obstacles, such as the trees and rocks. Finally, the last part focuses on building a game manager that connects everything into a complete game.</p><h3>Implementing the Player Object</h3><p>The player object is drawn using four different images to simulate the player’s running animation (see figure 4).</p><p>The player assets can be downloaded from the project’s <a href="https://github.com/niiicolai/2d-runner-game">GitHub repository</a>, but you can also easily create your own character by drawing some similar images where the character is running.</p><figure><img alt="Figure 4: The player’s four running poses." src="https://cdn-images-1.medium.com/max/430/1*kSj1H9Tq_EpCeIHfVka_QA.png" /><figcaption>Figure 4: The player’s four running poses.</figcaption></figure><p>The animation is controlled by implementing a class called animator, which contains the animation’s images, play speed, etc.</p><p>An instance of the animator class is spawned and injected into the player object’s constructor together with instances of the movement class, the point2D class, and the collider class (see figure 5).</p><p>The movement class controls the player’s gravity and jump behaviour, the point2D class specifies the player’s position, and the collider class contains methods to check for collisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*K-8J1ga64JxSnNk_lt8x0A.png" /><figcaption>Figure 5: The classes used to create the player object.</figcaption></figure><h4>Animator Class</h4><p>The animator class contains five attributes. The attributes timer, playSpeed and showTime controls the overall speed of the animation. playSpeed determines how fast the object’s attribute timer should increase, and showTime determines the maximum time each image should be shown.</p><p>The attributes index and images controls the image shown in the animation. The attribute index determines the current image of the animation, and the attribute images determines both the order and the images in the animation.</p><p>The class has four methods. Three instance methods called update(), getImage(), and reset(), and one static method called create().</p><p>The method update() should be called to ensure the animator’s attribute index is increased over time, the method getImage() returns the animation&#39;s current image by using the current value of the index attribute, and the method reset() sets the value of index to zero to ensure the first image of the animation is shown.</p><p>Finally, the static method create() can be used to create an instance of an animator object by passing the location of the animation’s images, instead of HTMLImageELement objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3876fbdac61576e6dff8efdb8c481fb/href">https://medium.com/media/f3876fbdac61576e6dff8efdb8c481fb/href</a></iframe><h4>Point2D Class</h4><p>The point2D class consist of two attributes, x and y , which specifies a position in two-dimensional space (see figure 7). The class also have a method called add(dx, dy) that can be used to increment the values of x and y.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ca1eccc35c99bd813d445142ae5c78e/href">https://medium.com/media/3ca1eccc35c99bd813d445142ae5c78e/href</a></iframe><h4>Movement Class</h4><p>The movement class contains six attributes (see figure 8). The attribute position determines the position of the object in a 2-dimensional space. groundY, and height is used to find the value of y where the object is considered grounded.</p><p>jumpPower and jumpHeight controls the speed and distance the object can jump, and gravity controls how fast the object should return to the ground position after jumps.</p><p>The class has three methods called update(), jump(), and isGrounded(). The method update() implements the jumping and gravity behaviour of the player. It contains four if statements with the following purpose:</p><ol><li>The first if statement checks if the attribute isJumpingis set to true, and if that is the case, the y position of the object is decreased, to move the object up.</li><li>The second if statement checks if the y position of the object is less than groundY minus the height of the player, which is equivalent to the highest point the player can jump. If the check is true, the attribute isJumpingis set to false.</li><li>The third if statement checks if the attribute isJumping is set to false, and if the method isGrounded() returns false. If the condition evaluates to true, the y position of the object is increased, to move it towards the ground.</li><li>The fourth if statement checks if the y position is less than groundY minus the object’s height, and if the condition evaluates to true, the object is moved to the ground position.</li></ol><p>The method jump() sets the attribute isJumping to true, if the object is grounded, to start the jumping behaviour, and last, the method isGrounded() returns true, if the object is at the ground position.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53a2b8cd9da1cf316145d128c02832e6/href">https://medium.com/media/53a2b8cd9da1cf316145d128c02832e6/href</a></iframe><h4>Collider Class</h4><p>The collider class contains three attributes called position, w, and h (see figure 9). The purpose of the attribute position is to specify the location of the collider, and the purpose of the attributes w and h are to specify the width and height of the collider.</p><p>The class also contains two methods called overlaps(other) and overlapsWithOthers(others), which can be used to check for collision between the collider instance and one or several other objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02841ec1faed00715809d17233e16332/href">https://medium.com/media/02841ec1faed00715809d17233e16332/href</a></iframe><h4>Player Class</h4><p>The player class contains four attributes called position, animator, movement, and collider (see figure 10).</p><p>position specifies the player’s location in a two-dimensional space, animator controls the player’s animation, movement controls jumping and gravity, and lastly, collider provides methods to check for collisions.</p><p>The class also have four instances methods and one static method. update() is used to update the player’s movement and animation behaviour. draw(ctx) is used to draw the player by getting images from the animator object.</p><p>jump() can be used to trigger the player’s jump behaviour. overlapsWithOthers(others) can be used to check if the player collides with another object, and the static method create(options, groundY) can be used to create a player instance by passing the required parameters in an object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f27da41a1f38c58a217f448f99675974/href">https://medium.com/media/f27da41a1f38c58a217f448f99675974/href</a></iframe><h3>Implementing Obstacles</h3><p>The next step is to create the game’s obstacles and a spawner that can be used to continuously respawn the obstacles over time.</p><figure><img alt="Figure 11: The two types of obstacles." src="https://cdn-images-1.medium.com/max/154/1*72q07nANLgcSoqp29rgNhQ.gif" /><figcaption>Figure 11: The two types of obstacles.</figcaption></figure><p>The game contains two obstacles, a tree, and a rock (see figure 12). However, you can easily add your own custom obstacles by adding a new class with the attributes: position; w; h;</p><p>It is important that your new class contains these attributes because they are used by the collider class to check for collisions, and the spawner object to move the obstacles. The class must also include a method called draw(ctx) used to draw the obstacle.</p><p>The obstacles are controlled by another class called Spawner. The spawner class controls both the movement and respawning of obstacles.</p><figure><img alt="Figure 12: The classes used to create and spawn obstacles." src="https://cdn-images-1.medium.com/max/783/1*nwiLv0prX-w6WWM4R8iiFA.png" /><figcaption>Figure 12: The classes used to create and spawn obstacles.</figcaption></figure><h4>Tree Class</h4><p>The tree class have six attributes: position; trunkWidth; trunkHeight; crownRadius; w; h; (see figure 13).</p><p>position determines the location of the tree, trunkWidth and trunkHeight determines the dimensions of the tree’s trunk, crownRadius determines the crown’s radius, and lastly, w and h specifies the width and height of the tree’s collider.</p><p>The class also have five instance methods and one static method. calculateWidth() and calculateHeight() are used to calculate width and height based on the tree’s trunk and crown.</p><p>draw(ctx), drawTrunk(ctx), and drawCrown(ctx) are used to draw the tree.</p><p>Finally, create(x, y, trunkWidth, trunkHeight, crownRadius) is a method that can be used to create an instance of a tree without passing a point2D object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5be4405ccb85a492ffb88c1ba279c83/href">https://medium.com/media/a5be4405ccb85a492ffb88c1ba279c83/href</a></iframe><h4>Rock Class</h4><p>The rock class is similar to the tree class with the biggest difference being how the obstacle is drawn (see figure 14).</p><p>position determines the location of the rock. noOfParts determines the number of rectangles used to draw the rock. w and h are used by the collider as with the tree class.</p><p>The class also have two methods called draw(ctx) and create(x, y, w, h, noOfParts). draw(ctx) is used to draw the rock, and create(x, y, w, h, noOfParts) returns an instance of a rock without the need for passing a point2D object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b5660091438da2c0e8b1333c9bcc044/href">https://medium.com/media/5b5660091438da2c0e8b1333c9bcc044/href</a></iframe><h4>Spawner Class</h4><p>With the obstacle class in place, it is time to define the spawner class (see figure 15). The class have nine attributes: obstacles; maxActive; speed; startX; minLength; maxLength; activeObstacles; lastObstacles; nextSpawnLength;</p><p>obstacles is an array with all the instances of the game’s obstacles. maxActive specifies the maximum number of allowed obstacles at the same time. speed determines how fast the obstacles are moving. startX determines the x position where obstacles are respawned.</p><p>minLength and maxLength specifies a range used to calculate a random value of nextSpawnLength , which determines the distance the last spawn obstacle should travel before spawning any new obstacles.</p><p>activeObstacles is an array containing all obstacles currently displayed within the scene, and lastObstacle specifies the last spawned obstacle.</p><p>The class contains six methods: draw(ctx); update(); trySpawn(); spawn(); getInactiveObstacles(); create(options, startX, groundY);</p><p>draw(ctx) is used to draw all active obstacles. update() is used to move active obstacles, remove active obstacles when they leave the scene, and spawn new obstacles.</p><p>trySpawn() can be continuously executed to spawn an obstacle if the following requirements are fulfilled:</p><ul><li>The number of active obstacles must not be greater than the value of the attribute maxActive.</li><li>The last spawned obstacle, if any, should have travelled a distance greater than the value of nextSpawnLength.</li><li>There must be an inactive obstacle that can be spawned to the scene.</li></ul><p>spawn(obstacle) is used to spawn an inactive obstacle to the scene. It also keeps track of the last spawned obstacle and calculates the next spawn length.</p><p>getInactiveObstacles() returns an array of inactive obstacles by finding obstacles currently not within the scene.</p><p>Finally, create(options, startX, groundY) can be used to create a spawner object by passing an object of options specifying obstacle instances and spawn conditions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19866f15ddd81fb3c31372a77a94239f/href">https://medium.com/media/19866f15ddd81fb3c31372a77a94239f/href</a></iframe><h3>Putting the Pieces Together</h3><p>The game only requires two more classes at this point, one called Background controlling the colour of the scene, and another called EndlessRunnerGame controlling the game’s overall behaviour (see figure 16).</p><figure><img alt="Figure 16: The classes connecting everything to a complete game." src="https://cdn-images-1.medium.com/max/1024/1*T5YljExn4m5q65KiP2EYCg.png" /><figcaption>Figure 16: The classes connecting everything to a complete game.</figcaption></figure><h4>Background Class</h4><p>The background class contains five attributes: max; w; h; current; decrease; and two methods: draw(ctx); update(); (see figure 17).</p><p>max determines the maximum intensity of the scene&#39;s colour, w and h determines the width and height of the background drawn within the scene, current specifies the current intensity of the colour, and decrease specifies whether or not the value of current should increase or decrease.</p><p>The method draw(ctx) is used to draw the background colour and update the fill and stroke colour of CanvasRenderingContext2D, and the method update() is used to either increase or decrease the value of current.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97e6efe872daad5381547ac35a48e495/href">https://medium.com/media/97e6efe872daad5381547ac35a48e495/href</a></iframe><h4>EndlessRunnerGame Class</h4><p>Finally, it is time to write the last class (see figure 18). The class may look a bit complex at first, and the behaviour could easily be split into classes with less responsibility, but to avoid the article getting too long, I decided to keep the final game behaviour in a single class.</p><p>The class contains the following attributes: canvas; ctx; frameRate; groundY; playerOptions; spawnerOptions; difficulty; background; player; spawner; speed; score; gameOver;</p><p>canvas specifies the canvas where the game is shown. ctx specifies the canvas’s CanvasRenderingContext2D. frameRate determines how fast the game should execute.</p><p>groundY determines the y position where the ground should be drawn. playerOptions and spawnerOptions specifies the player and spawn options. difficulty specifies the rate at which the game’s speed should increase over time, and the maximum speed.</p><p>background, player, and spawner refers to the background, player, and spawner instances. speed specifies the current speed applied to obstacle movement and the player’s jump power and gravity.</p><p>score specifies the player’s current score, and lastly, gameOver specifies whether or not the game has ended.</p><p>The class also contains the following methods: initialize(); start(); keydown(event); loop(); increaseDifficulty(); drawGameOver(); drawScore(); drawGround();</p><p>initialize() is used to reset variable attributes to their initial values, and it can, therefore, also be used to reset the game when the player loses.</p><p>The method start() is used to start the game for the first time, it adds the ‘keydown’ event listener to keep track of key events, and starts an interval executing the behaviour of loop().</p><p>keydown(event) is used to check if the player presses the space key to either trigger the jump behaviour or restart the game, depending on the game’s current state.</p><p>loop() executes the continuous behaviour of the game. The first line of the method, executing clearRect(x, y, w, h), is added to erase the content of the canvas before any new content is drawn. Then, the method calls the draw method on the background, ground, score, player, and spawner.</p><p>Last, the method checks if the game has ended which can result in one of two things:</p><ol><li>If the game has ended, the method just displays a text saying ‘GAMEOVER’.</li><li>If the game is running, the method first increases the difficulty, calls the background, the player, and the spawner’s update methods, checks for collisions, and lastly increase the score.</li></ol><p>increaseDifficulty() is used to increase the difficulty of the game over time. The method is designed to increase the speed of the obstacles, and the jump power and gravity of the player, if the maximum speed has not been reached yet.</p><p>drawGameOver() is used to display the game over text, drawScore() is used to display the score text, and drawGround() is used to draw the line representing the ground.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34aa7f522e01300684c05f7f6cf0508d/href">https://medium.com/media/34aa7f522e01300684c05f7f6cf0508d/href</a></iframe><h4>Start the Game</h4><p>The EndlessRunnerGame class’ constructor has six arguments required to start the game: id; frameRate; groundOffset; playerOptions; spawnerOptions; difficulty; (see figure 19).</p><p>The first argument, id, specifies the id of the canvas the game should use, frameRate specifies how often the game loop should execute, and groundOffset specifies how far from the bottom of the canvas the ground should be placed.</p><p>playerOptions, spawnerOptions, and difficulty are simple objects containing the details of the player, obstacles, and the game’s difficulty.</p><p>The only thing left to do, when an instance of the class EndlessRunnerGame is instantiated, is to call the object’s start() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6fa0e1456ac09a7602c9afec0ff278f/href">https://medium.com/media/e6fa0e1456ac09a7602c9afec0ff278f/href</a></iframe><p>I hope you enjoyed the article and if you have any questions or feedback do let me know.</p><p>You can find a complete example of the game in the project’s <a href="https://github.com/niiicolai/2d-runner-game">GitHub repository</a>.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11940ab797bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-build-a-2d-endless-runner-game-with-javascript-and-html-11940ab797bf">How to Build a 2D Endless Runner Game With JavaScript and HTML</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Relational Database & MySQL]]></title>
            <link>https://medium.com/@niiicolai/the-relational-database-mysql-c0c6d802d704?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0c6d802d704</guid>
            <category><![CDATA[database-normalization]]></category>
            <category><![CDATA[database-relationships]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Sat, 12 Nov 2022 20:29:42 GMT</pubDate>
            <atom:updated>2022-11-13T02:52:12.930Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introduction to the relational database model and MySQL</h4><figure><img alt="Mock-up tables linked together." src="https://cdn-images-1.medium.com/max/701/1*Ip3abQIFhYuvVEtH9J4O-g.png" /></figure><p>There are many different choices when choosing a database for your application. Some of the most commonly used databases are based on the relational database model. For example, MySQL, Microsoft SQL Server, and PostgreSQL (<a href="https://en.wikipedia.org/wiki/MySQL">Wikipedia, 2022a</a>) (<a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server">Wikipedia, 2022b</a>) (<a href="https://en.wikipedia.org/wiki/PostgreSQL">Wikipedia, 2022c</a>). The purpose of this article is to explain some of the concepts related to relational databases in general, combined with a guide to getting started with MySQL.</p><p><strong>Key points:</strong></p><ul><li>Relational model</li><li>Structured query language (SQL)</li><li>MySQL</li><li>MySQL Workbench</li><li>Data integrity</li><li>Constraints</li><li>Relationships</li><li>Normalization</li></ul><h3>1. What is a Relational Database?</h3><p>A relational database is based on concepts such as tables, relationships, constraints, normalization, and structured query language (SQL) (<a href="https://en.wikipedia.org/wiki/Relational_database">Wikipedia, 2022d</a>).</p><p>The organization of data in the relational database is based on tables, rows, and columns, also known as relations, records/tuples, and attributes (<a href="https://en.wikipedia.org/wiki/Relational_database">Wikipedia, 2022d</a>).</p><p>The tables in the relational model represent different entities (<a href="https://en.wikipedia.org/wiki/Relational_database">Wikipedia, 2022d</a>). For example, one table may represent invoices and another table may represent accounts. The table’s columns specify different types of data values (<a href="https://en.wikipedia.org/wiki/Column_(database)">Wikipedia, 2022f</a>), or in other words, the properties a single entity is made of. For example, the invoice table could have columns such as id, create_date, company_id, etc. The table’s rows each specify a single entity of data (<a href="https://en.wikipedia.org/wiki/Row_(database)">Wikipedia, 2022g</a>). So, a row in the invoice table from the last example would specify the data of a single invoice (see figure 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*q7U6aNKSJKsRpz1siG7WGw.png" /><figcaption>Figure 1. An example of an invoice table with six columns and four rows. The purple line represents a column, the green represents a row, and the intersection represents a single cell of datum.</figcaption></figure><p>The model and theory behind the relational database were proposed by E. F. Codd in 1970 (<a href="https://en.wikipedia.org/wiki/Relational_database">Wikipedia, 2022d</a>). Codd also defined a set of thirteen rules outlining the requirements of a <em>relational database management system</em> (RDBMS), known as Codd’s 12 rules (ordered 0–12) (<a href="https://en.wikipedia.org/wiki/Codd%27s_12_rules">Wikipedia, 2022h</a>).</p><p>For example, Codd’s third rule describes the requirements for the behavior of absent information, which should be represented using a NULL value (<a href="https://en.wikipedia.org/wiki/Codd%27s_12_rules">Wikipedia, 2022h</a>). Another example is Codd’s fifth rule which describes the requirements related to having a least one language that can be used for database operations such as data manipulation or authorization (<a href="https://en.wikipedia.org/wiki/Codd%27s_12_rules">Wikipedia, 2022h</a>).</p><p>A language widely used to configure relational databases is SQL (<a href="https://en.wikipedia.org/wiki/SQL">Wikipedia, 2022j</a>). The language can be divided even further into sublanguages (see figure 2) called <em>data query language</em> (DQL), <em>data definition language</em> (DDL), <em>data control language</em> (DCL), <em>data manipulation language</em> (DML), and <em>Data Transaction Language</em> (DTL) (<a href="https://en.wikipedia.org/wiki/SQL">Wikipedia, 2022j</a>) (<a href="https://en.wikibooks.org/wiki/MySQL/Language/Definitions:_what_are_DDL,_DML_and_DQL%3F">Wikibooks, 2022</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*lGOMTSg47n-huijUQfViNQ.png" /><figcaption>Figure 2. An overview of the statements and purpose of SQL sublanguages.</figcaption></figure><p>Non-relational, or NoSQL databases are in contrast to relational databases based on other types of data structures than tables, such as key-value pairs or document stores (<a href="https://en.wikipedia.org/wiki/NoSQL">Wikipedia, 2022e</a>). Examples of non-relational databases are MongoDB and Redis (<a href="https://www.mongodb.com/compare/relational-vs-non-relational-databases">MongoDB, 2022</a>) (<a href="https://redis.com/nosql/what-is-nosql/">Redis, 2022</a>).</p><h3>2. Get Started With MySQL</h3><p>MySQL is an open-source RDBMS released by a company named MySQL AB in 1995, and, at the time of writing (2022), distributed by Oracle Corporation (<a href="https://en.wikipedia.org/wiki/MySQL">Wikipedia, 2022a</a>) (<a href="https://en.wikipedia.org/wiki/MySQL_AB">Wikipedia, 2022i</a>) (<a href="https://dev.mysql.com/doc/refman/8.0/en/what-is-mysql.html">Oracle, 2022</a>a). The RDBMS is supported on several operating systems such as Microsoft Windows 10, different versions of Linux Ubuntu, and macOS (<a href="https://www.mysql.com/support/supportedplatforms/database.html">Oracle, 2022b</a>).</p><h4>2.1. MySQL Workbench</h4><p>An easy way to get started with MySQL is to download <a href="https://dev.mysql.com/downloads/mysql/">MySQL Community Server</a> and <a href="https://dev.mysql.com/downloads/workbench/">MySQL Workbench</a>. You can also use the <a href="https://dev.mysql.com/downloads/installer/">MySQL Installer</a>, currently only supported on Windows. MySQL Workbench is a tool that can be used to manage a MySQL Server, for example, MySQL Workbench can be used to send SQL statements to the server (<a href="https://dev.mysql.com/doc/workbench/en/wb-intro.html">Oracle, 2022c</a>).</p><p>After installing the workbench, connect to the database by pressing the local instance and entering the password you created in the installation process (see figure 3).</p><figure><img alt="A screenshot of the connection process in MySQL Workbench." src="https://cdn-images-1.medium.com/max/1024/1*2xb_7o-4SAlmMPATl_TkjQ.png" /><figcaption>Figure 3. A screenshot of the connection process in MySQL Workbench.</figcaption></figure><p>MySQL Workbench got many different features for managing the database, but it is actually really easy to get started.</p><p>Figure 4 shows an example of how a simple SQL statement can be executed. The purple box on the left side of figure 4 shows where the statement should be written, and the green box shows how to execute the statement. The purple box on the right side of figure 4 shows where the result is outputted, and the green box shows information about the request.</p><figure><img alt="A screenshot of MySQL’s graphical user interface." src="https://cdn-images-1.medium.com/max/1024/1*MHYJ52Q2ucq3a_SEXARn2A.png" /><figcaption>Figure 4. A screenshot of MySQL’s graphical user interface.</figcaption></figure><h4>2.2. Creating a Database</h4><p>A new database can be added to the instance by using the statement: CREATE DATABASE; followed by a preferred name (<a href="https://dev.mysql.com/doc/refman/8.0/en/create-database.html">Oracle, 2022c</a>). Let’s create a new database called test which will be used in the following in section 2 (see figure 5).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46e51439023575247eb39e5bf9952927/href">https://medium.com/media/46e51439023575247eb39e5bf9952927/href</a></iframe><p>The statement: SHOW DATABASES; returns a list of databases on the connected instance (<a href="https://dev.mysql.com/doc/refman/8.0/en/show-databases.html">Oracle, 2022d</a>). The list should return the new test database, created in the last example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a208a14d5cb422056f4fef9e6817d7f/href">https://medium.com/media/5a208a14d5cb422056f4fef9e6817d7f/href</a></iframe><h4>2.3. Creating Tables</h4><p>Tables can be created using the statement: CREATE TABLE; followed by the table’s name, and column definitions (<a href="https://dev.mysql.com/doc/refman/8.0/en/create-table.html">Oracle, 2022e</a>).</p><p>Figure 7 shows an example of how to add a simple invoice table to the test database. The database is specified by inserting the database name before the table’s name: test.invoices; (see line 1).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e7840c766186f1e80c5ade731802235/href">https://medium.com/media/2e7840c766186f1e80c5ade731802235/href</a></iframe><p>The invoice table has four columns: id; due_amount; due_date; create_date; The data type of the column is specified after the column’s name, for example, line 2 specifies the column id should be of type INT, and line 3 specifies the column due_date should be of type FLOAT. NOT NULL specifies that a column cannot be empty, and DEFAULT specifies a default value, for example, the column create_date is defined to set the CURRENT_TIMESTAMP as the default value for new rows added to the table.</p><p>CURRENT_TIMESTAMP returns the current time, and AUTO_INCREMENT ensures the column id automatically gets assigned an incremented number for each row (<a href="https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_current-time">Oracle, 2022h</a>) (<a href="https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html">Oracle, 2022i</a>).</p><p>PRIMARY KEY, line 6, sets the column id as the table’s primary key. The primary key is set to specify a unique identifier for each row, however, more details about primary keys will be introduced later in the article‘s section 3.</p><h4>2.4. Inserting Into Tables</h4><p>The statement: INSERT; can be used to insert new rows (<a href="https://dev.mysql.com/doc/refman/8.0/en/insert.html">Oracle, 2022f</a>). The statement should be followed by INTO, the table’s name, attributes, and values.</p><p>Figure 8 shows an example of how to insert a new invoice with a due amount of 120.5. The invoice’s due_date would automatically be set to null since none was provided, and the create_date would automatically be set to the specified default value (CURRENT_TIMESTAMP).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d16cd57c1001809fc0e36c9b37c4e52/href">https://medium.com/media/7d16cd57c1001809fc0e36c9b37c4e52/href</a></iframe><p>Figure 9 shows an example of how to insert a new invoice with both a due_amount and a due_date. It should be noticed that the order of columns in the first parenthesis refers to values inserted in the same order in the second parenthesis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc55618cc0541f17036b55191adbcb3f/href">https://medium.com/media/bc55618cc0541f17036b55191adbcb3f/href</a></iframe><h4>2.5. Selecting Rows From Tables</h4><p>The statement: SELECT; can be used to get rows from a table (<a href="https://dev.mysql.com/doc/refman/8.0/en/select.html">Oracle, 2022g</a>). The statement should be followed by columns and a table’s name. Asterisk (*) can be used instead of specific column names to get all columns of a table. Figure 10 shows an example of how to get all rows in the invoices table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94080c3ec623c72a4d637f98e9dc651b/href">https://medium.com/media/94080c3ec623c72a4d637f98e9dc651b/href</a></iframe><p>It can be seen in figure 11 that the first row, inserted in the first example in section 2.4, has an id set to 1, a due_amount set to 120.5, a due_date set to null, and a create_date set to the time the row was inserted (Note: you should see two rows if you executed both insert examples in section 2.4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wC6jNl2_58znpsCE1r1DiA.png" /><figcaption>Figure 11. A screenshot of the rows returned from executing the select statement.</figcaption></figure><h4>2.6. Updating Rows</h4><p>The statement: UPDATE; can be used to update rows in a table (<a href="https://dev.mysql.com/doc/refman/8.0/en/update.html">Oracle, 2022j</a>). The statement should be followed by the table’s name, SET, and the columns’ names set equal to their new values. Furthermore, the WHERE clause can be added to specify the specific rows that should be updated.</p><p>Figure 12 shows an example of how to replace the due_date of the first invoice inserted in section 2.4.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/566cf3999099aa79d19a81dd06e7c1dd/href">https://medium.com/media/566cf3999099aa79d19a81dd06e7c1dd/href</a></iframe><h4>2.7. Deleting Rows</h4><p>The statement: DELETE; can be used to delete rows from a table (<a href="https://dev.mysql.com/doc/refman/8.0/en/delete.html">Oracle, 2022k</a>). The statement should be followed by FROM, and the table’s name. Furthermore, the WHERE clause can be used to specify the specific rows as shown in the example with the UPDATE statement.</p><p>Figure 13 shows an example of how to delete an invoice with an id equal to one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a91edbb47f9752c7668af808146a526d/href">https://medium.com/media/a91edbb47f9752c7668af808146a526d/href</a></iframe><h4>2.8. Altering Tables</h4><p>The statement: ALTER TABLE; can be used to modify a table’s structure (<a href="https://dev.mysql.com/doc/refman/8.0/en/alter-table.html">Oracle, 2022m</a>). The statement should be followed by the table’s name and the modification specification. For example, ALTER TABLEcan be used to ADD, MODIFY, or DROP a column.</p><p>Figure 14 shows an example of how a new column named state can be added to the invoices table. The column’s data type is set to VARCHAR with a length of 255. VARCHAR is a string data type that can contain a set of characters, for example, words, numerical values, and symbols (<a href="https://en.wikipedia.org/wiki/String_(computer_science)">Wikipedia, 2022l</a>) (<a href="https://dev.mysql.com/doc/refman/8.0/en/string-types.html">Oracle, 2022n</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/407461404dfb2858a0b3dad0d83fe2b3/href">https://medium.com/media/407461404dfb2858a0b3dad0d83fe2b3/href</a></iframe><p>Figure 15 shows an example of how to change the length of VARCHAR to 300.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdc1d613fed9d0bbd9faea31c6dff8a0/href">https://medium.com/media/fdc1d613fed9d0bbd9faea31c6dff8a0/href</a></iframe><p>Figure 16 shows an example of how to delete the column state from the invoices table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea9ee514963251a67cd9b22a7e281da1/href">https://medium.com/media/ea9ee514963251a67cd9b22a7e281da1/href</a></iframe><h4>2.9. Dropping Tables</h4><p>The statement: DROP TABLE; can be used to delete tables from a database (<a href="https://dev.mysql.com/doc/refman/8.0/en/drop-table.html">Oracle, 2022l</a>). The statement should be followed by the table’s name.</p><p>Figure 17 shows an example of how to delete the invoices table from the test database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75812cf2cb82571952b3a800af46eb18/href">https://medium.com/media/75812cf2cb82571952b3a800af46eb18/href</a></iframe><h3>3. Data Integrity</h3><p>Constraints can be used to ensure the data integrity of the database. Three types of integrity constraints in the relational database model are <em>domain integrity, entity integrity, and referential integrity </em>(<a href="https://en.wikipedia.org/wiki/Data_integrity#TYPES">Wikipedia, 2022m</a>).</p><h4>3.1 Domain Integrity</h4><p>Wikipedia (<a href="https://en.wikipedia.org/wiki/Data_integrity#TYPES">2022m</a>) defines domain integrity as the requirement of columns to have a defined domain, and a domain in relational databases refers to a set of valid values allowed in rows of a specific column (<a href="https://en.wikibooks.org/wiki/Database_Design/The_Relational_Data_Model">Wikibooks, 2022b</a>). For example, the column due_amount in the invoices table, in section 2.3, was defined to be of type FLOAT and NOT NULL, restricting the column’s domain to only allow numerical values.</p><p>There are many other ways to restrict the domain of a column, for example, by using a check constraint. The check constraint was introduced in MySQL in version 8.0.16 (<a href="https://dev.mysql.com/blog-archive/mysql-8-0-16-introducing-check-constraint/">Hulakund, 2019</a>).</p><h4>3.2. Entity Integrity</h4><p>Entity integrity is defined as a requirement that states a row must have an identifier that is unique and not null (<a href="https://en.wikipedia.org/wiki/Entity_integrity">Wikipedia, 2022n</a>). The identifier is called the primary key (PK) (<a href="https://en.wikipedia.org/wiki/Entity_integrity">Wikipedia, 2022n</a>).</p><p>A primary key can be defined with a single column, or several columns (<a href="https://en.wikipedia.org/wiki/Relational_database">Wikipedia, 2022d</a>). Primary keys combined with several columns are called composite keys (<a href="https://en.wikipedia.org/wiki/Relational_database">Wikipedia, 2022d</a>).</p><p>Two types of primary keys are surrogate and natural keys (<a href="https://en.wikipedia.org/wiki/Surrogate_key">Wikipedia, 2022p</a>) (<a href="https://en.wikipedia.org/wiki/Natural_key">Wikipedia, 2022q</a>). A surrogate key is a sequential key with no relation to the rest of the table’s data, simply used to uniquely identify a row (<a href="https://en.wikipedia.org/wiki/Relational_database">Wikipedia, 2022d</a>).</p><p>A natural key is defined using the columns defining the table’s real-world entity (<a href="https://en.wikipedia.org/wiki/Natural_key">Wikipedia, 2022q</a>). For example, a table of addresses could be assigned a primary key based on street name, street number, city, and country. This would mean that each address is identified by the real-world properties of an address, and it would also ensure that each address is unique.</p><h4>3.3. Referential Integrity</h4><p>Referential integrity is defined as a requirement concerned with whether or not a row in one table refers to an existing row in another table (<a href="https://en.wikipedia.org/wiki/Referential_integrity">Wikipedia, 2022o</a>). This concept prevents having rows with invalid references. A column in a table can be defined as a foreign key to ensuring referential integrity is enforced (<a href="https://en.wikipedia.org/wiki/Referential_integrity">Wikipedia, 2022o</a>).</p><p>The foreign key, in contrast to the primary key, is not required to be unique or not null (<a href="https://en.wikipedia.org/wiki/Relational_database">Wikipedia, 2022d</a>). If a row with a column defining the foreign key is null, it simply means the row has no relationship.</p><h3>4. Different Types Of Relationships</h3><p>Three types of relationships in the relational database model are one-to-one, one-to-many, and many-to-many (<a href="https://en.wikipedia.org/wiki/Relational_database">Wikipedia, 2022d</a>).</p><h4>4.1. One-to-many</h4><p>One-to-many describes a relationship where a row in one table has a relationship to many rows in another table (<a href="https://en.wikipedia.org/wiki/One-to-many_(data_model)">Wikipedia, 2022r</a>).</p><p>For example, imagine an application where a user can get assigned a task. The database has two tables, one containing users with a column named id as the primary key, and another table containing tasks with a column named user_id as the foreign key (see figure 20).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*5BnaoETzIheUmCGin9YKXA.png" /><figcaption>Figure 20. An entity-relationship diagram showing a one-to-many relationship between users and tasks.</figcaption></figure><p>Figure 21 shows an example of how to create the one-to-many relationship illustrated in figure 20. It should be noticed that the foreign key of the task table is defined on line 11 by using the keywords FOREIGN KEY and REFERENCES. FOREIGN KEY should be followed by the name of the column that should be defined as a foreign key, and REFERENCES should be followed by the name of the table and primary key that the foreign key has a reference to.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b26546d2c1b219848c21abbdde40dbf/href">https://medium.com/media/7b26546d2c1b219848c21abbdde40dbf/href</a></iframe><p>Figure 22 shows an example of how to add a user and a couple of tasks with a reference to the user. It should be noticed that the tasks are referring to a user with an id equal to one. If the tasks should refer to another user or no user at all, the user_id could simply be changed to another value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be665612904b0c849a1331ba92f67884/href">https://medium.com/media/be665612904b0c849a1331ba92f67884/href</a></iframe><p>But what if a task referring to a non-existing user was inserted? Figure 23, shows the insertion would fail with the following response:</p><p><em>Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`test`.`tasks`, CONSTRAINT `tasks_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))</em></p><p>This error occurs because the insertion violates the referential integrity enforced by the foreign key configuration between the tables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50292683c361efc59422f81703aadcaa/href">https://medium.com/media/50292683c361efc59422f81703aadcaa/href</a></iframe><h4><strong>4.2. One-to-one</strong></h4><p>The one-to-one relationship is very similar to the one-to-many relationship. A one-to-one relationship between two tables means a single row in one table refers to a single row in another table (<a href="https://en.wikipedia.org/wiki/One-to-one_(data_model)">Wikipedia, 2022s</a>).</p><p>Figure 24 shows an example of a one-to-one relationship where a single user can have a single address. It should be noticed the primary key of the address table is also the foreign key which refers to the user’s primary key. This configuration ensures that only one address for each user can exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*rkr4EdyEbfbJ0JPa48D_ww.png" /><figcaption>Figure 24. An example of a one-to-one relationship.</figcaption></figure><p>Figure 25 shows an example of how to create the users and addresses table with a one-to-one relationship. It should be noticed the primary key defined in the addresses table does not include the AUTO_INCREMENT configuration. This is because the primary key (and foreign key) should be equal to a user’s primary key, instead of being assigned a sequential value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/100756c0c6f34f6e26605f6992442ee8/href">https://medium.com/media/100756c0c6f34f6e26605f6992442ee8/href</a></iframe><p>Figure 26 shows an example of adding a user and an address into the tables with a one-to-one relationship.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/839180209bc6b1c559b33d8cbecee1e7/href">https://medium.com/media/839180209bc6b1c559b33d8cbecee1e7/href</a></iframe><p>As explained in section 3.1, the insertion would fail if the specified foreign key was referring to a non-existing user, but what if two addresses were inserted with the same user_id?</p><p>Figure 27 shows the insertion would fail with the following response:</p><p><em>Error Code: 1062. Duplicate entry ‘1’ for key ‘addresses.PRIMARY’</em></p><p>This is because the table already contains a row with a primary key equal to one, thereby preventing a violation of the one-to-one relationship.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd0c4f6ad99408e0e5b4e449da25a18c/href">https://medium.com/media/bd0c4f6ad99408e0e5b4e449da25a18c/href</a></iframe><h4><strong>4.3. Many-to-many</strong></h4><p>A many-to-many relationship between two tables means a row in one table can have a relationship with many rows in another table, and one row in the other table can have a relationship with many rows in the first table as well (<a href="https://en.wikipedia.org/wiki/Many-to-many_(data_model)">Wikipedia, 2022t</a>).</p><p>The many-to-many relationship, in contrast to one-to-one and one-to-many, includes a third table mapping the relationship, known as the associative table (<a href="https://en.wikipedia.org/wiki/Associative_entity">Wikipedia, 2022u</a>).</p><p>Figure 28 shows an example of a many-to-many relationship where a user can have many messages, and a message can have many users. For example, imagine an application where a message can be sent to one or multiple recipients. Each user would, in this case, need the ability to have multiple messages, and the message could be for multiple users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*Mo4GCnu170yodagRSrUSSA.png" /><figcaption>Figure 28. An example of a many-to-many relationship.</figcaption></figure><p>Figure 29 shows an example of how to create a many-to-many relationship between the users and the messages table by an associative table called user_message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f2a9d43ca09c423135ff193f3433ac7/href">https://medium.com/media/5f2a9d43ca09c423135ff193f3433ac7/href</a></iframe><p>Figure 30 shows a simple example of how data can be inserted to create a message belonging to two different users. If this example were executed twice, it can be seen the users would have references to multiple messages, and the messages would have references to multiple users.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/901e50cfe8487f4c5e764bb2f06a4e56/href">https://medium.com/media/901e50cfe8487f4c5e764bb2f06a4e56/href</a></iframe><h4>4.4. Fetch Entities With Relation</h4><p>The last thing I want to introduce about relations is how to use the JOIN clause to get entities together with matching entities in another table.</p><p>There exist different types of JOIN clauses such as LEFT, RIGHT, INNER, or CROSS (<a href="https://dev.mysql.com/doc/refman/8.0/en/join.html">Oracle, 2022o</a>). Each type returns a different result, for example, LEFT JOIN returns NULL for the right table for all entities where there is no matching entity (<a href="https://dev.mysql.com/doc/refman/8.0/en/join.html">Oracle, 2022o</a>).</p><p>Imagine the scenario in section 4.2. with a one-to-one relationship between users and the addresses table. LEFT JOIN could be used in this scenario to get all users and their addresses by matching addresses using the user_id column (see figure 31).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3360938ed69175d2b466a73c8d8fd58a/href">https://medium.com/media/3360938ed69175d2b466a73c8d8fd58a/href</a></iframe><p>If two users were created and one of them only had an address, the result would return NULL for the address table for the user who does not have an address (see figure 32).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTCVDCrPJZg_EBQNgjyNgQ.png" /><figcaption>Figure 32: An example of the results returned using a LEFT JOIN statement.</figcaption></figure><h3>5. Normalization Of The Structure</h3><p>Database normalization concerns avoiding anomalies and redundant data by structuring tables after the rules of normal forms (<a href="https://en.wikipedia.org/wiki/Database_normalization">Wikipedia, 2022v</a>). The concept was introduced by Codd in 1970 (<a href="https://en.wikipedia.org/wiki/Database_normalization">Wikipedia, 2022v</a>).</p><h4>5.1. Anomalies</h4><p>Three types of anomalies are the insertion anomaly, update anomaly, and deletion anomaly (<a href="https://en.wikipedia.org/wiki/Database_normalization">Wikipedia, 2022v</a>).</p><p><strong>5.1.1. Insertion Anomaly</strong></p><p>The insertion anomaly occurs when records cannot be inserted because of the table’s design.</p><p>For example, a table is created to assign students to different classes (see figure 33). The table’s column class is defined as NOT NULL because it is part of a natural primary key together with student ID. This means a student only can be created if the class is already known.</p><p>It may be thought that the column class could be removed from the primary key, but this would result in rows which are no longer unique, so that is not a possibility.</p><figure><img alt="An Insertion anomaly where a student cannot be inserted before being assigned to a class." src="https://cdn-images-1.medium.com/max/592/1*O7hfkEU7rGIFpUpRpYgFMg.png" /><figcaption>Figure 33. An Insertion anomaly where a student cannot be inserted before being assigned to a class.</figcaption></figure><p><strong>5.1.2. Update Anomaly</strong></p><p>The update anomaly occurs when multiple rows contain the same data and an update fails to update all rows specifying the same.</p><p>For example, the table in figure 34 contains two records of classes John Doe is a part of. At some point, John Doe changes his surname to Johnson resulting in all the existing records should be updated.</p><p>However, in a scenario where the update fails to change the data for every row would leave the database in a state where John Doe/Johnson is recorded with two different surnames.</p><figure><img alt="An update anomaly where the student same student is recorded with two different surnames." src="https://cdn-images-1.medium.com/max/592/1*zOfxcktEOVst2pv5DiVw1w.png" /><figcaption>Figure 34. An update anomaly where the student same student is recorded with two different surnames.</figcaption></figure><p><strong>5.1.3. Deletion Anomaly</strong></p><p>The deletion anomaly occurs when deleting a row result in losing additional data.</p><p>For example, the table in figure 35 contains information about both the students’ names and the classes they are attending.</p><p>In a scenario where a student is removed from all their classes would result in all information about the student getting completely removed from the database.</p><figure><img alt="Deletion anomaly where removing a student from a class deletes all the students information." src="https://cdn-images-1.medium.com/max/592/1*78ZBrDb6I1u2yEcWaqJfUQ.png" /><figcaption>Figure 35. Deletion anomaly where removing a student from a class deletes all the students information.</figcaption></figure><h4>5.2. Normal forms</h4><p>There are different levels of normalization known as normal forms. The level starts with the least normalized form (First Normal Form, 1NF) and expands to the most normalized form (Sixth Normal Form, 6NF) (<a href="https://en.wikipedia.org/wiki/Database_normalization">Wikipedia, 2022v</a>).</p><p><strong>5.2.1. First Normal Form, 1NF</strong></p><p>The rules of the first normal form are cells should only contain atomic values and every row must be unique (<a href="https://en.wikipedia.org/wiki/Database_normalization">Wikipedia, 2022v</a>).</p><p>Figure 36 shows an example of a table containing students and their classes. It should be noticed the cells containing Student ID and Names are specifying multiple ids and names for each class which means the cells does not contain atomic values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*il0m3M5wMgqysQREEo-avA.png" /><figcaption>Figure 36: An example of a table in unnormalized form (UNF).</figcaption></figure><p>The solution if only a first normal form was the goal would be to ensure every student has its own row, split names up into two columns called first name and surname, and define the Class ID and Student ID as a composite key (see figure 37).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*qiKg0xmJLaJpPvKNZB9V8w.png" /><figcaption>Figure 37: An example of a table in first normal form (1NF).</figcaption></figure><p><strong>5.2.2. Second Normal Form, 2NF</strong></p><p>The rules of the second normal form are tables should be in the first normal form, and partial functional dependencies of non-key attributes are <em>not</em> allowed (<a href="https://en.wikipedia.org/wiki/Database_normalization">Wikipedia, 2022v</a>).</p><p>Figure 38 shows the table from the last example which is currently in the first normal form. It can also be seen that it contains partial dependencies of non-key attributes only depending on part of the primary key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*a1UihVQ9LW2XG-TzE2ZYVA.png" /><figcaption>Figure 38: An example of a table with partial dependencies.</figcaption></figure><p>The solution is to split the table up into the following three tables (see figure 39). The columns/attributes of each table are now fully dependent on the primary key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*OFHZiDTKtkojI-JBYw1Zow.png" /><figcaption>Figure 39: An example of tables in both the second and third normalized form (3NF).</figcaption></figure><p><strong>5.2.3. Third Normal Form, 3NF</strong></p><p>The rules of the third normal form are tables should be in the second normal form, and transitive functional dependencies of non-key attributes are <em>not</em> allowed.</p><p>To demonstrate the idea of a transitive dependency, let’s assume the unnormalized table in figure 36 was redesigned to only use the Student ID as the primary key (see figure 40).</p><p>This design would not really make sense if a student were supposed to be assigned to multiple classes, but I think it clearly demonstrate the idea of the transitive dependency.</p><p>Because, if a student changes the Class ID to another class id, it automatically requires the class name also to be changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*cTJNryatrGqGovZf2jlq7g.png" /><figcaption>Figure 40: An example of a transitive dependency.</figcaption></figure><p>The solution is to either adding a one-to-many relationship, or a many-to-many relationship as shown in figure 39.</p><h3>8. Bibliography</h3><p>Hulakund. P. 2019.<em> MySQL :: MySQL 8.0.16 Introducing CHECK constraint.</em> [online] Available at: &lt;<a href="https://dev.mysql.com/blog-archive/mysql-8-0-16-introducing-check-constraint/">https://dev.mysql.com/blog-archive/mysql-8-0-16-introducing-check-constraint/</a>&gt; [Accessed 1 October 2022].</p><p>MongoDB. 2022. <em>Relational Vs. Non-Relational Databases | MongoDB</em>. [online] MongoDB. Available at: &lt;<a href="https://www.mongodb.com/compare/relational-vs-non-relational-databases">https://www.mongodb.com/compare/relational-vs-non-relational-databases</a>&gt; [Accessed 2 October 2022].</p><p>Oracle. 2022a. <em>MySQL :: MySQL 8.0 Reference Manual :: 1.2.1 What is MySQL?</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/what-is-mysql.html">https://dev.mysql.com/doc/refman/8.0/en/what-is-mysql.html</a>&gt; [Accessed 1 October 2022].</p><p>Oracle. 2022b. <em>MySQL :: Supported Platforms: MySQL Database</em>. [online] Available at: &lt;<a href="https://www.mysql.com/support/supportedplatforms/database.html">https://www.mysql.com/support/supportedplatforms/database.html</a>&gt; [Accessed 1 October 2022].</p><p>Oracle. 2022c. <em>MySQL :: MySQL 8.0 Reference Manual :: 13.1.12 CREATE DATABASE Statement</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/create-database.html">https://dev.mysql.com/doc/refman/8.0/en/create-database.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022c. <em>MySQL :: MySQL Workbench Manual :: 1 General Information</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/workbench/en/wb-intro.html">https://dev.mysql.com/doc/workbench/en/wb-intro.html</a>&gt; [Accessed 2 October 2022].</p><p>Oracle. 2022d. <em>MySQL :: MySQL 8.0 Reference Manual :: 13.7.7.14 SHOW DATABASES Statement</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/show-databases.html">https://dev.mysql.com/doc/refman/8.0/en/show-databases.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022e. <em>MySQL :: MySQL 8.0 Reference Manual :: 13.1.20 CREATE TABLE Statement</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/create-table.html">https://dev.mysql.com/doc/refman/8.0/en/create-table.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022f. <em>MySQL :: MySQL 8.0 Reference Manual :: 13.2.6 INSERT Statement</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/insert.html">https://dev.mysql.com/doc/refman/8.0/en/insert.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022g. <em>MySQL :: MySQL 8.0 Reference Manual :: 13.2.10 SELECT Statement</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/select.html">https://dev.mysql.com/doc/refman/8.0/en/select.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022h. <em>MySQL :: MySQL 8.0 Reference Manual :: 12.7 Date and Time Functions</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_current-time">https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_current-time</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022i. <em>MySQL :: MySQL 8.0 Reference Manual :: 3.6.9 Using AUTO_INCREMENT</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html">https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022j. <em>MySQL :: MySQL 8.0 Reference Manual :: 13.2.13 UPDATE Statement</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/update.html">https://dev.mysql.com/doc/refman/8.0/en/update.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022k. <em>MySQL :: MySQL 8.0 Reference Manual :: 13.2.2 DELETE Statement</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/delete.html">https://dev.mysql.com/doc/refman/8.0/en/delete.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022l. <em>MySQL :: MySQL 8.0 Reference Manual :: 13.1.32 DROP TABLE Statement</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/drop-table.html">https://dev.mysql.com/doc/refman/8.0/en/drop-table.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022m. <em>MySQL :: MySQL 8.0 Reference Manual :: 13.1.9 ALTER TABLE Statement</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/alter-table.html">https://dev.mysql.com/doc/refman/8.0/en/alter-table.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022n. <em>MySQL :: MySQL 8.0 Reference Manual :: 11.3 String Data Types</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/string-types.html">https://dev.mysql.com/doc/refman/8.0/en/string-types.html</a>&gt; [Accessed 3 October 2022].</p><p>Oracle. 2022o. <em>MySQL 8.0 Reference Manual :: 13.2.10.2 join clause</em>. [online] Available at: &lt;<a href="https://dev.mysql.com/doc/refman/8.0/en/join.html">https://dev.mysql.com/doc/refman/8.0/en/join.html</a>&gt; [Accessed: November 12, 2022].</p><p>Redis. 2022. <em>What Is NoSQL | Redis</em>. [online] Available at: &lt;<a href="https://redis.com/nosql/what-is-nosql/">https://redis.com/nosql/what-is-nosql/</a>&gt; [Accessed 2 October 2022].</p><p>Wikipedia. 2022a. <em>MySQL — Wikipedia.</em> [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/MySQL">https://en.wikipedia.org/wiki/MySQL</a>&gt; [Accessed 1 October 2022].</p><p>Wikipedia. 2022b. <em>Microsoft SQL Server — Wikipedia.</em> [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server">https://en.wikipedia.org/wiki/Microsoft_SQL_Server</a>&gt; [Accessed 1 October 2022].</p><p>Wikipedia. 2022c. <em>PostgreSQL — Wikipedia.</em> [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/PostgreSQL">https://en.wikipedia.org/wiki/PostgreSQL</a>&gt; [Accessed 1 October 2022].</p><p>Wikipedia. 2022d. <em>Relational database — Wikipedia.</em> [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Relational_database">https://en.wikipedia.org/wiki/Relational_database</a>&gt; [Accessed 1 October 2022].</p><p>Wikipedia. 2022e. <em>NoSQL — Wikipedia.</em> [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/NoSQL">https://en.wikipedia.org/wiki/NoSQL</a>&gt; [Accessed 1 October 2022].</p><p>Wikipedia. 2022f. <em>Column (database) — Wikipedia.</em> [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Column_(database)">https://en.wikipedia.org/wiki/Column_(database)</a>&gt; [Accessed 1 October 2022].</p><p>Wikipedia. 2022g. <em>Row (database) — Wikipedia.</em> [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Row_(database)">https://en.wikipedia.org/wiki/Row_(database)</a>&gt; [Accessed 1 October 2022].</p><p>Wikipedia. 2022h. <em>Codd’s 12 rules — Wikipedia.</em> [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Codd%27s_12_rules">https://en.wikipedia.org/wiki/Codd%27s_12_rules</a>&gt; [Accessed 1 October 2022].</p><p>Wikipedia. 2022i. <em>MySQL AB — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/MySQL_AB">https://en.wikipedia.org/wiki/MySQL_AB</a>&gt; [Accessed 1 October 2022].</p><p>Wikipedia. 2022j. <em>SQL — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/SQL">https://en.wikipedia.org/wiki/SQL</a>&gt; [Accessed 2 October 2022].</p><p>Wikipedia. 2022k. <em>SQL syntax — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/SQL_syntax">https://en.wikipedia.org/wiki/SQL_syntax</a>&gt; [Accessed 2 October 2022].</p><p>Wikipedia. 2022l. <em>String (computer science) — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/String_(computer_science)">https://en.wikipedia.org/wiki/String_(computer_science)</a>&gt; [Accessed 3 October 2022].</p><p>Wikipedia. 2022m. <em>Data integrity — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Data_integrity#TYPES">https://en.wikipedia.org/wiki/Data_integrity#TYPES</a>&gt; [Accessed 5 October 2022].</p><p>Wikipedia. 2022n. <em>Entity integrity — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Entity_integrity">https://en.wikipedia.org/wiki/Entity_integrity</a>&gt; [Accessed 5 October 2022].</p><p>Wikipedia. 2022o. <em>Referential integrity — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Referential_integrity">https://en.wikipedia.org/wiki/Referential_integrity</a>&gt; [Accessed 5 October 2022].</p><p>Wikipedia. 2022p. <em>Surrogate key — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Surrogate_key">https://en.wikipedia.org/wiki/Surrogate_key</a>&gt; [Accessed 5 October 2022].</p><p>Wikipedia. 2022q. <em>Natural key — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Natural_key">https://en.wikipedia.org/wiki/Natural_key</a>&gt; [Accessed 5 October 2022].</p><p>Wikipedia. 2022r. <em>One-to-many (data model) — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/One-to-many_(data_model)">https://en.wikipedia.org/wiki/One-to-many_(data_model)</a>&gt; [Accessed 11 October 2022].</p><p>Wikipedia. 2022s. <em>One-to-one (data model) — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/One-to-one_(data_model)">https://en.wikipedia.org/wiki/One-to-one_(data_model)</a>&gt; [Accessed 11 October 2022].</p><p>Wikipedia. 2022t. <em>Many-to-many (data model) — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Many-to-many_(data_model)">https://en.wikipedia.org/wiki/Many-to-many_(data_model)</a>&gt; [Accessed 11 October 2022].</p><p>Wikipedia. 2022u. <em>Associative entity — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Associative_entity">https://en.wikipedia.org/wiki/Associative_entity</a>&gt; [Accessed 11 October 2022].</p><p>Wikipedia. 2022v. <em>Database normalization</em>. Available at: <a href="https://en.wikipedia.org/wiki/Database_normalization">https://en.wikipedia.org/wiki/Database_normalization</a> (Accessed: October 23, 2022).</p><p>Wikibooks. 2022a. <em>MySQL/Language/Definitions: what are DDL, DML and DQL? — Wikibooks, open books for an open world</em>. [online] Available at: &lt;<a href="https://en.wikibooks.org/wiki/MySQL/Language/Definitions:_what_are_DDL,_DML_and_DQL%3F">https://en.wikibooks.org/wiki/MySQL/Language/Definitions:_what_are_DDL,_DML_and_DQL%3F</a>&gt; [Accessed 3 October 2022].</p><p>Wikibooks. 2022b. <em>Database Design/The Relational Data Model — Wikibooks, open books for an open world</em>. [online] Available at: &lt;<a href="https://en.wikibooks.org/wiki/Database_Design/The_Relational_Data_Model">https://en.wikibooks.org/wiki/Database_Design/The_Relational_Data_Model</a>&gt; [Accessed 5 October 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0c6d802d704" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Custom Video Player for Your Website]]></title>
            <link>https://medium.com/better-programming/a-tutorial-to-the-html-video-element-b8b9a4bf2f76?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8b9a4bf2f76</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Thu, 20 Oct 2022 20:31:12 GMT</pubDate>
            <atom:updated>2022-10-21T01:59:29.711Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tutorial to the HTML video element</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*M-w5XdLvSwd2WeKsgW4BqA.png" /></figure><p>Are you building a website where your visitors can stream video, but find the default design of the HTML video element quite uninteresting? Do not worry! This article explains how to modify your video HTML elements to give them a bit more refreshing design.</p><h3>1. What Is The HTML Video Element?</h3><p>The video element provides a way to embed video directly into an HTML document (<a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video">Mozilla, no date, a</a>). It has a comprehensive set of properties, events, and methods that can be used to bind features to new elements.</p><h4>1.1. Attributes</h4><p>The video element can be configured directly using different attributes such as autoplay, controls, src, muted, poster, etc. (See figure 1). The video element has many more attributes than those mentioned, and I recommend looking at <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#browser_compatibility">Mozilla (no date, a)</a> if you are interested in other attributes.</p><figure><img alt="An explanation of video element attributes." src="https://cdn-images-1.medium.com/max/453/1*MP7N1WATBVSJYoWmxZuDSQ.png" /><figcaption>Figure 1. An explanation of video element attributes (<a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video">Mozilla, no date, a</a>).</figcaption></figure><p>The video element can be configured with single or multiple sources (see figure 2). The reason to use multiple sources is to provide an alternative format for browsers that may not support a specific format (<a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video">Mozilla, no date, a</a>). No support errors can be communicated to the user by inserting a message within the video element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c95519011c3da0c65452cbeb0fa69d59/href">https://medium.com/media/c95519011c3da0c65452cbeb0fa69d59/href</a></iframe><p>The default browser controls provide graphical user interface (GUI) elements for different video operations. This includes operations such as play/pause, timeline, time info, volume setting, fullscreen, play speed, and integrated image (see figure 3).</p><figure><img alt="An example of the video element with default browser controls. The image the video element is displaying is from a video created by Artem Podrez." src="https://cdn-images-1.medium.com/max/310/1*AdJfLdt9Atej01Uu6JPIdg.png" /><figcaption>Figure 3. An example of the video element with default browser controls. The image the video element is displaying is from a video created by <a href="https://www.pexels.com/da-dk/video/by-vej-himmel-solnedgang-4832083/">Artem Podrez</a>.</figcaption></figure><h4>1.2. Methods &amp; Properties</h4><p>The interface of the HTML video element inherits properties, events, and methods from the HTML media element interface (<a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement">Mozilla, no date, b</a>). This includes methods such as play() and pause(), and properties such as volume, duration, currentTime, and paused.</p><figure><img alt="An explanation of properties and methods of the HTML media element." src="https://cdn-images-1.medium.com/max/453/1*BH3rWMvx7elkxDCsYiKdSA.png" /><figcaption>Figure 4. An explanation of properties and methods of the HTML media element (<a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement">Mozilla, no date, b</a>).</figcaption></figure><p>The properties and methods can be utilized simply by getting the video element from the HTML document (see figure 5).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bb38768c6c676fed15fceff34e9ba62/href">https://medium.com/media/6bb38768c6c676fed15fceff34e9ba62/href</a></iframe><p>Note: Calling the method play() before any interaction may result in the following error: <em>DOMException: play() failed because the user didn’t interact with the document first.</em></p><p>This error occurs because browser-specific autoplay policies are enforced (<a href="https://developer.chrome.com/blog/autoplay/">Beaufort, 2017</a>).</p><h4>1.3. Events</h4><p>The HTML media element interface also provides a set of events executed in different scenarios (see figure 6).</p><figure><img alt="An explanation of events of the HTML media element." src="https://cdn-images-1.medium.com/max/453/1*Z_tlvjSBcabPSKOw7VnYpA.png" /><figcaption>Figure 6. An explanation of events of the HTML media element (<a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement">Mozilla, no date, b</a>).</figcaption></figure><p>An event can be assigned by calling the method element.addEventListener(event, function) or by assigning it as a property (<a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement">Mozilla, no date, b</a>). When an event is assigned by the property it is possible to specify a single function, but the method addEventListener() can be used to specify multiple functions. When a method assigned to an event is called, an event object is passed to the method containing the element executing the event (see figure 7).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6511fd23da2ca912c718533c8670840/href">https://medium.com/media/b6511fd23da2ca912c718533c8670840/href</a></iframe><h3>2. Build A Custom Video Player</h3><p>This section of the article will explain how to build custom GUI elements for your HTML video element.</p><h4>2.1. Mockup Design</h4><p>Before writing any HTML, CSS, or JavaScript, I want to introduce an overview of the design (see figure 8). The design can be divided into three different sections: top; video; bottom;</p><p>The top section contains page navigation elements and additional video options such as a playback speed slider or a fullscreen button. The video section contains the actual video element, timeline, current time info, and main video options such as play/pause, rewind, and forward. The bottom section contains elements displaying video information such as title, duration, and description.</p><figure><img alt="A mockup design of a video player." src="https://cdn-images-1.medium.com/max/826/1*MDSD9YQFVyexN9a6Kd1DOw.png" /><figcaption>Figure 8. A mockup design of a video player.</figcaption></figure><p>The additional option sliders are hidden by default, and their visibility can be toggled by pressing a button next to their position (see figure 9).</p><figure><img alt="Figure 9. An illustration of toggling visibility of sliders." src="https://cdn-images-1.medium.com/max/1024/1*7Ec0JrAOjmwEOll12MbUAg.png" /><figcaption>Figure 9. An illustration of toggling visibility of sliders.</figcaption></figure><p>The video controls are automatically hidden when the cursor is moved outside the video area, or it has not been moved for a while (see figure 10).</p><figure><img alt="An illustration of how GUI elements are hidden when the cursor is not within the video area." src="https://cdn-images-1.medium.com/max/1024/1*B-ZsH2LZRy9SM7_8GFofOg.png" /><figcaption>Figure 10. An illustration of how GUI elements are hidden when the cursor is not within the video area.</figcaption></figure><p>Video information is hidden when fullscreen is active, but video controls can still be accessed (see figure 11).</p><figure><img alt="An illustration of how video information is hidden when fullscreen is active." src="https://cdn-images-1.medium.com/max/1024/1*TTaRXYTPtoaNgQ5ozp55NQ.png" /><figcaption>Figure 11. An illustration of how video information is hidden when fullscreen is active.</figcaption></figure><h4>2.2. Building The HTML Structure</h4><p>The first step is to set up a simple HTML structure (see figure 12). The HTML structure in figure 12 includes two external resources, <a href="https://fontawesome.com/">Font Awesome</a>, and <a href="https://fonts.google.com/specimen/Nunito?query=nunito">Google Fonts Nunito</a>. Font Awesome provides a collection of icons that can be displayed by specific classes, and Google Fonts Nunito will be used as the page’s primary font family.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8c800208bcdf20208bd0675e60b8d46/href">https://medium.com/media/e8c800208bcdf20208bd0675e60b8d46/href</a></iframe><p>The next step is to add the divided sections (top, video, bottom) introduced in section 2.1, Mockup Design (see figure 13). This includes a div element with a class called video-player wrapping the three sections. The top section has a class called top , the video section has a class called video-container, and the bottom section has a class called video-information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8417051e155823c22608ac7a8318fe8b/href">https://medium.com/media/8417051e155823c22608ac7a8318fe8b/href</a></iframe><p>The last step is to add the different input and output elements (see figure 14). I won’t go into details about the specific HTML elements because it does not include anything especially advanced.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a675bbcbd8ee808d0ed41cc27f7f796c/href">https://medium.com/media/a675bbcbd8ee808d0ed41cc27f7f796c/href</a></iframe><h4>2.3. Styling The Video Player</h4><p>With the HTML structure in place, it is time to add some styling. Add a separate file called style.css, and link the resource within the HTML document’s head (see figure 15).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e9071557769d9616aae08bc58c30c32/href">https://medium.com/media/2e9071557769d9616aae08bc58c30c32/href</a></iframe><p>Start by adding a couple of general classes to the stylesheet (see figure 16). These classes are not bound to any specific type of conceptual element (fx top, video-container, etc.), and they are meant to be combined within the HTML document.</p><p>For example, btn defines the default appearance of a button within the video player, but it does not specify text color. However, the button’s text color can be defined by combining the class with txt-white.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afa279c0a9c0d8adcb45dd641c6b53ca/href">https://medium.com/media/afa279c0a9c0d8adcb45dd641c6b53ca/href</a></iframe><p>The next step is to add the general classes to the relevant HTML elements. The design contains four different elements that should be displayed using the flex property (see figure 17).</p><p>The top div element should contain a combination of the flex, space-between, and align-center classes to ensure the navigation and ‘additional video options’ are adjusted to their respective side, and aligned centered vertically (see figure 17, line 13).</p><p>The ‘additional video options’ div element should also contain the flex class to ensure buttons and the input sliders’ wrapping div element are displayed inline (see figure 17, line 22).</p><p>The primary video options should contain the flex and space-between classes to ensure the buttons are displayed apart from each other (see figure 17, line 37).</p><p>Last, the div element containing current time info and timeline should contain the classes flex, align-center, and gp-20 (see figure 17, line 44). Align-center ensure the timeline and time info text are centered vertically and gp-20 adds a gap with a size of 20px between the timeline and time info text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/213f7c8e279122e8d10209a7e95fdb15/href">https://medium.com/media/213f7c8e279122e8d10209a7e95fdb15/href</a></iframe><p>The video-container div should contain the relative class to ensure children elements defined as absolute are positioned relative to the video-container div (see figure 18, line 16).</p><p>The primary video options div should contain the absolute, and absolute-center classes to specify the div element should be positioned at the center of the video-container div, and on top of the video element (see figure 18, line 25).</p><p>The time info div should contain the absolute and absolute-bottom to specify it should be positioned at the bottom of the video-container div, and on top of the video element (see figure 18, line 33).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0d3e45dafb52262bdde7fb5d8ab738d/href">https://medium.com/media/f0d3e45dafb52262bdde7fb5d8ab738d/href</a></iframe><p>The next step is to style the button and anchor elements and add text colors. Buttons and anchor elements within the top div tag should contain four different classes: btn; txt-white; txt-white-alpha-hover; font-m; (see figure 19, lines 16–38)</p><p>btn removes the default button design and adds 5 pixels of padding. txt-white sets the text color to white. txt-white-alpha-hover sets the text color to a transparent white when the mouse hovers over the element containing the class. font-m sets the font size to medium.</p><p>Buttons within the primary video options div should also contain four classes: btn; txt-white-alpha; txt-white-hover; font-xl; (see figure 19, lines 55–64)</p><p>txt-white-alpha sets the text color to a transparent white. txt-white-hover sets the text color to white if the mouse hovers over the element. font-xl sets the font size to extra large.</p><p>The div elements showing the current time info and additional video information should contain the txt-white classes to ensure the text is white (see figure 19, lines 77–84).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aadc7128e10cf16f060510e03b6b6b13/href">https://medium.com/media/aadc7128e10cf16f060510e03b6b6b13/href</a></iframe><p>The last general class is pd-20. This class simply adds 20px of padding. Add the class to the top div, the time info div, and the video information div (see figure 20).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32bca94aba3581c52c24939be8e47872/href">https://medium.com/media/32bca94aba3581c52c24939be8e47872/href</a></iframe><p>The next step is to add some width, height, and margin configurations to some of the conceptual elements such as the top div and the video options div (see figure 21). Add the additional CSS of figure 21 to the top of style.css.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1487a9234c43b382ab728702dd92957/href">https://medium.com/media/a1487a9234c43b382ab728702dd92957/href</a></iframe><p>The class timeline should also be added to the timeline’s progress element (see figure 22, line 27).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c49ba45b13f64440cc6a0a1fdfda852/href">https://medium.com/media/1c49ba45b13f64440cc6a0a1fdfda852/href</a></iframe><p>The next step is to add four definitions that add styling to elements with a data-state attribute equal to either none, flex, block, or maximized. Add the CSS in figure 23 to style.css.</p><p>The definitions for none , flex and block are used to either hide or show elements depending on their data-state value, and the definition for maximized is used to ensure the top div element is on top of the video element when it is in fullscreen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/262b40a8b51b679172823116bb99583f/href">https://medium.com/media/262b40a8b51b679172823116bb99583f/href</a></iframe><p>The top div and video-container div should be wrapped inside a new div element with an id called fullscreen-container, and a data-state attribute set to minimized (see figure 24, line 13).</p><p>The last step of styling is to add the data-state attribute none and flex to the div elements (see figure 24, lines 20–78). Some of the elements may already be displayed using the flex property, but the data-state property will be used later in the tutorial.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c13e8e7a2abd18bc20d11d6d20dbac44/href">https://medium.com/media/c13e8e7a2abd18bc20d11d6d20dbac44/href</a></iframe><p>At this point, the video player should look similar to the screenshot in figure 25.</p><figure><img alt="A screenshot of the video player. The image the video element is displaying is from a video created by Artem Podrez." src="https://cdn-images-1.medium.com/max/398/1*111NFKg05j--ELCfnAZc9A.png" /><figcaption>Figure 25. A screenshot of the video player. The image the video element is displaying is from a video created by <a href="https://www.pexels.com/da-dk/video/by-vej-himmel-solnedgang-4832083/">Artem Podrez</a>.</figcaption></figure><h4>2.4. Adding Event And Control Functionality</h4><p>Before adding any specific methods or events, add a new file called video-player.js, and include it within the HTML file (see figure 26).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19b8f4e135a15c41b48960c70b268116/href">https://medium.com/media/19b8f4e135a15c41b48960c70b268116/href</a></iframe><p>Add a method to the javascript file called toggleVisibility(id) (see figure 27). The responsibility of this method is to set the data-state attribute of an element to either ‘none’ or ‘block’ depending on its current data-state value.</p><p>The method should also be added to an empty object called VideoPlayer to have an enclosed scope to call methods from.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dac24a97017fd9815610d67e212e4636/href">https://medium.com/media/dac24a97017fd9815610d67e212e4636/href</a></iframe><p>The next step is to add ids to the wrapping div elements, and the method toggleVisibility(id) to the playback speed slider and volume slider buttons (see figure 27).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89983797d4a45149fc6774c079e6368b/href">https://medium.com/media/89983797d4a45149fc6774c079e6368b/href</a></iframe><p>Before adding the last methods to video-player.js, a couple of ids should be added to the video element, sliders, buttons, and other relevant div elements (see figure 28).</p><p>It should also be noticed the rewind and forward buttons should contain a data-state attribute specifying the seconds they modify the current time property (see figure 28, lines 69–86).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c904a450e68572468f287984725e9c8/href">https://medium.com/media/2c904a450e68572468f287984725e9c8/href</a></iframe><p>The next thing the video player need is the methods controlling the video functionality (see figure 29).</p><p>setVideoElement(videoId) should <em>always</em> be executed before the other methods because some of the other methods are designed to get the video element from a property called videoElement (see figure 29, lines 22–24).</p><p>setPlaybackSpeedEvent(sliderId) binds a slider to set the playback rate property of the video equal to the slider’s value (see figure 29, lines 30–36).</p><p>setVolumeEvent(sliderId) binds a slider with a range between 0–100 to set the volume property of the video equal to the slider’s value (see figure 29, lines 42–48).</p><p>setCurrentTimeEvent(buttonId) binds a button’s click event to increment the current time property of the video based on the button’s data-state attribute (see figure 29, lines 64–61).</p><p>setPlayPauseEvent(buttonId) binds a button’s click event to either play or pause the video based on the video’s paused property (see figure 29, lines 68–77).</p><p>setCurrentTimeInfoEvent(containerId) binds the video’s timeupdate event to set the content of a container equal to the video’s current time (see figure 29, lines 84–90).</p><p>setTimelineEvent(timelineId) binds the video’s timeupdate event to set the value of a progress element to a number between 0–100 based on the video’s current time compared to its duration (see figure 29, lines 98–107).</p><p>setFullscreenEvent(buttonId, containerId) binds a button’s click event to set the container either to fullscreen or not (see figure 29, lines 117–133).</p><p>setOnHoverEvent(containerId) binds mouse events to either hide or show the HTML elements containing the class video-hover-event (see figure 29, lines 143–175).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f8456cfb078188d7669afe64beb5b31/href">https://medium.com/media/3f8456cfb078188d7669afe64beb5b31/href</a></iframe><p>Last, add the class video-hover-event to the div elements with a data-state attribute equal to flex, and add a script tag with the initialization of the video player (see figure 30).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a62388a7968280d84187859c684930ff/href">https://medium.com/media/a62388a7968280d84187859c684930ff/href</a></iframe><p>That is everything! The custom video controls are now connected to the video element.</p><h3>3. Future improvements</h3><p>I have intentionally left out some important elements such as hiding the cursor, the ability to click on the timeline, or formatting the current time. The reason is to keep the article short. Another aspect is support for tablets and mobiles, the design is currently only tested on a desktop.</p><p>Find the complete code at <a href="https://github.com/niiicolai/video-player">https://github.com/niiicolai/video-player</a></p><h3>4. Bibliography</h3><p>Mozilla. No date. a. <em>&lt;video&gt;: The Video Embed element</em>. Available at: <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video</a> (Accessed: October 19, 2022).</p><p>Mozilla. No date. b. <em>HTMLMediaElement</em>. Available at: <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement">https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement</a> (Accessed: October 19, 2022).</p><p>Beaufort, F. (2017) <em>Autoplay policy in Chrome</em>, <em>Chrome Developers</em>. Available at: <a href="https://developer.chrome.com/blog/autoplay/">https://developer.chrome.com/blog/autoplay/</a> (Accessed: October 19, 2022).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8b9a4bf2f76" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/a-tutorial-to-the-html-video-element-b8b9a4bf2f76">Build a Custom Video Player for Your Website</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Tic-Tac-Toe with HTML and JavaScript]]></title>
            <link>https://medium.com/better-programming/create-tic-tac-toe-with-html-and-javascript-ea1c245a9f1f?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1c245a9f1f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 06:02:47 GMT</pubDate>
            <atom:updated>2022-07-20T07:24:52.520Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn to implement the game on your website</h4><figure><img alt="Photo by Pixabay: https://www.pexels.com/da-dk/foto/farve-form-hjerte-kamp-220057/" src="https://cdn-images-1.medium.com/max/1024/1*sCEvZy_elAyRLnjI20qftQ.jpeg" /><figcaption>Photo by Pixabay: <a href="https://www.pexels.com/da-dk/foto/farve-form-hjerte-kamp-220057/">https://www.pexels.com/da-dk/foto/farve-form-hjerte-kamp-220057/</a></figcaption></figure><p>Tic-tac-toe, noughts and crosses, or as we call it in danish “kryds og bolle”. It may seem like one of the most simple games to recreate, but it includes some valuable problems which are great for beginners. This article explains how to create the game with an HTML Canvas element and JavaScript.</p><figure><img alt="A GIF showing the game created in the article." src="https://cdn-images-1.medium.com/max/244/1*XNk50ajM-_RZoC5YMRb8Nw.gif" /><figcaption>A GIF showing the game created in the article.</figcaption></figure><h3>1. Setup the Game</h3><p>The first step is to create an HTML file with the general HTML structure, a canvas element, and a script tag (See figure 1). You could easily implement the JavaScript in a separate file instead, but for the sake of the tutorial, I decided to keep everything in a single file.</p><p>The canvas element will be used as the game’s scene, but you could also implement the game in other elements, such as a div tag, however, it will require some modifications to the code in this tutorial.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c601a0b72c9383c0e4718dacccb0038/href">https://medium.com/media/2c601a0b72c9383c0e4718dacccb0038/href</a></iframe><h3>2. The Game’s Classes</h3><p>Before introducing the JavaScript code defining the game, I want to introduce some of the ideas behind the design. I decided to write the game using two different classes, TicTacToe and Square (See figure 2).</p><p>The class TicTacToe is used to instantiate the game by passing the id of a canvas element to the class’ constructor. This ensure the class can be used with several canvas elements on the same HTML page by simply creating multiple instances of the class for each canvas id.</p><p>The second class Square is used to represent a square on the board. This class keeps track of each square’s position, size, and whether or not a player has clicked on it. It also contains the behavior for drawing the visual of the square and the symbol of the player.</p><figure><img alt="Figure 2: A UML Class diagram showing the classes used in the game." src="https://cdn-images-1.medium.com/max/491/1*fekVylx8ywtfZNXukVslBw.png" /><figcaption>Figure 2: A UML Class diagram showing the classes used in the game.</figcaption></figure><h3>3. The Square Class</h3><p>The Square class is used to instantiate a square object for each square for a 3x3 grid (see figure 3).</p><figure><img alt="Figure 3: An illustration of a Square object instantiated by the Square class." src="https://cdn-images-1.medium.com/max/193/1*KpLjQWwfsGZ2yvCNu94umg.png" /><figcaption>Figure 3: An illustration of a Square object instantiated by the Square class.</figcaption></figure><p>The class will require five properties: x; y; width; height; ctx; actor;</p><p>x and y define the square’s position, width and height define the square’s dimensions, ctx is a reference to the canvas’ rendering interface, and actor specifies the player who filled out the square with either an ‘x’ or ‘o’.</p><p>All the properties, except actor should be passed to the constructor upon instantiation (see figure 4). However, the actor property should be set to null within the constructor to ensure the property exists on Square objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdd76ac3348431ad6d0b79c3092aae6f/href">https://medium.com/media/cdd76ac3348431ad6d0b79c3092aae6f/href</a></iframe><p>The class will also need a method, called draw() which is responsible for drawing a square and the symbol of the player who clicked on it.</p><p>The method calls another method on the ctx property called <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeRect">strokeRect(x, y, width, height)</a> to draw the square (see figure 5, line 20). The ctx property also contains another property called strokeStyle which can be used to set the border’s color (see figure 5, line 19).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d03a86097b396e190b7ab3fa16c325ea/href">https://medium.com/media/d03a86097b396e190b7ab3fa16c325ea/href</a></iframe><p>The draw method uses another method from the ctx property called <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillText">fillText(text, x, y)</a> to write the symbol of the player who clicked on the square (see figure 5, line 27). The text is positioned at the center of the square. The center position can be found by adding the square’s x and y position to half of its width and height (see figure 6). The ctx property contains another property called textAlign which can be set to center to ensure the text is aligned toward the center (see figure 5, line 26).</p><figure><img alt="Figure 6: An illustration of how to find the center position of the square." src="https://cdn-images-1.medium.com/max/412/1*RxtUqvtES-0MkULP_SO2_w.png" /><figcaption>Figure 6: An illustration of how to find the center position of the square.</figcaption></figure><h3>4. The TicTacToe Class</h3><p>The next step is to create the TicTacToe class. The class will require a constructor and three methods: click(event); checkForWinner(); reset();</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecf7dbefe8f2ef829f196e328ec02a12/href">https://medium.com/media/ecf7dbefe8f2ef829f196e328ec02a12/href</a></iframe><h4>4.1 The Constructor</h4><p>The constructor of the TicTacToe class is designed to require a string with the id of a canvas element to be instantiated.</p><p>The id is used to get an HTML canvas element with the specified id using the JavaScript function getElementById(id) and the element is set to a property called canvas (see figure 7, line 15).</p><p>After configuring the canvas property, the property is used to get an instance of its <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">CanvasRenderingContext2D</a>which is set to a property called ctx (see figure 7, line 16). The ctx property provides the interface to draw within the canvas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2abcf12be33915cfc17f24bb365fee88/href">https://medium.com/media/2abcf12be33915cfc17f24bb365fee88/href</a></iframe><p>The next step is to instantiate the Square objects. This is done by looping 3x3 and instantiating a Square object for each iteration which is added to a property called squares (see figure 7, lines 19–28).</p><p>The loop starts by creating a square at the position (x=0, y=0) and then loops from top to bottom until 9 squares are created (see figure 8).</p><figure><img alt="Figure 10: Shows the different win combinations in Tic-tac-toe. The numbers represent the squares’ index in the squares array." src="https://cdn-images-1.medium.com/max/199/1*38W7fSAbbF9wpGZ6zurTXA.png" /><figcaption>Figure 8: An illustration of the 3x3 loop finding each square’s position.</figcaption></figure><p>The class will require three other properties called actors, turn and gameOver (see figure 7, lines 31–37). actors is an array of two strings defining both the number of players and their symbols (‘x’ &amp; ‘o’). turn defines a number between 0–1 which is specifying the actor from the actors array who should have the next turn. gameOver is a bool that returns true if the game is ended.</p><p>The last part of the constructor is to call the square objects draw() method and add a click event listener to the class’ click() method (see figure 7, lines 40–43).</p><h4>4.2 The Click Method</h4><p>The click method is designed to be executed whenever a user clicks on the canvas, and the position of the cursor at that moment can be read from the argument event.</p><p>The first section of the click method includes a guard clause which resets the game if the gameOver property is set to true. This gives the user the ability to start a new game by clicking on the canvas (see figure 9, lines 21–24).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c1a4458156de958f6d9a15b47dfc4af/href">https://medium.com/media/2c1a4458156de958f6d9a15b47dfc4af/href</a></iframe><p>The next part of the method loops all the Square objects and checks if the mouse position was within one of the squares. If the check evaluates to true, the current actor is added to the Square object’s actor property to signal the player has selected the square, and the turn property is set to either 0 or 1 to allow the next player to select a square (see figure 9, lines 27–43).</p><p>Last, the method calls the checkForWinner() method to see if a winner can be found (see figure 9, line 46).</p><h4>4.3 The Check for Winner Method</h4><p>The checkForWinner() method is designed to check if one of the players has selected three squares on a horizontal line, vertical line, or diagonal line (see figure 10).</p><figure><img alt="Figure 10: Shows the different win combinations in Tic-tac-toe. The numbers represent the squares’ index in the squares array." src="https://cdn-images-1.medium.com/max/593/1*q94ofnVUlEF83bvzTredFg.png" /><figcaption>Figure 10: Shows the different win combinations in Tic-tac-toe. The numbers represent the squares’ index in the squares array.</figcaption></figure><p>The beginning of the method defines an array of arrays specifying the different win combinations (see figure 11, lines 26–33).</p><p>The array of arrays is used to loop all the win combinations and check whether or not three squares match one of the combinations (see figure 11, lines 36–66). If the check evaluates to true, the property gameOver is set to true to signal that the next click on the canvas should reset the game.</p><p>The method also draws a line showing the winner combination and writes a text displaying the winner (see figure 11, lines 54–63).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4806977d99f35f73000f16cbca47dd2a/href">https://medium.com/media/4806977d99f35f73000f16cbca47dd2a/href</a></iframe><p>The last part of the method checks whether or not all the squares have an actor which is not null to see if the game should end as a draw. It is important the check is added after checking whether or not the game has a winner to avoid the game evaluating to a draw in cases where a winner is found by selecting the last empty square (see figure 11, lines 69–75).</p><h4>4.4 The Reset Method</h4><p>The reset method is designed to set the properties of an instance of the TicTacToe class to a state where the players can play a new game.</p><p>The method starts by clearing the pixels of the canvas by using the ctx property’s <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clearRect">clearRect(x, y, width, height)</a> method (see figure 12, line 31).</p><p>After clearing the pixels of the canvas, the squares’ actor property is set to null and the squares are drawn within the canvas again.</p><p>Last the method sets turn to 0 to reset the players turn, and set gameOver to false, to signal the click() method can add players to squares again and look for a new winner, or draw.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30befdf625a9cbb0c5384d413777b230/href">https://medium.com/media/30befdf625a9cbb0c5384d413777b230/href</a></iframe><h4>4.5 Starting the Game</h4><p>The game is now ready to be played. Add a new line below the class definitions which creates a new instance of the class (see figure 13, line 13).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4792f9bc76d08e298e5202f8f7eddf23/href">https://medium.com/media/4792f9bc76d08e298e5202f8f7eddf23/href</a></iframe><p>You can find a Github gist with the complete code at <a href="https://gist.github.com/niiicolai/e763fc1bb3481ee908f575a815f95201">this link.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1c245a9f1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/create-tic-tac-toe-with-html-and-javascript-ea1c245a9f1f">Create a Tic-Tac-Toe with HTML and JavaScript</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create the Classic Space Invaders Game with JavaScript and HTML]]></title>
            <link>https://medium.com/better-programming/create-the-classic-space-invaders-game-af087786d63b?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/af087786d63b</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 04:56:31 GMT</pubDate>
            <atom:updated>2022-06-29T05:06:09.444Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tutorial to recreate Space Invaders with HTML and JavaScript</h4><figure><img alt="A GIF showing the game created in the article." src="https://cdn-images-1.medium.com/max/600/1*vcPgmIFzmnUXAvZNALjONg.gif" /><figcaption>A GIF showing the game created in the article.</figcaption></figure><p>Do you want to add a simple 2D game to your website? Or do you want to learn the basics of creating 2D games? This article explains how to recreate the classic Space Invaders game for most modern browsers with only HTML, and JavaScript.</p><h3>Game specifications</h3><p>It can be a great idea to specify the basic features of a game before starting the development to get an overview of the work that needs to be done.</p><h4>The game’s specifications can be defined as follows:</h4><ul><li>The game requires an object that can be moved, drawn to the canvas’ surface, and provides collision checks.</li><li>The enemy and player objects should be able to fire bullets toward each other.</li><li>A bullet object should only be able to move in one direction.</li><li>The player object should only be able to move left and right on the x-axis within the canvas’ borders.</li><li>An asteroid object should consist of several destroyable parts.</li><li>The game should restart if all the enemies are destroyed, or if one of the enemies reaches the position of the player on the y-axis.</li></ul><h4>The game’s objects</h4><p>The class diagram in figure 1 shows an overview of the game’s different classes and their relations. It can for example be seen that all visual objects are created by the base class GameObject, or that the Player class is inheriting properties and behavior from both the SpaceShip and the GameObject class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*WQ4O34FOSJXAXI-O15Otnw.png" /><figcaption>Figure 1: Shows a UML class diagram of the game.</figcaption></figure><h3>The game area</h3><p>The first step is to set up the HTML document with a canvas element (See figure 2). An HTML canvas provides the ability to draw various 2D graphics (Mozilla, 2022a).</p><p>It is for example possible to draw simple shapes or images inside the canvas (Mozilla, 2022b) (Mozilla, 2022c). The canvas element in figure 2, line 9, is defined with the id, width, and height properties.</p><p>The id property is used to reference the canvas element in JavaScript, and the width and height properties simply specify the dimensions of the canvas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8702d273862dc40d9ef809bb43e8a2e/href">https://medium.com/media/f8702d273862dc40d9ef809bb43e8a2e/href</a></iframe><p>The next step is to set up a JavaScript object that can be used to hold different properties and behavior (Mozilla, 2022d). Figure 3, line 12, shows an implementation of the Javascript object, which is called game.</p><p>The idea behind using a JavaScript object to hold properties and behavior in this tutorial is to avoid the game’s logic being available as a lot of global variables and functions.</p><h4>General properties</h4><p>Three properties are added to the game object on lines 15–19, in figure 3. The canvas property refers to the HTML canvas element, ctx refers to the interface, that can be used to draw on the canvas surface (Mozilla, 2022e), and backgroundColor refers to the canvas’ background color.</p><h4>General behavior</h4><p>Five methods are added to the game object on lines 22–43, figure 3. update() defines the game’s continuous behavior, such as drawing elements, moving elements, etc. The first two lines within the update() method (lines 24–25, figure 3) set the background of the canvas to the value of the backgroundColor property.</p><p>Redrawing the background for each time update() is called ensures objects which are moving will be drawn at the new position instead of both the new and old position.keydown() defines what should happen if a key on the keyboard was pressed. init() defines the initialization of the game which starts the game loop. stop() defines how to stop the game loop, and restart() defines how to restart the game.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fa0cc76482903b6c31fbc6df866c92d/href">https://medium.com/media/5fa0cc76482903b6c31fbc6df866c92d/href</a></iframe><h3>Game object</h3><p>A class called GameObject is added to define the general behavior of objects used within the game. The general game object contains five properties. x and y defines the position of the game object. width and height defines the size of the game object’s rectangle, and color defines the color of the rectangle.</p><p>The GameObject class also contains three methods. draw() is used to draw the game object within the canvas. update(dx, dy) moves the game object in any given direction, and collidesWith(obj) returns true if a given game object overlaps with the game object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99aef6126d018710c920c13819bab462/href">https://medium.com/media/99aef6126d018710c920c13819bab462/href</a></iframe><h3>Bullet</h3><p>After adding the GameObject class, a simple Bullet class can be added which inherits the properties and behavior from the GameObject class.</p><p>The Bullet class contains an additional property called dy which is used to define the direction the bullet should move on the y axis. The update(dx, dy) method inherited from the GameObject class is overridden in the bullet class (see lines 22–25, figure 5) to define it always should move towards the given start direction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33404cceafce8737308133e2ac4a6601/href">https://medium.com/media/33404cceafce8737308133e2ac4a6601/href</a></iframe><h3>Spaceship</h3><p>A class called SpaceShip is added to define the general properties and behavior of the player and enemy objects. The SpaceShip class is also a subclass of the GameObject class.</p><p>The SpaceShip class has five additional properties. canvasHeight is used to specify the boundaries for the bullets fired by a SpaceShip. bulletWidth and bulletHeight defines the dimension of the bullets. bulletColor defines the color of the bullets, and bullets is an array used to specify bullets spawned by a SpaceShip.</p><p>The SpaceShip class is designed to override the draw(ctx) method inherited from the GameObject class to implement a check removing bullets outside of the screen and to implement a loop drawing and moving bullets.</p><p>The SpaceShip class also includes an additional method called shoot(dy) which is used to spawn bullets moving towards the given direction on the y axis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a51bc251facb11fed72ffd14f763d499/href">https://medium.com/media/a51bc251facb11fed72ffd14f763d499/href</a></iframe><h3>Player</h3><p>A Player class is added as a subclass of the SpaceShip class to implement properties and behavior specific to the player object.</p><p>The Player class has an additional property called canvasWidth defining the width of the game’s canvas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*2ciXhXCLM37Mszqcr7nb-g.gif" /><figcaption>Figure 7: The green line represents the path where the player can move.</figcaption></figure><p>The property is used to check if the player is outside of the screen on the x-axis. The check is implemented by overriding the update(dy, dx) method inherited from the parent class and adding some additional lines of code moving the player position on the x-axis either to zero or the canvas width minus the player width.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/836ce74a75a35dd9be83a4fb5340fd2c/href">https://medium.com/media/836ce74a75a35dd9be83a4fb5340fd2c/href</a></iframe><h3>Asteroid</h3><p>The last class needed is the Asteroid class. This class is not a subclass of the game object class, however, the class is closely connected to the game object class, because it contains a property called parts which is an array of game objects.</p><p>This design allows an asteroid in the game to be destroyed part by part (see figure 9).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*exy48yA6rBdaXQdQa9uPbA.gif" /><figcaption>Figure 9: Shows an example of the player shooting an asteroid.</figcaption></figure><p>The Asteroid class also contains three methods. draw(ctx) is used to draw the asteroid’s game objects. collidesWith(obj) returns true if one of the asteroid’s game objects collides with the given game object, and removeOnCollide(obj) removes one of the asteroid’s game objects if one of the asteroid’s game objects collides with the given game object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44d219cfd2e092d5ee4a0705db2b1779/href">https://medium.com/media/44d219cfd2e092d5ee4a0705db2b1779/href</a></iframe><h3>Adding parameters for Asteroids and enemies</h3><p>Figure 11, lines 24–45 shows the implementation of the additional required game properties for the asteroids and enemies.</p><h4>Additional Asteroid properties</h4><p>asteroidsParts defines the number of game objects an asteroid is made of, noOfAsteroids is used to define the number of asteroids the game should contain, and asteroidsSpace defines the space between each asteroid.</p><h4>Additional enemy properties</h4><p>enemiesEachLine define the number of enemies that should be spawned on each line. enemyLines defines the number of lines of enemies. enemySpace defines the space between each enemy. enemyFireRate defines how often enemies should fire a bullet, and enemyFireTimer is a variable used to keep track of the time since the last shot. enemyDirection defines if the enemies should move left or right (left = -1, right = 1), and enemyStep defines how much the enemies should be moved on the y-axis when reaching either the left or right side of the canvas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f4be29cedf1f5d01e24c0f78500edbf/href">https://medium.com/media/6f4be29cedf1f5d01e24c0f78500edbf/href</a></iframe><h3>Initialize objects</h3><p>It is now possible to complete the game object’s init() method (see lines 27–62, figure 12). The method should include some additional lines of code defining how to create the player, the enemies, and the asteroids, at their start position.</p><p>This design allows using the game object’s restart() method, to reset the game to the initial state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43b62adae11edba542561f6c2d45dbe8/href">https://medium.com/media/43b62adae11edba542561f6c2d45dbe8/href</a></iframe><h3>Detect keyboard events</h3><p>The game object’s keydown() method is called every time a user presses a key on the keyboard (see lines 23–36, figure 13). The specific key pressed can be read as a number from the argument e by reading its property keyCode.</p><p>For example, the number 37 defines the left arrow key, and the number 39 defines the right arrow key. The keydown() method is designed to check if the user pressed one of the arrow keys, or the A-key and D-key, which moves the player either left or right. It also includes an additional check to detect whenever the user presses the space key which spawns a bullet at the player’s position.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae351c6d3268e96701f1bcffd2c4e9b6/href">https://medium.com/media/ae351c6d3268e96701f1bcffd2c4e9b6/href</a></iframe><h3>Updating the game</h3><p>The final method of the game that needs modification is the game object’s update() method (see lines 23–154, figure 14).</p><h4>Draw the player, asteroids, and enemies</h4><p>Lines 29–38, figure 14, simply call the draw(ctx) method on the different objects to ensure they are drawn within the canvas. Line 39, figure 14, in the same loop drawing the enemies, moves the enemies towards the direction specified in the enemyDirection property.</p><h4>Enemy count check</h4><p>Lines 43–46, figure 14, check if the game object’s enemies array is empty, and restarts the game if the check evaluates to true. This check could include some additional code decreasing a player&#39;s life property until it reaches zero, which then would restart the game.</p><h4>Enemy movement</h4><p>Lines 49–91, figure 14, check if the enemyDirection property is either 1 or -1. If the property is 1, the method finds the enemy closest to the right side of the screen, and if that enemy reaches the right side, the method sets the enemyDirection to -1 and moves all the enemies down by the value of enemyStep. The opposite happens if the value of enemyDirection is -1.</p><h4>Enemy random shot</h4><p>Lines 94–99, figure 14, increase the enemyTimer property until a random enemy is selected to fire a shot that moves towards the player.</p><h4>Bullet collision checks</h4><p>Lines 102–154, figure 14, show four loops with almost the same behavior. For example, the first loop, lines 101–110, figure 14, loops through all player bullets and checks if they collide with one of the astroids’ game objects. The third loop, lines 125–134, figure 14, loops through all player bullets and checks if one of the bullets collides with one of the enemies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3df1498dfa4632699cd9d19263af51ae/href">https://medium.com/media/3df1498dfa4632699cd9d19263af51ae/href</a></iframe><p>The complete code can be found at <a href="https://gist.github.com/niiicolai/325c1f4f113569a3857f2ece01f5ba65">this link.</a></p><h3>Bibliography</h3><p>Mozilla. 2022a. Canvas API. <br><a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API</a>. <br>Accessed: 28th June 2022</p><p>Mozilla. 2022b. Using images. <br><a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images">https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images</a>. <br>Accessed: 28th June 2022</p><p>Mozilla. 2022c. Drawing shapes with canvas. <br><a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes">https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes</a>. <br>Accessed: 28th June 2022</p><p>Mozilla. 2022d. Working with objects. <br><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects</a>.<br>Accessed: 28th June 2022</p><p>Mozilla. 2022e. CanvasRenderingContext2D.<br><a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D</a>.<br>Accessed: 28th June 2022</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af087786d63b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/create-the-classic-space-invaders-game-af087786d63b">Create the Classic Space Invaders Game with JavaScript and HTML</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An introduction to movement in 2D games]]></title>
            <link>https://medium.com/@niiicolai/an-introduction-to-movement-in-2d-games-281ff3b58533?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/281ff3b58533</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[processing]]></category>
            <category><![CDATA[2d-movement]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Fri, 20 May 2022 02:53:27 GMT</pubDate>
            <atom:updated>2022-05-20T03:00:57.394Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn the basics of moving objects in 2D space</h4><figure><img alt="Photo by MART PRODUCTION from Pexels" src="https://cdn-images-1.medium.com/max/1024/1*KlwmLbU3qzZ4lJZWt-tzWQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/da-dk/@mart-production?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">MART PRODUCTION</a> from <a href="https://www.pexels.com/da-dk/foto/matematik-tavle-skrevet-formel-8471854/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Do you want to get a better understanding of the concepts behind moving 2D objects in games? This article aims to explain some of the concepts behind moving a 2D object in a game by simple Euclidean vector operations.</p><p>The examples are presented with the programming language Java and the <a href="https://processing.org/">Processing library</a>, but the concepts could be applied in other programming languages as well.</p><h3>Environment and simple movement</h3><p><em>This section will give a short description of what a Cartesian coordinate system is, and how it will be used further in the article to present a simple environment in a 2D game.</em></p><p>I think most people have heard of a Cartesian coordinate system (see figure 1). A Cartesian coordinate system is a coordinate system with two coordinate axes that intersect at origo <em>(0, 0), </em>and it can be used to represent two-dimensional but also three-dimensional space if a third axis is added (Wikipedia, 2022a).</p><figure><img alt="Figure 1: A Cartesian coordinate system with two points, P1 and P2." src="https://cdn-images-1.medium.com/max/333/1*WQxWMoHLIS-_dKEY33UaKw.png" /><figcaption><strong>Figure 1:</strong> A Cartesian coordinate system with two points, P1 and P2.</figcaption></figure><p>Figure 1 shows a Cartesian coordinate system with three points, Origo, P1, and P2. Another perspective of the coordinate system and the points could be to imagine the coordinate system as a 2D space in a game and the points as positions of different objects such as players. Figure 2 shows an illustration of this idea, the coordinate system’s green background represents grass, and P1 and P2 are now Player 1 and Player 2 respectively.</p><figure><img alt="Figure 2: A Cartesian coordinate system with a green background representing grass and two points representing the positions of players in a game." src="https://cdn-images-1.medium.com/max/337/1*9adHHOBYfQw5oTw-XeAfNw.png" /><figcaption><strong>Figure 2:</strong> A Cartesian coordinate system with a green background representing grass and two points representing the positions of players in a game.</figcaption></figure><p>The players could be represented as a class in Java called Player with two float properties called x and y specifying the player’s current point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f808559f85eceb3e30b264eae2c75b1/href">https://medium.com/media/9f808559f85eceb3e30b264eae2c75b1/href</a></iframe><p>The players can be moved anywhere within the grass field by simply giving them a new point using the setter methods setX(x) and setY(y) (see figure 4).</p><figure><img alt="Figure 4: A GIF showing the players being set to new positions." src="https://cdn-images-1.medium.com/max/404/1*yBnAaiElYpK6afvl20E01g.gif" /><figcaption><strong>Figure 4:</strong> A GIF showing the players being set to new positions.</figcaption></figure><p>But what if the players should move more smoothly instead of teleporting? The answer is simple, the coordinates of a player should <em>slowly </em>increase or decrease instead (see figure 5).</p><figure><img alt="Figure 5: A GIF showing the players’ position slowly increasing over time." src="https://cdn-images-1.medium.com/max/406/1*2Bj2OyfRE6FzzIgHY05V9g.gif" /><figcaption><strong>Figure 5:</strong> A GIF showing the players’ position slowly increasing over time.</figcaption></figure><p>To add smooth movement to the player class, extra properties are required which specify the number of units, the player should move along the x-, and y-axis. These properties could be called xDir and yDir , meaning x-direction and y-direction (see figure 6).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/744d3c254c92fb9ebe08510d52eaee07/href">https://medium.com/media/744d3c254c92fb9ebe08510d52eaee07/href</a></iframe><h3>Moving towards objects</h3><p><em>This section will describe how to calculate a direction from one object to another, and how it can be used to move the objects towards each other.</em></p><p>What if the two players wanted to move toward each other, how would the direction be calculated? This is where Euclidean vectors come into the picture. Wikipedia (2022b) defines a vector as a geometric object with a length and direction. Figure 7 shows a vector <strong><em>v</em></strong> pointing toward player 1, and vector <strong><em>u</em></strong> pointing toward player 2.</p><figure><img alt="Figure 7: The red arrow from origo (0, 0) represents a vector denoted v and the blue arrow represents a vector denoted u." src="https://cdn-images-1.medium.com/max/343/1*VgmzGvzBAqyfNhnOq5mtuQ.png" /><figcaption><strong>Figure 7:</strong> The red arrow from origo (0, 0) represents a vector denoted v and the blue arrow represents a vector denoted u.</figcaption></figure><p>The values of a vector to a specific point can simply be represented by the values of the point, for example, the vectors <strong><em>v</em></strong> and <strong><em>u </em></strong>in figure 7 would be defined mathematically by player 1 and player 2’s point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*__5OnrNuX7PVynOK0i-VwQ.png" /></figure><p>To move player 1 towards player 2, it is required to know how many units player 1 has to move on the x-, and y-axis. If player 1 moved to player 2’s point, this would mean that player 1 now has the same point as player 2, and the required vector added to vector <strong><em>v </em></strong>should give a sum of vector <strong><em>u</em>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*DktdDymLs3s-UjcY2W6orQ.png" /></figure><p>The equation above could be solved by the following rearrangement and is the same as subtracting vector <strong><em>v</em></strong> from <strong><em>u</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*Dsdjif3yaE3F4RpDQvMfZw.png" /></figure><p>Player 1’s vector <strong><em>v</em></strong> could now slowly be increased by 100 units of x and 80 units of y, and it would reach player 2’s position. If player 2 should move to player 1, it would simply require subtracting vector <strong><em>u</em></strong> from <strong><em>v</em></strong> instead.</p><figure><img alt="Figure 8: The vector denoted x has a length equal to the space between the two players and a direction pointing towards player 2." src="https://cdn-images-1.medium.com/max/339/1*3vrS7V6vRhzKmvKe621nWg.png" /><figcaption><strong>Figure 8:</strong> The vector denoted x has a length equal to the space between the two players and a direction pointing towards player 2.</figcaption></figure><p>The concept of getting a direction from one player to another could be added as a method in the player class called getVectorDirectionTo(player), returning a vector object (See figure 9).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f4d410a8a4ec4761ca8f806c42f83c8/href">https://medium.com/media/9f4d410a8a4ec4761ca8f806c42f83c8/href</a></iframe><p>The direction vector specifies the number of units player 1 has to travel on the x-, and y-axis, but how can it be ensured player 1 moves on a straight line directly towards player 2? Vector <strong><em>x</em></strong> could be normalized into a unit vector. Wikipedia (2022c) defines a unit vector as a vector with a maximum length of 1, and it can be calculated by dividing a vector by its length:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*PqzRorKIxkDYrPU_M0HbAA.png" /></figure><p>The unit vector of vector <strong><em>x</em></strong> can be calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*jDm1hu6Ln-QlUjh6CQQN4A.png" /></figure><p>This means that instead of having a vector that has a length equal to the space between the two players, the vector now has a length less than 1 but still points towards player 2, and therefore very conveniently can be slowly added to player 1’s position over time until player 1 has reached player 2’s position (See figure 10).</p><figure><img alt="Figure 10: The small blue arrow starting at player 1 and pointing toward player 2 represents the unit vector of vector x." src="https://cdn-images-1.medium.com/max/408/1*sIjM_8vQUpToMQSdhA6j3A.gif" /><figcaption><strong>Figure 10:</strong> The small blue arrow starting at player 1 and pointing toward player 2 represents the unit vector of vector x.</figcaption></figure><p>The normalized direction vector method could be implemented very similarly to the last implemented method called getVectorDirectionTo(player). The values of the direction vector could be calculated using the same lines of code from the method getVectorDirectionTo(player) and used to calculate length, and thereby the normalized vector (see figure 11).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc4cd6bec44d2e7ed8d3b17512157f0/href">https://medium.com/media/2dc4cd6bec44d2e7ed8d3b17512157f0/href</a></iframe><p>The final player script can be found at <a href="https://gist.github.com/niiicolai/fc5b5771cf70a4f2bc692c9a95a7e583">this link.</a></p><h3>Summary</h3><p>An object with a position (x, y) can be teleported anywhere in a 2D space by giving it a new point, and it can be moved slowly by increasing or decreasing its current position. The direction from object A to another object B can be calculated by subtracting a vector to object A from a vector to object B (direction = <strong><em>b-a</em></strong>). The unit vector of the direction can be used to calculate a vector with a maximum length of 1, which can be used to ensure an object moves on a straight line towards another.</p><h3>Bibliography</h3><p>En.wikipedia.org. (2022a). <em>Cartesian coordinate system — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Cartesian_coordinate_system">https://en.wikipedia.org/wiki/Cartesian_coordinate_system</a>&gt; [Accessed 19 May 2022].</p><p>En.wikipedia.org. (2022b). Euclidean vector<em> — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Euclidean_vector">https://en.wikipedia.org/wiki/Euclidean_vector</a>&gt; [Accessed 17 May 2022].</p><p>En.wikipedia.org. (2022c). <em>Unit vector — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Unit_vector">https://en.wikipedia.org/wiki/Unit_vector</a>&gt; [Accessed 19 May 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281ff3b58533" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create the Classic Ping-pong Game With Java]]></title>
            <link>https://medium.com/better-programming/create-the-classic-ping-pong-game-3aea1f7b16e6?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aea1f7b16e6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Tue, 17 May 2022 04:59:13 GMT</pubDate>
            <atom:updated>2022-05-17T05:08:45.575Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Java and Processing library tutorial</h4><figure><img alt="A GIF showing Ping-pong." src="https://cdn-images-1.medium.com/max/358/1*D03gtwOfjTPb6TLb7hW2BA.gif" /><figcaption>A GIF showing the Ping-pong game from this article.</figcaption></figure><p>Are you looking for a tutorial explaining how to recreate the classic Ping-pong game? Then, look no further, this article focuses on recreating the game using the Processing library and Java. I have also written another article on <a href="https://medium.com/better-programming/create-the-classic-snake-game-with-processing-and-java-18f9db48fac4">how to recreate the classic snake game</a> if you want to create another game.</p><h3>1. Download and install Processing</h3><p>To download Processing go to <a href="https://processing.org/download">processing.org/download</a> and choose the version matching the preferred platform.</p><h3>2. What is Processing?</h3><p>Processing provides a graphical library and an integrated development environment (IDE) and it uses the programming language Java (Wikipedia, 2022a).</p><h3>3. Game Requirements</h3><p>The requirements of the game are presented in two different parts. The first part describes the visual requirements related to representing the players, ball, and environment. The second part describes the functional requirements of how the different objects and the application should behave.</p><h4>3.1 Visual requirements</h4><ul><li>The player object should be represented by a rectangle.</li><li>The ball object should be represented by a circle.</li><li>The game should contain two text elements showing each player’s score.</li></ul><h4>3.1 Functional requirements</h4><ul><li>The player object should only be able to move on the y-axis.</li><li>The ball object should be able to move on the x-, and y-axis.</li><li>The ball object should change its direction on the x-axis to the opposite if it overlaps with a player object.</li><li>The ball object should change its direction on the y axis to the opposite if it moves out of the screen on the y-axis.</li><li>The ball object’s position and direction should be reset if it moves out of the screen on the x-axis.</li><li>A player gets a point whenever the ball moves out of the screen on the opposite side.</li><li>The first player should be controlled by the keyboard and the second player by the computer.</li></ul><h3>4. Game Objects</h3><p>The game will contain two different classes, one to represent a player object, and another to represent the ball object. Figure 1 shows a UML class diagram containing the two classes. For those of you never heard of a UML class diagram, it is simply a diagram with a system’s classes, properties, methods, and relations (Wikipedia, 2022b).</p><figure><img alt="Figure 1: A UML Class diagram showing the two classes used in the Ping-pong game." src="https://cdn-images-1.medium.com/max/743/1*O6QWaNLHKy_FDdIDqwSp3A.png" /><figcaption><strong>Figure 1: </strong>A UML Class diagram showing the two classes used in the Ping-pong game.</figcaption></figure><h4>4.1 The player object</h4><p>The player class will be used to create objects for both players, it is, therefore, important the position and y-direction are unique for each player, but it can be argued that width, height, and boundary could be static variables since the values are the same on all objects. Figure 2 illustrates the idea behind the positioning of the players and the boundaries of their movement.</p><figure><img alt="A GIF showing the properties of each player and the path (the red line) they can move." src="https://cdn-images-1.medium.com/max/354/1*zkqNiw_HBiFvZdsjUhMswQ.gif" /><figcaption><strong>Figure 2:</strong> A GIF showing the properties of each player and the path (the red line) they can move.</figcaption></figure><p><strong>4.1.1. Player Properties</strong></p><p>The class requires five properties (see figure 1), and each of these properties has the following purpose:</p><ul><li>position — A PVector that defines the player’s x and y position.</li><li>yDir — A float that defines the direction and speed of the player’s movement.</li><li>w — A float defining the width of the player’s rectangle.</li><li>h — A float defining the height of the player’s rectangle.</li><li>b— A float defining the boundaries of the player’s movement.</li></ul><p>The implementation of the properties in the player class can be seen in figure 3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8018e79f625696709679275ed20ea4e1/href">https://medium.com/media/8018e79f625696709679275ed20ea4e1/href</a></iframe><p><strong>4.1.2. Player Methods</strong></p><p>The class also requires five methods (see figure 1), and each of these properties has the following purpose:</p><ul><li>update() — A void method that is used to update the behavior of the player related to movement, boundaries check, and drawing of the visual object.</li><li>setDirection(yDir) — A setter method that is used to update the player object’s direction on the y-axis.</li><li>getPosition() — A getter method that returns the player object’s position.</li><li>getHeight() — A getter method that returns the player object’s height.</li><li>getWidth()— A getter method that returns the player object’s width.</li></ul><p>The Player class also needs a constructor to set the initial values of the position and direction on the y-axis. The constructor’s argument is designed with floats to represent the start position which within the constructor is used to create an instance of a new PVector object for the player’s position.</p><p>This will ensure player objects do not refer to the same PVector object in memory which could have been the case if several player objects were given the same PVector object on instantiation.</p><p>The getter method for the direction will allow the direction to be set on an object outside the class, and the setter methods for position, height, and width will allow these properties to be read on an object outside the class (see the implementation in figure 4).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e787fd86eb82f544e3bea6960fc91c7d/href">https://medium.com/media/e787fd86eb82f544e3bea6960fc91c7d/href</a></iframe><p>The last method needed in the player class is the update() method. Figure 5 shows the implementation of the method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9456afcc0e5687d0c4b94b58011ee464/href">https://medium.com/media/9456afcc0e5687d0c4b94b58011ee464/href</a></iframe><p>Its behavior can be described as follows:</p><ul><li>Line 10 — This line will increase the player’s y position if the value of ydir is positive and decreases the player’s y position if the value of ydir is negative.</li><li>Line 14 — The first line checks if the player’s y position is less than the value of b which was used to define the boundaries of the player’s movement. Or in other words, if the player has reached its boundary at the top of the screen.</li><li>Line 16 — Reset the player’s y position to value of b to prevent it from moving any further toward the top of the screen.</li><li>Line 19 — A similar check to line 14 but checks if the player has reached the bottom of the screen instead. This check includes the player’s height and the value of b to ensure the rectangle stops at the correct position (See figure 6 for an explanation).</li><li>Line 21 — Reset the player’s y position at the bottom of the screen to prevent it from moving out of the screen on the y-axis.</li></ul><figure><img alt="The player object is moved at the anchor point (the value of the position property) and it should therefore stop at the screen height subtracted by b and h to ensure the rectangle stop when its bottom side reaches the boundary." src="https://cdn-images-1.medium.com/max/233/1*P0PDw4bywL3o9TFGWNP42A.png" /><figcaption><strong>Figure 6:</strong> The player object is moved at the anchor point (the value of the position property) and it should therefore stop at the screen height subtracted by b and h to ensure the rectangle stop when its bottom side reaches the boundary.</figcaption></figure><p>A final example of the player class can be found at <a href="https://gist.github.com/niiicolai/132af98673f96ea33671593c769ad389">this link.</a></p><h4>4.2 The ball object</h4><p>The ball class is very similar to the player class, but it is allowed to move on both the x- and y-axis. Figure 7 illustrates how the values of the ball’s position and direction change while it moves.</p><figure><img alt="A GIF showing the properties of the ball object." src="https://cdn-images-1.medium.com/max/356/1*eZVYlENJnOsIzNCrzmgOzw.gif" /><figcaption><strong>Figure 7:</strong> A GIF showing the properties of the ball object.</figcaption></figure><p><strong>4.1.1. Ball Properties</strong></p><p>Figure 1 shows the ball class requires four properties which can be described as follows:</p><ul><li>position — A PVector that defines the ball’s x and y position.</li><li>direction — A PVector that defines the direction and speed of the ball’s movement.</li><li>d — A float defining the diameter of the ball’s circle.</li><li>s — A float defining the start speed of the ball.</li></ul><p>The implementation of the ball’s properties can be seen in figure 8.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a9c8ad479dd227e43093c80508a1ee0/href">https://medium.com/media/3a9c8ad479dd227e43093c80508a1ee0/href</a></iframe><p><strong>4.1.2. Ball Methods</strong></p><p>The ball class should also have five methods as the player class which can be described as follows:</p><ul><li>update() — A void method updating the movement, boundaries, and visuals of the ball.</li><li>getPosition() — A getter method that returns the ball’s position.</li><li>resetMovement() — A void method that reset the ball’s position to the center of the screen and resets its direction to a random value.</li><li>setDirection(x) —A setter method that sets the x-direction of the ball.</li><li>overlapsWith(player) — A boolean method returning true if the ball overlaps with the given player.</li></ul><p>The implementation of the ball’s constructor and the methods, getPosition(), resetMovement(), setDirection(x), and update() can be seen in figure 9.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a595c858385b05d5181b30eecb688dae/href">https://medium.com/media/a595c858385b05d5181b30eecb688dae/href</a></iframe><p><strong>4.1.2. Collision Methods</strong></p><p>The last method that should be implemented in the ball class is the overlapsWith(player) method. Before I show the implementation I want to give a short description of the mathematical ideas behind the solution.</p><p>Figure 10 shows the ball drawn within a coordinate system, and the anchor point is positioned at origo. The anchor point is equal to the position property of the ball.</p><p>Each vector/arrow in the figure points towards a point relative to the anchor point which should be used in the collision check. The points can be calculated by the formula for converting degrees to radians and the rotation matrix.</p><figure><img alt="The figure shows the ball drawn within a coordinate system. The anchor point is the ball’s position, and each vector/arrow points to a point relative to the ball’s anchor point. Each vector is rotated 45 degrees." src="https://cdn-images-1.medium.com/max/531/1*05icJeA0UlSR3Mk6PZIWqg.png" /><figcaption><strong>Figure 10:</strong> The figure shows the ball drawn within a coordinate system. The anchor point is the ball’s position, and each vector/arrow points to a point relative to the ball’s anchor point. Each vector is rotated 45 degrees.</figcaption></figure><p>The formula for converting degrees to radians can be defined as (Wikipedia, 2022c):</p><figure><img alt="The formula for converting degrees to radians." src="https://cdn-images-1.medium.com/max/269/1*IDZl8L7VZiMOIll7-eXLsg.png" /></figure><p>The formula for rotating a vector <strong><em>v, </em></strong>θ radians can be defined as (Wikipedia, 2022d):</p><figure><img alt="The formula for rotating a vector v, θ radians" src="https://cdn-images-1.medium.com/max/424/1*sCz_s5D6xkReNbq_lmQgVQ.png" /></figure><p>The points calculated with the formulas above are used to check if one of them is between the corner points of a player which would mean the ball is overlapping with the player (See figure 11).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*mwHzxTiDzaf0Ew1JIq8kVw.png" /><figcaption><strong>Figure 11: </strong>The figure shows a player object overlapping with the ball object. It also shows each corner point of a player based on its position, width, and height property.</figcaption></figure><p>Line 24, in figure 12 shows the implementation of the formula used to convert degrees to radians, and line 28–29, in figure 12 shows the implementation of the rotation matrix used to rotate a 2D vector 45 degrees.</p><p>Line 33–34, in figure 12 shows the check that returns true if the points are within the player’s corner points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ae88801f3e09ce87e76085717c3abc5/href">https://medium.com/media/5ae88801f3e09ce87e76085717c3abc5/href</a></iframe><p>A final example of the ball class can be found at <a href="https://gist.github.com/niiicolai/b7bf280f984e6902c4a4573db6987864">this link.</a></p><h3>5. Setting up Processing control flow</h3><p>The application needs three Processing methods, the setup() method which is executed once the application starts (Processing.org, 2022a), the draw() method which is executed once every frame until stopped (Processing.org, 2022b), and the keyPressed() method which is executed when a key is pressed (Processing.org, 2022c).</p><h4>5.1 Global properties</h4><p>The game requires a couple of global properties used to reference the player objects, the ball object, speed, and player scores (See figure 13).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d49beaff070d61084ca85d44b7e71b32/href">https://medium.com/media/d49beaff070d61084ca85d44b7e71b32/href</a></iframe><h4>5.2 Setup</h4><p>The setup() method is used to initialize player and ball instances and set the screen size (see figure 14).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ca366af7e321f5efd4f99c14ccce9a7/href">https://medium.com/media/6ca366af7e321f5efd4f99c14ccce9a7/href</a></iframe><h4>5.3 Draw</h4><p>The draw() method is used for the game’s repeating logic. Line 20–33 in figure 15 shows an if- and else if-statement checking if the ball is outside the screen, and if that is the case, one of the players gets one point and the ball’s position and direction are reset. Line 36–29 in figure 14 shows a check that evaluates to true if one of the players overlaps with the ball which inverts the ball’s x-direction. Line 43–58 in figure 14 shows a small implementation of how the computer controls its player object (p2) and line 61–64 shows the implementation of the players’ score text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c851cdb4444e678ecae0124bf7a86d2c/href">https://medium.com/media/c851cdb4444e678ecae0124bf7a86d2c/href</a></iframe><h4>5.4 KeyPressed</h4><p>The last code the game need is for the functionality handling the keyboard events that move the p1 object (See figure 16).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d60ea619ec408dc2cafd5b1401c1b35/href">https://medium.com/media/2d60ea619ec408dc2cafd5b1401c1b35/href</a></iframe><h3>6. Summary</h3><p>The Ping-pong game in the article is created using the Processing library and Java. It contains two classes, a Player class used to represent player objects and a Ball class used to represent the ball object.</p><p>The classes are used together within Processing’s setup() draw(), and keyPressed() methods to set up the continuous behavior and the structure of the game. The first player object can be controlled by the keyboard using s and w, and the second player is controlled by the computer.</p><p>An example of the complete game can be found at <a href="https://gist.github.com/niiicolai/246eba2b9d8c76355e5e89b5d8af6d95">this link.</a></p><h3>Bibliography</h3><p>En.wikipedia.org. (2022a). <em>Processing (programming language) — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Processing_(programming_language)">https://en.wikipedia.org/wiki/Processing_(programming_language)</a>&gt; [Accessed 30 April 2022].</p><p>En.wikipedia.org. (2022b). <em>Class diagram — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Class_diagram">https://en.wikipedia.org/wiki/Class_diagram</a>&gt; [Accessed 16 May 2022].</p><p>En.wikipedia.org. (2022c). <em>Radian — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Radian">https://en.wikipedia.org/wiki/Radian</a>&gt; [Accessed 17 May 2022].</p><p>En.wikipedia.org. (2022d). <em>Rotation matrix — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Rotation_matrix">https://en.wikipedia.org/wiki/Rotation_matrix</a>&gt; [Accessed 17 May 2022].</p><p>Processing.org. (2022a). setup() [online] Available at: &lt;<a href="https://processing.org/reference/setup_.html">https://processing.org/reference/setup_.html</a>&gt; [Accessed 30 April 2022].</p><p>Processing.org. (2022b). draw() [online] Available at: &lt;<a href="https://processing.org/reference/draw_.html">https://processing.org/reference/draw_.html</a>&gt; [Accessed 30 April 2022].</p><p>Processing.org. (2022c). keyPressed() [online] Available at: &lt;<a href="https://processing.org/reference/keyPressed_.html">https://processing.org/reference/keyPressed_.html</a>&gt; [Accessed 30 April 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aea1f7b16e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/create-the-classic-ping-pong-game-3aea1f7b16e6">Create the Classic Ping-pong Game With Java</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop worrying and start coding: Python Edition]]></title>
            <link>https://medium.com/@niiicolai/stop-worrying-and-start-coding-python-edition-2c8b75e9cd0f?source=rss-188a6546660a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c8b75e9cd0f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <dc:creator><![CDATA[Nicolai Andersen]]></dc:creator>
            <pubDate>Sat, 14 May 2022 23:38:11 GMT</pubDate>
            <atom:updated>2022-05-15T03:14:33.004Z</atom:updated>
            <content:encoded><![CDATA[<h4>A beginner’s guide to getting started with Python in 8 minutes.</h4><figure><img alt="Photo by Ekaterina Belinskaya from Pexels" src="https://cdn-images-1.medium.com/max/1024/1*cdIh9PSdMr3qx2U6m8-aLA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/da-dk/@ekaterinabelinskaya?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Ekaterina Belinskaya</a> from <a href="https://www.pexels.com/da-dk/foto/skilt-vejskilt-tekst-information-4700118/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h3>1. Introduction</h3><p>Learning new skills in life can both be hard and provoke anxiety, especially if you are studying for an exam, and learning to code is no different. So, what can you do when you hit a wall and may not believe there is an end to the road? Should you follow tutorials on Youtube until you exhaust yourself? Or maybe should you read every page of the material you were given by your teacher or instructor? While I do not believe there is a universal answer to these questions since everyone is different, I do believe that <em>having a strategy is the way to go</em>. A strategy I often use when I’m trying to learn something I find overwhelming is to buy or borrow books that offer to learn you a skill within some <em>timeframe</em>, for example, Learn Python in one day. While these books may not provide every detail of a topic, I found that they can be really useful to give an overview of core concepts and decrease the level of difficulty reading more comprehensive material. Based on this idea, the article aims to provide the most general concepts necessary to learn to stop worrying and start coding: Python.</p><figure><img alt="“This is fine”-meme" src="https://cdn-images-1.medium.com/max/717/1*wBh5IQW2tpBQAPIT6Hus0A.jpeg" /><figcaption>Meme generated with <a href="https://imgflip.com/">https://imgflip.com/</a></figcaption></figure><h4>1.1 Getting started with Python</h4><p>To get started with Python, you have to ensure it is installed on your local machine. Go to <a href="https://www.python.org/downloads/">python.org/downloads</a> to download Python for the preferred platform. Installing Python gives access to entering the python command in a terminal program such as Command prompt on Windows. I highly encourage you to try some of the examples in this article while reading to get a better understanding of what is going on. If you open a terminal program and simply type python the terminal will launch something called an interactive session where it is possible to run and write Python code (Ramos, n.d).</p><h3>2. Data types</h3><p>Wikipedia (2022a) describes a data type as a way to inform the compiler or interpreter of the intention with the data. While this may sound complex, it simply refers to that information such as numbers, letters, or even positions are divided into different types with different meanings, methods, and properties, and that the system processing the code (the compiler or interpreter) should know each type used within the program. But what is a compiler or interpreter? Wikipedia (2022b) describes an interpreter as a program that directly executes code without the requirement of compiling the code to machine language, and Wikipedia (2022c) describes the compiler as a program translating code into another language, for example, machine language. While the interpreter and compiler are important concepts related to coding, the crucial concept to understand in this section is that information is organized into different types. There exist many types within the different programming languages, Wikipedia (2022a) describes integer, float, character, and boolean as some of the basic types supported in most programming languages. It should be noticed that the data type character is not supported in Python but is represented as the data type string instead with a length of one (Python.org, 2022b).</p><h4>2.1 Variables</h4><p>A topic closely related to data types is variables. Wikipedia (2022e) describes variables as containers for a specific type of data which is referred to by a symbolic name. For example, if an integer of some value is required within a program, a variable of type integer could be defined with some sort of name describing the purpose of the integer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6b4061a1dc0a2f7157cb80da71c6df9/href">https://medium.com/media/e6b4061a1dc0a2f7157cb80da71c6df9/href</a></iframe><h4>2.2 Integer</h4><p>An integer is a whole number without a fraction part (Wikipedia 2022d). This simply means that data of the type integer only can be numbers such as -33, 2, 4, etc. Figure 2 shows an example of how to set a variable to an integer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efb4527ba50b718dde67899a113846fe/href">https://medium.com/media/efb4527ba50b718dde67899a113846fe/href</a></iframe><h4>2.3 Float</h4><p>A float is a floating-point number (Python.org, 2022a). The data type float can be used to define the values of numbers with greater precision than integers because it has a fraction part. Figure 3 shows an example of how to set a variable to a float.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcd3d58691dec6e0d1456553961e9e67/href">https://medium.com/media/dcd3d58691dec6e0d1456553961e9e67/href</a></iframe><h4>2.4 String</h4><p>The string data type can be used to represent text (Python.org, 2022b). The data type can both contain letters, numbers, and symbols. Figure 4 shows an example of how to set a variable to a string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c371ed6244729f4b5817ecd6f529a447/href">https://medium.com/media/c371ed6244729f4b5817ecd6f529a447/href</a></iframe><h4>2.5 Boolean</h4><p>The boolean data type can be used to represent a value that is either true or false (Wikipedia, 2022f). The data type can be used to maintain a value of state within applications, for example, a system handling user login could have a variable of the type booleancalled signed_in that is set to true if the user is signed in and otherwise is set to false. Figure 5 shows an example of how to set a variable to a boolean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7193188d1852f16575a5fa2fef930ad9/href">https://medium.com/media/7193188d1852f16575a5fa2fef930ad9/href</a></iframe><h4>2.6 Arithmetic operations</h4><p>Arithmetic operations include addition, subtraction, multiplication, division, etc. (Wikipedia, 2022g). Arithmetic operations are very common when writing code, for example, two floats may be multiplied to calculate a total price if one of them contained a unit price and the other a quantity. Python also supports other arithmetic operations than the aforementioned, for example, the modulo operator % can be used to calculate the remainder (Python.org, 2022a).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c7d6f9ed8d96408caba82deaa940aad/href">https://medium.com/media/7c7d6f9ed8d96408caba82deaa940aad/href</a></iframe><h3>3. Functions</h3><p>Wikipedia (2022h) describes a function or subroutine as a sequence of instructions that complete some specific task. This means functions can be used to define multiple lines of codes callable by a single reference/symbolic name. It is also possible to pass parameters to a function that can be used within the operations of the function. The keyword def can be used within Python to define functions (Python.org, 2022c). It should be noticed that a function in Python always starts with the def keyword, followed by a symbolic name, and parentheses defining the allowed arguments/parameters (See figure 7).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d03b0c0c2e8a7337289a8c04f81bd73/href">https://medium.com/media/2d03b0c0c2e8a7337289a8c04f81bd73/href</a></iframe><h4>3.1 Functions return value</h4><p>Functions can return a value after or in the middle of their operations to the part of the code calling the function. The return keyword can be used to return a specific value, however, if a function does not contain a return keyword the function returns a value which in Python is called None (Python.org, 2022c). The none value is representing that it has no value (Python.org, 2022d). Figure 8 shows an example of a function that uses the return keyword to return the value of two variables multiplied.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbd73dcd024a54f4d2d1026192f984f9/href">https://medium.com/media/fbd73dcd024a54f4d2d1026192f984f9/href</a></iframe><h3>4. If-statement</h3><p>The if-statement can be used to execute specific lines of code if a conditional expression evaluates to true (Python.org, 2022h). The keyword if is used to create an if-statement in Python. Figure 10, line 6 shows an implementation of an if-statement evaluating a comparison. Python.org (2022i) describes Python have eight comparison operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63246b14dc7b601108c22264c66137ae/href">https://medium.com/media/63246b14dc7b601108c22264c66137ae/href</a></iframe><h4>4.1 Comparisons</h4><p>Comparisons can be used directly in if-statements and the result of the comparison can also be stored in a variable (see figure 11).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bb49f33820ad774727ff4f58f827320/href">https://medium.com/media/7bb49f33820ad774727ff4f58f827320/href</a></iframe><p>The eight comparison operations in Python can be seen in figure 12.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8ecc064fab97baf69c348324ae587a5/href">https://medium.com/media/c8ecc064fab97baf69c348324ae587a5/href</a></iframe><h4>4.2 Elif condition</h4><p>The keyword elif can be used to add additional execution paths that only will execute if the checks before evaluates to false (See figure 13).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2bfaf3975e241111e228f3546524eb9/href">https://medium.com/media/d2bfaf3975e241111e228f3546524eb9/href</a></iframe><h4>4.3 Else condition</h4><p>The keyword else is used to add lines of code that should be executed if the if-statement and elif-statement before are evaluated to false (See figure 14).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df0a412ea0f0e865f3100389469695d0/href">https://medium.com/media/df0a412ea0f0e865f3100389469695d0/href</a></iframe><h3>5. List</h3><p>A list is a sequence type (Python.org, 2022f). A list can be used to refer to a sequence of data referred by a single variable. Each element in a list can be accessed by an index, and the first element is at index zero (see figure 15).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ba5c8d84680ba4fba6245970ee18d6d/href">https://medium.com/media/6ba5c8d84680ba4fba6245970ee18d6d/href</a></iframe><h4>5.1 IndexError</h4><p>If the list is accessed by an index out of bounds, the program will throw an IndexError exception (see figure 16).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8455d82192eba12cb35ecbf55091182c/href">https://medium.com/media/8455d82192eba12cb35ecbf55091182c/href</a></iframe><h4>5.2 Modifying the list</h4><p>The list has many methods that can be used to add and remove elements. For example, pop(index) can be used to remove an element at a specific index, insert(element, index) can be used to insert an element at a specific index, and append(element) can be used to add an element at the end of the list (Python, 2022g).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16e6b5f8f350ee8b6ba4d86a8c33ed00/href">https://medium.com/media/16e6b5f8f350ee8b6ba4d86a8c33ed00/href</a></iframe><h4>5.3. Looping the list</h4><p>Wikipedia (2022j) describes a for-loop as a control flow statement allowing repeated execution of code. The keyword for is used in Python to define a for-loop (Python.org, 2022c).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01b7f025cc4a3f17c7f95db6773d8e1b/href">https://medium.com/media/01b7f025cc4a3f17c7f95db6773d8e1b/href</a></iframe><p>There exist also other types of loops such as the while-loop. Python.org (2022h) describe that the while-loop executes until the condition is false. Figure 19 shows an example of a while-loop that executes until the variable i is greater than three. It should be noticed the variable i will never be greater than three if line 7 in figure 19 is removed, which will result in an infinite loop.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fd53d62cef0537474054c99f007cd95/href">https://medium.com/media/5fd53d62cef0537474054c99f007cd95/href</a></iframe><h3>7. Classes</h3><p>Classes can be used to create objects with properties and methods (Wikipedia, 2022k). Properties refer to that classes can contain various variables with data, and methods refer to that classes can contain functions. Each class functions as an object type (Python.org, 2022j). Remember the data types from section 2, Data types? (For example, string) Classes basically provide the structure to create your own data types with different meanings, properties, and behavior. The keyword class is used to define classes in Python (see figure 20).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b81a60b319a26a1fe7ee742dee190559/href">https://medium.com/media/b81a60b319a26a1fe7ee742dee190559/href</a></iframe><h4>7.1 Adding properties</h4><p>There are two different ways of adding properties to a class. Figure 21 defines a class variable called a that can be accessed and modified at the class level by SomeClass.a without the need for creating an instance of the class. The class in figure 21 also defines a variable called b which is a property that can be set when creating a new instance of the class. The keyword self is used to refer to the instance used in the operation, for example, if an instance of a class is created and stored in a variable a , then self would refer to that particular instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d65706055cd460f7b5455e14bd85fb4/href">https://medium.com/media/9d65706055cd460f7b5455e14bd85fb4/href</a></iframe><h4>7.2 Adding methods</h4><p>There are also two ways to add methods to a class. Figure 22 shows an implementation of two methods, one called multiply and another called addition, the difference between these methods (besides one is multiplication and the other addition) is the keyword self added in the method&#39;s arguments. The difference is similar to the example in section 7.1, Adding properties, because calling a function with the self keyword requires an instance of the class (see figure 22).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/344388520376e7c9b632e75fd9ce961e/href">https://medium.com/media/344388520376e7c9b632e75fd9ce961e/href</a></iframe><h4>7.3 A simple banking system</h4><p>To get a better understanding of the idea of classes, let’s assume you need to build a simple banking system with banking accounts with the ability to hold cash, withdraw cash, and deposit cash. This could be done by adding a class called Account or something similar with a cash property and deposit and withdraw methods (see figure 23).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5f8e122625a327d13155a000a271ce5/href">https://medium.com/media/e5f8e122625a327d13155a000a271ce5/href</a></iframe><h3>8. Scope</h3><p>Wikipedia (2022i) describes a scope as the part where a variable or the name of an entity can be used. For example, if a variable is defined within a function, the variable is only available inside the function and the program would throw an error if the variable was mentioned outside the function (see figure 24). The error thrown is called an exception and the specific exception related to calling an undefined variable in Python is called NameError (Python.org, 2022e). The NameError exception would also occur if an undefined function or class were called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba15b596f3c2aa55f2faf919f742b35/href">https://medium.com/media/0ba15b596f3c2aa55f2faf919f742b35/href</a></iframe><h3>9. Where to go from here</h3><p>Python offers many more concepts and features than mentioned in this article. The list below links some concepts that were not meant in the article but maybe interesting for beginners looking into next.</p><ul><li><a href="https://docs.python.org/3/tutorial/errors.html">Errors and Exceptions</a></li><li><a href="https://docs.python.org/3/tutorial/classes.html#inheritance">Inheritance</a></li><li><a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files">Reading and writing files</a></li><li><a href="https://docs.python.org/3/tutorial/classes.html#generators">Generators</a></li><li><a href="https://docs.python.org/3/tutorial/classes.html#iterators">Iterators</a></li><li><a href="https://docs.python.org/3/tutorial/classes.html#private-variables">Private variables</a></li></ul><h3>Bibliography</h3><p>Docs.python.org. (2022a). <em>Built-in Types — Python 3.10.4 documentation</em>. [online] Available at: &lt;<a href="https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex">https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex</a>&gt; [Accessed 13 May 2022].</p><p>Docs.python.org. (2022b). <em>Built-in Types — Python 3.10.4 documentation</em>. [online] Available at: &lt;<a href="https://docs.python.org/3/library/stdtypes.html?#text-sequence-type-str">https://docs.python.org/3/library/stdtypes.html?#text-sequence-type-str</a>&gt; [Accessed 13 May 2022].</p><p>Docs.python.org. (2022c). <em>4. More Control Flow Tools — Python 3.10.4 documentation</em>. [online] Available at: &lt;<a href="https://docs.python.org/3/tutorial/controlflow.html#defining-functions">https://docs.python.org/3/tutorial/controlflow.html#defining-functions</a>&gt; [Accessed 14 May 2022].</p><p>Docs.python.org. (2022d). <em>Built-in Constants — Python 3.10.4 documentation</em>. [online] Available at: &lt;<a href="https://docs.python.org/3/library/constants.html?#None">https://docs.python.org/3/library/constants.html?#None</a>&gt; [Accessed 14 May 2022].</p><p>Docs.python.org. (2022e). <em>8. Errors and Exceptions — Python 3.10.4 documentation</em>. [online] Available at: &lt;<a href="https://docs.python.org/3/tutorial/errors.html?#exceptions">https://docs.python.org/3/tutorial/errors.html?#exceptions</a>&gt; [Accessed 14 May 2022].</p><p>Docs.python.org. (2022f). <em>Glossary — Python 3.10.4 documentation</em>. [online] Available at: &lt;<a href="https://docs.python.org/3/glossary.html#term-list">https://docs.python.org/3/glossary.html#term-list</a>&gt; [Accessed 14 May 2022].</p><p>Docs.python.org. (2022g). <em>5. Data Structures — Python 3.10.4 documentation</em>. [online] Available at: &lt;<a href="https://docs.python.org/3/tutorial/datastructures.html">https://docs.python.org/3/tutorial/datastructures.html</a>&gt; [Accessed 14 May 2022].</p><p>Docs.python.org. (2022h). <em>8. Compound statements — Python 3.10.4 documentation</em>. [online] Available at: &lt;<a href="https://docs.python.org/3/reference/compound_stmts.html#the-if-statement">https://docs.python.org/3/reference/compound_stmts.html#the-if-statement</a>&gt; [Accessed 14 May 2022].</p><p>Docs.python.org. (2022i). <em>Built-in Types — Python 3.10.4 documentation</em>. [online] Available at: &lt;<a href="https://docs.python.org/3/library/stdtypes.html#comparisons">https://docs.python.org/3/library/stdtypes.html#comparisons</a>&gt; [Accessed 14 May 2022].</p><p>Docs.python.org. (2022j). <em>9. Classes — Python 3.10.4 documentation</em>. [online] Available at: &lt;https://docs.python.org/3/tutorial/classes.html&gt; [Accessed 14 May 2022].</p><p>En.wikipedia.org. (2022a). <em>Data type — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Data_type">https://en.wikipedia.org/wiki/Data_type</a>&gt; [Accessed 13 May 2022].</p><p>En.wikipedia.org. (2022b). <em>Interpreter (computing) — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Interpreter_(computing)">https://en.wikipedia.org/wiki/Interpreter_(computing)</a>&gt; [Accessed 13 May 2022].</p><p>En.wikipedia.org. (2022c). <em>Compiler — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Compiler">https://en.wikipedia.org/wiki/Compiler</a>&gt; [Accessed 13 May 2022].</p><p>En.wikipedia.org. (2022d). <em>Integer — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Integer">https://en.wikipedia.org/wiki/Integer</a>&gt; [Accessed 13 May 2022].</p><p>En.wikipedia.org. (2022e). <em>Variable (computer science) — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Variable_(computer_science)">https://en.wikipedia.org/wiki/Variable_(computer_science)</a>&gt; [Accessed 13 May 2022].</p><p>En.wikipedia.org. (2022f). <em>Boolean data type — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Boolean_data_type">https://en.wikipedia.org/wiki/Boolean_data_type</a>&gt; [Accessed 13 May 2022].</p><p>En.wikipedia.org. (2022g). <em>Arithmetic — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Arithmetic">https://en.wikipedia.org/wiki/Arithmetic</a>&gt; [Accessed 13 May 2022].</p><p>En.wikipedia.org. (2022h). <em>Subroutine — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Subroutine">https://en.wikipedia.org/wiki/Subroutine</a>&gt; [Accessed 14 May 2022].</p><p>En.wikipedia.org. (2022i). <em>Scope (computer science) — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/Scope_(computer_science)">https://en.wikipedia.org/wiki/Scope_(computer_science)</a>&gt; [Accessed 14 May 2022].</p><p>En.wikipedia.org.(2022j). <em>For loop — Wikipedia</em>. [online] Available at: &lt;<a href="https://en.wikipedia.org/wiki/For_loop">https://en.wikipedia.org/wiki/For_loop</a>&gt; [Accessed 14 May 2022].</p><p>Ramos, L. P., (n.d). <em>How to Run Your Python Scripts — Real Python</em>. [online] Realpython.com. Available at: &lt;<a href="https://realpython.com/run-python-scripts/#how-to-run-python-code-interactively">https://realpython.com/run-python-scripts/#how-to-run-python-code-interactively</a>&gt; [Accessed 14 May 2022].</p><p>Wikipedia. (2022k). <em>Class (programming) — Simple English Wikipedia, the free encyclopedia</em>. [online] Available at: &lt;<a href="https://simple.wikipedia.org/wiki/Class_(programming)">https://simple.wikipedia.org/wiki/Class_(programming)</a>&gt; [Accessed 14 May 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c8b75e9cd0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>