Simultaneous loops with array exercise javascript

654 views Asked by At

I want to keydown trigger the movement of a block and then with another keydown, add another moving block. And if I keydown again, then another moving block appears. As it is now, the keydown stops the movement of the first block. I would like to have all the blocks moving simultaneously. Here's the code. It's also available on jsfiddle http://jsfiddle.net/7eUEE/

Thank you!

var canvas = document.getElementById("canvas"); 
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
window.addEventListener("keydown", addnew, true);
window.addEventListener("keydown", move, true);
var list = [];
var id = 0;
var color = 'blue';
var x = 0;
var y = 0;

window.onkeydown = function(s){
    s.preventDefault();
    if(!s){
        s = window.event;
    }

    var keycode;
    if(s.which){
        keycode = s.which;
    }else{
        keycode = s.keyCode;
    }

}
function box(id, color, x ,y){
    box.id = id;
    box.color = color;
    box.x = x;
    box.y = y;
}   

function addnew(e){
    e.preventDefault();
    if(!e){
        e = window.event;
    }                   

    //space
    if(e.keyCode == 32){
        list[id] = new box(id, color, x, y);
        id++;
        y = y + 100;
        box.y = y;
        box.color = 'red';
        console.log(box.y);
    }
}

list[0] = box(id, color, x ,y);

function move(e){
    e.preventDefault();
    if(!e){
        e = window.event;
    }                   

    //right
    if(e.keyCode == 39){
        list[id];
        setInterval(loopdraw);
    }
}

var loopdraw = function draw(){
    box.x = box.x + 1;
    console.log(box.x);
    ctx.beginPath();
    ctx.fillStyle = box.color;
    ctx.fillRect(box.x, box.y, 50, 50);
    ctx.closePath();
}
1

There are 1 answers

0
Rudie On BEST ANSWER

Your Box objects don't behave like objects, because you use them in 3 ways:

  • class: list[id] = new box(id, color, x, y);
  • function: list[0] = box(id, color, x ,y);
  • object: box.y = y;, box.color = 'red'; etc

The list part is right: keep a collection of (moving) boxes. The loop part isn't, because you don't use the list. You only 'loop' 1 box.

I've updated the fiddle: http://jsfiddle.net/rudiedirkx/7eUEE/1/ and I've renamed the box class to Box, because there might be Box objects named box.

The important parts:

// Create initial box
list[id++] = new Box(id, color, x ,y);

// Create more boxes
list[id++] = new Box(id, 'red', x, y);

// Loop through existing boxes animation
function loopdraw() {
  list.forEach(function(box) {
    // Draw