Sunday, June 26, 2011

NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7

Since Mibbu framework supports CSS animations, it's good moment to create version exclusively for mobile devices, without using heavy and hard to render canvas, and with very limited JavaScript DOM interactions - CSS FTW! So I remove about 50% of code from original branch and test it on my Samsung Wave (bada has one of the best mobile browsers ever, so that was my starting point). And it simply doesn't work:
NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7
After short research I saw that Allegro ('Polish Ebay') had the same problem on Desktop Chrome months ago. After couple more hours of reading documentation I found a clue, that Webkit is freaking out if you try to put HTML content into style tag. So I switch
var cssStyle = document.createElement('style');
    cssStyle.innerHTML = 'body { color: #000; }';
to
var cssStyle = document.createElement('style');
    cssStyle.innerText = 'body { color: #000; }';
and everything works.

Friday, June 24, 2011

Few words about my CSS Nyan Cat

Last week Mozilla together with Finnish demoscene hackers organized Flame Party in capital of Finland, Helsinki. More than 100 participants worked whole day on outstanding web demos in two main categories - Single Effect and Main Demo.
Because of nearly release of stable Firefox 5, first Mozilla's browser with CSS3 Animation support, I decide to create CSS3 demo for the Single Effect Compo.
Since I really enjoy all that 4chan-like mems stuff, I chose Nyan Cat, as one of the most 'fresh' ones. In case you don't know it (check the progress bar!):


I didn't use any graphics to code my CSS Nyan Cat. It is completely drawn and animated in CSS. The 'pop-tart' body is created with two rounded cornered divs and big, pink dots separated with non-breaking spaces:
#toastBody {
    background-color:#fad695;
    width:100px;
    height: 70px;
    border: solid #000 5px;
    border-radius: 15px;
    padding: 2px;
    position:absolute;
    z-index:19;
}

#toastBody > div {
    width:100px;
    height:70px;
    border-radius: 30px;
    background-color: #fc9dff;
    display:block;
    color: #da3eb9;
    font-size: 40px;
    line-height: 10px;
}
All the animations was declared with @-moz/webkit-keyframe (I wrote a lot about this method before).

I made couple of unusual things during development. For example, look on the cat's mouth:


Yup, it is rotated 'E' letter:
<div id="mainHead" class="skin">
    <div class="mouth">E</div>
</div>

.mouth {
    position: absolute;
    -moz-transform: scale(2, 0.7) rotate(-90deg);
    -webkit-transform: scale(2, 0.7) rotate(-90deg);
    font-family: Arial;
    font-size: 25px;
    font-weight: bold;
    top:9px;
    left:37px;
    color: #000;
}

What about the rainbow behind the cat? I just cropped part of original image, put it into CSS Gradient Editor by ColorZilla (awesome tool BTW, but still without couple of necessary features I use daily; I think I will create something like this on my own), which generates me css gradient ready for pasting into the div background:
.rainbow {
 position:absolute;
 width:45px;
 height:90px; 
 background: -moz-linear-gradient (top, #d91a12 15%, #e13300 15%, #ff7f14 16%, #f2ab03 32%, #ebc000 32%, #fade00 33%, #efff03 48%, #56fc02 49%, #52ff01 66%, #4ade7e 67%, #3baaf2 67%, #3baaf2 84%, #7337f7 84%, #6b40f2 100%);
}
The most annoying thing was the star. Animated stars in the background are made up from 8 animated elements. I google "nyan cat sprite" and found all the star frames [like this]. The only way to animate it was pixel-perfect animation of each of 8 divs. It took me really lot of time:
@-moz-keyframes star1 {
 0% { top: 0; height: 5px;}
 33.19% { top: 0; height: 5px; }
 33.2% { height:10px; top:0; }
 49.79% { height:10px; top:0; }
 49.8% { height:10px; top:5px; }
 66.39% {height:10px; top:5px; }
 66.4% { height:5px; top:10px;}
 82.99% { height:5px; top:10px;}
 83% { height: 5px; top: 15px; }
 99.99% { height: 5px; top: 15px; }
 100% { top: 0; height: 5px; }
}

@-moz-keyframes star2-3-6-7 {
 0% { visibility: hidden; }
 16.59% { visibility: hidden; }
 16.6% { visibility: visible; }
 33.19% { visibility: visible; }
 33.2% { visibility: hidden; }
 100% { visibility: hidden; }
}

@-moz-keyframes star4 {
 0% { left: 0; width: 5px; visibility: visible;}
 33.19% { left: 0; width: 5px; }
 33.2% { width:10px; left:0; }
 49.79% { width:10px; left:0; }
 49.8% { width:10px; left:5px; }
 66.39% {width:10px; left:5px; }
 66.4% { width:5px; left:10px;}
 82.99% { width:5px; left:10px;}
 83% { width: 5px; left: 15px; visibility:hidden;}
 99.99% { width: 5px; left: 15px; visibility:hidden;}
 100% { left: 0; width: 5px; visibility:hidden;}
}

@-moz-keyframes star5 {
 0% { left: 38px; width: 5px; visibility: visible;}
 33.19% { left: 38px; width: 5px; }
 33.2% { width:10px; left:33px; }
 49.79% { width:10px; left:33px; }
 49.8% { width:10px; left:28px; }
 66.39% {width:10px; left:28px; }
 66.4% { width:5px; left:28px;}
 82.99% { width:5px; left:28px;}
 83% { width: 5px; left: 15px; visibility:hidden;}
 99.99% { width: 5px; left: 15px; visibility:hidden;}
 100% { left: 0; width: 5px; visibility:hidden;}
}

@-moz-keyframes star8 {
 0% { top: 32px; height: 5px; visibility:visible;}
 33.19% { top: 32px; height: 5px; }
 33.2% { height:10px; top:28px; }
 49.79% { height:10px; top:28px; }
 49.8% { height:10px; top:23px; }
 66.39% {height:10px; top:23px; }
 66.4% { height:5px; top:18px;}
 82.99% { height:5px; top:18px;}
 83% { height: 5px; top: 15px; visibility:hidden;}
 99.99% { height: 5px; top: 15px; visibility:hidden;}
 100% { top: 0; height: 5px; visibility:hidden;}
}

.star {
 position: absolute;
 width: 40px;
 height: 40px;
 z-index: 10;
}

.star div {
 width: 5px;
 height: 5px;
 background-color: #fff;
 position: absolute;
 -moz-animation: star1 0.4s linear 0s infinite;
 -webkit-animation: star1 0.4s linear 0s infinite;
}

Here is the final result of everything: CSS NYAN CAT, and Github repo. If you like it, don't forget to click "I like it" on Mozilla's page!

Thursday, June 9, 2011

The Flame Party Helsinki


If you are planning to spend next weekend in Finland, you cannot omit Flame Party organized there by Mozilla, Alternative Party Crew and DOT. It will be awesome weekend full of coding, BBQ, free drinks, Finish saunas and outstanding workshops including one lead by my - "Dive into HTML5 Animation":
"During the workshop you will learn about different methods of animation in JavaScript. We will compare the performance and ease of it's implementation in various browsers on different devices. Are we condemned to use DOM? What about new CSS techniques? Or maybe canvas is future of the web games?"

So what are you waiting for? Register now and follow the party on Lanyrd and Facebook.

Sunday, June 5, 2011

CSS Animation in Firefox

Mibbu now supports CSS Animations also in Firefox. The only version in which I have tested it is 5.0/Beta, but I think it should works also in Aurora. Feature detection problem I describe last week wasn't the only unexpected behavior during implementing this (BTW, I want to thanks Anonymous guy who corrects my attempt - contact me, I have only your IP & Country you were writing from:), and Paul Irish for deeper explanation of the problem).

Every animation I've created using Mibbu in Firefox animate only once. No matter if I put 'infinite' as a value of AnimationIterationCount. Using MozAnimation shorthand property doesn't want to work. I rewrote everything couple of times in different ways without any result (sometimes it just stop working also on webkit:)). And then I figure out that setting 'none' as 'MozAnimationDelay' instead of 0 (as in the spec!) solves everything. Nice try Mozilla, but it is again 1:0 for me:). I really love everything from Mozilla, Firefox is my main browser, each day I'm working with technologies created there (also in my full time job in GaduGadu), I'm excited in every news like THIS ONE, and I even ran XUL workshop two weeks ago on FalsyValues conference. But sometimes I simply don't understand why they solve something in such a weird way.
I also had to use MozAnimation attribute using brackets notation because Closure Compiler don't understand it and minimized it to the single letter.
So, you can now download Mibbu from my Github account and play with it.

UPDATE
Ok, thanks to Marek Stepien's research done after my post we figured out that putting delay value without the unit ('0' instead of '0s') solves the problem. Probably, when we put single digit without units, Firefox thought that it is -animation-iteration-count (the only property without any units). Marek creates bug report for this here.

Monday, May 30, 2011

onGameStart tickets

It is now possible to register to onGameStart - first HTML5 game conference. Don't wait for anything, just go to http://ongamestart.com and do what you have to do:).

Sunday, May 29, 2011

CSS3 animations in Mibbu

Last week I implement CSS Animations in my gamedev micro framework, Mibbu.
It is possible now to animate sprites in three different ways - cropping parts of the sprite with .drawImage() in 'canvas mode', manipulating 'top' & 'left' attributes of absolute position of the image [both described in here] and CSS Animation in DOM mode.
For now Mibbu supports CSS animations only in webkit based browsers. I know that beta version of Firefox supports it as well, but I didn't find easy way to detect it. In webkit we can just check what is the initial value of given attribute (use whatever DOM element you want), like this:
if (typeof document.body.style.webkitAnimation !== "undefined") {
//all your animation are belong to us
} else {
//no css animations:(
}
Unfortunately it don't work in Aurora, mozAnimation always return 'undefined'. Is there any way to easy detect it?

The main point in creating css animations is preparing proper keyframes in a css classes and connecting it to the DOM elements with description parameters like duration or number of iterations. CSS engine will be responsible for sprite animation so draw() function of each sprite object should be empty. The keyframes are generated during constructing the object and append to the document - one class in one script element, it will be easier to edit them when the parameters of the animation will change during the gameplay. I also wrote a little function to convert speed of an animation (from Canvas & DOM mode) to the CSS Animation Duration parameter.
var calculateSpeed = function(speed, frames) {
    return (~~((1 / (60 / speed)) * 100) / 100) * (frames+1);
};

constructAnimationClass = function(){
 var animClass = "@-webkit-keyframes 's" + t.id + "' {\n",
        step = 100 / (t.fs + 1),
        str = '% { -webkit-transform: translate(';

    for (var q = 0; q < t.fs+1; q++) {
        animClass += ~~((step * q) * 100) / 100 + str + t.animation * t.width*-1 + 'px,' + q * t.height * -1 + 'px); }\n';
        animClass += ~~((step * (q + 1) - 0.01) * 100) / 100 + str + t.animation * t.width * -1 + 'px,' + q * t.height * -1 + 'px); }\n';
    }
                
    return animClass += '100'+ str +t.animation*t.width+'px, 0px); }\n}';
                
};

//append created class to the document
t.animStyle = document.createElement('style');
t.animStyle.innerHTML = constructAnimationClass();
document.body.appendChild(t.animStyle);
Above code creates class like this: And every sprite needs to implement description of the animation (name is created by concatenating 's' and internal id of the sprite:
t.style.webkitAnimation = "'s"+t.id+"' "+calculateSpeed(t.speed, t.fs)+"s linear 0 infinite";
Main problem I had with implementing this was pausing the game - even if main loop stops, CSS engine still animates the keyframes. So I just set '0' for the -webkit-animaition-duration parameter:
'off': function(){
    MB_Stop();
    if (MB_usingCSSAnimations){
        var i = MB_elements.length;
        for (;i--;){
            if (MB_elements[i].image)
                MB_elements[i].image.style.webkitAnimationDuration = 0;
        }
    }
};
It sucks but it works. Anyone know better solution? Next step is to provide support of webkitAnimationIterations for iteration's callbacks (now it is calculated using JavaScript, not with the events, but contrary to what I thought webkit has already supported DOM events for animation [thanks Askoth]). If you want help feel free and contribute: Mibbu on github. There are also some issues I found creating new features and I have no time to fix it now. If you use Mibbu and have some ideas or found any bugs, write me about it or fork & pull request on Github.

BTW, Github will be one of the sponsors of onGameStart, HTML5 Game Conference. We will open registration on Monday evening Central European time, so check the conference page and don't miss it!

Wednesday, May 4, 2011

Mibbu - javascript html5 game framework

I have just published initial release of Mibbu - my javascript microframework for fast game prototyping. To be honest - it is just set of functions and patterns I use always when I write my games. It is more a sandbox, starting place with basic tools, than a real framework (that's why I called it 'microframework'). It provides sprite animations, basic operations like movement or collisions, scrolling backgrounds and drawing on both - canvas or DOM. It uses DOM only when it is not possible to use Canvas (like in older IEs), but you can force it to do so with one single function (canvasOff()) - then it will be drawn with divs & imgs. It is the same mechanics I have used in OpenOdyssey or Janpu. I will try to write something more about using Mibbu later this week.

Saturday, April 30, 2011

First HTML5 Game Conference ever - onGameStart

As probably most of you already know - I'm organizing first HTML5 game conference ever. It will take place in my hometown - Warsaw at 22nd & 23rd of September 2011. I've done my best with selection of the speakers - so far it is the only chance to meet and talk with the best Open Web Game developers. Let me introduce some of them:
Bartek Drozd - creator of J3D - WebGL Library with Unity3d object/scene exporter.
Rob Hawkes - author of "Foundation HTML5 Canvas" book
Robby Ingebretsen - creator of Agent008Ball
Brandon Jones - author of glMatrix library and a lot of awesome webGL demos (like Quake III)
Martin Kool - creator of multiplayer, online versions of old good Sierra games - Sarien
Seth Ladd - Google developer advocate (he will speak on Google IO in two weeks - don't miss it!)
Simon Oberhammer - creator of pyGame port for Javascript - GameJS
Andreas Røsdal - originator of biggest strategy game made in open web technologies based on Sid Mayer's Civilization - Freeciv.net
Dominic Szablewski - creator of ImpactJS - most complex and so far the best Javascript game engine.

For more information about the conference check our site, lanyrd, twitter and facebook. And don't forget to preregister (it is possible on the site).

Sunday, April 10, 2011

GG Workshop

Yesterday I ran Javascript workshop about creating Apps & Games in Social Networks. Fourteen great developers in eight hours tried to create multiplayer checkers (draughts? what's the difference?) game and adapt it to two social network APIs (Facebook & GG.pl). I published source code of the final result on my Github, just as Maciej Konieczny, one of the participants. Here are also my slides and couple of photos:








I would like to thanks everyone for the presence and I hope we will meet on frontend meetings in near future (like those organized by Google Poland). If you will find some free time feel free to rate my workshop on SpeakerRate.

Tuesday, March 29, 2011

Sun^26

That post has nothing in common with programming or even computers but I was so excited when I discover things I want to write about that 140 chars of twitter wasn't enough for me.

The Sun is a star in the center of our Solar System Anyone knows that. But have you ever think about number '26' in Sun statistics?
  • Apparent magnitude of the Sun is -26,8
  • Mean distance from Milky Way 26,000ly
  • Galactic period 226.000.000 years
  • Radiant flux 3,827×10^26 W
  • Unicode of Sun symbol - 2609
  • Distance from Milky Way Equator - 26ly
  • Speed 260 km/s
  • Conversion rate of mass-energy 4.26 million metric tons per second
  • Mean mass loss in energy 26,732MeV
  • Total mass loss 6,5x10^26
  • STEREO observation mission starts at 26th of October 2006

Coincidence? Don't think so! :)

from Polish & English Wikipedia.

Saturday, March 19, 2011

meet.js in Warsaw

I have just returned from Warsaw edition of meet.js, polish javascript meeting organized by Damian Wielgosik and Paweł Czerski, organizers of FrontTrends and Falsy Values. During the meeting we ware able to watch four Javascript tech-talks.
First was Robert Tomaszewski from Hypermedia Isobar with his presentation about different context of calling Js structures. He started with a little of JS history, then explained basics of using 'this' depending on placement of the objects and different approaches of using 'this' in DOM events.
Next was Marek Stepień - lead of Aviary.pl, team of programmers and translators localizing open source software for Polish users. He started with review of past JS objects, its restrictions and methods of its elimination. Then he presented new methods of creating objects in Js 1.8.5 like defineProperty() etc.
After the break there were a little contest - I won weekend stay in Karpacz for my implementation of adding function (Thanks!:) ). Just after that Tomasz Tunik talked about his Einie framework. He showed a lot of cool examples (like mouse tracking and interactions with canvas objects, or Pew! Pew! Towers, game created in 48h by Thomas and Szymon Pilkowski on HTML5gameJam in Paris. All of that examples are published on Einie's site so don't hesitate to check it.

Last presentation was made by me. I was talking about pseudorandom numbers and Steganography. I won't describe my talk, maybe someone else will, I think in couple of days I will publish it as a blog post or maybe little JS library.
I want to thanks the organizers one more time, and I hope we will meet on the next meet.js (or at least on Falsy Values:) ).

Thursday, March 3, 2011

Birthday

My blog is one year old today.
I will try to write some summary of that period later this week or at the beginning of the next one. For sure one of the best things I wrote about was my HTML5 Canvas Game Tutorial, one of the most popular in all over the web, but there were also other posts I would like to remind.

Sunday, February 27, 2011

CSS3 sprite animation, issues in Safari

Together with CSS3 standard we get awesome tool for creating hardware accelerated css-only animated sprites. For now it is implemented only in webkit based browsers like Safari, Chrome or most of the mobile browsers. Paul Bakaus described it on his blog months ago, with additional approaches and performance optimization methods. Also Marek Pawlowski said a lot about this on his DevMeeting gamedev workshop. Working on my new mobile game, I've tested everything I could find all over web. And some of the examples (like that Paul's created with Doug Neiner) did not works on Safari and some mobiles (like Samsung's Dolfin on my bada Wave). I spend couple of annoying hours to figure out what happens, analyzing different use cases, different examples and documentation pages. But solution was simple as hell:
Safari and some of mobile browsers cannot animate any element with CSS3 animation if there is no '0%' and '100%' step.
That's why example from Paul's blog didn't want to work when I test them:
@-webkit-keyframes 'animationName' {
  0% { background-position: 0px 0px; }
  12.5% { background-position: -128px 0px; }
  25% { background-position: -256px 0px; }
  37.5% { background-position: -384px 0px; }  
  50% { background-position: -512px 0px; }
  62.5% { background-position: -640px 0px; }
  75% { background-position: -768px 0px; }
  87.5% { background-position: -896px 0px; }
}
Adding the last frame, with the same parameters as the first one, fixes the problem:
@-webkit-keyframes 'animationName' {
  0% { background-position: 0px 0px; }
  12.5% { background-position: -128px 0px; }
  25% { background-position: -256px 0px; }
  37.5% { background-position: -384px 0px; }  
  50% { background-position: -512px 0px; }
  62.5% { background-position: -640px 0px; }
  75% { background-position: -768px 0px; }
  87.5% { background-position: -896px 0px; }
  100% { background-position: 0px 0px; }
}
Of course I didn't want to show that Paul and other guys was wrong - for sure all of them has bigger experience and knowledge than me. And their solutions will eventually work when browsers will implement the standards (what was the point I supposed) - but I was looking for something what will work here and now.

Wednesday, February 23, 2011

Javascript random numbers with custom seed - part 2

Generator created in previous example was able only to create integer numbers from zero to the given maximum (2^50) using provided seed. But in most cases we need random numbers from some range, so lets modify previous example and add 'min' and 'max' arguments to the .next() method. Also, to make it more like the native Math.rand(), let's make it generating floats from 0 to 1.
var CustomRandom = function(nseed) {    
  
  var seed,    
    constant = Math.pow(2, 13)+1,    
    prime = 1987,    
//any prime number, needed for calculations, 1987 is my favorite:)  
    maximum = 1000;    
//maximum number needed for calculation the float precision of the numbers (10^n where n is number of digits after dot)  
    if (nseed) {    
      seed = nseed;    
    }    
    
    if (seed == null) {    
//before you will correct me in this comparison, read Andrea Giammarchi's text about coercion http://goo.gl/N4jCB  
      
      seed = (new Date()).getTime();   
//if there is no seed, use timestamp     
    }     
    
    return {    
      next : function(min, max) {    
        seed *= constant;    
        seed += prime;    
           
      
        return min && max ? min+seed%maximum/maximum*(max-min) : seed%maximum/maximum;  
// if 'min' and 'max' are not provided, return random number between 0 & 1  
      }    
    }    
}  
Now its easy to use it in such a way:
var rng = CustomRandom(23);
//use '23' as a seed
    rng.next(); // 0.426
    rng.next(); // 0.205
In the next part I will show some GameDev related examples of using Random Number Generators with custom seeds.

Check 1st part of the "Javascript random numbers with custom seed" tutorial

Thursday, February 17, 2011

Javascript random numbers with custom seed - part 1

Introduction
Any random number generator generates sequences of numbers using some initial seed. The same seed always gives the same sequence. Most popular initialization method is to provide actual timestamp as seed - it changes every second so probability of receiving same sequences is very low.
Generating pseudorandom sequences of numbers has wide variety of uses, ranging from creating random maps for games (with well constructed map generator all the game should remember is just the initial seed, not the array with list of map elements), to steganography, where you code & decode message on the sample image using the same seed (it is impossible to decode the information from the image without knowing exact number used as seed during coding it). I will create some examples in the next part of the series.

First attempt
Unfortunately, it is impossible to provide custom seed to the Javascript Math.random(). It always uses timesamp for initialization. So let us create our own generator with everything we need.
var CustomRandom = function(nseed) {

    var seed,
        constant = Math.pow(2, 13)+1,
        prime = 37,
        maximum = Math.pow(2, 50);
 
    if (nseed) {
        seed = nseed;
    }
 
    if (seed == null) {
//if there is no seed, use timestamp
        seed = (new Date()).getTime();
    } 
 
    return {
        next : function() {
            seed *= constant;
            seed += prime;
            seed %= maximum;
            
            return seed;
        }
    }
}
And now:
var rng = CustomRandom(23);
//use '23' as a seed
    rng.next(); //188476
    rng.next(); //1544183905
    rng.next(); //12651498733702
In the next parts I will extend that CustomRandom() generator with limits (min and max value) and implement some real-life use cases.

Check 2nd part of the tutorial: Javascript random numbers with custom seed

Wednesday, January 26, 2011

Most useless skills ever aka how to implement sqrt() in javascript.

Couple of day ago, Dominic Szablewski, author of Impact Engine tweets about interesting job interview:

Seriously, WTF? Why Javascript developer, even working for such a big company as Facebook, needs to know how to re-implement build-in language elements? Knowing everything about everything was bane of elementary education - we have all been trained (at least here, in Eastern Europe), that when we need to know something we shouldn't use 'outside' sources such as books then and Internet now. Why? Personally, I didn't know any developer who didn't sometimes read the documentation, especially if it takes less than 3s if you know what you are looking for.
In case that 'implementing sqrt()' task will ever occurs again, here are two of my JS implementations:) :
//in this way calculators implements square roots:
var ownSqrt = function(number) {
    return Math.exp(Math.log(number)/2);
}
But if it is forbidden to use Javascript Math object constants at all, the best way is to use approximation like this:
var ownSqrt2 = function(number) {
    var x = number;
    while (Math.abs(x*x-number) > 0.001) x = (x*x+number)/(2*x);
    return x;
}
There are a lot of different algorithms on Wiki, and their implementations all over the Web.

Friday, January 14, 2011

Mozilla Game On 2010

During last Thursday it was possible to send your entry to the Mozilla GameOn 2010 Competition. There were more than 160 games submitted, but some of them was disqualified because of using 'non open' technologies like flash or Unity. Finally, there are 124 chosen titles in the gallery. Checking almost every game I found couple of technologies, libraries, plugins, frameworks or engines I've never heard of before, or just forgot about. Some of them are worth describing in here. First of all I totally forgot about HTML5 Boilerplate, an "HTML/CSS/JS template for a fast, robust and future-proof site", used in Snake game [MGO2010]. Another technically interesting entry was Black Obelisk [MGO2010], written completely in haXe, opensource programming language with ability to compile to Javascript, Flash, NekoVM bytecode, PHP, C++ and C# or Java in the near future. Couple of games was written in Java with cross-compiled JavaScript presentation layer using GWT, eg SVG-EDU [MGO2010] or Zulu [MGO2010]. Main reason people used Flash in their games was enabling sound effects (like Sinuous [MGO2010], the winner of 10kApart). But Wizard Wars [MGO2010] used SoundManager2 to achieve same effect. Mad Tanks TD [MGO2010], one of my personal favorites in the competition, uses LESS, which "extends CSS with variables, mixins, operations and nested rules". Looks cool! (both, the game and the compiler:) ). I was impressed with amount of WebGL based games. In Red shooting Hood [MGO2010], made by Tymon Zgaiński from Poland, member of polish gameDev community Warsztat, I found Sylvester, "Vector and Matrix math for JavaScript". Open web implementation of simple and well known Frogger [MGO2010] was compiled to Javascript & canvas using Ristretto Mobile, "a Web-based Compiler for Running Interactive Games and Simulations". My own entry, OpenOdyssey [MGO2010]was made simultaneous with Mibbu framework and is based on it. I'm not satisfied with the final result, but I will develop both after the competition. If I will find some free time during the weekend I will write few words about OO & Mibbu.

Wednesday, January 12, 2011

Facebook Hackers Cup eliminations

Last weekend I was participating in the elimination part of Facebook Hacker Cup. There were three problems to solve and it was obligatory to finish at least one. Since it was last weekend before Mozilla GameOn 2010 deadline, I had no time for solving academical, non-real life, algorithmic problems I was always poor in. So I just took a look to the first one [mirror]. It looked quite easy, and in couple of minutes I had kind of prototype algorithm implemented in pure Javascript. Main idea of the problem was that the biggest number which square could be part of the input, cannot be bigger than square root of the input divided by two. So I simply iterate from 1 to that max, and in each iteration I checked square root of input number reduced by square of 'i'. If it was integer, we have sum of two squares. If float, we haven't. Piece of cake:). My Javascript implemetation in Rhino (as I described before):
var check = function(input) {
    var result = 0,
        max = Math.sqrt(input/2);

    if(Math.sqrt(input)%1==0) {
        result++;
    }

    for(i=1;i <= max;i++) {
        if(Math.sqrt((input-Math.pow(i, 2)))%1==0) {
            result++;
        }
    }
    return result;
}

var MainFunction = function(args) {
    var a = readFile(args).split("\n");

    for (var i=1, j=a.length;i < j ;i++) {
        print(check(a[i]));
    }
}(arguments);

Friday, January 7, 2011

JavaScript from command line - standard input & output

As you could already know from Mr. C's lectures from YUI Theater or FrontTrends - standard I/O is the worst thing programming languages could ever implement. Fortunately - Javascript has no input at all. And in most cases it doesn't need any - it was designed as script language for web pages. But nowadays we use Javascript in any other aspects of our programming life - we can build for desktops using XUL, server-side tools like node.js (for example with announced last week JSPP) or any other Server-side Javascript implemenation provide JS backend for the web, native mobile apps could be created using frameworks like Phonegap. So what about executing JS scripts from command line? And why do we need it?
The reason I've refreshed my experiences with JS scripts executing was Hacker Cup organized by Facebook - there are no language restrictions in there, your scripts just has to know how to analyze given input and write the answers on the standard output. It is quite unpopular way of using & writing Javascript, so I will show few tips of command line in here.

Engines
There is such a JavaScript engine called Rhino. It is completely written in Java, open source, and very easy to use. It is managed by Mozilla, so you can find a lot of docs and tutorials on Mozilla's page.
Rhino has few additional functions eg for working with files (readFile()) or serializing objects (serialize()), which makes it useful in solving algorithmic problems in competitions like FBHC. Full list of all shell function can be found on Mozilla's page.
Each time you run Javascript scripts from command line, all the arguments you provide will be stored in global variable called 'arguments'. Enriched with this knowledge we can begin with some examples. This is my implementation of binarySearch algorithm:
Array.prototype.binSearch = function(element) {
    var element = parseInt(element, 10), 
        left = 0,  
        right = this.length-1,
        middle = ~~((left+right)/2),
        lastMiddle;

    while (parseInt(this[middle], 10) !== element) {
    
        if (lastMiddle === middle) {
            return null; //nothing found, break
        }
        
        if (parseInt(this[middle], 10) < element)
            left = middle++;
        else 
            right = middle--;
        
        lastMiddle = middle;
        middle = Math.round((left+right)/2); 
    }        
    return middle; //index of found element 
}


var MainFunction = function(args) {

    var a = readFile(args).split("\n"),
        arrayElement = a[0].split(" "),
        result;
    
   
    print("Array: "+arrayElement);
    
    for (var i=1, j=a.length;i < j;i++) {
        result = arrayElement.binSearch(a[i]);
        if (result) 
            print("Element "+parseInt(a[i], 10)+" in on position nr "+result);
        else 
            print("Element "+parseInt(a[i], 10)+" cannot be found in the array");
    }

}(arguments)
As an input it takes filename with the elements of an array in first row and elements to find in that array in next rows, like this:
4 10 12 19 25 34 41 50 52 61 66 68 76 81 82 85 94 97 105 112 115 124 128 138 139 230 321 432 456 540 
61
82
94
2
10
4
24
432
Assuming that script file is called binSearch.js, data.txt is the file with input data, and both are in the same directory as Rhino, to run the script simply type
java -jar js.jar binSearch.js data.txt
Ideone You can simply achieve the same effect using online tools\, without installing anything on your computer. Ideone, online IDE & debugging tool allows you to run your scripts using Rhino or SpiderMonkey, another Mozilla's JS engine, this one written in C. You can edit your scripts in realtime and provide different inputs on every run. Good luck in FBHC!