Friday, September 18, 2015

Block Scoping - New in Node 4.0.0

Today wraps up "games week" on Amphibian.com. I had the frogs playing the lottery on Monday, Let's Make a Deal on Wednesday, and poker today. Since there's not much to discuss concerning poker being a game of skill or a game of chance, I'm back to discussing new JavaScript language features available in the recently released Node 4.0.0. (they've actually released 4.1.0 already but it's mostly just bug fixes).

So let's talk about Block Scoping!


This new ES6 feature gives you a new option for limiting the scope of declared variables to a block, statement, or expression. Just declare a variable with let instead of var and it won't be accessible to the entire function!

Here's an example that illustrates the point.

var x = 37;
if (x > 30) {
    let x = -1;
    let y = 900;
    console.log(x); // prints -1
    console.log(y); // prints 900
}
console.log(x); // prints 37
console.log(y); // prints undefined

if (x > 10) {
    var x = 5;
    var y = 777;
    console.log(x); // prints 5
    console.log(y); // prints 777
}
console.log(x); // prints 5
console.log(y); // prints 777

Inside the first if block, let x = -1 declares a block scoped variable x which is distinct from the global x variable declared on the first line. Changing it inside the block has no effect outside the block. By contrast, the second if block declares var x = 5, which isn't really much of a declaration at all. The x variable already in scope simply has its value reassigned. Once outside the block, it still has the value give it inside the block.

Also note the behavior of the y variable. Declared using let inside the first if block, it is undefined when used outside. But declaring it using var inside the second if block makes it global.

Declaring variables with let also works in for loops.

var i = 50;
for (let i = 0; i < 5; i++) {
    console.log(i); // prints 0 through 4
}
console.log(i); // prints 50

for (var j = 0; j < 5; j++) {
    console.log(j); // prints 0 through 4
}
console.log(j); // prints 5

The first loop, using let, prints the value of the variable i which is scoped to just the for loop. Outside of the loop, i still refers to the global variable. The second loop declares j with var and so j becomes available outside of the loop.

Making good use of let for variable declaration can make your code cleaner and lead to fewer bugs.

One final thing to note, however. While block scoping is available in Node 4.0.0+ it only works in strict mode. That means either launch node with the --use_strict flag or put
"use strict";
at the top of your source file. But you're probably using strict mode already, right?

Good. Now enjoy today's comic.

Amphibian.com comic for 18 September 2015

Wednesday, September 16, 2015

What Are the Odds?

I was going to return to discussions of new language features available in Node 4.0.0 today, but I feel like a discussion of today's comic is in order. Node's not going anywhere. I can talk about it on Friday.
Science! When you don't want a goat!

The Amphibian.com comic today is once again interactive as the story arc continues. Business Frog is trying to win money for the company instead of earning it. The lottery ticket plan from Monday failed, but with Science Frog's help maybe a television game show will work. Remember Let's Make a Deal? It spawned one of the most highly contested and poorly understood examples of the laws of probability...what is now known as the Monty Hall Problem.

The problem seems simple. The game show host, presumably Monty Hall, shows the contestant three doors. Behind one of the doors is the grand prize. Behind the other two are much less desirable prizes. In the classic description of the problem, the less desirable prizes are goats. I don't know why, but they are. Goats. Yes. After the contestant picks a door, Monty offers a deal. He'll give you whatever is behind one of the other two doors and the game ends. He opens one of the doors, revealing a goat. Do you want a goat? Probably not. You want the grand prize! So you continue. There are still two closed doors. Monty asks if you want to stick with your first choice door, or if you want to change your mind and pick the other closed door.

What should you do?

You should always change doors.

That's right. If you initially picked Door 1 and Monty opened Door 3, switch to Door 2. If you initially picked 3 and Monty showed you 2, switch to 1. And so on.

Your chances of winning the grand prize are greater when you switch doors. It seems counter-intuitive, but it is absolutely true.

Here's why. Assume that Monty knows what is behind each of the three doors. Initially, you have a 1 in 3 chance of picking the grand prize and a 2 in 3 chance of picking a goat. But after making your selection, Monty is going to open one of the other two doors. He's not going to open the door you selected, and he's certainly not going to open the one with the grand prize behind it! That means sticking with your original door still gives you a 1/3 chance, but the 2/3 chance of picking a goat is now a 2/3 chance of picking the grand prize since one of the two goats has been revealed and can no longer be selected!


It boggles the mind!

But to prove it, I put a working simulation of the game in the comic. In the third frame, help Business Frog win the money. Try it a bunch of times by refreshing the page and see for yourself - switching doors leads to wins more often than staying with your first choice.

In the end, though, I couldn't resist tossing in a more philosophical line about the nature of winning. How do you know if you're a winner? Business Frog always considers himself a winner. You should too.

Amphibian.com comic for 16 September 2015

Monday, September 14, 2015

Not a Chance

Luck has nothing to do with it.
Did you ever sit down to do something that you thought would be easy, only to give up in frustration many hours later? That's the story of today's Amphibian.com comic.

Well, maybe not the whole story. It started because I wanted to make a comic that included three things: scratch-off lottery tickets, a reference to The Lottery by Shirley Jackson, and a statement about the odds of winning the lottery.

One of my uncles gives a big stack of scratch-off lottery tickets to one lucky family member every year for Christmas. Everyone loves them for some reason. I've often wondered about the cost-to-wins ratio on those things, and how much time it would take to play a whole bunch of them. I thought I would make a comic where several of the frames were hidden beneath a silvery covering that could be "scratched" off with the mouse cursor on desktop browsers or your finger on mobile browsers.

The desktop, mouse-based interaction was fairly easy. There were just a few quirks that had to be addressed. Since the user would be holding down the mouse button and dragging a "coin" cursor all over the cell, there were the unfortunate side-effects of having the speech bubble text selected and the frog images getting drug around with that "ghost" effect.

To prevent text on a web page from being selected by the mouse cursor, there is some CSS that can be used. Here it is (with all the possible browser-specific versions):

.noselect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

I simply applied this .noselect class to the text in the scratch-off frames. To prevent the image drag ghosting, the solution is to set a handler for the dragstart event on all the images which simply returns false. No drags allowed. I use jQuery in my comic to do these tasks, as is reflected by the following code snippets:

$('.myclass').addClass("noselect");
$('.myclass img').on("dragstart", function() { return false; });

With those two issues out of the way it worked great on the desktop. Oh, but those mobile browsers... I had thought that I could make the page perform pretty much the same way on mobile by using touch events in addition to mouse events. I was wrong. So very wrong.

On the desktop it works by detecting the mouseenter event. When the mouse cursor enters on the cover elements (a bunch of rounded divs), the element is removed if the mouse button is down. In a mobile browser, there is of course no mouse cursor so I attempted to use a touchmove event instead. If the user is touching the screen and moves over one of the cover elements, it should vanish. Except that doesn't work.

It turns out that the target of a touchmove event is always the same element - the one where the touch started. Not that helpful, but I thought I could deal with it. Instead of capturing a finger moving across the cover divs, I could track the page X/Y of the touches on the comic cell div and use the little-known document.elementFromPoint(x, y) function to figure out which cover elements to remove.

var elem = document.elementFromPoint(x - window.scrollX, y - window.scrollY);
$(elem).remove();

Well, that maybe sorta worked. To get the right element you have to adjust for the page scroll, but the performance was terrible on my phone. I could have probably worked on it some more, but it was time to cut my losses. I'd spent too much time on this problem already. I made a mobile-specific, not-quite-as-cool, auto-scratch-off effect and called it a day.

I hate it when this happens, but it's worse to not ship than to ship with a sub-optimal product. At least in my opinion. That's why there are comics 3 times per week, even if some are terrible.

Amphibian.com comic for 14 September 2015

Friday, September 11, 2015

Generator Functions - New in Node 4.0.0

On Wednesday I wrote about arrow functions, a more concise syntax for anonymous functions that is now available in Node 4.0.0. But the new Node has many more new features! Another of the most interesting and useful additions is generator functions.

Generator functions are special functions which can be exited and then re-entered while maintaining their context. That means their variable bindings are saved across entrances. Their name comes from the ability to use these functions to produce sequences of values, like an Iterator in Java.

Generator functions are declared with the special function* syntax, and contain in their bodies a yield statement. Calling a generator function does not execute the body, but instead returns an iterator object which can be used to invoke the body. The statements in the body will be executed until the yield is reached, at which point control returns to the caller.

Consider this example code, which uses a generator function to print out the first 20 numbers in the Fibonacci sequence.

function* fibonacci(){
    var a = 0;
    var b = 1;
    var c = 1;
    while(true) {
        yield c;
        c = a + b;
        a = b;
        b = c;
    }
}

var gen = fibonacci();

for (var i = 0; i < 20; i++) {
    console.log(gen.next().value);
}

It might not be the most efficient way to generate Fibonacci numbers, but it's a good illustration of a generator. When gen.next() is called for the first time, the fibonacci function body is executed up to the yield statement on line 6. All subsequent calls to gen.next() pick up at the next line (seven), which happens to be inside the while loop. After changing the values of the internal variables, we're back to the yield again. This sequence of steps repeats every time gen.next() is called.

As you may notice, calling .next() actually returns on object with a value property. The value property contains whatever was yielded.

Generator functions can come in handy, but since they are part of the ECMAScript 2015 standard, or ES6, they aren't universally available yet. They've just come to Node. Use in the browser is limited to the latest Chrome and Firefox, which means that you're probably going to want to limit yourself to the server-side if you intend to incorporate them in your code.

But as my frogs have learned, being on the cutting edge can be less dangerous than living in the past.

Amphibian.com comic for 11 September 2015

Wednesday, September 9, 2015

Arrow Functions - New in Node 4.0.0

New! Improved! Skipping Numbers!
In news much more important than whatever my frogs did today, Node 4.0.0 was just released. If you're confused by that version number, you're in good company. I thought we were just on version 0.12.7. Did 1.x.x through 3.x.x end up in the same place as Windows 9?

No, no. Node 4.0.0 represents the merge of the Node and Io.js baselines. Io.js split off Node back in December but the two projects have settled their differences and come back together. This means Node now has support for a bunch of new features from the JavaScript ECMA-262 specification, like promises and arrow functions.

I've talked about promises before, but arrow functions...those are interesting. They are basically an even shorter way of expressing anonymous functions.

Consider this example. Let's say you had an array of the first 10 prime numbers and you wanted to add them all up. In a prior version of Node, you could reduce the array by supplying a simple anonymous function as the argument to reduce.

var arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];

var sum = arr.reduce(function(a, b) {
    return a + b;
});

Not bad. I'm sure we've all done simple anonymous functions like that before. But with an arrow function, the same process looks like this:

var arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];

var sum = arr.reduce((a, b) => a + b);

A bit shorter, and it looks nicer as a single line. So what does that syntax really mean?

The arrow function notation basically says execute one or more statements on the right side of the arrow using one or more arguments from the left side of the arrow. If there is only one statement, the return is implicit (above, the statement a + b is equivalent to return a + b). The arrow, of course, is just an equals sign followed by a greater-than sign. It's really just a more concise way of expressing a function which you may find appealing in certain situations.

// multiple args, one statement
var f = (a, b, c) => c ? a + b : a * b;
f(3, 6, false); // equals 18
f(3, 6, true);  // equals 9

// one arg, multiple statements
var g = a => { var b = a * a; var c = a / 2; return b + c };
g(44); // equals 1958
g(22); // equals 495

Nice, huh? There's a lot more new with Node 4.0.0 as well, so you might want to check it out. I'll probably be migrating Amphibian.com to it within the next few weeks. I expect a painless transition, but we'll see. In the mean time, continue to enjoy the comics served up by a prior version of Node.

Amphibian.com comic for 9 September 2015

Monday, September 7, 2015

Code Now Displayed with Hack

I hope everyone's having a nice Labor Day and not working. I'm not, unless you count working on more frog comics.

I did, however, take a few minutes to update my Eclipse to use this awesome font. It's called Hack, and it's designed specifically for source code.

This is the Hack font. Note how l looks different than 1, and 0 looks different than O. I like it.

After remembering that Eclipse has waaaaaay more configuration items than reasonably fit on its chosen method of display and fumbling through them anyway to find where to change the font, I had the thought that I should update the way I display code on my blog here to use Hack as well.

The code snippets that show up on my blog are styled using SyntaxHighlighter by Alex Gorbatchev. I downloaded it years ago and set it up on my web server. I then edited my blog template code here on Blogger to load the scripts and stylesheets necessary to make it work. Here's what I added inside the HEAD tag near the top of my Blogger template's HTML (not a real IP address - if you do this, use the address of wherever you have the SyntaxHighlighter installation):

<link href='//cdn.jsdelivr.net/font-hack/2.010/css/hack.min.css' rel='stylesheet' type='text/css'/>
<script src='//1.2.3.4/syntaxhighlighter/scripts/shCore.js' type='text/javascript'/>
<script src='//1.2.3.4/syntaxhighlighter/scripts/shBrushJScript.js' type='text/javascript'/>
<script src='//1.2.3.4/syntaxhighlighter/scripts/shBrushJava.js' type='text/javascript'/>
<script src='//1.2.3.4/syntaxhighlighter/scripts/shBrushXml.js' type='text/javascript'/>
<script src='//1.2.3.4/syntaxhighlighter/scripts/shBrushCss.js' type='text/javascript'/>
<script src='//1.2.3.4/syntaxhighlighter/scripts/shBrushBash.js' type='text/javascript'/>
<link href='//1.2.3.4/syntaxhighlighter/styles/shCoreEclipse.css' rel='stylesheet' type='text/css'/>
<script type='text/javascript'>SyntaxHighlighter.config.bloggerMode = true; SyntaxHighlighter.all();</script>

I am using a CDN for the Hack font itself, but my own server for SyntaxHighlighter. On my server, I just edited the CSS to prefer the Hack font first before "standard" monospace fonts. I also changed the font-size to 0.98em from 1em because I thought it was a bit large. I think it looks great now. Hopefully you agree, if you actually look at any of the code I post here.

When I post code, I use the <pre> method. I have to escape my HTML code with this method, but that's not usually a big deal. Take this snippet, for example:

<pre class="brush: js">
// I put JavaScript code here
console.log("log something");
while (froot) {
    console.log("loop")'
}
</pre>

It will look this this on the page:

// I put JavaScript code here
console.log("log something");
while (froot) {
    console.log("loop")'
}

Using SyntaxHighlighter to highlight the code used for syntax highlighting. So meta.

One thing I did notice about this font is that it is very similar to the default terminal font on my Red Hat Linux workstation. Maybe that's why I like it.

I hope you like today's comic as much.

Amphibian.com comic for 7 September 2015

Friday, September 4, 2015

Frog Soccer with Phaser - the Finishing Touches

I'm finally finishing up Frog Soccer, my 404 page game. There were a few outstanding bugs with it that I was able to fix this week (be sure to tell me if you find more!) and I also had to make the page a little nicer. I now include links to play it in full-screen mode as well as a link to the repository on GitHub.

There were two main issues.
WebGL fail! Ignore!
  1. If the web fonts could not be loaded, the game never started. It has come to my attention that some proxies (like the kind used in schools and businesses) prevent the web fonts from loading. Besides totally ruining the look of my comic, this actually causes the soccer game to fail since I wait on the active callback from the Typekit Web Font Loader before initializing the game. I fixed this by adding a callback for inactive, which is called when the fonts fail to load. Why the fonts fail to load is a problem for another day.
  2. If a frog stood in the corner of the field and blocked a ball toss-in twice in a row, the ball would end up in an endless toss-in loop. This was because a timer was being set to go off one second after the ball went out-of-bounds which assumed the ball had not re-entered play in between. If the ball toss-in bounced off a frog in less than a second, another toss cycle would begin which would be interrupted by the timer, which would move the ball back out-of-bounds and the cycle could continue without end. Crazy. I put a check in to see if the ball was already back in play before starting the toss. Maybe not the most eloquent solution but it works.
There was one additional minor issue. When I tried playing the game on my phone, a Samsung Galaxy S3, it always failed because of some WebGL problem. I believe this to happen in Phaser's startup process which checks to see if it should render with WebGL or Canvas. I changed the code to always use Canvas instead of auto-detecting and now it works...but I still sometimes see the error anyway. I'm going to chalk this one up to a device-specific annoyance and let it go for now. Could be something weird with Phaser's detection method too. I might look into it more if it's happening to other people as well.

var game = new Phaser.Game(width, height, Phaser.CANVAS, "gameArea", {
    preload: preload,
    create: create,
    update: update,
    render: render
});

One more thing - on the comic site, I changed the meta tag on the 404 page to set the page width to the width of the game's canvas. I don't usually set the width for responsive sites, but it made sense for this one page.

<meta name="viewport" content="width=800,user-scalable=1">

So what's next? I might tinker with this game from time to time, but I think I might start working on another one soon. This was my first experience using Phaser and I was very happy with it for the most part. I'm thinking of maybe making a (gasp!) Facebook game to integrate with Amphibian.com. Don't hate me. Look, here's today's comic...

Amphibian.com comic for 4 September 2015