Nie chce zakładać nowego tematu, dlatego zadam pytanie tutaj. Mam kilka obiektów.
-
SnakeGame
-
GameBoard
-
Grid
-
Snake
-
Worm
W obiekcie grid mam metodę draw:
Grid
draw: function(gameboard) {
var cellValue;
for (var x = 0; x < this.cols; x++) {
for (var y = 0; y < this.rows; y++) {
cellValue = this.get(x, y);
if(this.isEmpty(x, y))
gameboard.ctx.fillStyle = "#FFF";
else if (Snake.isPrototypeOf(cellValue))
gameboard.ctx.fillStyle = "#0FF";
else if (Worm.isPrototypeOf(cellValue))
gameboard.ctx.fillStyle = "#F00";
gameboard.ctx.fillRect(x * this.cellWidth, y * this.cellWidth, this.cellWidth, this.cellWidth);
}
}
}
Jak widać potrzbuję tam dostępu do ctx, który moim zdaniem powinien siedzieć w GameBoard.
GameBoard
/**
* Creates a grid filled with EMPTY values
* @param {Object} o options
*/
init: function(o) {
this.grid = Object.create(Grid);
this.grid.create(o.cols, o.rows, o.cellWidth);
this.width = this.grid.width;
this.height = this.grid.height;
this.canvas = document.createElement("canvas");
this.canvas.width = this.width;
this.canvas.height = this.height;
this.ctx = this.canvas.getContext("2d");
document.getElementsByTagName("body")[0].appendChild(this.canvas);
},
fill: function() {
this.grid.draw(this);
}
Funkcja init w głownym obiekcie SnakeGame:
function init() {
gameboard = Object.create(GameBoard);
snake = Object.create(Snake);
worm = Object.create(Worm);
gameboard.init(options.grid);
snake.init(options.snake);
worm.init();
gameboard.grid.set(snake);
gameboard.grid.set(worm);
gameboard.fill();
}
Zastanawiam się czy dobrą praktyką jest przekazanie w ten sposób jak w funkcji fill obiektu GameBoard, żeby mieć dostęp do ctx, czy po prostu przerzucić ten ctx do Grid...
Trochę się zakręciłem i nie wiem jak to rozwiązać z poziomu designu.
TLFC (fucking confused)
W jaki sposób można połączyć ze sobą powyższe obiekty, które wypisałem, żeby to miało ręce i nogi.