22. February 2016

Canvas Helicopter Game

I made another game in canvas! This time I went for the classic flash game where you're a helicopter in a cave trying to not hit the stalagmites & stalactites (think flappy bird but from 2000). Here's the game:

 

See the Pen Canvas Helicopter Game by Josh Fabean (@fabean) on CodePen.

 

This continues my quest of trying to get better at making games in JavaScript. As a side note I coded most of this game in a plane on the way back form Mexico. The hard thing I had to figure out here was collision with moving objects. I feel like this is probably the easiest game to calculate that since I'm just drawing rectangles and nothing too crazy yet.

My function to calculate this is pretty simple and is as follows, where path is an array of all the rectangles drawn on the screen (and they're the black part of the game).

let calcCollision = () => {
  // loop through path and see which one I'm current in
  for (let i=0; i<path.length; i++) {
    if (path[i].x < dot.x && path[i].x+PATH_WIDTH > dot.x) {
      // this means this is the path youre currently in

      if (path[i].y > dot.y || path[i].height+path[i].y < dot.y) {
        console.log('you collided');
        startScreen = true;
      }
    }
  }
};

I learned a decent amount making this game, and I think I'm going to figure out how to put it on a phone as an app which should take a couple hours. You can also see this as a git repo up on github if you wanted to fork it and have it be your own thing.

Hopefully this pen inspires you and make you want to learn fun stuff.

:wq

15. January 2016

Random Particles in Canvas

I made some randomly generated particles in canvas, best part is it made it to the front page of CodePen!

 

See the Pen Randomly Generated Particles by Josh Fabean (@fabean) on CodePen.

 

The bulk of the work I had to do was pretty simple, just loop and randomly come up with some numbers and use those numbers to display things on the screen.

for (let i=0; i<amountOfParticles; i++) {
  particles[i] = {
    y: Math.floor(Math.random() * canvas.height),
    x: Math.floor(Math.random() * canvas.width),
    speedX: (Math.floor(Math.random() * maxSpeed + 1) * (Math.random() < 0.5 ? -1 : 1)), 
    speedY: (Math.floor(Math.random() * maxSpeed + 1) * (Math.random() < 0.5 ? -1 : 1)),
    color: randomColor(),
    radius: Math.floor(Math.random() * maxSize)
  };
}

Once I've done that, in my render function I basically loop over it again but this time fill in some circles with the information I have.

for (let i=0; i<amountOfParticles; i++) {
  if (particles[i].x >= c.width || particles[i].x <= 0) {
    particles[i].speedX = -(particles[i].speedX);
  }

  if (particles[i].y < 0 || particles[i].y > c.height) {
    particles[i].speedY = -particles[i].speedY;
  }

  particles[i].x += particles[i].speedX; 
  particles[i].y += particles[i].speedY;

  drawCircle(particles[i]);
}

let drawCircle = (circle) => {
  ctx.fillStyle = circle.color;
  ctx.beginPath();
  ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI*2, true);
  ctx.fill();
}

All in all a very simple task, that a month or so would have been super confusing to me. Now that I've made a couple different projects using canvas it's not some weird mythical thing.

You should play with canvas and learn a lot!

:wq

03. January 2016

Pong In Canvas

I started playing with Canvas last year, but I finally made a game now!

 

See the Pen Pong in Canvas by Josh Fabean (@fabean) on CodePen.

 

I followed along on Chris Delong's tutorial on Udemy. I'd suggest doing that too if you're at all curious on how to do this. Once you get going it's not really too hard, and is a lot of fun.

2016 is going to be a good year of me making game and fun web projects. Look forward to it!

:wq

11. November 2015

I Played With Canvas

I started to learn canvas, and one of the first things you learn how to do is make rectangles and circles. I decided to make a random circle generator just to figure out how to do it. Turns out it's actually quite easy, well here it is.

 

See the Pen Canvas Random Circle Generator by Josh Fabean (@fabean) on CodePen.

 

The main magic happens on here:

function drawCircle() {
  i++;
  let weight = Math.pow(Math.random(), 2);
  let seed1 = Math.floor(Math.floor(weight * ((min / 2) - 0 + 1)));
  let seed2 = Math.floor(Math.random() * canvas.height);
  let seed3 = Math.floor(Math.random() * canvas.width);
  let primary = '#'+Math.floor(Math.random()*16777215).toString(16);
  let secondary = '#'+Math.floor(Math.random()*16777215).toString(16);
  let arc = {
    x: seed3 - (seed1 / 2),
    y: seed2 - (seed1 / 2),
    r: seed1,
    shadow: !(Math.random()+0.5|0),
    blur: Math.random() * (10 + 1),
    color: (!(Math.random()+0.5|0)) ? primary : secondary,
    stroke: Math.random() * (15 + 1),
    fill: !(Math.random()+0.5|0)
  };
  ctx.beginPath();
  ctx.arc(arc.x, arc.y, arc.r, Math.PI * 0, Math.PI * 2);

  if (arc.fill) {
    ctx.fillStyle = arc.color;
    ctx.fill();
  } else {
    ctx.strokeStyle = arc.color;
    ctx.lineWidth = arc.stroke;
    ctx.stroke();
  }
  if (i < 2000) {
    setTimeout(function(){
      drawCircle();
    }, 10);
  }
}

I based on the size of the canvas figure out what sizes of circles I can make, quick a random color using '#'+Math.floor(Math.random()*16777215).toString(16); which is a pretty cool way to to do it and I got it from Paul Irish. Then I based on all the values I got print the circle onto the page.

:wq

24. October 2015

Microsoft Sculpt Ergonomic Keyboard

I'm normally not a fan of promoting products, but this one has literally changed my life. As is semi common for a developer I started developing RSI about two years ago. I like all smart people pretty much ignored it for the first six months. After that I actually tried everything I could think of to make my wrists feel good, I would ice my wrists, use my mouse with my left hand, and not use my right hand for anything beyond typing. Nothing helped, and I pretty much just gave up and accepted my fate.

Maybe two months ago I finally decided to take the leap and get an ergonomic keyboard, and within one week my wrists were back to maybe 80-90% health. Now I would say my wrists are 95% healthy only slight pain at harsh angles some of the time. I actually got a couple different people at work to make the switch too.

You might be thinking but ergonomic keyboards are lame and I completely agreed with you until I got this keyboard. It was suggested on Shop Talk Show Episode 183, and The Wire Cutter two pretty reliable sources. You've been dealing with wrist pain enough you should just take the leap.

:wq

12. October 2015

Drupal Delete Users Cart

I just pushed up my first Drupal module, though it's currently only a sandbox module. It's also up on GitHub in case you don't want to look around awhile to find where Drupal hides it's code for sandboxed modules.

This is a module that I'm sure only one other person in the history of the world has ever needed, but I'm excited nonetheless. The description of the module is as follows:

In rare instances you need to delete everything out of your cart, unfortunately there is no great way to do this out of the box, that's what this module tries to remedy. Once installed you need to create a link for the user that goes to /cart/$user_id/delete this will then redirect them to whatever page you configure.

The instance I ran into where we need this is someone will be on the phone with a customer placing the order for them as a reseller. Then that user is like "oh nevermind", but they've already gotten far enough they don't want to go back a bunch of time and change all the fields so they just push this button. The biggest issue we were running into is we are using Auth.net hosted CIM which uses email and ID to create a new customer, so if you get to the last page of checkout then they change their mind you've already created them in Auth.net which we cannot let happen.

This is the main magic that happens:

<?php

function commerce_delete_cart_menu() {
  $items = array();
  $items['cart/%/delete'] = array(
    'title' => 'Delete Commerce Cart',
    'page arguments' => array(1),
    'page callback' => 'commerce_delete_cart_main',
    'access callback' => TRUE,
  );
  return $items;
}

function commerce_delete_cart_main($uid) {
  db_delete('commerce_order')
    ->condition('uid', $uid)
    ->condition('status', 'checkout_%', 'LIKE')
    ->execute();
  db_delete('commerce_order')
    ->condition('uid', $uid)
    ->condition('status', 'cart')
    ->execute();
  $redirect_url = variable_get('commerce-delete-cart-redirect', $defaults['commerce-delete-cart-redirect']);
  drupal_goto($redirect_url);
}

When you go to /cart/$user_id/delete it runs the function commerce_delete_cart_main which then goes and deletes straight out of the db all entries it could be. I need to combined those two db_delete into one, but the Drupal documentation on that didn't click for me in under 5 seconds so I skipped it.

One of the cooler things I did for this was making it user configurable which is pretty much required when you're looking to pass something off to the community.

I hope someone finds this module and it helps them, as I sure would have liked to find this last week.

:wq

11. October 2015

My CodePen Saturday

After Blake's CodePen talk about using CodePen just to have fun I made three pens in one day! It ended up basically being Pixel Art Saturday, All my pens have to do with pixel art as it's my favorite.

The first pen I made was this little Sonic Pixel Art guy. I sort of want to make him run around but this alone took me 1-2 hours to just do this one sprite. To make it run I'm looking at maybe 8 hours or so. I might do it, but not the point of a fun CodePen Saturday.

 

See the Pen Sonic Pixel Art Pure CSS by Josh Fabean (@fabean) on CodePen.

 

Then I made a 16x16 pixel random art with a Sass loop to randomize the colors. I was inspired by this picked pen which is a 10x10 random CSS pixel art block, you will see how similar it is.

 

See the Pen Random Pixel Art Generator by Josh Fabean (@fabean) on CodePen.

 

After that I did it again, but with JavaScript just to see it both ways. The one thing I learned is with JavaScript you cannot use HLSA colors so I wasn't able to color coordinate it as much as my previous pen. I did however make it change what the colors are all the time for fun.

 

See the Pen Random Pixel Art with Javascript by Josh Fabean (@fabean) on CodePen.

 

CodePen is a great place to learn, get inspired, show off your work, but most importantly to me it's a great place to have fun. Go out and do something you've never done before just for fun on CodePen.

:wq

07. October 2015

CodePen Meetup KC

CodeKoalas just yesterday hosted their first (Kansas City's second) CodePen Meetup! We had between 20-25 people show up, there was snacks, drinks, video chats with Tim Sabat, random Google Forms, Blake & I gave talks, then we went across the street to Ruins Pub.

You can see Blake's presentation on Mental Fatigue up on GitHub. and I spoke on my Ultimate Tic-Tac-Toe Pen I made with a node.js matchmaking server. You can view and try to play the game right here, it's pretty cool.

 

See the Pen CodePen Multiplayer Tic-Tac-Toe Game by Josh Fabean (@fabean) on CodePen.

 

I've written about this game enough so I don't want to go too in depth on it but you can see my presentation up on CodePen.

It was a lot of fun meeting new people in the City who are excited and work with the same things we work with. We also got to see some really cool work that people do. I cannot wait until the next CodePen meetup!

:wq

01. October 2015

Copy To Clipboard JavaScript Only

Just the other day Clipboard.js as released and I got super excited about not using Flash anymore to copy thing.

I looked through their code and they're just using Document.execCommand() to copy to clipboard. I figured I would play with it and did it myself in just a few lines of code. Here's the Pen of my work:

 

See the Pen Copy To Clipboard JS Only by Josh Fabean (@fabean) on CodePen.

 

The main magic of this is right on this one line of JavaScript:

document.execCommand('copy', false, document.getElementById('select-this').select());

I grab the input, select() it then run document.execCommand on it. Super easy, and fun to do. If you want to use this yourself you should probably use the full library as it has nice fallbacks and works in more cases anyways.

It ended up getting picked on CodePen so that's super cool too!

:wq

10. September 2015

Simple Match Making Server using WebRTC

With my Ultimate Tic-Tac-Toe Game I've already tackled how to let users manually connect to each other with a unique ID. But now it's time to take it a step further, how do you make it so users can connect with someone they don't know? I figured it out in only a couple lines of JavaScript.

First off, this is all up on github, I'm still working on making things better but the basic functionality is there and it's fresh so I'm writing about it.

The server is using Peer.js, which unfortunately seems to be a dead project, so I'll have to move away from that shortly. The code for a simple Peer server is two lines, they are:

var PeerServer = require('peer').PeerServer;
var server = new PeerServer({port: 9000, path: '/myapp'});

Simple as that. Okay, now we need to track when people connect and disconnect from the server, that's easy enough:

var connected = [];
server.on('connection', function (id) {
  var idx = connected.indexOf(id); // only add id if it's not in the list yet
  if (idx === -1) {connected.push(id);}
});
server.on('disconnect', function (id) {
  var idx = connected.indexOf(id); // only attempt to remove id if it's in the list
  if (idx !== -1) {connected.splice(idx, 1);}
});

So I made an array, then when someone connects to the server I add their id to the array of people connected. That's all I had going for awhile, then I ran into a flaw. How do you know they want to connect to people or aren't already connected to people? This is where I had to add in Express to be a normal node server. So my goal with this is to create two endpoints, one to say you want to connect, and another to remove you from that once you connect. The code for this was a bit more in depth, but still stupid simple:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var readyToConnect = [];

var jsonParser = bodyParser.json();

app.use(bodyParser.json());
app.get('/', function(req,res) {
  return res.json({'connected': connected, 'ready': readyToConnect});
});
app.post('/add-device', jsonParser, function(req,res) {
  readyToConnect.push(req.body);
  return res.json({'response': 'added to collection'});
});
app.get('/remove-device', function(req,res) {
  return res.json({'response': 'removed from collection'});
});
app.listen(8080, function() {
  console.log('listening');
});

I needed to add body-parser so it could parse the request body that the game was sending to the API, it used to be included in Express but it's not anymore. I'm following the same basic concept of the previous connected array, but now I have access to any values I want and I can add and remove things based on endpoints that the app hits when I tell it to. You can see the full server.js file up on github instead of seeing the broken up version as explained here.

What I learned from this is Express is super easy and not some scary voodoo like I thought it was. I didn't even look up documentation for Express, I only have to search on the body-parser issue, it's that simple. I still need to finish the match matching on the game side as it mostly now works and in only 35 lines of code. JavaScript is fun.

:wq