Hacker Wisdom

Today I’m going to share a little project I’ve been working on called Hacker Wisdom. It’s a web application built using Java, Apache Maven, Spring Boot, Thymeleaf, and the Hacker News API.

I visit the Hacker News website fairly regularly. It has a lot of great information and interesting discussions. One section I particularly enjoy is called “Ask HN”. People ask for advice on all sorts of topics. There are usually nuggets of wisdom and lively debate that follows in the comments.

I often find myself reading through these comments and saving off interesting looking links to other websites. There is a lot of collective wisdom and experience to be found there.

I felt like it would fit the spirit of Hacker News to automate that process and create a spin-off website that collects and displays some of the day’s hacker wisdom.

You can see the result by following this link, which also has a link to the source code on Github.

The rest of this post will be dedicated to describing how I built it.

Setting up the Project

I used IntelliJ for my IDE, and that tool makes it really easy to set up a Maven/Spring Boot project.

Spring Boot and its associated addons made it really easy to add Controllers to handle web requests, Services to handle the logic, and Thymeleaf templates to handle the front end.

Each controller method maps to a Thymeleaf template. The about page is static, but the home page is populated with dynamic data from the “Ask HN” section of Hacker News.

Retrieving the Links

I used to two API endpoints to retrieve the links:

https://hacker-news.firebaseio.com/v0/askstories.json?print=pretty
https://hacker-news.firebaseio.com/v0/item/{id}.json?print=pretty

The first endpoint gets me a list of ids, in the form of integers, of the top “Ask HN” posts. The second endpoint will retrieve any item, whether a post or a comment, by id. With the help of a recursive function, these two endpoints allowed me to drill down into the comments of these “Ask HN” posts.

Once I had the comments I had to look for the links contained in their text. I know that using a regex to parse HTML is generally a bad idea, but I was able to make it work. I didn’t feel compelled to pull in JSoup as a dependency once I had it working consistently.

After retrieving the links I removed duplicates and sorted them for a better user experience. I created a custom, case insensitive link sorter that ignores the http(s) prefixes.

Improving Responsiveness

Unfortunately, while my solution up until this point was accurate, it was not very fast. It takes a lot of API calls to retrieve all the necessary data, and those trips add up. The time can also vary depending on how popular the question is. Without any optimizations, this was taking an unacceptably long time.

My solution to this problem was to implement a caching strategy using Spring’s caching capabilities. The application stores the data in a cache with a name of “answeredQuestions” after retrieving it for the first time.

Meanwhile, in the background, a scheduled job will reperform the data parsing and update the cache every 10 minutes. I used Spring to implement the scheduling as well.

After the first request succeeds, subsequent requests bypass all of the calculations and can simply grab the stored result from the cache.

Subscribe to my blog or follow me on Twitter if you’re interested in seeing more projects like these.

Minimum Viable Dice Wars

Minimum Viable Dice Wars

Anybody else miss flash games?

Playing those games is one of my earliest and fondest memories on the internet. I remember making the trip to my elementary school’s computer lab where we were allowed to visit coolmath4kids.com (which looks a lot different decades later) because the games were supposed to be educational.

Despite the best efforts of our teacher to police it, we all snuck over to a section of the website known as “Spike’s Game Zone”. This was where the mindlessly fun games were.

As I grew up my tastes became more sophisticated. One flash game that I found very addicting as a kid was simply called “Dice Wars”. It’s like the board game “Risk” in a lot of ways, but with a little more luck involved. If you want to play the original, you can check it out here.

Minimum Viable Dice Wars

I decided it would be a fun project to try to build my own version of Dice Wars. I’m calling it, “Minimum Viable Dice Wars”, as it’s a bit different and not nearly as polished as the original. However, it is playable and has most of the same major features.

You can play my version of Dice Wars by clicking this link.

And you can check out the source code by clicking this link.


One thing I always get self-conscious about when I share more ambitious side projects with you all is the code quality. I make these games in bits of my spare time. As somebody who builds software professionally, I’m never quite satisfied with the end result.

Most of the algorithms in this project are brute force approaches, and there are plenty of performance optimizations that I could make. However, if I held off on sharing these projects until they were perfect I’m not sure I’d ever publish anything.

Instead of walking through all of the code and explaining it line by line, as I have done in some of my previous tutorials, I’ll be focusing on the approaches I took while implementing the more interesting sections.

I took a similar approach when discussing the crossword puzzle generator. It’s another project with a bit higher level of complexity, and that approach seemed to work well for demonstrating concepts without getting bogged down in the details.

Of course, feel free to ask questions about any particulars you find interesting or confusing.

Game Board Generation

I’m pretty sure the original version of Dice Wars uses some kind of tree or graph data structure for representing the game board. It really intrigued me how the original developers built it and integrated it with the graphics.

Going with the “minimum viable” theme, however, I decided to go with a 2D array. It gives the game a bit of a unique feel too, in my opinion.

The basic approach I took for generating random boards looks like this:

  1. Generate an empty square board of fixed size using a 2D array.
  2. Pick a random, but reasonable, number of tiles to make empty. When choosing the random placement of the tiles, don’t let these empty tiles be on the “inner ring” of the board. This will help us avoid creating hanging tiles. A hanging tile is one that doesn’t connect to any other tile and thus can never be captured.
  3. Randomly assign the same amount of dice to each team on the available tiles, and make sure they are distributed in varying amounts.
  4. Clean up any hanging tiles. The code I wrote for this doesn’t cover all cases, but I think it is sufficient given the additional precautions taken in step 2 above.
Minimum Viable Dice Wars - Inner Ring of board

Find Connected Tiles

One key element of Dice Wars is that you get bonus dice based on your largest group of connected tiles. This proved to be tricky, and I’ll admit I used Stack Overflow for a bit of initial direction. Once I understood the basic idea I was able to modify it to fit my use case.

The general idea is to loop through all the tiles on the board and use recursion to check each tile’s connected tiles to see if they are owned by the same team….and then do the same thing for each of those connected tiles…and so on.

Once all the branching tiles have been checked and the base case has been reached the function returns the connected tile count along with an array of the connected tiles.

I started by creating an array of the neighboring tiles. I represented each tile as an object containing coordinates, a name designating the directional relationship to the original tile, and whether it was a valid direction given its position on the game board.

Get neighboring tiles

The result of this function helps to simplify the recursive code. It allowed me to loop through the array and call the same function repeatedly instead of checking multiple if statements like shown in the Stack Overflow example.

Find number of connected tiles.

I added the tile to an array and incremented the total count whenever it was valid, belonged to the same team, and hadn’t already been checked.

Find number of connected tiles in direction

Artificial Intelligence

It took a bit of tweaking, but it turns out a few simple rules are all it takes to create a serviceable AI for a Minimum Viable Dice Wars. There are two main things the AI does. The AI will attack from a tile if:

  1. It is adjacent to a weaker tile owned by an opposing team.
  2. It has the maximum number of dice and is adjacent to a tile owned by an opposing team that also has the maximum number of dice.
Artificial Intelligence code for minimum viable Dice Wars

There are many ideas for improvement I haven’t implemented yet, including ranking the attack options, focusing attacks on the team in the lead, and attacking again from a conquered tile after a successful attack.

It seemed pretty fun to play against though, so I haven’t bothered with it yet.

Conclusion

I had a lot of fun making this minimum viable version of Dice Wars. I hope you enjoyed following along. Subscribe to my blog or follow me on Twitter if you’re interested in seeing more projects like these.

How To Build A Magic Eight Ball With JavaScript

Magic Eight Ball With JavaScript

Welcome to my latest tutorial, where you’ll learn how to build a magic eight ball with JavaScript.

I usually write tutorials for an audience of people who know at least a little bit of front-end programming. I’ve put more focus on the concepts and thought processes used in building the abstractions than on the technical details. One of my recent tutorials, a crossword puzzle generator, is a good example of what I’m talking about.

This post will be different. I’m going to show you how to build a magic eight ball with JavaScript, and the tutorial is designed for complete beginners.

You can check it out here.

And you can view the source code here. You can compare your code to mine if you run into troubles along the way.

My tutorials are fun because you get a working game at the end. I think there is a lot to be said for that. Most people don’t get into programming because they enjoy sorting lists or learning about data structures. They want to build something cool.

That being said, my tutorials usually require you to apply yourself and do more of your own research if you want to maximize the benefits to you. If you’re just blindly copying and pasting you won’t learn much.

True growth as a developer comes when you can combine structured learning of the fundamentals with building cool stuff.

The goal of this specific tutorial is to provide that kind of experience, with a little more focus on learning the fundamentals.

Technologies of the Web

We’ll be building this magic eight ball using front-end web technologies. Understanding these technologies is key to building a strong foundation as a web developer.

There are three fundamental technologies that every developer must know in order to write code that will run in a web browser: HTML, CSS, and JavaScript.

HTML

HTML stands for hypertext markup language. It is a domain specific programming language that allows you to display structured content in a web browser.

Notice how this page you’re reading has headings in larger font and breaks between paragraphs? That effect is due to HTML tags.

What are tags?

Tags are elements on the page that describe how content should be displayed. There are different tags for displaying headings, paragraphs, buttons, line breaks, images, and much more. If you want to be a web developer, HTML is the first thing you should learn. Fortunately, it’s pretty easy to pick up.

CSS

CSS stands for cascading style sheets. It is a programming language used for applying colors, fonts, positioning, borders, and much more to HTML elements. Basically, it makes the page look pretty.

It’s called cascading because of the way it determines which style to apply if more than one rule matches a particular element.

CSS can be included in the HTML directly, or pulled in from a separate file. It used to be considered poor form to have inline CSS, but that standard has changed a bit with some of the new front-end frameworks. For this tutorial, I’ll be including the CSS via a separate file.

JavaScript

Out of the three languages, JavaScript is probably the most challenging to learn (although advanced CSS can get pretty crazy). It’s also the most rewarding, as many of the same concepts will apply to other programming languages, like Java, Python, or C++.

JavaScript brings your page to life. It allows you to introduce dynamic behavior to the page. You can add functionality that is dependent upon the actions of the user. It’s where the bulk of the difficulty, and fun, of programming lies.

Like CSS, you can include JavaScript directly in the HTML. I’ll be including it via a separate file.

We’ll be displaying the answers from our magic eight ball with JavaScript.

Where To Write The Code

To start developing for the web, all you really need is a text editor program. I like Sublime, but there are many good ones to choose from. You can even use plain old Notepad, but I recommend downloading something better. Here is a good list to pick from:

  • Sublime
  • Visual Studio Code
  • Notepad++
  • Atom

Make Your Life Easier With a Debugger

In my opinion, it’s also worth familiarizing yourself with your browser’s developer tools. They are extremely helpful for experimenting, debugging issues, and seeing what’s going on in your code behind the scenes. For this tutorial I’ll be using Google Chrome.

In Chrome, you can bring up the developer tools by using the keyboard shortcut: Ctrl + Shift + I, or by right clicking on the page and selecting “Inspect”. Check out this post to familiarize yourself with the basics of how to use these tools.

Alternatively, you can wait and learn them when you need them.

Creating the HTML File

Ok, let’s get started making the magic eight ball.

Once you have downloaded a text editor you have all you need to begin. Pick any folder/directory on your computer as the location of your website. It can be a simple as creating a folder called “magic-eight-ball” on your Desktop. This is the location where you will be saving your HTML, CSS, and JavaScript files.

Next, open up a brand new file in your text editor of choice. This is where we are going to write the HTML code.

Begin by adding the following code to the file:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
  </body>
</html>

This is the basic structure of an HTML document. The words in angle brackets are called tags.

There are opening and closing tags. The tags that have a forward slash before the name are the closing tags. Although most HTML elements require both, there are many HTML elements that do not require a closing tag. We’ll see some examples of this in a moment.

The content you will be adding goes between the opening and closing tags. These tags are what create visible elements on the page.

The first element you see is the doctype. This is not an HTML tag, but information the browser needs to know what kind of document to display. In our case, the type of document is an HTML document. There are other doctypes, but that discussion is beyond the scope of this tutorial.

We have three tags so far: html, head, and body. The html tag signifies the beginning of the HTML document. Everything on the page goes inside it. The head tag contains meta information about the page and can also be used as a place to import other files. The body tag is where the bulk of our content will go.

Go ahead and save this file as index.html in the folder you previously created.

Now add some more code so your HTML looks like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Magic Eight Ball</title>
    <link rel="stylesheet" href="magic-eight-ball.css">
    <link rel="shortcut icon" 
          href="https://mitchum.blog/wp-content/uploads/2019/05/favicon.png" />
  </head>
  <body>
    <main>
      <h3 class="heading">Magic Eight Ball</h3>
      <h5 class="heading">
      	<a href="https://mitchum.blog/building-a-magic-eight-ball-with-javascript/">Tutorial</a> |
        <a href="https://github.com/mmaynar1/games/tree/master/magic-eight-ball">Github</a> |
        <a href="https://mitchum.blog/subscribe/">Subscribe</a>
      </h5>
    </main>   
  </body>
</html>

Let’s look at what we added. You should notice that the head and body tags have even more tags inside of them now.

Head Tag

We have added a title tag and two link tags. The title tag will be displayed in the tab of your browser.

Magic Eight Ball title tag
The title of our page is “Magic Eight Ball”.

The first link tag pulls in the CSS class which we have yet to create. We’ll do that in a moment.

The second link tag sets the favicon image. This is the little icon that shows up in the browser tab. We’re pulling the image from the web server that runs my blog.

The favicon
The favicon shows up in the tab as well.

Body Tag

We have added a main tag inside the body. This element contains the main content of the page. In our case, this is almost everything. On other websites, however, you might find items like common footers and navigation elements outside of the main tag.

Inside our main tag we have added two h tags. These are heading tags that display larger text meant to serve as headings for sections of content.

The first heading tag contains text representing the title of our page: Magic Eight Ball. It also contains a class property labeled “heading”. This is a CSS class. Later we will add style to it by adding code to our CSS file.

Adding Hyperlinks

The second heading tag, which is also assigned the “heading” class, contains hyperlinks to my blog and Github page.

You might know hyperlinks by their more common nickname: links. These hyperlinks are created by using “a”, or “anchor” tags. The href property specifies which url the hyperlink will direct the browser to. The text between the anchor tags specifies what the link name will be.

You should really click on that Subscribe link and submit the form. I’ve made it easy for you by adding my own link to it right here. 😉

At this point you should save your changes. Then, navigate to this file and open it in a browser. In the address bar you should be able to see the path to your file. On the page itself you should see the title and the links below it.

Finishing Up the HTML

Now it’s time to add the rest of the HTML content. See the new additions below:

<!DOCTYPE html>
<html>
  <head>
    <title>Magic Eight Ball</title>
    <link rel="stylesheet" href="magic-eight-ball.css">
    <link rel="shortcut icon" 
          href="https://mitchum.blog/wp-content/uploads/2019/05/favicon.png" />
  </head>
  <body>
    <main>
      <h3 class="heading">Magic Eight Ball</h3>
      <h5 class="heading">
      	<a href="https://mitchum.blog/building-a-magic-eight-ball-with-javascript/">Tutorial</a> |
        <a href="https://github.com/mmaynar1/games/tree/master/magic-eight-ball">Github</a> |
        <a href="https://mitchum.blog/subscribe/">Subscribe</a>
      </h5>
      <br>
      <div id="answerButton"> 
      	<button class="button" type="button" onclick="displayAnswer()">Shake It</button>
      </div>
      <br>
      <div id="magicEightBall">
        <div id="circle"></div>
        <img src="magic-eight-ball.png"/>
      </div>
      <br>
    </main>   
   <script src="magic-eight-ball.js"></script>
  </body>
</html>

In this step we’ve added the bulk of the HTML needed to make our magic eight ball. We’ve added two div tags. People use div tags a lot. You can think of them as generic placeholders for content.

Adding the “Shake It” Button

The first div is given the id of “answerButton”. We’ll use this id for adding styling via CSS. Inside the div tag is a button child tag.

Child tags are tags inside of other tags. The outer tag is referred to as the parent tag. (Image description?)

This button is assigned the class “button”, the type “button”, and a JavaScript function to execute when somebody clicks it. We’ll write this function later when we get to the JavaScript file. The text on the button will say “Shake It”. When you click this button, you’ll get an answer from the magic eight ball.

The second div is given the id of “magicEightBall”. We’ll use this id for adding styling via CSS, but also for adding functionality in the JavaScript code.

Adding the Magic Eight Ball

There are two child tags in this div. The first is another div with the id of “circle”. The second is an img tag with a src attribute pointing to an image called “magic-eight-ball.png”. You’ll need to download this image from my server, give it the name “magic-eight-ball.png”, and save it in your working folder/directory along with your other files.

There are also br tags scattered throughout to provide spacing between different page elements. Go ahead and add those as well.

Finally, there is a script tag right outside the main closing tag. The src attribute points to magic-eight-ball.js, the JavaScript file we will be adding later.

If you save and open the HTML file now it will have all the content, but it will look pretty ugly:

Magic Eight Ball with no CSS
Our magic eight ball web page with no CSS applied looks like this.

We’re going to fix that by adding the CSS file, magic-eight-ball.css.

Creating the CSS File

Open up a brand new file in your text editor and save it in the same location as your index.html file under the filename, “magic-eight-ball.css”.

It’s important that the name matches the one you specified in the HTML file, otherwise the CSS file won’t be found. Add the following blocks of code one at a time, and save as you go. Observe how the page changes as you go.

Setting the Background Color

body {
  background: cornflowerblue;
}

This block of code does one thing and one thing only. It sets the background color of the body HTML element to a nice blue color. If you save the file and refresh your browser you’ll notice the color change.

Centering the Page Contents

main {
  max-width: 610px;
  margin: auto;
}

After refreshing the page you should see everything centered on the page much more nicely. We have set the max width of the main element to 610px (px stands for pixels), and we have set the margin to auto, horizontally centering all of the content within it.

Applying Styles to Our HTML Elements

 h3, h5, #answerButton, #magicEightBall {
  text-align: center;
  color: khaki;
  margin: 5px;
}

This block of code is applying styles to four different HTML elements: all h3 tags, all h5 tags, the HTML element with the id of “answerButton”, and the HTML element with the id of “magicEightBall”.

By adding this code block we will apply three different styles to these elements. We’ll center the text within them, set their text color to khaki, and set the margin (the space around the element) to 5px.

Styling the Answer Display Circle

#circle {
  font-size: 14pt;
  background-color: white;
  color: black;
  position: absolute;
  margin-left: 70px;
  margin-top: 70px;
  height: 150px;
  width: 150px;
  border-radius: 50%;
  display: none;
}

There is a lot going on in this code block. We are applying many different styles to the HTML element with the id of circle, which represents the area where the answer will appear.

We are setting the font size to 14pt. This seemed reasonable after I did a little bit of testing. We are also setting the background to white and the text color to black so that the answer area will have good contrast and look good on top of the magic eight ball image.

We are using absolute positioning. This will cause the element to be positioned relative to the nearest position ancestor, which in our case is the HTML element with the id of “magicEightBall”. We are also adding left and top margins of 70px to help us begin centering the answer area in the middle of the magic eight ball.

We are setting the height and width of element to 150px, creating a square. Then we set the border radius to 50% which rounds the corners into a square.

Finally, we set the display to none, hiding it from view until the person shakes the magic eight ball.

Now the magic eight ball looks a lot better:

Magic Eight Ball with CSS
Our magic eight ball web page looks much better after we apply CSS to it.

Creating the JavaScript File

Now it’s time for the fun part. We’re going to make our magic eight ball come to life with JavaScript.

Open up a brand new file in your text editor and save it in the same location as your index.html file under the filename, “magic-eight-ball.js”. It’s important that the name matches the one you specified in the HTML file, otherwise the JavaScript file won’t be found.

Creating the Answers Array

The first thing we’re going to do is create a list of possible answers the magic eight ball can respond with. We’ll refer to this list as an array. The term array is very common among different programming languages. Simply put, it is a structure for storing a sequential list of data in memory. In our case, the data will be the answers that the magic eight ball will give to us. Let’s define the array in our code:

let answers = [
  'Seems unlikely.',
  'Not a chance.',
  'In your dreams.',
  'Get real, kid.',
  'Absolutely.',
  'Maybe.',
  'It is certain.',
  'Ask me later.',
  'Chances seem good.',
  'I don\'t know, I\'m just a stupid piece of plastic.',
  'Ask again later.',
  'Signs point to yes.',
  'No.',
  'Yes.',
  'Nope.',
  'Don\'t count on it.',
  'Is the Pope Catholic?',
  'Does a one legged duck swim in a circle?'
]

We’ve used the let keyword to define a variable named answers. A variable is a name that refers to a piece of data.

We have set this answers variable (via the = sign) to hold an array of strings. For this tutorial, you can think of a string as a sequence of characters. We’ll be using strings to represent our answers.

A comma is used to separate each element of the array. By adding the code above we have defined a variable that holds an array containing 18 answers, each represented as a string.

Creating the displayAnswer Function

Now let’s add the JavaScript function to display the answers when the player clicks the “Shake It” button.

let displayAnswer = function()
{
  let index = Math.floor(Math.random() * answers.length);
  let answer = answers[index];
  let element = document.getElementById( 'circle' );
  element.style.display = 'inline-block';
  element.innerHTML = '<br><br>' + answer;
}

We’ve defined another variable, but this time we have pointed it to a function instead of an array. You can think of a function as a container for code that can be reused. You can run the code inside by “calling” that function.

If you search through the index.html file we created and look for displayAnswer() you’ll see where this function is called from. Whenever we click the “Shake It” button, this function will be called.

Functions are very useful to us as programmers. We can use them for organizational purposes and to prevent us from writing the same code over and over again.

Inside our displayAnswer function is code that will show a random answer on the magic eight ball. Let’s break down each line.

Getting a Random Index

let index = Math.floor(Math.random() * answers.length);

The first thing we do is get a random index. This random index will correspond to one of the elements in our answers array. Each element in the array is assigned an index, starting with 0. So the array above looks like this:

We generate this random index by using a few functions provided by JavaScript’s built in Math object. We multiply the length of the answers array by a random number between 0 (inclusive) and 1 (exclusive). Then, we round it down to the nearest integer.

Picking a Random Answer

let answer = answers[index];

Once we have our random index we need to retrieve the corresponding answer from the array. We do this by declaring a new variable and setting it to a value in the array corresponding to that index.

Finding the Circle

let element = document.getElementById( 'circle' );

Once we have our answer we need to display it on the page inside the magic eight ball. The first step is finding the HTML element. We use the above line of code to grab the element with the id of “circle”. In this case “document” refers to our web page. We save off a reference to it in a variable named “element”.

Displaying the Circle

element.style.display = 'inline-block';

Now that we have the element we need to make it visible. Remember, in our CSS file we previously hid this element from view. We will change its display from “none” to “inline-block”.

Showing the Answer

element.innerHTML = '<br><br>' + answer;

Finally, we need to populate the element with the answer. We’ll create a string of two br tags, to help center the answer in the middle of the circle, and then append the answer to it. The plus symbol can be used for doing math, but in the case of strings it will concatenate them together.

Now save your file and check out the game you’ve created! You should get a random answer every time you click the “Shake It” button.

Magic Eight Ball with JavaScript displaying the answer
Our magic eight ball can now answer our questions, all thanks to JavaScript.

Congrats, you have created a magic eight ball with JavaScript!

I hope you learned something from this tutorial, especially if you are brand new to programming. We have barely begun scratching the surface on what we can accomplish with these programming languages. The whole web is built using these technologies, and there are many more elements we can create, styles we can apply, functions we can write. There is boundless room for creativity.

If you’d like to keep learning more, check out some of my other game tutorials.

You can also follow me on Twitter and subscribe to this blog to stay up to date with what I’m up to.

It’s Time to Revisit Minesweeper

Revisit Minesweeper

Over a year ago I built a minesweeper clone using JavaScript, HTML, and CSS. To my delight and surprise, the project and associated tutorial became pretty popular and made it to the front page of Hacker News and Reddit.

Of course, along with the success came the haters.

Revisit minesweeper to own the haters

I received some criticism on various choices I made. As you should come to expect on the internet, some of it was respectful and some of it was not. However, as all the great ones do, I decided to channel the negative energy to become even better. I’m basically the Michael Jordan of independent, part-time, game tutorial creators.

I considered the feedback I received, ate some humble pie, and realized the haters were correct in many cases. There are definitely improvements that can be made to the original implementation, and I decided to revisit minesweeper to make a few of those changes. Check out the new version, which shouldn’t feel much different than the old one:

Play the new and improved minesweeper!

View the code on Github!

The two big improvements I made were removing jQuery as a dependency, and preventing losses on the first click of the game. I also started taking advantage of some of the newer additions to the language, like the “let” keyword for declaring variables.

Take a glance at the git history for this project. I copied the original files into a new directory and removed jQuery from each function until I completely eliminated the dependency from the project. I worked on preventing immediate losses once jQuery was completely gone.

Removing jQuery

Revisit minesweeper and remove jQuery

The jQuery library was great for its time, but it’s usually an unnecessary abstraction in modern browsers. Today’s browsers are much better at following the same standards, and we now have more native methods for accomplishing just about anything jQuery can do. Most of the changes I made involved replacing jQuery functions with native methods.

However, I still have a soft spot in my heart for jQuery, and I did find one situation while refactoring the code where I really missed having it: event listeners. It’s really easy to add and remove event listeners using jQuery. It keeps track of the references for you, which makes removing them all at once a simple method call that you can chain to other jQuery methods.

In vanilla JavaScript you have to be much more explicit about which event listeners you want to remove. You typically have to pass the callback function to the removeEventListener function, and this can be error prone when dealing with multiple event listeners and different levels of scope.

My first attempt at replacing the event listeners with vanilla JavaScript resulted in adding new event listeners to minesweeper cells every time the player pressed the New Game button. This caused us to process events multiple times on a single cell click. Chaos ensued. You can check out these two commits and see what it took to restore order.

Preventing a Loss on the First Click

While you’re looking at the changes in that first commit above you’ll also notice the code I added to prevent a loss on the first click. This is a feature in the original game that I did not consider when building the clone. It’s a nice feature to have because it’s pretty frustrating to lose the game on your first click on an empty board.

Here’s the general approach I used to implement this feature.

  1. Keep track of whether it’s the players first click on the board, and reset that variable each game.
  2. If it’s the player’s first click and he’s about to lose, remove the mine and randomly place it somewhere else on the board.
  3. If you moved a mine, recalculate the neighboring mine counts.

Hopefully that description makes sense when you take a look at the code, but definitely leave me a comment if you found any of it confusing.

Conclusion

I know you’ve all been waiting eagerly in anticipation for over a year for me to revisit minesweeper, so I’m really happy for you guys. You can all rest easy at night knowing that some random code has been made better. Of course, I also hope this was instructive to some of you.

As always, subscribe to see more brutal takedowns of my haters.

How to Store JSON in an Environment Variable

Store JSON in an Environment Variable

I recently ran into a problem that compelled me to store some configuration data in a JSON object. The data wasn’t likely to change very often, but I didn’t want to hard code it in the application code. Unfortunately, there was not a good external data store immediately available to me for this kind of use case.

Ultimate Guitar PDFs

The search for a good solution led me to an idea. Could I store JSON in an environment variable? It turns out I can. I’m still not convinced it is the best solution, but it certainly has been a useful one. It at least allows me to change the configuration data without changing the code artifact. If you’ve worked in a web development or devops role long enough you’ll recognize the value of this.

The first problem I ran into was the raw JSON data breaking the config file. The JSON object has lots of special characters in it. These characters caused things to break when I tried to set the environment variable on the Linux server to the raw JSON string.

After a bit of thought I came up with the obvious solution: get rid of those stupid characters. Unfortunately, those characters are kind of important. I couldn’t just remove them.

What I could do was represent the data differently. I minified the JSON block and then base64 encoded it. That took the data from looking like this:

{
   "person": "you",
   "action": "subscribe",
   "when": "now",
   "happy": true
}

To looking like this:

{"person":"you","action":"subscribe","when":"now","happy":true}

And then finally this:

eyJwZXJzb24iOiJ5b3UiLCJhY3Rpb24iOiJzdWJzY3JpYmUiLCJ3aGVuIjoibm93IiwiaGFwcHkiOnRydWV9

When the JSON data only consists of alphanumeric characters it becomes a lot easier to work with. My application code can now read it from the environment variable and base64 decode it on the other side.

I thought I’d share this pattern in case it becomes useful for anybody else. In the past I’ve also used base64 encoding to pass image byte data across the internet. It’s a handy little technique with various applications. You do have to be careful with the size of the data though.

Now, go leave me a comment telling me why storing JSON in an environment variable is a horrible idea and subscribe so you can offer similar criticism in the future.

How To Use Your Browser’s Developer Tools

How To Use Your Browser's Developer Tools

It is difficult to become an effective web developer. One way to make it easier is to leverage the technology available to you, like your browser’s developer tools.

Learning how to use your browser’s developer tools is very important. You will find these tools very helpful when working through my JavaScript tutorials. They can be used for experimenting, debugging issues, and generally seeing what’s going on behind the scenes. In this post I’m going to show you some of the most useful things you can do with them.

I’ll be using Google Chrome, but any browser will have similar tools available. In Chrome, you can open up your browser’s developer tools using several different methods. The quickest method is probably using the keyboard shortcut, Ctrl + Shift + I. Since you’re presumably reading this post in your web browser, go ahead and do that right now.

Once you have the developer tools opened up you’ll notice a toolbar at the top. There are many tabs, and all have their uses. The ones I use most often are the Elements, Console, and Sources tabs.

There are also two little icons in the top left. One let’s you jump to any HTML element on the page, and the other let’s you see what the page would look like on a mobile device. I find those little buttons helpful too.

Here is a screenshot pointing all this out.

How To Use Your Browser's Developer Tools - A Google Chrome Diagram

Elements

The Elements tab will let you make changes in real time to the HTML and CSS. This is handy because it let’s you try out changes before adding them to your HTML or CSS file. It speeds up development and allows you to iterate faster.

Just make sure you don’t get carried away. It’s possible to make a whole bunch of changes in here, but they will get reset if you refresh the page. Make sure you add your changes to the code itself if you want to keep them permanently.

Changing page elements with your browser's developer tools

Console

The Console tab lets you execute arbitrary JavaScript code in the console. This is helpful for testing things out and inspecting the contents of variables in real time.

For example, we can see below what is contained inside the answers array in the code I wrote for the ear trainer tutorial. Just type the name of the variable you want to inspect in the console and press enter.

Utilizing the console in your browser's developer tools

Sources

The Sources tab will show you the contents of your HTML, CSS, and JavaScript files.

In my opinion, the most useful thing about this tab is that you can put break points in your JavaScript code. Break points allow you to pause the execution in the middle of your running program and step through it line by line. You can also inspect the contents of different JavaScript variables that are in scope.

This is very helpful when debugging problems with your code. You can see here how I’ve set a break point at the line where we evaluate if an answer is correct. I’ve also evaluated the variables in the console so I can see if they match.

Setting break points in our JavaScript code using our browser's developer tools.

Mobile Friendly

Finally, by clicking the mobile device icon we can see a preview of what my crossword puzzle generator post looks like on a mobile device. You can choose from different device types and orientations. Testing on real devices is always the best, but this is a handy feature to make sure the page generally looks good.

Showing a mobile preview using your browser's developer tools.

You should take the time to explore more of these buttons and tabs on your own, as there is a lot of really cool and useful functionality for you to discover.

The best way to get good at using your browser’s developer tools is good old fashioned practice. Keep that in mind as a silver lining the next time you’re frustrated by a bug in your JavaScript code.

As always, thanks for reading. Follow me on Twitter if you’d like to keep up with what I’m up to.

You can also  subscribe to my blog if you’d like some tips on writing functions and to have my blog posts show up in your inbox.

Building A Crossword Puzzle Generator With JavaScript

How To Build a Crossword Puzzle Generator With JavaScript

It’s time once again for a JavaScript tutorial. This will be the most complex code I’ve introduced to date, so I hope you’ve been paying attention and not just copy and pasting! In this post you will learn how to build a crossword puzzle generator with JavaScript.

First I’ll give an introduction into what inspired this project, next I’ll discuss what the different components are and how they fit together, and finally I’ll talk about the performance optimizations I made.

You can try it out by clicking this link. Be patient after clicking the button though, as sometimes it takes a moment to create a crossword puzzle. You’ll see why soon enough. While you’re there, go ahead and use your developer tools to familiarize yourself a bit with the code.

And you can click here to check out the source code on GitHub.

A Word of Encouragement

I’ve been programming for many years now and have made lots of mistakes along the way. I like to think of myself as somebody who knows a thing or two about building software. There is an enormous number of things I don’t know, but I’m confident in my skill set and my ability to learn new concepts and technologies as needed.

However, I didn’t get that confidence overnight. I used to be pretty bad, and when I get the chance to look at some of my code from years back it makes me cringe at the silly things I did.

So if that’s you right now don’t feel bad! We all have to start from the beginning to become good at anything worthwhile.

The Source of Inspiration

And this brings me to a little a story. I created this crossword puzzle generator by porting an old Java program I wrote back when I first got out of college. I hadn’t looked at it in years, and let me tell you, it was pretty rough. You can check it out on GitHub if you want to laugh at me.

I began the porting process by going one Java method at a time. I replaced each one with a shiny new JavaScript function that replicated its logic. As I progressed I began to refactor it, fix bugs, and improve the performance.

The Fruits of My Labor

The finished product isn’t perfectly clean code, but it’s a whole lot better than it was before.

After finishing the JavaScript version of my crossword puzzle generator I began wondering to myself if it’s worth writing a tutorial for. I’m 100% certain there are better algorithms than the one I used, and I’m also 100% certain there are more readability and efficiency improvements I could make. I don’t want to teach you guys any bad habits.

It’s also very complex and not the easiest material to teach.

In the end I decided it would be a good idea. So many tutorials out there are really trivial, and don’t give you a good sense of what a typical company code base looks like. This will give you a better approximation of that. It’s a collaboration of multiple developers with varying ability levels on a fairly complex problem over many years. It just so happens that both of the developers are me. 😂

It will also give you an opportunity add your own improvements, which is key to growing as a developer.

What Exactly Are We Building?

We are building a crossword puzzle generator with JavaScript, HTML, and CSS. The idea is to take a big list of words, pick some random ones, and try to make a crossword puzzle out of them.

We’ll start by placing a word on a grid. Then we’ll get another word that is a possible candidate to connect to that word. Then we’ll do the same for another word. We’ll continue this process on an on, picking a different word each time the a word is placed or doesn’t fit anywhere in the puzzle.

When do we stop trying to place words? That’s a complicated answer determined by two main factors:

  • Have we already placed a bunch of words on the crossword puzzle?
  • Do we have a lot of word intersections on the crossword puzzle?
crossword puzzle word intersection
An example of a word intersection.

Once a crossword puzzle is made, we’ll go ahead and create some more. Then we’ll find the one with the most word intersections and show it on the screen!

Breaking Down The Problem

I won’t go into the weeds as much in this post as I do in some of my previous tutorials. There are just too many functions and edge cases to go through. Instead, I think it will be most helpful if I explain in detail the high-level components we will be creating. Knowing how all the pieces fit together is half the battle.

I really encourage you to study what each function is accomplishing while keeping in mind which variables are being changed. The comment section is a great way to reach out for help if you don’t understand something. Others will probably thank you for it.

The Big List of Words

javascript list of words

The first thing we need is a big list of words to pick from.

In my original version I pulled the King James Bible in from a text file.

In the updated version I just made a JavaScript array with a bunch of words in it. You can check it out here.

Representing a Word

To place a word on the grid we’ll need to know a few things about it. Obviously we’ll need to know the text of the word itself, but we’ll also need to know about it’s positioning. We’ll need a row and a column to mark it’s starting position. We’ll also need a boolean value to represent whether the word is horizontal or vertical in orientation.

javascript object representing a word on a crossword puzzle

We’ll represent words using a word object we create ourselves. You can check it out here.

Representing the Crossword Puzzle

The crossword puzzle objects we’re creating are representations of fully completed crossword puzzles. Each one will have various functions serving different purposes. Here is the comprehensive list of each function and what it does:

  • update: Try to add a word to the grid.
  • canBePlaced: Check if a word can be added to the grid.
  • getIntersections: Returns a count of the number of word intersections in the grid.
  • placementLegal: Determines if a word can legally be placed at a specific row/column position.
  • invadingTerritory: Determines if a word will invade another word’s territory at a certain position.
  • endOfWord: Determines if a particular row/column position corresponds to the end of the word.
  • doesCharacterExist: Determines if a character exists at a certain position.
  • overwritingHorizontalWord: Determines if placing a character at a particular row/column would be overwriting a horizontal word.
  • overwritingVerticalWord: Determines if placing a character at a particular row/column would be overwriting a vertical word
  • isInterference: Checks for interference at a set of row/column positions.
  • isLetter: Checks if there is a letter at a row/column position.
  • isEmptyCell: Checks if a row/column position is empty.
  • addWord: Adds a word to the grid.
  • fitsOnGrid: Checks if a word fits within the bounds of the grid.
  • isValidPosition: Checks if a row/column position is a valid one for the grid.

You can check it out here.

Generating the Best Crossword Puzzle

Once we have the ability to place words on a grid we need to start making a whole bunch of crossword puzzles. Then, we need to pick the best puzzle and display it on the screen. The top-level function that does all this is called createCrosswordPuzzle.

The createCrosswordPuzzle function has several nested functions that help accomplish its goals. Here is the comprehensive list of each function and what it does:

  • generateGrids: Generate a bunch of crossword puzzles.
  • attemptToPlaceWordOnGrid: Take a given a word and try to place it on the crossword puzzle.
  • getAWordToTry: Fetch a word that we want to try placing on the crossword puzzle.
  • getBestGrid: Pick the best crossword puzzle from the ones we generated.
  • isGoodWord: Determine if a word is a good candidate to try placing on crossword puzzle based on the letters on the board.
  • displayCrosswordPuzzle: Show the crossword puzzle on the screen.
  • pushUsedWords: Mark a word as used and add its letters to a list of ones present on the crossword puzzle.

In addition to the functions above, this file contains some helper functions for getting unused words and various random values.

You can check it out here.

Performance Optimizations

I hope the previous sections have helped you see how all the pieces fit together. A crossword puzzle generator is a non-trivial problem, but breaking it down into smaller problems is a good way to approach it. In fact, that’s a good approach for any programming task.

I would like to cover one more aspect in further detail. By default, this code isn’t very fast. There is a very large amount of nested looping.

I’m going to share with you the steps I took to make it faster. If you know of better algorithms I’d love for you to write me a comment. This is a life long craft, and I’m as much of a student as I am a teacher.

There are 4 steps I took to improve the performance. I’ll refer to them as Adjusting The Inputs, Smart Word Picking, Knowing When To Quit, and Calling It Good Enough.

Adjusting The Inputs

There are two variables that can have a major affect on the speed of the program. One controls the number of grids to make, and the other controls the number of attempts to fit words on the grid.

Adjusting the inputs to the crossword puzzle

I found that a high number of attempts meant that I could lower the total number of grids to make. A high number of attempts helps ensure that the crossword puzzle will be densely packed with words.

Play around with these inputs yourself and notice how they affect the speed of the program and what the crossword puzzle looks like. I tried to optimize for creating a good looking crossword puzzle while not causing the page to timeout.

Smart Word Picking

One way to speed things up is to limit our word selection to words that have a chance at being placed on the grid.

At first I picked each word totally at random, but that resulted in trying to place words on the grid that had no possible way of fitting. So I wasted a bunch of time looping through the grid, and I also wasted attempts at fitting words on the grid.

To fix this I started keeping a list of which letters exist on the crossword puzzle. That way I could limit my word selection to only words that start with one of those letters. I created the function below to aid in identifying good words to try. It isn’t perfect, but it prevents some unnecessary looping.

javascript function for smart word picking

Knowing When To Quit

Sometimes you just gotta know when to quit. As more words are added to the crossword puzzle, the likelihood of successfully placing another word goes down. There isn’t as much space for it, and the requirements for placement become stricter.

Eventually we’ll start failing for an exceedingly long time to place a word on the grid. I decided it would be better to just end things at that point. If we are having trouble placing words on the grid it is probably pretty full anyways.

It’s the law of diminishing returns at work.

Here is the section of code where this takes place. The number 470 is pretty arbitrary. It seemed about right after doing some testing.

stop placing words when we start failing a lot

Calling It Good Enough

The final step I took to improve performance was to stop generating crossword puzzles once I had created one with at least 4 word intersections.

A crossword puzzle with 4 word intersections usually looks pretty good, so stopping once we have one of those cuts down on our average generation time.

See below.

breaking out when a crossword puzzle is good enough

Conclusion

Wow that was a long and tedious post. I really hope somebody actually reads this far. If you do, leave me a comment. It will make me feel better about writing all of this 😂

I hope you’ve been able to get your own crossword puzzle generator up and running. It’s a fun project with a lot of details to consider. If you can implement it yourself and understand how all the pieces work you’ll definitely be a better developer for it.

As always, thanks for reading. Follow me on Twitter if you’d like to keep up with what I’m up to.

You can also subscribe to my blog if you’d like some tips on writing functions and to have my blog posts delivered to your inbox.

How To Build An Ear Trainer with JavaScript

song cover music note

Hey all you cool cats and kittens! Since we are all stuck at home trying to avoid the apocalypse, I thought it would be a good time for a new programming tutorial.

Carole Baskin

I’ve heard some encouraging news that at least one teacher has been using these tutorials to keep their kids doing something constructive during the quarantines. So that has made me happy and increased my motivation to be productive.

Instead of building another game like minesweeper or hangman, this tutorial will focus on another one of my passions: music.

Click here to check out the ear trainer you’ll be building!

Click here to view the code!

I’m no professional by any stretch of the imagination, but I’ve always had love for music. Whether it was church hymns or classic rock, music was an important part of every car ride as kid, and I’m still trying to get better at singing and playing guitar (You can check out my progress if you’re interested).

Ear Training

One area I’ve been working on is my ability to recognize common music intervals, like major thirds, perfect fifths, and octaves. A common term for this is “ear training”. You can start doing this by associating the different intervals with the beginning of certain songs ( fourth = Amazing Grace, fifth = Star Wars Theme, octave = The Office Theme, etc). But my goal is for my ear to eventually recognize these intervals instantaneously.

I’ve downloaded various apps to help me do this, but it occurred to me that I could combine my passions and build one myself!

So that’s what we’ll be covering in this tutorial: how to build an ear trainer with JavaScript. For those less musically inclined, we’re also going to be using two programming techniques I haven’t covered in previous tutorials: playing audio and local client-side storage. Let’s get started! If you get lost, the full project is on github.

Making the Music

The first thing that I had to do was create the audio files. I used a program called Audacity to record myself playing various intervals on my guitar. I used a naming convention of {intervalName}{integer} in order to make the programming task easier.

You can record your own intervals and follow my naming convention, or if you’re in a hurry you can just download or point your code to the files I created. You can find them all here on my blog, or here on github.

Structure and Style

I’m not going to focus too much on describing how the page is structured and styled. I’ll leave it as an exercise for you to explore the HTML and CSS on your own. You’re welcome to ask questions in the comment section if you run into any issues with the files provided.

The main takeaways are that we have a start button, a replay interval button, a confirm answer button, a drop down list to pick our answer, and an area for displaying messages. Our JavaScript code will interact with each of these elements as the state of the test progresses.

Also, you’ll want to make sure you update any paths so that they are pointed to where your files are located. For example, if you add your own audio files, you’ll have to make sure your code is looking in the right directory for them.

Variables

Alright it is time to move on and finally start talking about the JavaScript. We’ll begin by discussing the variables that will be changed as the player progresses through the test:

let questions = [];
let answers = [];
let questionIndex = 0;
let correctAnswers = 0;
let questionCount = 20;
let beginTime = "";

As you can see, we’re initializing an two empty arrays. One array is for keeping track of the questions, and the other is for keeping track of the answers.

We’re also initializing three variables holding integers. The questionIndex variable keeps track of which question we are on, while the questionCount variable keeps track of the total number of questions. The correctAnswers variable will be updated every time an interval is guessed correctly.

Also, we have a beginTime variable which will be set when the quiz begins. This variable will help us determine if the player has beaten his/her previous high score.

Helper Functions

Next, let’s talk about some helper functions we are going to create to make our lives easier. We’ll reuse them throughout the code, so it’s best to familiarize yourself with them early on.

Play Interval

let playInterval = function( id )
{
document.getElementById(id).play();
}

This function takes the id of an html element as a parameter. It attempts to get the element by id and call play on it. This will work if the id belongs to an audio element, but you won’t have much luck if it doesn’t. The audio elements are present in the HTML document, and each one is associated with a unique audio file.

Hide

let hide = function( id )
{
  document.getElementById(id).style.display="none";
}

The hide function takes an id and sets its display property to none. We could write this every time we need it, but “hide” is much more terse and easier to read.

Show

let show = function( id, value )
{
let element = document.getElementById(id);
element.style.display = "";
if( value !== undefined )
{
element.innerHTML = value;
}
}

The show function is the opposite of the hide function in that it makes an element visible. It also has the optional ability of setting the inner HTML content of the element. If no content is provided it won’t set it to anything and the element’s content will remain unchanged.

Get Random Integer

let getRandomInteger = function( min, max )
{
   return Math.floor( 
          Math.random() * ( max - min ) ) + min;
}

This function takes a min and max value as parameters and returns a random integer lying somewhere in between them. It will include the min but not the max as possible outputs.

Get Random Index

let getRandomIndex = function()
{
return getRandomInteger( 0, 10 );
}

This function builds on the getRandomInteger function. It’s purpose is to return a random valid index. I’ve created ten audio files for each interval, with indexes ranging from 0 to 9. So we’ll pass in 0 as the min value and 10 as the max value to satisfy our requirements.

Get Random Interval

let getRandomInterval = function()
{
    let interval = getRandomInteger( 0, 5 );
    return getInterval( interval );
}

This function is similar to getRandomIndex. You’ll call this function when you want to retrieve a random interval. In the select drop down you’ll notice that we have mapped each interval type to an integer. We have five intervals: major thirds, minor thirds, perfect fourths, perfect fifths, and octaves. These correspond to the integers 0 through 4.

After getting the random integer we call a function called getInterval to get the interval object. Keep reading to find out what that function does.

Get Interval

let getInterval = function( id )
{
    id = id + "";
    let interval = { 
                     code: "third", 
                     name: "Major Third"
                   }
    switch( id )
    {
      case "0":
        interval = { 
                     code: "third", 
                     name: "Major Third" 
                   };
        break;
      case "1":
        interval = { 
                     code: "minorthird", 
                     name: "Minor Third"
                   };
        break;
      case "2":
        interval = {
                     code: "fourth", 
                     name: "Perfect Fourth" 
                   };
        break;
      case "3":
        interval = { 
                     code: "fifth", 
                     name: "Perfect Fifth"
                   };
        break;
      case "4":
        interval = { 
                     code: "octave", 
                     name: "Octave"
                   };
        break;
      default:
        // Return whatever was set as the default
    }

    return interval;
}

The purpose of this function is to retrieve the interval object for whatever interval id was passed in. An interval object consists of a code and a name. The code matches the name of the audio file without the attached index number. The name is for display purposes.

Generating the Test

Now that we have some helpful functions created, let’s start building the test itself. For starters, we are going to need some values in our questions and answers arrays. Let’s look at where this get populated, in a function called, generateTest.

How to build an ear trainer with javascript: Generate Test

This function is called when the player clicks on the start test button. The first thing that happens is we hide and show some elements on the screen. We show the question area, which includes our buttons for replaying sounds and choosing answers. We hide the start test button because at this point the test is already underway. Also, we show the message area with a non-breaking space. This is to keep the size of the container the same whether there is a message to display or not.

The next thing we do, after initializing a few local variables, is start adding questions and answers until we have reached the number set by the questionCount variable. We set each question to a random index appended to a random interval code. The random interval is then stored at the same index in the parallel answers array.

Finally, we set the beginTime of the test, and proceed to the next question by calling the appropriately named, nextQuestion function.

Proceeding to the Next Question

How to build an ear trainer with javascript: Next question function

The nextQuestion function is a pretty simple one. It does two things. First, it will show which question the player is on. Next it will play the audio file corresponding to the interval in question.

Replaying the Interval

What if the player needs to hear the interval again before answering? In that case they can trigger the replayInterval function by clicking on the replay interval button. Notice how boring my variable and function names are? That’s a good thing.

How to build an ear trainer with javascript: replay interval

This function is even simpler than nextQuestion. All we do is call play interval and pass in the current question that we are on.

Choosing an Answer

choosing a final answer for interval

The player selects his/her desired answer from the drop down list, and then clicks on the confirm answer button to guess what the interval is. When this happens, the confirmAnswer function is called.

Confirm answer function

The first thing that happens is the answer is evaluated to see if the player guess correctly. We’ll cover that function in a bit.

Next, the questionIndex is updated. If the questionIndex is less than the questionCount, we call the nextQuestion function. Otherwise, we call the finishGame function.

Evaluating the Answer

evaluating the answer for the interval

The purpose of the evaluateAnswer function is to determine if the player answered correctly and update the state of the game appropriately. Fortunately, the consequences for answering incorrectly will not be nearly as dire as in Indiana Jones.

How to build an ear trainer with javascript: evaluate answer

The first thing we do is retrieve the answer from the selected option in the drop down list. Then we get the interval object by calling getInterval.

Finally, we check if the chosen interval’s code matches the one we have stored in our answers array. If the answer is correct, we increment the correctAnswers count and don’t show a message. If the answer is wrong, we show a message to the player informing them of what the correct answer was.

Finishing the Game

How to build an ear trainer with javascript: Finish the game

After the last question has been answered we need to show the start button again and hide the question area.

Next, we need to determine the player’s score, which consists of the number of correct questions and the total time it took him/her to complete the test.

Before showing the score to the player we will determine if he/she beat his/her previous high score. This will help us determine which message to show on the screen.

We find this out by calling the saveHighScore function.

Saving a High Score

George from Seinfeld with frogger

We will be storing the high score client side in the player’s web browser. This means that the high score will persist even if the player closes their browser. This feature will allow players to compete against themselves and become faster and more accurate in their ability to guess intervals.

Save high score

We start out by assuming that the player did not beat his/her high score. After grabbing the score and time out of local storage, we check if they did beat it. We consider a score better if the player answered more questions correctly or answered the same number correctly in less time. If the player beat his/her high score, we override the values in local storage.

Conclusion

That’s it! You have successfully created your own ear trainer. You should be proud of yourself.

From here you can go in lots of different directions. I can think of so many features to add that are beyond the scope of this tutorial. You could add more intervals, descending and ascending intervals, or the ability to choose a subset of intervals you want to train on. The list goes on and on.

Have you implemented other cool feature ideas? Are you stuck on anything you saw here? I’d love to hear from you in the comments. Be sure to subscribe to stay up to date with the latest content.

NULL Values in SQL Queries

NULL Values in SQL Queries

Today’s post is about NULL values in SQL, and comes courtesy of my friend and database wizard, Kaley. You should check out his website if you’d like to learn more about SQL, Oracle database, and making queries run faster .


Here’s a topic that gets a lot of budding developers in trouble–the concept of NULL values in SQL queries.

Whenever you issue a SQL query to a database…and you want to know whether a column has a NULL value in it…what is the proper way to write a query that will find the result?

Should you use a query like this?

SELECT * FROM SOME_TABLE
WHERE SOME_COLUMN = NULL

Or! Should you use a query like this?

SELECT * FROM SOME_TABLE
WHERE SOME_COLUMN IS NULL

…The answer is, you should be using the second query (WHERE SOME_COLUMN IS NULL).

Now why is that?

We don’t use the “IS” keyword with any other comparisons in the database, right?

If we want to know if a field is equal to one, we use a WHERE clause like this:

WHERE SOME_COLUMN = 1

So why on earth would we do the IS keyword with a NULL value? Why would we need to treat NULL differently?

The answer is this: In SQL, NULL represents the concept of “unknown” (so a NULL value represents an “unknown” value).

Null as an Unknown

In most databases, there is a difference between NULL and an empty string (represented by a “double apostrophe” or ”).

But this isn’t always true for all databases:  For example, Oracle database won’t allow you to have an empty string. Anytime Oracle database sees an empty string, it automatically converts the empty string into a NULL value.

For the majority of the other databases out there, though, a NULL value is treated differently than an empty string:

  • An empty string is treated like a known value where there is no value.
  • A NULL value is treated like a value that is not known.

This would be the difference between me asking the question, “What was U.S President Theodore Roosevelt’s middle name?”

  • One answer might be, “Well, I don’t know what Theodore Roosevelt’s middle name is.” (This idea could be represented by a NULL value in the MIDDLE_NAME column for Theodore Roosevelt’s record)
  • Another possible answer could be “President Theodore Roosevelt actually didn’t have a middle name. His parents never gave him a middle name, and I know for a fact that Theodore Roosevelt didn’t have a middle name.” (You would represent that by putting an empty string, or a ” into the MIDDLE_NAME column)

Oracle database is the most notable exception where those two values are actually both going to be represented by NULL–most databases other than Oracle are going to treat NULL and an empty string very differently.

As long as you can remember that a NULL value represents an unknown value, then this is going to help you craft your SQL queries, and help you work around some of the trickier situations that you can get in with NULL values.

If, for example, you were to have a query that uses a WHERE clause like this:

SELECT * FROM SOME_TABLE
WHERE 1 = 1

This query will return rows (assuming SOME_TABLE isn’t an empty table!) because the expression “1 = 1” is provably true…it can be proven to be true.

If I were to say:

SELECT * FROM SOME_TABLE
WHERE 1 = 0

…then the database sees this and evaluates “1 = 0” as false (meaning this query would never return any rows).

But if I were to say:

SELECT * FROM SOME_TABLE
WHERE 1 = NULL

The database basically goes, “I don’t know if these two values (1 and our black-box NULL value) are equal”…so it doesn’t return any records.

Ternary Logic

When you have a WHERE clause in a SQL query, it can have one of three different results:

  • It can be true (and it will return rows)
  • It can be false (and it won’t return rows)
  • Or it can be NULL or unknown (an unknown is also not going to return values)

You may be thinking, “Okay, but why do I care that there’s a difference between false and null since the database handles those two values exactly the same?”

Well, let me show you where you can run into trouble:  Let’s introduce the NOT() condition.

If you were to say:

SELECT * FROM SOME_TABLE
WHERE NOT(1 = 1)

Then the database is first going to evaluate 1 = 1 and say, “Okay, that’s clearly true.”

But then it’s going to apply the NOT() condition to it. The database is going to go, “Well true, when notted, turns to false…so the NOT() condition causes our WHERE clause to be false here.”

So the query above isn’t going to return any records.

However, if you were to say:

SELECT * FROM SOME_TABLE
WHERE NOT(1 = 0)

Then the database first evaluates expression 1 = 0 and says, “That’s clearly false.”

But then it’s going to apply the NOT() condition, which will give us the opposite result, so it becomes true.

So this query will return records!

What if I issued the following query though?

SELECT * FROM SOME_TABLE
WHERE NOT(1 = NULL)

The database is first going to evaluate 1 = NULL. (Remember, it’s going to treat NULL like an unknown value!)

It’s going to say, “I can’t say whether or not 1 is equal to NULL because I don’t know what the NULL (unknown) value is.”

So it doesn’t yield a true result, and it doesn’t yield a false result–it instead yields a NULL (or unknown) result.

This NULL result is going to be interpreted by the NOT() operator.

Whenever you take a NULL and you put it in a NOT() condition…the result is another NULL! (the opposite of unknown is…well…another unknown).

So the NOT() operator doesn’t do anything with null conditions.

So NEITHER of these queries…

SELECT * FROM SOME_TABLE
WHERE NOT(1 = NULL)

SELECT * FROM SOME_TABLE
WHERE 1 = NULL

…is ever going to return any records…even though they’re opposites!

NULL and NOT IN

If I issued a query with a WHERE clause like this:

SELECT * FROM SOME_TABLE
WHERE 1 IN (1, 2, 3, 4, NULL)

…then clearly the WHERE clause is going to be true, and this query will return records, since 1 is in our IN list…

But if I were to say:

SELECT * FROM SOME_TABLE
WHERE 1 NOT IN (1, 2, 3, 4, NULL)

Then clearly this is going to be false, and this query will never return records, since the number 1 appears in our IN list and we’re saying “NOT IN”…

Now what if I were to say something like this?

SELECT * FROM SOME_TABLE
WHERE 5 NOT IN (1, 2, 3, 4, NULL)

This WHERE clause will never return any records, since it is not provably true (it cannot be proven to be true). The number 5 doesn’t explicitly appear in the “IN” list–But 5 could be inside our “black box” NULL value (the database doesn’t necessarily know what the value of NULL is).

This yields a NULL result (meaning an unknown result) and this WHERE clause is never going to return any records.

This is why it’s important to consider a NULL value to be equivalent to an unknown value–it’s going to help you whenever you craft complex SQL queries.

Hopefully you’re now equipped to deal with NULL values in SQL queries! For more information on SQL, Oracle database, and making queries run faster, visit blog.tuningsql.com.

A Web Developer’s Attempt to Make Pong with Unity in One Night

Pong in Unity

I’m a solid developer. Don’t get me wrong, I’m not the best in the world, but I can think logically and solve problems. Still, I find myself in awe when I look at the work produced by the giants in our field.

As a web developer I, along with millions of others, depend on a few tools conceived in the mind of Linus Torvalds. Without Linux and Git, my job would be a lot more frustrating. But Linus is only the first of many people that come to mind. So many important languages and tools are the creations of single, brilliant individuals.

Perhaps most inspiring of all, yet often overlooked, are video game developers. My theory is because they often work in large teams they don’t always get the individual credit they deserve. Guys like John Carmack and the founders of Naughty Dog have worked on the bleeding edge of technology while creating software that has brought more joy to people than the latest front end Javascript framework ever will. You should read the story of how Naughty Dog created Crash Bandicoot. It’s incredible.

Getting Inspired

I’ve always romanticized game development. I think every kid who grew up playing video games has dreamed of building a masterpiece themselves. Even as an adult I sometimes dream about undertaking such an ambitious project.

These thoughts have inspired me to delve into that world as a bit of a hobby. You all have probably seen my previous game tutorials using web technologies, but I wanted to challenge myself a bit more with something different and closer to the real thing.

I decided to build pong in one night (or two) using the Unity Engine (Version 2019.2.18f1). Unity is C# based game development engine used by a lot of indie game developers. I’ve followed some in-depth Unity tutorials in the past, but never built something on my own. Let’s just say that the finished product is not quite ready for the market, but it’s as done as I care to be for this blog post:

Unity is free to use for individuals, and you’re welcome to download my project files below and boot them up. This post won’t be a full tutorial though, just a higher level overview of what I did and what I learned as I struggled with a new development environment.

How I Made Something Kind Of Like Pong

I started by following this helpful tutorial, and then customized it to be a more complete game. I find that to be a helpful tactic when solving new problems: find somebody to hold your hand at first, and then spread your wings from there.

Main Camera

Camera for Pong

I built everything with 3D objects that I created directly in Unity. The main camera is fixed in position and used for showing the game as if it were in 2D. This trick seems like it could be useful in other games as well.

Directional Light

Directional Light

This object was there when I created the project. I assume it is providing light to the scene, but I really don’t know how important it is!

Bumper (2)

Bumpers for Pong players 1 and 2

These are controlled by players one and two and are used to hit the ball back and forth. They are controlled by the following script:

Bumper script

Every frame we check to see if we need to translate the position of the bumper. If it is within the acceptable range we translate it by a factor of the speed and input direction of the bumper as well as the time in seconds since the last frame. Otherwise we force the bumper back to within its acceptable bounds.

Wall (2)

Walls for Pong

These are the outer walls that keep the ball in play. Pretty straightforward stuff.

Background

Pong background

A big black sheet providing a background that provides contrast with the rest of the game.

Ball

Ball

The ball is what the players are hitting back and forth. It has an attached script:

Ball script

This script initializes the position of the ball in the middle of the screen and sets it off in a semi random direction. The ball object also contains a method called “Halt” which will stop the ball and fix it in the middle of the screen. This is called when the game ends.

Goal (2)

Pong goals

The goals are where the players need to get the ball to. Each goal object has this script attached:

Goal script

The script checks for collisions with the ball. On each collision it checks to see how many goals have been scored and, if the game is over, displays the winning message and stops the ball in the middle of the screen. If the game is still going on then it resets the ball to the center of the screen and sets it off in a semi-random direction.

I also included a check for user input here on every frame. There is a probably a better place to put this, but I’m just a humble web developer bumbling my way through this. You can press “r” to reset the game, and “escape” to close the game.

Score

Score

I used 3D text objects for displaying the score. They look really bad. I imagine there must be a better way to do this. Here is the script to control them:

Score script

Every frame I’m just setting the score text to the appropriate number of goals.

Winning Message

Winning Message

Finally, the last object. I’m really tired of uploading screen shots. This message is invisible until the game is over. Then it displays either player one or player 2 as the winner.

Important Project Settings

I changed a few defaults in the project settings to make everything work reasonably well.

I had to make the physics bouncy by default.

Physics settings

I also had to setup keyboard controls for player 1 and 2 via the input settings.

Input settings

Lessons Learned

  • The physics engine is powerful and can help you a lot, but I need to understand it better to use it to its fullest extent. Sometimes the ball just rolls perfectly horizontal along the wall, and I’m not sure how to fix that. I’ve even managed to get the ball to stop entirely.
  • Zero gravity was important.
  • Collision detection is easy to get wrong. I know I need to use Rigidbody objects, but I don’t totally grasp the fundamentals quite yet. I had to increase the mass of the goals to a huge number to prevent them from moving on collision with the ball. I have the feeling I’m doing something silly there.
  • I probably could benefit from researching some Unity best practices. Often I solved the problems but felt uneasy about the solutions. Maybe something like this would help.
  • The 3D text objects look really bad. I bet there is a better way to do that.
  • Some of the design patterns I learned in web development are relevant, but I get the feeling that game development requires a different way of thinking a lot of the time.
  • A trusty search engine is your friend.