Friday, July 31, 2015

Make Memes via API Calls

In today's comic the frogs are recycling pictures into memes, and by clicking on the meme in the last frame you can create your own frog meme. You just type in your own text and your personalized meme appears. You can even share it.

I don't want to get into a debate about how the sharing of memes has destroyed what remains of our humanity - it's just a comic about frogs. The interesting thing is how I was able to find a meme generation API that I could work with to make this comic possible.

My first attempt at this used memegenerator.net. It's a very popular meme site. They have a JSON API and there are even some modules for Node.js that interface with it. That all sounded good. I tried out the node-meme module and it worked - for all the read methods. Once I tried to create a meme with it I was informed by an error code that I needed valid login credentials.

No problem! I'll just register for an account.

Nope.
Or not. Apparently, account registration has been unavailable for quite some time. All attempts at it result in a rather unintelligible error message. There goes that plan!

After some more searching I found Imgflip.com. They have both a meme-generation API and functioning account registration! Yeah!

To make the comic work the way I intended, I needed to make all the memes from my server and then just update the browser with the Imgflip URL. This prevents everyone who uses the comic from having to get their own account, but it makes things a little more complicated for me. I essentially had to set up a meme-generation proxy. Your browser POSTs data to my server, my server POSTs data to Imgflip, Imgflip generates a meme and tells my server the URL, and finally my server tells your browser the URL.

This also required me to do something I haven't done a lot of before - use the Node http client. Sure, I've done simple things with it in the past, but the out-of-the-box features make it a bit difficult to use when you want to access a REST web service.


So I also started using the request module. It greatly simplifies working with HTTP(S) requests in Node. Here is an example of how I use it to interact with Imgflip's API:

var request = require("request");

var formData = {
    template_id : "41754803",
    username : "user",
    password : "passwd",
    text0 : "i look displeased...",
    text1 : "but i have no idea what's going on"
};

request.post("https://api.imgflip.com/caption_image", {
    form : formData
}, function(error, response, body) {

    var meme = JSON.parse(body);

    if (!error && response.statusCode == 200) {
        console.log(meme.data.url);
    }

});

Simple, right? The first parameter to request.post is the URL.

The second is what to POST. In this case, I want to POST a form, specifying the form data as an object. Imgflip only accepts form data as input, and every POST must include your username and password. You get those by registering on their site. The template_id form field is the id number for the meme image you want to use. If you upload your own meme template images, you can find the id numbers on template details page linked from your account. The text0 field is the text for the top of the image, and text1 is for the bottom.

The third parameter is the callback function for when the POST completes. This function gets an error (if there was one), the response object for checking the status code (and other stuff if you want), and the body of the response. In the case of the Imgflip web service, I know the body will be JSON. In this example I just log the meme image URL.

That is much simpler than doing it the purely native way. I recommend the request module if you need to do any kind of REST API access and there's no custom client available.

Now the fun begins: frog memes for everyone!

Amphibian.com comic for 31 July 2015

Wednesday, July 29, 2015

Making a Smarter Opponent

The frog soccer game made with Phaser is coming along nicely.

After getting the ball-out-of-bounds logic working pretty well over the weekend I was thinking more about the opponent logic. The pattern followed by the other frog seemed to work but was too simple. I wanted something a little better.

The frog should pick a different target location based on her position relative to the ball, but there are a lot of zones to consider. Is she directly in line with the ball on the X or Y axis? Is she below the ball on the Y axis? Is she on the goal side of the ball? What should be done to get her to the next location?

When dealing with these kinds of problems I find it helpful to draw a picture. I keep a graph paper tablet around for times such as these.

Frog zone sketch
I sketched out the different zones the frog could be in relative to the ball and what I believed the target should be when in each of those zones. After that, it was easy to translate these behaviors into code.

function setTarget(o, b) {

    var zone = 0;

    if (o.position.x < (b.position.x - 90) && o.position.y < (b.position.y - 5)) {
        zone = 1;
    } else if (o.position.x >= (b.position.x - 90) && o.position.x <= (b.position.x + 30) && o.position.y < (b.position.y - 30)) {
        zone = 2;
    } else if (o.position.x > (b.position.x + 30) && o.position.y < (b.position.y - 30)) {
        zone = 3;
    } else if (o.position.x > (b.position.x + 30) && o.position.y <= (b.position.y) && o.position.y > (b.position.y - 30)) {
        zone = 4;
    } else if (o.position.x > (b.position.x + 30) && o.position.y > (b.position.y) && o.position.y < (b.position.y + 30)) {
        zone = 5;
    } else if (o.position.x > (b.position.x + 30) && o.position.y > (b.position.y + 30)) {
        zone = 6;
    } else if (o.position.x >= (b.position.x - 90) && o.position.x <= (b.position.x + 30) && o.position.y > (b.position.y + 30)) {
        zone = 7;
    } else if (o.position.x < (b.position.x - 90) && o.position.y > (b.position.y + 5)) {
        zone = 8;
    } else if (o.position.x < (b.position.x - 90) && o.position.y >= (b.position.y - 5) && o.position.y <= (b.position.y + 5)) {
        zone = 9;
    }

    var ret = {
            x: o.position.x,
            y: o.position.y
    };

    if (zone === 1) {
        ret.x = b.position.x - 180;
        ret.y = b.position.y + 20;
    } else if (zone === 2) {
        ret.x = b.position.x - 180;
        ret.y = b.position.y - 150;
    } else if (zone === 3) {
        ret.x = b.position.x - 180;
        ret.y = b.position.y - 150;
    } else if (zone === 4) {
        ret.x = b.position.x + 90;
        ret.y = b.position.y - 90;
    } else if (zone === 5) {
        ret.x = b.position.x + 90;
        ret.y = b.position.y + 90;
    } else if (zone === 6) {
        ret.x = b.position.x - 180;
        ret.y = b.position.y + 150;
    } else if (zone === 7) {
        ret.x = b.position.x - 180;
        ret.y = b.position.y + 150;
    } else if (zone === 8) {
        ret.x = b.position.x - 180;
        ret.y = b.position.y - 20;
    } else if (zone === 9) {
        ret.x = b.position.x + 90;
        ret.y = b.position.y - 15;
    }

    return ret;

}

Making the sketch plan in advance made it much easier to code, and it worked well on the first try. It still needed some fine-tuning, but it was really close. I know I could have combined some things in the code above but I wanted to keep the logic very clear and clean so I could tune it. If necessary I can always optimize it later. I tend to favor readability over other factors.

I made another video of the frogs playing. The computer-controlled frog starts out on the right side of the ball but moves herself around to the left and starts moving toward the goal. She chases it quite well when I manage to kick it away from her.


Remember, the full source code is on GitHub if you want to try improving the logic.

And that's all I have for today. Like I said, I only work on this for a few minutes each day...and this might be the last update this week. I have something different going on for Friday's comic. But I'm getting ahead of myself. Here's today's comic:

Amphibian.com comic for 29 July 2015

Monday, July 27, 2015

Playing a Sound with Phaser

Work on the Amphibian.com 404-page game continued even this weekend. Among other things, I added the logic to catch the ball being kicked out-of-bounds. In that case, a whistle is blown, play stops momentarily, and the ball gets tossed back into play from the sidelines.

The weird part is that there don't seem to be any examples on the Phaser site that demonstrate audio. Fortunately it wasn't that big of a deal. Audio resources are handled in much the same way as image resources and the documentation is fairly clear.

In my preload function, I added a line to load the .mp3 of the whistle sound. Just like with images, you specify a key so you can reference them later. I used "whistle" as my key.

function preload() {

    // "normal" images
    game.load.image('frog', 'images/frog.png');
    game.load.image('goal', 'images/goal.png');
    game.load.image('net', 'images/net.png');

    // spritesheet for ball animation
    game.load.spritesheet('ball', 'images/ball_animation.png', 45, 45);

    // tilemap and tiles
    game.load.tilemap('map', 'images/ground.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', 'images/field-tiles.png');

    // sounds
    game.load.audio('whistle', 'audio/whistle.mp3');

}

Then in my create function, I create a Phaser.Sound object by calling game.sound.add("whistle"). This references the key "whistle" that I made in preload, so this object will be in control of the .mp3 file specified there.

var whistle;

function create() {

    // ... create all the other stuff ...

    whistle = game.sound.add("whistle");

}

Finally, in the update function I check to see if the ball has traveled beyond the bounds of the soccer field. I removed the collideWorldBounds setting from the ball as well, so it won't bounce back into play when it hits the world bounds on the other side of the line.

if (mode === PLAY_MODE
        && (ball.position.x < 40 || ball.position.y < 50
            || ball.position.x > 1640 || ball.position.y > 800)) {

    whistle.play();

    tossBall(ball.position.x, ball.position.y); 

}

To play the sound I just call the play() function on my whistle object to play the sound. All parameters to the play function are optional and the defaults make sense for basic sounds.

I think the sound adds a nice touch. I'm not going to do background music or anything in the game, but I will probably add a few more sounds for things like scoring a goal or maybe when the game starts.

Remember that the full source code to the game is available on GitHub! Updates roughly every other day!

I need to work on the logic for the opponent a little more. It is far from perfect. Much like today's comic.

Amphibian.com comic for 27 July 2015

Friday, July 24, 2015

I Have Goals (in my Phaser game)

Maybe I don't have any goals in real life, but I do now have goals in my 404-page Phaser game. Soccer goals.

If you've been reading the blog for the last week or so, you'd know that I am working on a game for the Amphibian.com 404 page - frog soccer. It really doesn't have anything to do with a 404 page, but my kids liked the idea.

I have been very time-constrained this week, so the only things I've added since Wednesday is a new tilemap with field tiles that look like an actual soccer field, and the goals. The new tiles were as easy as drawing some new squares in GIMP and using Tiled again (see Monday's post). But the goals were slightly more interesting.

My goal for the goals was simple. Using an image of the side of the goal (with net) and an image of the top of the goal (again, with net), I could draw the side twice and the top once to create the appearance of a goal viewed from the standard top-down angle. The frog or ball or whatever should be able to walk into the goal and appear under the net.

Here are some pictures to illustrate what I'm talking about.

The side of the goal. Used twice per goal.

The top of the goal. Drawn above the two sides.
The frog standing behind the goal.

The frog standing in the goal. She appears under the net.

The sides of the goal were simple. Just like the trees, I can create them as sprites and give them custom collision bodies. The frog will be able to walk in front of and behind them normally because of the group.sort('bottom', Phaser.Group.SORT_ASCENDING) call on each update. Just like the trees. But what about the top of the goal? And the net that hangs down from it? It should always be on top.

The key is to not put it in the group.

The way I create the top-down effect in the game is to draw the objects that are closer to the bottom of the screen on top of things that are closer to the top. The group.sort() function takes care of this. But that sorts inside the group only. Any other object created before or after the group will always draw either under or above the group.

function create() {

    game.stage.backgroundColor = "0x409d5a";

    map = game.add.tilemap('map');
    map.addTilesetImage('field-tiles', 'tiles');;
    layer = map.createLayer('groundLayer');
    layer.resizeWorld();

    group = game.add.group();

    // this net will always be on top of the group
    var net = game.add.image(-41, 237, 'net');

    // ... add other stuff to group ...
  
    goal1 = group.create(-40, 400, 'goal');
    game.physics.enable(goal1, Phaser.Physics.ARCADE);
    goal1.body.setSize(112, 22, 0, 98);
    goal1.body.immovable = true;

    goal2 = group.create(-40, 240, 'goal');
    game.physics.enable(goal2, Phaser.Physics.ARCADE);
    goal2.body.setSize(112, 22, 0, 98);
    goal2.body.immovable = true;

    // ... do some other stuff ...

}

In my create code above, the first thing I do is create the ground tiles using the tilemap. The very next thing I do is create the group for all the sprites. Now everything in the group will draw above the ground. If I were to move the game.add.group() call to before the game.add.timemap() call, all the sprites in the group end up below the ground. They are there but can't be seen.

I realized this the other day when I was playing around with tilemaps for the first time. So all I have to do to make sure that net is always on top of the goal sides and the frog is to add it to the game after the group. Objects can be added to the group after the net is added, but the group itself must simply be created first.

Remember, the complete source to the game is on GitHub if you want to try things yourself.

I think there's a way to change the draw order of things after you create them, but I haven't been able to get it to work yet. Maybe more on that later. For now, enjoy today's confusing comic about confusing organizational structure.

Amphibian.com comic for 24 July 2015

Wednesday, July 22, 2015

Adding Opponents in my Phaser Game

Up until now, my Phaser-based 404-page frog soccer game hasn't been much of a challenge. You just move the frog around the bump the ball. In a real game of frog soccer, there would be at least one opponent trying to take the ball away from you. Today I tried to add such an opponent.

Adding another frog was the easy part. In my create function, I just create a new sprite (named otherFrog) using the same sprite image as the first frog. With the exception of the starting position, all of its settings are the same as the first frog.

var frog, otherFrog;

// ... other variables ...

function create() {

    // ... other sprite creation ...
  
    otherFrog = group.create(600, 200, 'frog');
    game.physics.enable(otherFrog, Phaser.Physics.ARCADE);
    otherFrog.body.drag.set(300);
    otherFrog.body.setSize(60, 25, 0, 42);
    otherFrog.body.allowGravity = false;
    otherFrog.body.collideWorldBounds = true;
    otherFrog.body.maxVelocity.set(200);
    otherFrog.chase = true;

    // ... other stuff (see previous posts)

}

The only difference is that I set a boolean value called chase to true. This will be one of the flags I use to control the new frog's behavior. When chase is true, it means the frog should be chasing the ball and trying to line herself up for a shot. Yes, I've decided that the frogs in this soccer game are female. Women's soccer is very popular at the moment in this country, and the frog soccer was my daughters' idea.

In the update function, I made a few changes. First, this one to the collision check:

game.physics.arcade.collide(group, group, function(o1, o2) {
    if ((o1 === otherFrog && o2 === ball) || 
        (o2 === otherFrog && o1 === ball))
    {
        otherFrog.chase = false;
        otherFrog.kick = false;
        setTimeout(function() {
            otherFrog.chase = true;
        }, 250);
    }
});

I specify a function as the third parameter to game.physics.arcade.collide that gets called when any two sprites collide. In it, I check to see if those two sprites happen to be the ball and the opponent frog. If she did touch the ball, I turn off her chase and kick modes, wait 250 milliseconds, and then put her back into chase mode.

Also in the update function, I added this code to control her behavior:

if (otherFrog.chase) {

    var targetX, targetY;

    if (otherFrog.position.x > ball.position.x - 100) {
        targetX = ball.position.x - 100;
        targetY = otherFrog.position.y;
    } else if (otherFrog.position.y > ball.position.y ||
               otherFrog.position.y < ball.position.y - 25)
    {
        targetX = ball.position.x - 100;
        targetY = ball.position.y - 25;
    } else {
        otherFrog.chase = false;
        otherFrog.kick = true;
    }

    game.physics.arcade.moveToXY(otherFrog, targetX, targetY, 100);    

} else if (otherFrog.kick) {

    game.physics.arcade.moveToObject(otherFrog, ball, 150);

}

If she's in chase mode, I check to see if she's on the left side of the ball. If not, I set her target location to be her current y-coordinate and the ball's x-coordinate minus 100. This will move her to a good position on the left side. If she's already there, I check to see if she's lined up with the ball on the y-axis. If she's not within a 25-pixel zone near the ball, I set her target position to be the ball's x-coordinate minus 100 and the ball's y-coordinate minus 25. When she gets there, she'll be lined up perfectly for a kick. Which is why I turn off chase mode and turn on kick mode if neither of the first two conditions are true. After I determine the new target, I use the game.physics.arcade.moveToXY function to make the frog move towards that position. Since this function gets called pretty much constantly, she'll continuously be re-targeted towards wherever the ball might move to.

If she's in kick move, I simple use the game.physics.arcade.moveToObject function to make the frog move directly to the ball's position. This will result in her colliding with the ball, which will kick the ball, turn off chase and kick modes, and set the timer for a return to chase mode.

Here is a short video I made of the game in action now. It's not perfect yet, but you can see how the other frog tries pretty hard to get in my way and take the ball.


Obviously, I still have a way to go here. Those frogs still need some animation of their own, and I need to add goals and make the ground tiles actually look like a soccer field. I only have a few minutes each day to work on it, so whatever little progress I make is good. Remember that the full source code is on GitHub if you want to play around with it yourself!

Don't forget to read today's comic...and if you have a minute do me a favor and vote for Amphibian.com on the Top Webcomics site. Here's the link: Amphibian.com Voting Gateway.

Amphibian.com comic for 22 July 2015

Monday, July 20, 2015

Phaser Tilemap

I was out of town all weekend for my daughter's soccer tournament, but I found 15 minutes to spend trying out tile maps in Phaser.

The ground in my frog soccer game is just green, set by the game.stage.backgroundColor field. It would be nice to have some grass or soccer field lines on it. Sure, I could make some images and set them on the screen manually just like the other sprites, but a tile map would be easier.

Phaser makes it very simple, as long as you are using Tiled for a map editor. I just had to remember what I named my layer and tileset when I changed the code.

In Tiled, I created a single layer with a single tileset. I named the layer groundLayer and I named the tileset groundTiles. The tileset was create from a texture sheet I made a while ago using TexturePacker.

Name the Layer something meaningful - and remember it!

The Tileset name and image have to match what you use with Phaser!

After saving my tile map in Tiled's JSON format as ground.json, I updated my game code. In the preload phase I added two lines of code, one to load the tile map itself and one to load the image with all the tiles in it. This is the same image I used to create the tileset in Tiled.

function preload() {

    game.load.image('tree2', 'images/tree2.png');
    game.load.image('frog', 'images/frog.png');
    game.load.spritesheet('ball', 'images/ball_animation.png', 45, 45);

    game.load.tilemap('map', 'images/ground.json',
            null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', 'images/groundTiles.png');

}

I once again added a few more variables, map and layer. Then in the create phase, it only took four lines of code to get myself grounded.

var map;
var layer;

function create() {

    game.stage.backgroundColor = "0x409d5a";

    map = game.add.tilemap('map');
    map.addTilesetImage('groundTiles', 'tiles');;
    layer = map.createLayer('groundLayer');
    layer.resizeWorld();

    group = game.add.group();

    // ... other stuff ...

}

The call to game.add.tilemap("map") on line 8 creates a map object that represents the whole map exported from Tiled. In this case, since there is only one layer, there's not all that much to it. Immediately after creating the map, I had to call addTilesetImage (line 9) to add the image created in preload to the map and associate it with the tileset in the file. Since my tileset was named groundTiles in Tiled, I associate that with the "tiles" image - which was the same one I used to create the groundTiles tileset. Making these match is important!

The next step is to create the layer I want. Again, my simple map had only one layer named groundLayer. After creating the layer object on line 10, I can conveniently use it to resize the world to match the layer dimensions.

One note here...I don't create the group object that holds all my other sprites until after the map/layer thing is done. If I create the group object first, event if I don't add any sprites to it yet, everything that is added to it will draw under the ground tiles. Took me a few minutes to catch that mistake the first time.

Alright, that's all for today. I know it's not much but I did actually put this thing in an open repo on GitHub if you want to look at the full source code. Also, remember to check the comic for today.

Amphibian.com comic for 20 July 2015

Friday, July 17, 2015

Speed Based Animation with Phaser

I'm still working on my game for the Amphibian.com 404 page. Initially I had an idea of where I wanted to go with it, but after making a demo of the frog kicking a soccer ball my daughters decided that a frog soccer game would be awesome. Since they outnumber me, I have decided to go with their idea and implement the rest of the game as frog soccer.

The goal for this weekend: add goals.

But before I get to that, I wanted to add a simple animation to the soccer ball. I want to add animation to the frog too, but it's been a busy week. Anyway, I just wanted the ball to spin when the frog kicks it, and the speed of rotation to slow down as the forward motion of the ball slows down.

Here is an animated GIF I created of the game to illustrate what I mean.


So it behaves like a real soccer ball - it appears to roll in a more-or-less realistic manner.

Here's what I had to do in order to achieve this effect.

First, I needed to create a sprite sheet of all the frames of the ball's rotation. I used Inkscape and the GIMP to create a 45x360 pixel image of the ball at different phases of spin. A single frame of the animation is 45x45.

soccer ball spritesheet
Going back to my game code from Wednesday, I replaced the image load for the ball with a spritesheet load which specifies the frame size (line 5 below).

function preload() {

    game.load.image('tree2', 'images/tree2.png');
    game.load.image('frog', 'images/frog.png');
    game.load.spritesheet('ball', 'images/ball_animation.png', 45, 45);

}

I then added another variable for the animation, and put it in the proper scope to be referenced by both the create and update functions. After creating the ball sprite like normal, I create the animation named "roll" by calling ball.animations.add("roll").

var frog;
var tree;
var ball;
var group;
var cursors;
var anim;

function create() {

    group = game.add.group();

    // ... create other sprites ...

    ball = group.create(300, 300, 'ball');
    game.physics.enable(ball, Phaser.Physics.ARCADE);
    ball.body.bounce.set(1);
    ball.body.drag.set(20);
    ball.body.allowGravity = false;
    ball.body.setSize(45, 35, 0, 8);
    ball.body.collideWorldBounds = true;

    anim = ball.animations.add("roll");

    // ... other stuff ...

}

The tricky part comes in the update function. I check and use the velocity of the ball to determine if the animation should be playing and how fast it should run. Look at the code below:

if (ball.body.velocity.x == 0 && ball.body.velocity.y == 0) {
    anim.stop();
} else {
    var speed = Math.min(1, Math.max(Math.abs(ball.body.velocity.x),
                Math.abs(ball.body.velocity.y)) / 200) * 9;
    if (anim.isPlaying) {
        anim.speed = speed;
    } else {
        anim.play(speed, true);
    }
}

If the ball has no velocity on either the x or y axis then it is not moving at all. In that case, stop the animation. Otherwise, I calculate the animation speed. In Phaser, animation speed is specified in frames per second and has a minimum value of 1. I want the maximum frame speed to be 9, and I want to use that when the velocity of the ball is equal to or greater than 200. Velocities under 200 will calculate an animation frame rate as a ratio, but not go under 1. A velocity of 100 will result in a frame rate of 4.5, for example. If the animation is already playing, I just change the speed. If the animation is not currently playing, I start it at the calculated speed.

I am very happy with how it turned out.

I know I haven't made this code available on GitHub yet, but I will soon. Like tomorrow. For today, though, just read the comic.

Amphibian.com comic for 17 July 2015