Sunday, November 14, 2010

Experiments in HTML5: canvas 2

So after knocking out a quick example yesterday of an HTML5 canvas app, I ended up making pong. This is the typical "hello world" game to make, and I've done them before so I was familiar with the already pretty simple logic.

Here is the high level breakdown:

  • has two "classes", paddleObj and ballObj
  • there are two instances of the paddleObj, one for each side
  • the objects will keep track of the location and has helper functions clear, draw
  • the ballObj acts much like a controller, in that is can reset the board, performs collision detection and all the logic involved, and maintains its own automatic movements with a move function
  • the move function drives the game, it is set on interval of 100ms
  • has a toggleGame function to start and stop the interval when needed
  • use a direction variable as negative or positive and a change variable for each axis (x and y)
  • reverse appropriate direction on collision, increase change variables on paddle collision
  • if ball is past either paddle, reset board, increase score, toggleGame to pause
  • W, S control player 1 (left) and up, down control player2 (right), click or space control toggleGame
There isn't too much to a pong game. Regardless of the language, the "objects" will remain the same, the rules are the same, etc. Some helper notes: 
  • store x,y,width and height for sprites
  • make (x+width) and (y+height) your best friends
  • you need an "engine" to drive motion
  • remember to check the y's on the paddle for collision detection
Some of the more customizable things I have found:
  • How to handle paddle bounce backs (include paddle momentum, increase speed each time?)
  • How fast should everything move?
  • How to track score and what is a winning score?
  • Graphics, incentives, etc
Unfortunately, I only have weekends to really work on these projects, so it was more important for me to get something up and working than to make it polished. I hate to pass out my "work" when it is hardly ideal, but then again when is a program ever really "ideal" and I am still learning this stuff. So keep in mind that this is not optimized, fully debugged, browser tested, source cleaned up, fully commented, etc, but it DOES WORK! (in all non-IE browsers, except maybe 9) 

Have a look at the source code here.
And the demo here.

I also thought it was pretty funny that I used plain old javascript (POJS) for the entire game, but used jquery for the show/hide form. I gotta get that out of there haha.

I am also working on an iPhone version that was pretty much complete, but doesn't seem to like running on the server like it did running locally. If anyone has any iPhone dev experience and knows what I'm missing (for example evt.preventDefault() doesn't work), I'm initially guessing its a cross-script thing? But I am also having an issue with the graphics not getting cleared entirely, leaving a "frame-trail", like the outline of the object being left behind where it moves.

Hope you like and come on people leave me some comments, I'm dying for feedback here!

Saturday, November 13, 2010

Experiments in HTML5: canvas

With HTML5 quickly becoming all the rage, and rightfully so, I think it was very important to learn what seems to be one of the more groundbreaking innovations, the canvas.

I started by searching through my Google Reader (RSS reader which I've become a fan of) since I know I had starred a few articles on HTML5 and the canvas element in particular. Here is what I came up with, sixrevisions.comAWESOME examples from tutsplus.combouncing ball from sixrevisions.com, again, I'm sold, this stuff is WAY too call to ignore!

After a quck 5 minute browsing of some tutorials and samples, it seems pretty similar in use to a typical graphics api. I've had some minor exposure to these in the form of OpenGL, DirectX, and XNA, but it was very limited and I quickly lost interest as it was dealing with what I consider the dying native app. I still have the desire to make a game and perhaps now I have the technology to reach the audience and potential I was looking for.

Here is the recommended canvas template:

<html>
<head>
<title>Canvas</title>
<script type="text/javascript">
// When the window has loaded, DOM is ready. Run the draw() function.
window.onload = draw;   

function draw(){
  var canvas = document.getElementById('myCanvas');
  if (canvas.getContext){
    var context = canvas.getContext('2d');
    // Put canvas drawing stuff here, e.g. context.fillStyle
  }
  else{
    // Put code to execute if browser doesn't have canvas support here
  }
}
</script>

<style type="text/css">
  canvas { border: 1px solid black; }</style>
</head>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
</body>
</html>

Since I already have a page set up, I'm just taking the necessary pieces and placing them where they belong according to this template. I started with a 500 x 500 canvas, this is rather arbitrary, but I have found the most limiting size on regular web pages is facebook profiles at 520px. I styled the canvas to be center aligned by display: block, margin: 0px auto, and border so I know where it is! I put the javascript on the html page, but will remove this once initial development is done.

Ok not too bad to get set up. Now lets get to the fun stuff! I used a great tutorial from Mozilla to get these intial startups going.

The first set of instructions are about drawing shapes, pretty simple stuff really. The only pre-defined shape is a rectangle, but there are several "path" functions. These are similar to drawing freehand. You can draw lines, arcs, and curves using a typical coordinate system in which (0,0) is the top left of the canvas and (width, height) is the bottom right of the canvas. All of this is unfortunately familiar to me. I only say unfortunately because drawing with geometry can be a painful experience at times. First successful canvas javascript api will make someone really rich and/or really famous for shaping internet gaming forever (hint, hint).

The images section reads much like a chapter on sprites in my opinion. I barely read this section since the methods are rather self explanatory. Something that is very important to note on this page though is how images are "loaded". You can use any image already on the page or within the canvas by selecting it by id or tag name, or you can also use document.images, though I personally am unfamiliar with this method. But it seems the preferred method in this tutorial is to load the image using a javascript Image object:

var img = new Image();   // Create new Image object  
img.src = 'myImage.png'; // Set source path  

You can then position, scale, and crop this image and draw it to the canvas with drawImage functions. The rest of the article is still very good, but I ran out of patience and wanted "something". I was somewhat familiar with the remaining topics, and since they are somewhat "heady" I didn't feel like absorbing all that knowledge (probably again) right now. If all of this sounds crazy to you, take it slower, and experiment a lot as the gap between code and visuals is too big to bridge just in your head. So I figured I'll make a small canvas with a "sprite" of some kind, or perhaps a drawn image, that will move around according to key presses. Lets start.

First things first, I am using this as my groundwork.



Nice work by this guy and just wanted to give credit even though I plan on doing some things a little differently. Lets get our shape on there, for simplicity I'm going to create a small 20x20 gray square in a paint tool and draw it to the canvas in the top left:

var img = new Image();
 // When the window has loaded, DOM is ready. Run the init() function.
 window.onload = init;

 function init() { 
  ctx = document.getElementById("mycanvas").getContext("2d");
  img.src = "/images/dev/gray_box.png";
  img.onload = function() {
   ctx.drawImage(img,0,0); 
  }
 }

Now lets add some logic to make it move on a key press:

function keyDown(evt) {
 // so a key was pressed, only react to the keys below
 // left = 37, up = 38, right = 39, down = 40
 // movement workflow: get key, check if at edge, if not move, 
 // if moved off edge then set it to edge, draw at new location
 // if you drew a new square then prevent default key action
 if(evt.keyCode == 37) {
  if(imgObj.x > 0) {
   imgObj.x -= 20;
   if(imgObj.x<0) { imgObj.x=0; } 
   draw();
   evt.preventDefault();
  }
 }
 if(evt.keyCode == 39) {
  if(imgObj.x + imgObj.w < 500) {
   imgObj.x += 20;
   if(imgObj.x + imgObj.w > 500) {imgObj.x=500-imgObj.w; }
   draw();
   evt.preventDefault();
  }
 }

 if(evt.keyCode == 38) {
  if(imgObj.y > 0) {
   imgObj.y -= 20;
   if(imgObj.y<0) { imgObj.y = 0; }
   draw();
   evt.preventDefault();
  }
 }
 if(evt.keyCode == 40) {
  if(imgObj.y + imgObj.h < 500) {
   imgObj.y += 20;
   if(imgObj.y + imgObj.h > 500){imgObj.y = 500 - imgObj.h; }
   draw();
   evt.preventDefault();
  }
 }
 return false;
}

I tried to document the process as concisely as possible. And finally our new draw function:


function draw(){
 // we get the context again (needs efficiency improvement for that)
 var ctx = document.getElementById("mycanvas").getContext("2d");
 // clear the entire canvas, should have a built in function like ctx.clear();
 ctx.clearRect(0,0,500,500);
 // save context (not needed here but a best practice for future)
 ctx.save();
 // draw square in new location
 ctx.drawImage(img,imgObj.x,imgObj.y);
 // restore the context (again not needed but a best practice)
 ctx.restore();
}

Here you can find the complete javascript file.
And a working demo.

This was all done in an hour or two (including the initial research). This is proof that this is a great entry way for web developers to get a taste of game development without such a steep learning curve. A lot of this code isn't anywhere near optimized and was simply more to get a working example and get my feet wet.

I plan to clean this code up, comment more fully, then add functionality, and finally some polish. Hopefully by the end I'll have a fully functional, yet rudimentary html5 canvas game!

UPDATE: Check out the same demo page above for a version of pong.

Friday, November 12, 2010

Quick thoughts

Every week I listen to a google focused podcast and a "neutral" though more apple leaning podcast (at least that is the impression I get from the host). And one thing that I have noticed with the hosts and guests of both shows are that the google folks are usually much more rounded in their technology knowledge. This isn't really a shocker, but I think it's interesting to note as I closely follow google v apple.

So I wanted to use javascript in a cool way, well this guy puts it to shame in some early demos. Yes, its a gameboy emulator taking shape in javascript. It's up on github for anyone who fancies (under MIT and Apache too, ya know so that it has a real chance to grow). This whole thing tells me to scrap the css and jump into the canvas.

The markets were down for the week. No real shocker as it was time to take some profits and everyone had to come down off that caffeine high of last week. Now we have to deal with Chinese currency issues and their effect on commodity prices. And next week should be quite active for US markets at least. Lots of earnings reports and GM IPO. Should be interesting, but I'm thinking it'll be another up week! Here is a better preview of the week to come.

Just installed some chrome extensions for fun: Yoono a social networking "mashup", MeasureIt a quick tool to measure the screen in pixels, and Xmarks a bookmark synchronizer (passwords too if you wish).

Happy weekend, enjoy!

Saturday, November 6, 2010

The Week Went Perfect

It's really amazing to me how much can totally change in the markets over just a week. All three major indices are set to hit 2-year highs next week. QE2 is locked in at a point very slightly above the lower expectations of $500 billion. Jobs numbers were surprisingly good for the previous month. We have a republican house and democratic senate, and Obama appears to be making a concentrated effort to spark the economy and the markets in particular.

Here are some articles that summarize all this data:
Stocks Finished Week At 2-Year High On QE2 And Jobs
Treasuries Drop, Stocks Fluctuate as Jobs Growth Tops Estimates

And of course the bears want their say too:
Analysis: Fed's QE2 raises alarm of commodity bubble
QE2: $600 Billion Fed Move Targets New Jobs, But Risks Inflation

I am very much bullish on this market, especially after Friday. I felt if the market had gone up big again on Friday, the drop on Monday could have a longer lasting price effect than needed. If the market had gone down and erased some or even all of Thursday's gain, I would be afraid of the negative sentiment it would leave over the weekend. Luckily, in my opinion, the market stayed essentially flat all day. To me this signifies that the market has now moved into a new range.

Of course there will be some profit taking in the next week or two that will pull the markets down from those 2-year highs, but only briefly. I expect the rest of November to be a great buying oppportunity and by the end of the month I expect to be breaking through some of those multi-year highs. In other words, if you wanted a time to get into the market, I think watching for some profit taking in any stocks you are interested in will be the best price opportunity you will get for the next year or two, possibly more.

Something that has me very excited about the future of the economy is Obama's apparent new attitude. Coming out after the elections and saying the things he needed to say was a great sign. Now Obama is touring Asia on what he has said will be a markedly domestic trip, primarily about the US economy. And this announcement today out of India may be some of the biggest news of the week, though we may not see its full impact for a year or more. For those of you in Boeing (BA) or GE, (I own some GE), kudos!! This is nothing but good news for the two companies, though you may not see any immediate effects, the long term impacts could be huge.

I can barely wait for the next few weeks, to establish some more solid positions! Here are my anticipated moves for the week:
Citigroup (C) - $50
Kraft (KFT) - $70
Marathon Oil (MRO) - $50
AT&T (T) - $30

I use Sharebuilder because of my low liquidity and they allow you to purchase fractional shares on a weekly, non-commissioned trade. I don't normally put in this much in one week, but I have to put my money where my mouth is these next two weeks!

*Note that these are all purely opinions of a very amature investor. In no way do I endorse or work for any of the mentioned companies. I do hold positions in GE, C, KFT, and T already and will be establishing a position in MRO this week.

Friday, November 5, 2010

Forget Fuck Censorship

So for starters this is the song that brought this to mind for me:
Cee Lo Green - Forget You
Radio Version
Real Version

Now I think most people can relate to some extent to the lyrics and, if anything, it's a topic that carries a lot of emotions. So to me, censoring the song has drastically reduced its effectiveness on the audience.

This is of course just one song (and a currently popular one, I'm too cool to like pop music, ha). But one of my favorite examples from the past is Radiohead - Creep. The censored version to me is just a song, the real version is much closer if not entirely in the deepest realms of art.

And let's extend it even further. I've only covered censoring cursing, what about the rest? Well, I still feel the same there too. I think when a good piece of work is put out with what some consider inappropriate material and that material gets censored, the piece of work is no longer in existence and simply a dumbed down replica.

Of course there is the other side of it that involves rampant totally valueless cursing. This is where subjectivity gets in the way and case by case basis is not acceptable. So really it has to be all or nothing in my opinion, and in case you haven't guessed, I vote for absolutely no censorship. Someone said something that offends you? Grow up and take it for what it's worth (or go beat them up). You want to shelter your kids? Well first of all, have you ever gone to public schools? Or browsed the internet for more than 10 minutes? The fact of the matter is, sheltering your kids from obscenities, etc simply glorifies them and also means that you won't have any control over how they are eventually exposed to it.

Finally, this is one of the many reasons I love the very ideology of the internet: it's all there, all the time, its just up to you to find and view it. If I want to hear my uncensored music, I do it. If I want to look at lewd pictures, so be it.

This whole post may seem trivial to you, but keep in mind that censorship is a notoriously slippery slope. Today it's the F word, tomorrow it's joking about bombing an airport, oh wait I forgot jokes aren't funny anymore. This whole FBI etc spending a bunch of money to track down, arrest, and charge someone for joking about bombing an airport is a VERY SLIPPERY SLOPE!!! In fact the whole "war on terror" is, in my opinion, a simple way to get praised for extremely limiting your citizen's rights. But that is a whole other can of worms!

Thursday, November 4, 2010

What a Day on the Market

With the elections behind us and QE2 locked in, the markets soaked it up today!

All three major indices hit their yearly highs and five stocks went up for every one that went down on the NYSE on good volume. I personally did pretty well today, up 2.48% in stocks and roughly 14% in options. Macys (M) and Ford (F) were my big winners in the stocks, but Akami (AKAM) was my largest relative gainer at roughly 11%!

I love these numbers on the options, I love them so much I'm looking to ring the register soon. I will definitely be looking to dump DEER next week assuming earnings do what I hope (fingers crossed), though if I see a significant enough rise before Wednesday's earnings I will certainly still take the money and run. Akami, however, I am looking at some pricing action to see a good time to get. It may be soon though.

With the biggest news behind us, I'm anxious to see what happens tomorrow. Continue the climb?? Catch its breath?? Buyers remorse??

Wednesday, November 3, 2010

Facebook...WTF!?

Ok so this already has rant written all over it right? And if you've worked with me over the past few days, you probably know most of what I'm about to say. But I need to air it out more and maybe get some other opinions on the issue.

For starters lets talk about facebook's "non-event" today. So you are planning to integrate more tightly with mobile devices? Thanks for the incite you progressive minded "genius". I would like to announce that I plan to eat food over the coming months. I do agree though that the iPad is not a mobile platform and I loved Zuck's apparent delivery of the line, "It's a computer. Sorry". Does someone have a favorite mobile OS? Maybe Zuck and I could get along after all ha!

I got most of my information from Engadget's coverage and general google searches. For a real analysis of the event I'd recommend you do the same because I definitely won't do it justice.

Overall its a reasonable roadmap for facebook that was laid out today. In my opinion there really wasn't anything worthy of an event announced today. Though this excellent write up says otherwise. In short, iPhone gets updated app with Groups, Deals, and enhanced Places. Android get additions as well. Deals sounds a little too "market-y" for my liking. And maybe its just me, but I really am not comfortable with telling the world where I am all the time? It's all a little big brother-like to me.

Now you'll see that throughout the event (and the above blog) how much they plug how much the developers "love" it and how its so "easy" to use. I'd also like to point out that they had an Android and an iPhone crash during the demo. And we reach the ranting:

Now I don't claim to be a programming god (still just working on guru status) but I have picked up a few programming languages, APIs, frameworks, CMSs, etc, over the past few years. And of course there were bumps in the road, but overall the experience was progressive and mostly painless. I have been using (attempting to) the facebook apis for the past two weeks and its been painful.

I want to be the first to admit that I am not the most adept facebook user in the world (where the hell is logout you sneaky bastards!) but the whole concept of pages, tabs, and applications makes my eyes glaze over. Yes, there are times when the distinction is clear as day. But other times applications are on tabs on a page. And other times an application isn't a page at all (apps.facebook.com domain). Oh and applications actually have pages of their own, but the page doesn't actually have the application on it. Or wait are those pages or profiles, because you know they are different.

This instantly puts me at a disadvantage, and I would normally take the blame for this, but give a read through their documentation sometime. Essentially every api page starts with: "Use this new api rather than this old api. Oh, unless you're on a page then you have to use the old api. But keep in mind that we're retiring this api in the next month." Holy crap! Think I'm exagerating? Directly from their documentation:
Note: We do not recommend FBML for new developers. If you aren't already using FBML, you should instead implement your application within an iframe, using the JavaScript SDK and social plugins for client-side integration with Facebook services. The one exception: if you absolutely must create an application that appears as a tab on a Facebook Page, you will need to use FBML for now; tabs do not currently support iframes directly. We will be transitioning tabs to iframes later this year -- please see the developer roadmap for more details.
Now can I start to put some of the blame on them instead of myself? Perhaps the most telling thing is that in 50% of the examples they give you, a direct copy and paste will not run. Ok, so the documentation sucks, not like their the first ones to suffer from that. This admission gives me hope, and there have been several updates on the facebook developer blog as well.

I won't be all negative though. Their PHP SDK worked pretty well, though I had a bit of a hiccup with hosting using PHP 5.1 and the SDK requiring JSON (I put most of the blame on hosting for that). And it was a bit tough to get a work around in CodeIgniter, again not really a facebook issue. In their defense it seems they are in transition right now and will perhaps come out much cleaner in 2011, but until then I'm not a big fan.

The main culprit for all of this is the god forsaken FBML and FBJS. These are essentially languages that take their normal counter parts (HTML and Javascript), strip most of their usefulness, then add a bunch of custom tags that are completely uncustomizable and have no significant tutorials. In addition to this the whole "view source" trick to get ideas doesn't work because of their bloated markup.

There, I'm done. I'm sure in a few days I will have that "a ha!" moment and zip through it (fingers crossed) but until then, wtf facebook?

UPDATE: I was finally able to accomplish my task, AJAX and all. I wasn't able to bind events the way I would have liked, but I guess that cake wasn't for eating. But a HUGE thanks goes out to these guys and their blog article. All the examples worked and he responded to his comments, what a novel idea!! I will follow up with more details for any who are interested.