vendredi 12 juin 2020

MAP -> Gril

class Gril

Le plan est représenté sous forme de matrice.

Pour représenter un point dans une matrice, on peut soit déclarer un tableau de tableau soit un seul tableau.

Le passage de l'un à l'autre se fait facilement en prenant en compte les dimensions de la matrice.

 M[x][y] == M[x+y*dim].

Remarque : en JS les tableaux Multi-dimensions ne sont pas natifs. Il est doncplus simple d'utilisation la représentation simple dimension.

'use strict';
class Vector {

  constructor (x, y){
    this.x = x;
    this.y = y;
  }
}

class Grid {

  constructor (W, H){
    this.width = W;
    this.height = H;
    this.space = new Array( this.width * this.height);
  }

  get ( vector) {
    return this.space[ vector.x + this.width*vector.y ];
  }

  set ( vector, value){
    this.space[ vector.x + this.width*vector.y ] = value;
  }
}

// test

let G = new Grid (5,5);
G.set( new Vector(2,2),"top");
console.log(G.get( new Vector(2,2)));


version array of array

'use strict';
class Vector {

  constructor (x, y){
    this.x = x;
    this.y = y;
  }

}

class Grid {

  constructor (W, H){
    this.width = W;
    this.height = H;

    this.space = new Array( this.height );
    for (var i=0; i < this.height; i++)
        this.space[i] = new Array(this.width);
  }

  get ( vector) {
    return this.space[vector.x][vector.y];
  }

  set ( vector, value){
    this.space[vector.x][vector.y] = value
  }
}

// test

let G = new Grid (5,5);
G.set( new Vector(2,2),"top");
console.log(G.get( new Vector(2,2)));

mardi 12 avril 2016

Array.from pour initialiser un tableau

Array.from permet d'initialiser un tableau.

 Array.from(new Array(5), (x,i) => i)    [ 0, 1, 2, 3, 4 ]

Voici la nouvelle écriture de la classe Grille.

'use strict';
class Vector {

  constructor (x, y){
    this.x = x;
    this.y = y;
  }
}


class Grid {

  constructor (W, H){
    this.width = W;
    this.height = H;

    this.space = Array.from(new Array(this.height), () => new Array(this.width));

  }

  get ( vector) {
    return this.space[vector.x][vector.y];
  }

  set ( vector, value){
    this.space[vector.x][vector.y] = value;
  }
}

// test

let G = new Grid (5,5);
console.log(G.space.length);
G.set( new Vector(2,2),"genial");
console.log(G.get( new Vector(2,2)));

Class Vector

'use strict';
class Vector {

  constructor (x, y){
    this.x = x;
    this.y = y;
  }

}

La classe Vector permet de mémoriser un état. Cet état représente les coordonnées d'un point dans le plan (x,y).

Le passage de paramètre se trouve simplifié. On passe un vecteur et non les deux coordonnées.