Sunday, September 30, 2012

Remove Falling Letters

‹prev | My Chain | next›

I continue working with my learn-to-type Three.js. So far, I have letters falling. More precisely, I have a letter falling—"f". To start the game just the home keys, "f" and "j" should fall. So I create a nextLetter() function to supply a random next letter:
  function nextLetter() {
    var pool = ['f', 'j'];
    return pool[Math.floor(Math.random() * pool.length)];
To determine whether or not I have hit the right key, I am going to need to know the list of currently falling letters. As of last night, I am not storing the letter—just writing it in a texture for a Three.js sprite. So, instead of maintaining a list of sprites that are falling, I maintain a list of objects that includes the letter and the sprite:
  function addLetter() {
    var letter = nextLetter();
    var canvas = document.createElement('canvas');
    canvas.width = canvas.height = 50;
    var context = canvas.getContext('2d');
    context.font = '48px Arial';
    context.fillText(letter, 0, 40);

    var texture = new THREE.Texture(canvas);
    texture.needsUpdate = true;
    var sprite = new THREE.Sprite({
      map: texture,
      useScreenCoordinates: false
    sprite.position.set(0.5* window.innerWidth - Math.random() * window.innerWidth, window.innerHeight/2,0);
      letter: letter,
      sprite: sprite
I still worry that this is too long a function for kids to type and I can see no obvious way to shorten it up. Still, I will leave that problem for another day.

For now, I add a document listener to remove the falling letters:
  document.addEventListener('keypress', function(event) {
    for (var i=0; i<meteors.length; i++) {
      if (String.fromCharCode(event.keyCode) == meteors[i].letter) {
        var rest = meteors.slice(i+1);
        meteors = meteors.slice(0, i).concat(rest); 
I am pretty excited to find a legitimate use of the continue keyword (to break out of the for loop). That aside, the only interesting bit in there is the call to String.fromCharCode to compare the keycode of the keypress event with the falling letters/meteors. And that seems to work fairly well.

While String.fromCharCode is interesting, I am again frustrated in my efforts to make a simple coding example for kids by JavaScript's lack of a remove() method on arrays. Here, I muck with slices and concat to simulate the effect, but I would really prefer to avoid that kind of thing. Next thing I know, I'll be teaching kids on the wonders of fencepost problems.

Thwarted, at least for the time being, in my efforts to come up with a simpler way of doing this, I call it a night here.

Code so far

Day #525

No comments:

Post a Comment