Now that we have a board to receive items, we will create the game items' factory. The factory is a design pattern that allows us to create an object without exposing the creation logic to the caller. This factory can be seen as a helper class that will handle all the dirty tasks required when you want to create a new game item from JavaScript. Do you remember GameEntity.qml? It is the parent component of Apple.qml, Snake.qml, and Wall.qml. The factory will be able to create a specific entity for a given a type and coordinates. We will use the property type to identify an entity kind. Here is the factory pattern schema used in our snake game:
We can now create the factory.js file, which begins like this:
var SNAKE_TYPE = 1; var WALL_TYPE = 2; var APPLE_TYPE = 3; var snakeComponent = Qt.createComponent("SnakePart.qml"); ...