Canvas, Chickens and Gimp

This past week has been spent building a “Rogue-like Dungeon Crawler” as a project for FreeCodeCamp.

This marks the end of the React section of the course and is roughly the half-way point for finishing the Data Visualization certificate for me. As this was the final project in a section, I had feared it would crush me. The previous challenge, Build a Game of Life was incredibly difficult for me. For some reason I kept hitting bug after bug after bug, and if I remember correctly it took just over three weeks to finish, as well as a Meetup group of JavaScript enthusiasts’ help debugging.

This dungeon game was the complete opposite. Granted, the project was bigger than anything I’ve done previously, weighing in at just shy of 1,200 lines of code and 22 PNG files, not including all of the node modules required to build it, but size does not necessarily indicate difficulty.

For me, the key is to break the project up into small pieces, then break those pieces into even smaller pieces. Going from small task to small task simplifies even the largest projects.

Canvas

Given that the project is part of the React section, my initial thought was to build the entire app with React. I have spoken with someone who did this and I guess the final product was such a resource hog that her laptop would overheat. Fearing this, and seeing how taxing the Game of Life was on my system, step one for me was buying a new laptop. I figured stepping up from an i5 to an i7, and from 4gb memory to 16gb would give me everything I needed to slay this next challenge.

The example project just had some colored squares moving around the board which did not inspire me too much. I really wanted a dungeon that looked like a dungeon, with heroes, villains, things that look reasonably good. Having seen some examples of what is possible with HTML Canvas I decided to do some reading to see if it would give me better options for a good looking game.

Canvas, as it turns out, is the perfect solution. For my use-case it has really low overhead and it seems to play nice with React.

What’s That About A Chicken And A Gimp?

My favorite thing about building my game this way is that it allowed me to create PNG files in the open source graphics program, Gimp. The majority of my game is made up of tiny, 49 pixel by 49 pixel tiles. Right in the center of it all is my hero, a chicken. Well, if you want to be technical it’s a rooster, but there’s no need to get all pedantic about farm animals.

So, in the end, the project was much simpler than anticipated. Lots of code, lots of images, but really nothing too difficult to grasp. At least I got a sweet new laptop out of the deal.

Back To The Basics

Working through the course material at FreeCodeCamp moves you rather quickly from one area of Web Dev to the next. I began with basic HTML, CSS and a little jQuery. I made a few projects using what I learned, and then the course moved on to JavaScript and algorithm scripting. After many lessons in JavaScript I created a few more projects using my new-found JavaScript knowledge. All of this culminated with me earning my front-end certificate.

some random code

Next came the Data Visualization portion of the FCC course. This starts off right away with 5 projects under the heading “React”. This was a little jarring for me. Up until this point there had been a pretty consistent pattern of “here’s how you do a thing” then “go put that thing to use”. This pattern was not only broken, but shattered here in the Data Visualization section of the course.

In all fairness to FCC, although the project introduction videos specifically instructed the students to use React and Sass for these challenges, those instructions were omitted in the assignment text. I suppose I could have just tried to complete the assignments using the HTML/CSS/JS I had previously learned but I dismissed that idea rather quickly. React seemed like a pretty useful tool and I had noticed while nosing around on Indeed.com that many companies were looking for people who were familiar with React. So, I set out to learn React.

This Is Not A Story About Learning React

Phew, thank the coding gods. I’ve written my thoughts on React in a previous post, so I won’t duplicate all that effort here. However, React is vastly different than most of the things I learned while earning the first certificate. Well, I shouldn’t say different, it’s more in how it’s applied. And this leads me to the crux of today’s post. While working on the third React challenge, a project to create a recipe box with persistent local storage and functionality which allows the user to create, edit and delete recipes, I found the FCC help chat room. Most of the people I encounter here are working through the first certificate, which I had completed about a month prior to discovering this chat room. They come to ask questions about the lessons they’re working on and get help from those who have already learned what they need help with. My first thought while reading through these questions was, “holy crap I’ve forgotten all of that.”

Learning The New Without Retaining The Old

I suppose charging through the front-end lessons felt good at the time, but here I was faced with the realization that I had failed to retain all but a fraction of what I had learned. It was a classic ‘use it or lose it’ scenario. This in-and-of itself was not necessarily a bad thing; I know how to find the information if I need it, but at some level I felt bad for not retaining the information.

Since having that realization I’ve made a point to spend at least a portion of most days with the FCC help chat room open. While I may not actively be helping people, I do read through the questions and answers. I think about solutions others are coming up with, read through their code and try to figure out what I would have done differently or what I could incorporate in my future projects. As more and more questions get asked, I find that I recall more and more answers. It may not be perfect recollection but it’s definitely better than I had. Also, there’s something about explaining a concept to someone else that really helps me understand it myself.

Learning How To Learn

Web dev, front-end development, programming, coding, whatever you want to call it, is not easy. I’m sure at some point people get to a place where they can get through most of a day purely on the knowledge they already have, but I don’t believe that people live in that state for very long. All technology changes at a rapid pace, and everything you are confident you know today will be deprecated tomorrow.

Such A Gloomy Outlook

Quite the opposite for me, really. The worst thing that has happened to me professionally is stagnation. I really dislike knowing that everything I do today will be a repeat of yesterday, the day before, and the day before that. This is one of the key reasons I’m so infatuated with the idea of becoming a web developer. Some day I hope to be at the top of the game, on the very cutting edge of technology. And when that happens, the game will change and I will have a whole new game to learn.

The important thing for me is to always feel like there’s another mountain to climb, another path to explore, another sea to sail. I’ve always loved the quote:

And when Alexander saw the breadth of his domain, he wept for there were no more worlds to conquer.

I don’t know if Alexander the Great really said that, or Caesar to whom it’s often mis-attributed, but I can empathize with it. Maybe it’s a product of my limited, 30-something years of life experience, but I do not like the thought of never doing or learning anything again.

Learning How To Learn

All this rambling leads here. In web dev, you will always encounter things you don’t know. For me, I’m more surprised when I encounter things I do know. For everything else the most important thing you can learn is how to find what you need and the obvious solution there is Google. I don’t know how programmers did it before Google. I’m imagining huge stacks of dog-eared books, manuals, and a whole host of other reference material which will sadly be out of date by the time it makes it to press. I feel very lucky to have Google. And I use it. A lot. One thing that amazes me is now I can ask google something quite vague and ambiguous like “what does sort return” and third result down is a link from the Mozilla Developer’s Network telling me all about JavaScript’s Array.prototype.sort() method.

I wonder if programmers at Microsoft are required to use Bing? Maybe that’s why Windows is the way it is?

I’ve spent so much time pouring through github README.md;s, Stack Overflow, MDN. Every question I’ve ever had I’ve been able to find an answer to, but the real challenge was learning how to ask the right questions, and how to vet the answers. Many times I’ve gone down a rabbit hole of solutions only to find the answer was presented seven years ago and is no longer viable.

In summation, to bastardize a quote from John Van Buren,

Google early, and Google often.

Most of my coding time is spent debugging. Most of my debugging time is spent Googling. And cussing. It’s really about 50/50.

NPM and Building Locally

Part of learning React for me involved learning a bit about Node.JS and NPM (Node Package Manager), Webpack, and some of their associated tools.
A list of files in my node_modules folder
I do love writing code in the text editor (I currently use Atom) so getting used to the NPM way of doing things was a logical step in my learning. For anyone not familiar, NPM is a utility that tracks all of the tools you use to develop your website (node modules), keeps them up-to-date or at a certain release depending on your requirements, and makes it easy for anyone else to install your package by automatically including all the necessary modules.

All of this magic happens through a file called package.json.

Looking in my node_modules folder, I see a total of 848 files for my current project. This would be intimidating to try to manage on my own, but having NPM manage it for me means that I don’t need to know what’s in there. In fact, the first time I’ve looked in that folder was to take that picture. What I do pay attention to is the package.json file, which looks like this:

{
  "name": "portfolio",
  "version": "1.0.0",
  "description": "A place to show what I'm working on",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --open",
    "build": "NODE_ENV='production' webpack -p",
    "deploy": "npm run build && firebase deploy",
    "firebase-init": "firebase login && firebase init"
  },
  "babel": {
    "presets": [
      "env",
      "react"
    ]
  },
  "author": "Kyle Holm",
  "license": "ISC",
  "dependencies": {
    "prop-types": "^15.5.8",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-env": "^1.4.0",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.0",
    "file-loader": "^0.11.1",
    "firebase-tools": "^3.6.1",
    "html-webpack-plugin": "^2.28.0",
    "image-webpack-loader": "^3.3.0",
    "sass-loader": "^6.0.3",
    "style-loader": "^0.16.1",
    "webpack": "^2.4.1",
    "webpack-dev-server": "^2.4.5"
  }
}

Even this can appear daunting, but most of this is generated automatically when running commands in the console. In fact, the only lines I had to add manually are the "scripts": entries and the "babel": entries.

Looking at each section of this file makes it a bit less intimidating. All we have is a bunch of key/value pairs, each with a specific purpose. I’m not going to go into details about all the things happening in this file, but everything in my node_modules folder gets managed right here.

I’ve heard that there are other package managers out there, and maybe someday I will branch out and give them a try. For today, I really like using NPM and all the hard work it does for me. When I team it up with Webpack, I feel like I can really focus more on creating, and less on the tools I use to create. I’ll talk more about Webpack later.

My Adventures in React

I haven’t written anything in a while, and this is largely due to attempting to learn React.

For anyone who is unfamiliar, React, or React.js, is a JavaScript library used for building websites. Originally developed by Facebook, it is an extremely popular utility which allows websites to be built quickly, efficiently and provides a great framework for building responsive, interactive sites/apps.

All that being said, React is a pain-in-the-butt. For a beginner like myself, React has a pretty steep learning curve and it has nearly crushed my soul.

What Makes React Different?

I’d like to preface this by saying that React is not a new technology. It has been around for some time now, and has a huge following, so anything I have to say about what React is and what it can do has undoubtedly been covered extensively by people with much more skill & knowledge than I have.

With that in mind, here are some of my observations:

  • React uses small components to build big things
  • React components are written in JavaScript
  • JSX is used to write pseudo html inside JavaScript
  • React forces coders to learn good code.
  • React has components manage state, rather than the DOM

Let’s look at each of these things, so that maybe I at least can understand them better.

Small Components

I have read in several places that good React components do a single thing. If you need to do two things, build two components. I have tried to take this approach, and the result is I end up with a lot of tiny components. I like this because every component has a single task and when it comes to debugging I know quickly where to look.

Another advantage here is when I read other people’s code who have taken this approach, I can pretty quickly get an idea of what they are trying to achieve.

Components Are Written In JavaScript

Well, this one’s pretty self-explanatory. Most of my React apps have an html page consisting mostly of

<div id='container'></div>

The entire markup is created in JavaScript through the React component’s render() function. This all gets rendered to a ‘virtual DOM’, which I’m told is a pretty great thing but I don’t understand the process well enough to really comment one way or the other.

JSX

As I mentioned above, the usage of html is pretty limited with React, and instead the markup is created inside the JavaScript. Since you can’t just write html inside JavaScript, instead we use a type of XML syntax called JSX, which will look a lot like html and ends up accomplishing much of the same things. But it’s not html.

Learn Good Code

This is more about best practices. With JavaScript in general, it’s best to create functions which accomplish a single task. This makes it easier to reuse these functions whenever a need arises and makes debugging a bit easier. Since React is just JavaScript, this practice remains ‘best practice’.

I didn’t realize the usefulness of this until I built my last project. Part of it utilized a modal window for user input and in the course of development I was faced with the decision of building multiple, similar modal windows every time I needed one, or just reusing the first one I built and passing the necessary differences as arguments. Seeing as how the modal window ended up consisting of around 10 different components with all associated CSS and state, re-usability was looking like a pretty good option. I don’t know if this choice made me a better coder, but it used less code and felt pretty awesome when I finished it.

Components Managing State

There have been so many times, while building standard html/css/js(jQuery) pages that I’ve needed a certain bit of information and resorted to using JavaScript (or more often jQuery because I’m lazy) to access pieces of my html to find the information.

In React, this is frowned upon. State lives in the components and once something is rendered to the DOM it is as good as gone and forgotten. If you need information displayed in the DOM you store it as state, then access the state as needed. If the information needs to change, it changes as state and then React will update everything associated with that state.

For me, at first, this was really confusing. I had always looked at coding from an imperative perspective, and felt it necessary to micromanage every step along the way. One of React’s greatest strengths is that it is declarative rather than imperative. You tell React what you want to do and React just does it. No need to spell it out every step of the way. When your state changes, React triggers a re-render and the changes get pushed to the DOM. No muss, no fuss.

Best Of All

Since growing in popularity, folks are realizing that React is not just for websites. React Native allows coders to build iOS, Android and Windows Mobile apps using React. React VR, you guessed it, is a framework for building VR apps using React. The long and short of it is, if you have a DOM there’s a good chance you can use React to develop for it.

For anyone wishing to learn React, the React Fundamentals Course by Tyler McGinnis was an excellent resource. The material is presented in an easy-to-understand format and you get the feeling that Tyler really understands what he’s teaching.

My Introduction to Bootstrap

As I discussed in my first post, First Steps in Web Development, I’m currently studying Front End Development through Free Code Camp.

The first exercises covered basic HTML and CSS, something I felt fairly comfortable with already, but there were some things that added to my knowledge. Prior to this course I had never heard of Bootstrap and I never knew that building responsive websites could be so simple. In just a few hours my web pages went from basic styling reminiscent of the old days of GeoCities, to relatively modern, sleek and stylish.

So What Is Bootstrap?

Much of the reference material I’ve read refers to Bootstrap as Twitter Bootstrap but I never really knew why. According to this article on Wikipedia Bootstrap was developed at Twitter as a framework to be used internally which would provide consistency throughout the company. In 2011 it was released as an open source project and began being picked up by web designers everywhere.

I am sure that I’ve only scratched the surface of Bootstrap’s capabilities, however there are a few functionalities I’ve used that now I can’t imagine doing without. One of the big things Bootstrap is known for is simplifying website layout by implementing a grid-like system of rows and columns. This makes it easy to put things where you want them, and choose how they will appear on smaller screens as well. But of all the functionality I’ve tried my favorite so far is a navigation header, or ‘navbar’, which is easily customized and implemented. With just a few simple lines of code you get results very similar to the navbar at the top of this page.

One of my favorite things about this navbar is the scaling. As the screen size is reduced, the buttons on the right side of the bar get rolled up into a drop-down menu. Here’s a Fiddle showing it in action. The example code navbar is set up for a single page where you would want to navigate up and down to different sections, but can easily be adapted to multiple pages by changing the href attributes to urls. If you were using the navbar to navigate a single page, consider building your body tag similar to:

<body data-spy="scroll" data-target="#navbar">
Or
<body data-spy="scroll" data-target="#navbar" data-offset='100'>

This will change the highlighting on the navbar items as you scroll, making it easy to identify where you’re at on the page at a glance. Of course, this is not necessary if you choose not to have the navbar stick to the top of the screen.

So That’s Bootstrap?

Well, yes and no. This is just a sample of one of the built-in items Bootstrap has to offer. As I continue my education in web development, I’m sure I’ll begin to run into some of the limitations of Bootstrap and maybe will eventually move away from it altogether. Until then, I will enjoy the ease of use and great results it provides.

A New Contender

There is a feature of CSS3 called <grid> which could be an interesting alternative to Bootstrap, or at the very least a viable option to replace some of Bootstrap’s alignment/positioning functionality. This feature is not widely supported by any browsers yet, but I believe it will start to gain traction as browsers are updated.

Becoming More Than A Beginner

I imagine most everyone who sets out to learn coding will at some point look at someone else’s code. I try to do this as much as possible, and I especially like to see how others have solved the same problems I’m working on. It is in these moments that I often realize just how far I have to go.

I Am Relatively New To Javascript

And my code shows it. Take for example this exercise from the beginning algorithm section of the course I’m working on:

One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount.

A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus ‘A’ ↔ ‘N’, ‘B’ ↔ ‘O’ and so on.

Write a function which takes a ROT13 encoded string as input and returns a decoded string.

All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.

My solution works. I know that if something works that’s the important thing, but I also know that for every solution I come up with, there’s a more elegant solution possible.

function rot13(str) { // LBH QVQ VG!
  var arrA = str.split('');
  for (var i = 0; i < arrA.length; i++) {
    if (arrA[i].match(/[a-z]/i)) {
      arrA[i] = translate(arrA[i]);
    } else {
      continue;
    }
  }
  return arrA.join('');
}

function translate(char) {
  var x = char.charCodeAt(0);
  var y = 0;
  if ((x - 13) < 65) {
    y = (x - 65);
    x = 13 - y;
    x = 91 - x;
  } else {
    x = (x - 13);
  }
  return String.fromCharCode(x);
}

rot13("SERR PBQR PNZC");

All things considered, it’s not a terribly difficult problem and it doesn’t necessarily require an overly complex solution. However, if I were sitting in a job interview and they asked me to code a solution to this problem (I don’t know if that would ever actually happen, as I’ve interviewed for exactly zero coding jobs at this point in my life) I would feel a lot better giving a more elegant solution just to show that my knowledge of Javascript is a bit deeper than the average beginner could learn in an afternoon.

Were I to solve this problem today, I would likely use Array.reduce() in place of the for (...) {...} loop, and rather than implementing a separate function to handle the math I’d use an inline function since I don’t need to call the math function anywhere else. So something like:

function rot13(str) { // LBH QVQ VG!
  return str.split('').reduce(function(a, b) {
    if (b.match(/[a-z]/i)) {
      var temp = function(x) {
        if ((x - 13) < 65) {
          x = 91 - (13 - (x - 65));
        } else {
          x = (x - 13);
        }
        return String.fromCharCode(x);
      };
      a.push(temp(b.charCodeAt(0)));
    } else {
      a.push(b);
    }
    return a;
  }, []).join('');
}

rot13("SERR PBQR PNZC");

As you can see, there’s not a great reduction in the number of lines of code, but the Intermediate Solution takes advantage of more advanced techniques which I feel would show a greater understanding of Javascript. I feel the math bit in the middle is the next portion to be improved upon, and I can’t wait to learn those things which would allow me to improve upon it.

What Does This Have To Do With Looking At Other’s Code?

I think Quincy Larson, creator of Free Code Camp, summed up my experience very well in this Youtube interview when he says, “Free Code Camp is essentially like self-learning together.” While there are many others currently doing the same course-work I’m doing, and many, many others who have already completed the course, when it comes down to it I’m learning all of this on my own. Sure, in the challenge text they may tell you to read some reference material, but anyone who can look at this reference page and then know how Array.reduce() works is a lot smarter than I am. So instead, I read others’ code to see how they use it and learn from their successes. Also, as I’ve mentioned before there are chatrooms, forums and message boards available to those needing help as well, but I generally try to find the solution on my own.

It’s fun to go back and re-solve old problems in new ways, and helps me see my progress. Having that kind of perspective really helps to keep me motivated.