Sunday, February 28, 2010

A blinking aside

This post isn't related to the explosion of boxes, but it is related to the blinking of chikins. In the near future, the organic nature of chikins will be permanently fused with an electronic brain, for a more regular blinking. The designer of such a brain will have need to be able to predetermine the rate of blinking for a given chikin. This is not a difficult task, but it does get tedious, and what good are computers if they won't do tedious tasks for us? Therefore, I present the glorious

Chikin Blinker Calculator
AKA 555 timer astable mode calculator and visualiser. Canvas not supported!

R1:
R2:

Time on: ms
Time off: ms
C: μF

This simple script calculates the time on and off for a 555's output given two resistor values and a capacitor value, as well as the two resistor values given time spent on and off and a capacitor value. In addition, there is a convenient visualisation and circuit diagram, drawn in a <canvas> context, which blinks at the rate specified. I think this ought to be useful for anyone who likes electronics, but doe not like tedious number-crunching.

Bullets and points.

I want to move this toy project further toward a game project, so it's pretty reasonable to throw in a new variable to keep track of score and a new variable to keep track of ammo, and modify some functions to increment and decrement those scores as needed.

...
   var score = 0;
   var ammo = 10;
...
   clicker = function(event){
    var x = 0;
    var y = 0;
    if(event){
     x = event.pageX - newCanvas.offsetLeft;
     y = event.pageY - newCanvas.offsetTop;
    }
    if(ammo > 0){
     ammo--;
     for(i=0;i<boxes.length;i++){
      box = boxes[i];
      if(Math.abs(x-box.x)<box.size/2 && 
         Math.abs(y-box.y)<box.size/2){
       explodeBox(i);
      }
     }
    }
   } 
...

   stickPhysics = function(stick,n){
...
    if(newy > 495){
     sticks.splice(n,1);
     ammo++;
     score++;
    }
...
   }
...
The bold text above is the new stuff. It will keep track of the total number of sticks that fall off the bottom of the screen, with the score variable, as well as the "ammo" the player has available. If ammo runs down to zero, the player can't shoot down any more boxes until more sticks fall off the bottom of the screen.

Another big step from toy to game would be an end condition. In fact, just by implementing ammo I've actually created a condition under which the game can't go any further. All that's left is to let he player know that it's all over and clicking on boxes is fruitless. To do this, a conditional sits in the draw() function and draws a "Game Over" screen if the player has run out of ammo and the sticks array is empty.

...
   draw = function(){
...
    if(ammo == 0 && sticks.length == 0){
     var y = 125;
     newContext.fillStyle='rgba(255,100,100,0.9)';
     newContext.fillRect(20,80,280,320);
     newContext.fillStyle="red";
     newContext.strokeStyle="#000000";
     newContext.font = "45px sans-serif bold";
     newContext.textAlign="center";
     newContext.fillText("Game Over",160,y);
     newContext.strokeText("Game Over",160,y);
     newContext.font = "25px sans-serif";
     newContext.fillStyle = 'black'
     var scoretxt = "Final Score: ";
     newContext.fillText(scoretxt + score,160,y+30);
    }
...
}

This takes care of the case in which the player runs out of ammo, but ignores the case in which the game runs out of boxes. Obviously, if there are no boxes, the game can't continue. Killing just ten boxes and being done, however, isn't all that fun. Rather, the boxes ought to be endless, but harder to kill, so that the player is eventually forced to use up all of his ammo. This means levels!

Levels means altering quite a few things, but without any really major changes. Since it's also nice to know what level a player is on, I'll go ahead and drop in a little scoreboard.

...
   var level = 0;
...
   makeBox = function(x,y){
    ...
    var vx = (level/2+1)*(Math.random()-1.0)/6;
    var vy = (level/2+1)*(Math.random()-1.0)/6;
    ...
   }
...
   init = function(){
    ...
    for(i=0;i<3;i++){
     var x = Math.random()*318 + 1;
     var y = Math.random()*478 + 1;
     makeBox(x,y);
    }
    ...
   }
...
   draw = function(){
    ...
    if(boxes.length == 0){
     level++;
     for(i=0;i<3;i++){
      var x = Math.random()*318 + 1;
      var y = Math.random()*478 + 1;
      makeBox(x,y);
     }
    }
    ...
    if(ammo == 0 && sticks.length == 0){
    ...
     newContext.fillText("You have run out of ammo",160,y+30);
     newContext.fillText("on level "+level,160,y+60);
     newContext.fillText("with a final score of "+ score,160,y+90);
    }
    ...
    // The scoreboard
    newContext.fillStyle="rgba(230,230,230,0.8)";
    newContext.fillRect(320-80,5,75,42);
    newContext.fillStyle="#000000";
    newContext.font="10px sans-serif";
    newContext.textAlign="left";
    newContext.fillText("Ammo: "+ammo,245,18);
    newContext.fillText("Score: "+score,245,30);
    newContext.fillText("Level: "+level,245,42);
    ...
   }

And so, I have a game! Hooray!

The only problem is that if someone plays it in its current form, it takes a click to shoot down a box. This means that to get rid of the hundreds of sticks of ammo a player ends up collecting, the player would have to nearly break his finger clicking the mouse button. A better approach is to have a machine-gun effect, where holding down the mouse button is enough to keep killing boxes.

...
   var lastShot = 0;
   var firing = false;
   var mousex = 0;
   var mousey = 0;
...
   clicker = function(event){ 
    var x = 5;
    var y = 5;
    newCanvas.onmouseup = up;
    newCanvas.onmousemove = move;
    if(event){
     x = event.pageX - newCanvas.offsetLeft;
     y = event.pageY - newCanvas.offsetTop;
     mousex = event.pageX - newCanvas.offsetLeft;
     mousey = event.pageY - newCanvas.offsetTop;
    }
    shoot();
    firing = true;
   }
   up = function(event){
    newCanvas.onmousemove = null;
    firing = false;
   }
   move = function(event){
    if(event){
     mousex = event.pageX-newCanvas.offsetLeft;
     mousey = event.pageY - newCanvas.offsetTop;
    }
   }
   shoot = function(){
    var x = mousex;
    var y = mousey;
    var t = new Date().getTime();
    if(t-lastShot > 50){
      lastShot = t;
      if(ammo > 0){
      ammo--;
      for(i=0;i<boxes.length;i++){
       var box = boxes[i]
       if(Math.abs(x-box.x)<45 && Math.abs(y-box.y)<45 && box.size == 90){
        explodeBox(i);
       }
       if(Math.abs(x-box.x)<15 && Math.abs(y-box.y)<15 && box.size == 30){
        explodeBox(i);
       }}}}
   }  
...
   draw(){
    ...
    if(firing) shoot();
   }

The problems, however, never end. Now that I've got a machine-gun going, it's pretty frustrating to have no real way of telling how fast your ammo's going. The firing rate is high enough, and the <audio> tag is annoying enough to use, that a sound for each shot isn't feasible. Rather, I want to use yet another array of visual elements: bullet holes.

...
   var bulletholes = new Array();
   
   Hole = function (x,y,t){
    this.x = x;
    this.y = y;
    this.time = t;
   }
...
   draw(){
    ...
     for(i=0;i<bulletholes.length;i++){
     var hole = bulletholes[i];
     var hc = 'rgba(0,0,0,';
     alpha = 1 - (time-hole.time)/3000
     hc = hc + alpha;
     hc = hc + ")";
     if (alpha <= 0){
      bulletholes.splice(i,1);
     } else {
      newContext.fillStyle = hc;
      newContext.fillRect(hole.x-1,hole.y-1,2,2);
     }
    }
...
   shoot = function(){
    ...
    if(t-lastShot > 50){
     ...
     if(ammo > 0){
      bulletholes.push(new Hole(x,y,t));
      ...
     }
     ...
    }
    ...
   }

And the final result is below. It's not quite the same script as in the first post, but it is the same game. That took a rather long time.

Canvas not supEported in your browser.

Wednesday, February 24, 2010

Explosions!

Boxes are cooler when they explode. Quite reasonably, boxes should explode when clicked on, so I need to reassign the creation of boxes to a function that happens to be not the click handler. The initialization function strikes me as a good place to put all that!

...
   init = function(){ // This function will start things
    time = new Date().getTime();
    setInterval("draw();",20);
    for(i=0;i<20;i++){
     makeBox(5,5);
    }
   }
...

Now, that makes a whole lot of boxes, so let's make some way to explode the damn things:

...
   explodeBox = function(n){
    box = boxes[n];
    boxes.splice(n,1);
    if(box.size == 90)
    for(i=0;i<3;i++){
     var y = (box.y-30)+30*i;
     for(j=0;j<3;j++){
      var x = (box.x-30)+30*j;
      var dvx = (Math.random()-1.0)/9;
      var dvy = (Math.random()-1.0)/9;
      boxes.push(new Box(x,y,box.vx+dvx,box.vy+dvy,30,box.color));
     }
    }
   }
...
This function accepts the index of the box I want to explode in the boxes array as its input and starts by removing that box from the array. After that, the function pushes nine new, smaller boxes into the array, each having the same color as the original and randomly varied velocity.

All that's left is to make some way to tell the javascript that I want some box to explode, and which box it is. I do this by modifying the click handler:

...
   clicker = function(event){
    var x = 0;
    var y = 0;
    if(event){
     x = event.pageX - newCanvas.offsetLeft;
     y = event.pageY - newCanvas.offsetTop;
    }
    for(i=0;i<boxes.length;i++){
     box = boxes[i];
     if(Math.abs(x-box.x)<45 && Math.abs(y-box.y)<45 
                             && box.size==90){
      explodeBox(i);
     }
    }
   }  
...

The result is quite interesting, visually, but isn't a game yet. Sure, you can click on boxes to make more boxes, but there is no score and no end, so it's just a toy. A good step in the direction of a game is some sort of situation in which the player know he's done, so I'm going to make the smaller boxes explode as well, but this time, the remains won't stay on the screen until the end of time. This way, a "player" can clear the screen and feel good about himself.

So, to destroy boxes altogether, I need to declare an array to hold the elements the boxes break up into. Sticks are my shape of choice, since that's what squares are made up of.

...
   var sticks = new Array();
...
   Stick = function(x,y,theta,vx,vy,length,omega,color){
    this.x = x;
    this.y = y;
    this.theta = theta;
    this.vx = vx;
    this.vy = vy;
    this.length = length;
    this.omega = omega;
    this.color = color;
   }
...
Unlike boxes, sticks can rotate, so the sticks have an extra coordinate, theta, and an extra velocity term, omega. Like boxes, sticks have a color and a size.

Next, I want to modify the function that explodes boxes to be able to handle the smaller boxes:

...
   explodeBox = function(n)...
...
    if(box.size == 30){
     var dvx = (Math.random()-1.0)/11;
     var dvy = (Math.random()-1.0)/11;
     var omega = (Math.random()-1.0)/90;
     sticks.push(new Stick(box.x,box.y+15,0,
                           box.vx+dvx,box.vy+dvy,
                           30,omega,box.color));
     dvx = (Math.random()-1.0)/11;
     dvy = (Math.random()-1.0)/11;
     omega = (Math.random()-1.0)/90;
     sticks.push(new Stick(box.x,box.y-15,0,
                           box.vx+dvx,box.vy+dvy,
                           30,omega,box.color));
     dvx = (Math.random()-1.0)/11;
     dvy = (Math.random()-1.0)/11;
     omega = (Math.random()-1.0)/90;
     sticks.push(new Stick(box.x+15,box.y,Math.PI/2,
                           box.vx+dvx,box.vy+dvy,
                           30,omega,box.color));
     dvx = (Math.random()-1.0)/11;
     dvy = (Math.random()-1.0)/11;
     omega = (Math.random()-1.0)/90;
     sticks.push(new Stick(box.x-15,box.y,Math.PI/2,
                           box.vx+dvx,box.vy+dvy,
                           30,omega,box.color));
    }
   }
...

My next step is to modify the click handler so that it calls the box exploding code for the smaller boxes, as well as the large ones:

...
   clicker = function(event){
...
    for(i=0;i<boxes.length;i++){
     box = boxes[i];
     if(Math.abs(x-box.x)<box.size/2 && 
        Math.abs(y-box.y)<box.size/2){
      explodeBox(i);
     }
    }
...
As well as the drawing function, so it actually draws the sticks:
...
   draw = function(){...
...
    for(i=0;i<sticks.length;i++){
     var stick = sticks[i];
     var x1 = stick.x + (stick.length/2)*Math.cos(stick.theta);
     var y1 = stick.y + (stick.length/2)*Math.sin(stick.theta);
     var x2 = stick.x - (stick.length/2)*Math.cos(stick.theta);
     var y2 = stick.y - (stick.length/2)*Math.sin(stick.theta);
     stickPhysics(stick,i);
     newContext.lineWidth = 3;
     
     newContext.beginPath();
     newContext.moveTo(x1,y1);
     newContext.lineTo(x2,y2);
     newContext.strokeStyle = stick.color;
     newContext.stroke();
    }
...
A keen eye will spot in there a call to the function stickPhysics, so I should probably make that function so I don't run into errors.
...
   stickPhysics = function(stick,n){
    var newTime = new Date().getTime();
    var dt = newTime - time;
    var newx = stick.x + dt*stick.vx;
    if(newx > 320){
     stick.vx = -Math.abs(stick.vx);
     newx = stick.x + dt*stick.vx;
    }
    if(newx < 0){
     stick.vx = Math.abs(stick.vx);
     newx = stick.x + dt*stick.vx;
    }
    stick.x = newx;
    stick.theta = stick.theta+dt*stick.omega;
    if(stick.theta > 2*Math.PI){
     stick.theta = stick.theta - 2*Math.PI;
    }
    if(stick.theta < 0){
     stick.theta = stick.theta + 2*Math.PI;
    }
    stick.vy = stick.vy + dt*0.0001;
    var newy = stick.y + dt*stick.vy;
    stick.y = newy;
   }
...

The result of all this is below Canvas not supported in your browser.
Next time, I work to make this more into a game and less of a toy.

Tuesday, February 23, 2010

A bit of motion

A canvas element with a single immobile square on it is boring. There might be an argument made for the exciting demonstration of power and such, but that argument is best left to wiser people than I. Instead, I want to have squares that move!

Moving squares means squares that keep track of their location, and maybe even speed. Since I also want to have squares of different sizes and colors, without much else different about the squares, it would also make sense to keep track of how big they are. So, I want to create an array to keep track of all of the boxes and a constructor function to create them. In addition, I'm going to want a global variable that keeps track of time, to make the physics and such work correctly.

...
   var boxes = new Array();
   var time = 0;
   
   Box = function(x,y,vx,vy,size,color){
    this.x     = x;  // x position
    this.y     = y;  // y position
    this.vx    = vx; // x velocity
    this.vy    = vy; // y velocity
    this.size  = size;
    this.color = color;
   }
...
These boxes should move at their given velocities and bounce off the edges, so I'll need a function that works out where a given box should be:
...
   boxPhysics = function(box){
    dt = (new Date().getTime())-time; // Time since last frame
    newx = box.x+dt*box.vx;
    if(newx > 320){
     box.vx = -Math.abs(box.vx);
     newx = box.x+dt*box.vx;
    }
    if(newx < 0){
     box.vx = Math.abs(box.vx);
     newx = box.x+dt*box.vx;
    }
    var newy = box.y + dt*box.vy;
    if(newy > 480){
     box.vy = -Math.abs(box.vy);
     newy = box.y + dt*box.vy;
    }
    if(newy < 0){
     box.vy = Math.abs(box.vy);
     newy = box.y + dt*box.vy;
    }
    box.x = newx;
    box.y = newy;
   }
...
This function will keep the boxes bouncing as though there is a peg sticking out the center that runs into the sides of the canvas. I did this on purpose. If you would rather have the boxes bounce whenever an edge of the box makes contact with the frame of the canvas, modify the if statements to check for contact with a bounding box that is smaller by half the box's size. So, for the x-position, the two if statements would look like this:
...
if(newx > 320-box.size/2){...}
if(newx < 0+box.size/2){...}
...

Now that I have a way to create and re-locate the boxes, I need a way to draw them. Before, I only had to draw a box once, since the image displayed by the canvas never changed. Now, I am looking to make an animation, so I need a function I can call repeatedly, every time I want to update the frame.

...
   draw = function(){
    newContext.fillStyle='white';
    newContext.fillRect(0,0,320,480); // Clear the canvas
    for(i=0;i<boxes.length;i++){
     box = boxes[i];
     boxPhysics(box);                 // Move the box, as needed
     newContext.fillStyle=box.color;
     newContext.fillRect(box.x-box.size/2,box.y-box.size/2,
                                          box.size,box.size);
    }
    time = new Date().getTime(); // Update the global time
   }
...

Now that I have a way to store boxes, a way to create boxes, and even a way to draw boxes, it would be nice to have some way for the user to specify where these boxes should go. Specifically, I want to let the user (myself) click anywhere within the canvas to create a box. It helps to make two functions for this:

...
   makeBox = function(x,y){  // Makes box with random color + velocity
    var clr = "rgba(";
    for (i = 0; i < 3; i++) { //Loop to specify the color
      var v = Math.floor(Math.random()*256); // 0-255;
      clr += v + ",";
    }
    clr += "0.7)";
    var vx = (Math.random()-1.0)/6;
    var vy = (Math.random()-1.0)/6;
    boxes.push(new Box(x, y,vx,vy,90,clr))
   }

   clicker = function(event){ // Function to respond to mouse clicks
    var x = 0;
    var y = 0;
    if(event){
     x = event.pageX - newCanvas.offsetLeft;
     y = event.pageY - newCanvas.offsetTop;
    }
    makeBox(x,y);
   }
...
In order to make the clicker function respond to mouse clicks I still need to modify the original use of the canvas tag. I might as well also change the size of the canvas to the size of an iPhone's screen:
...
<canvas id='newCanvas' width='320' height='480'
style="border: 1px dashed; width:320px;height:480px" 
onmousedown="clicker(event);">
...
And finally, I need to modify the initialization function to set up the starting time right, and then start a timer that will repeatedly call the draw function:
...
init = function(){ // This function will start things
    time = new Date().getTime();
    setInterval("draw();",20);
   }
...

And so, the result of all that 'hard' work is below. Click inside the canvas to make joyful, bouncing squares appear. Canvas not supported in your browser.

Next time, I make the boxes explode!

Monday, February 22, 2010

First steps

I suspect a proper first step for a proper software project would involve a good deal of research and thinking. A good design might be involved, with clearly outlined goals and approaches. The libraries and technologies used in the project would probably be well-understood and well-defined. There might even be some fancy figures.

Fortunately for me, I did not aspire to the high standards of "proper software project." Instead, I did what any ADD-afflicted seven year old would do. Threw together scraps of code out of functions and elements as I learned about them.

Nonetheless, it was very helpful to start with a reference or two. This was the primary reference for me. Specifically, the part related to the <canvas> element. In addition, I looked closely at several of the examples on this page, and would frequently end up on the w3 schools' javascript pages through google searches for how to achieve this or that effect with javascript.

With a few tabs and a text editor open, I went at it, and it didn't take me too long to get to my first, super-exciting, <canvas> element with something drawn in it:

<html> <body> <!-- First, create the canvas element. It seem necessary to set the width and the height attributes, or else the canvas itself is distorted by the style attribute. --> <canvas id='newCanvas' width='100' height='100' style="border: 1px dashed; width:100px;height:100px" > Canvas not supported in your browser. <!--The stuff inside the canvas tag will be the output if the canvas tag is not  supported by the web browser --> </canvas> <script> // Do some scripting! This will have in it all the          // logic I come up with, as well as the drawing calls    // I start by declaring two global variables. One is a     // reference to the canvas. The other is the drawing context    // of that canvas.    var newCanvas = document.getElementById("newCanvas");    var newContext = newCanvas.getContext('2d');        initA = function(){ // This function will get everything      // In this case, the only thing I do is set the fill color     // running of the drawing context to yellow, and ask the      // context to fill in a rectangle starting at position 5,5      // and 70 pixels to a side.     newContext.fillStyle='yellow';     newContext.fillRect(5,5,70,70);    }    initA(); // Launch the function that actually draws in the     // canvas
</script> </body> </html>

The result is below:
Canvas not supported in your browser.

Obviously, this is a very hello-world example of canvas' power, but even so, it took me a good hour to get this far the first time around. It is a godsend that there is absolutely no waiting for anything to compile the code, or else I probably wouldn't have even made it this far.

For next time, I think I'll try and write up my struggles with mouse events and a bit about bouncing boxes.

Friday, February 12, 2010

Box killer

At some point in the last month or so I became rather interested in the capabilities of HTML5 and the &lang canvas &rang tag. This was in part because I'd heard a good deal of talk of HTML5 being a flash killer. While I don't really have anything against flash as a concept, I was very interested in having at my disposal the capabilities of flash without the hassle of actually working with flash.

Because I'm rather cheap about computer-related hobbies, I have been trying hard for a few years now to create web games without putting any money into it. This meant fiddling with mxmlc and later haxe. Although both were nice enough, I never had the patience or focus to get anywhere with either. Part of the problem is that the four to forty seconds it takes either to compile even the simplest flash file are easily taken up by becoming distracted with very random things on the internet. The other part, a need for an actual web server, set up either on my desktop or elsewhere, to serve up the flash content.

Both problems are conveniently absent from working with &lang canvas &rang and javascript. The speed with which I can check the effect my edits have a great focusing effect, and it doesn't seem at all a waste to reload a web page to check out two lines worth of edited code.

The result of this newfound focus is below, in the dash-lined box. It took around two weeks, with no previous knowledge of javascript or the HTML5 standard to get to that point, and in order to spend less time on my next effort, I want to document carefully the steps (and missteps) that went into making this simple game work.

Your browser does not support the canvas tag. Sorry.