(http://eloquentjavascript.net/07_elife.html)Impostazione di una griglia. Eloquente js capitolo 7
Im avendo difficoltà a capire quali sono i metodi di griglia abbiamo aggiunto .get e .SET anche do.Firstly, lascia andare attraverso un caso di esempio. var grid = new Grid(5,5)
; ora lo spazio è un array di elementi 25
. E naturalmente width
e height
are
5.
Ora la domanda è qual è il metodo per "fare".
Ora abbiamo detto console.log(grid.get(new Vector(1, 1)));.
Così x
diventa 1
, y
diventa 1
nel nuovo oggetto che abbiamo creato. Ovviamente abbiamo bisogno di fare grid.get quindi restituiamo this.space[1+ 1 * 5]
il sesto posto nello spazio array che è lungo 25
elementi. Quindi perché questa stampa è indefinita? È perché non c'è nulla nell'array spaziale?
TLDR
Come le .get
e .set
prototipi lavoro qui (cosa fanno)? Inoltre, perché impostiamo return this.space[vector.x + this.width*vector.y];
, c'è qualche significato numerico a vector.x+this.width*vector.y
?
function Vector(x,y){
this.x = x;
this.y = y;
}
Vector.prototype.plus = function(other){
return new Vector(this.x + other.x, this.y + other.y);
}
var grid = ["top left", "top middle", "top right",
"bottom left", "bottom middle", "bottom right"];
function Grid (width,height){
this.space = new Array(width * height);
this.width = width;
this.height = height;
}
Grid.prototype.isInside = function(vector){
return vector.x >=0 && vector.x<this.width && vector.y>=0 && vector.y<this.height;
}
Grid.prototype.get = function(vector){
return this.space[vector.x + this.width*vector.y];
// 5 + 5 * 1;
}
Grid.prototype.set = function(vector,value){
this.space[vector.x + this.width *vector.y] = value;
}
var grid = new Grid(5, 5);
console.log(grid.get(new Vector(1, 1)));
// → undefined
grid.set(new Vector(1, 1), "X");
console.log(grid.get(new Vector(1, 1)));
// → X
Hmm ... Penso di aver capito ma potrei aver bisogno di pensarci più –
Quindi cosa rappresenta in realtà vector.x + this.width * vector.y? È quello dove metteremo qualcosa? –
Aggiungerò presto qualche altro dettaglio su come funziona l'intera cosa vettoriale ... –