i make game in canvas with ts.
need help with architecture
it is a board game. i have Board class in which board is stored as property field[] as array 36. field is 6x6
so in this array i store class Tile - it is cell in game.
in Tile i have property Hex - it is hexagon drawing
so in Board update(delta) i call foreach tile do tile.draw() and in tile i have draw(delta) in which i need to draw hexagon in hex.
but how to flow x,y coordinates of canvas? how to transfer them in Hex class? or maybe there's some other way, cause Hex should not know about anything. and now only how to draw hexagon of some size. how to do it properly?
Assistant
User
ah, okay, so it is pretty fine to send coordinates to draw method, not in constructors
Assistant
To create a clean architecture for your board game, particularly when dealing with a grid of tiles and their drawing capabilities, there's a balance that needs to be struck between encapsulation and the need for interaction. Below are some suggestions on how to approach this challenge to keep your architecture clean and maintainable.
Architecture Suggestions
Separation of Concerns:
Keep your Tile class focused on its responsibility: managing its own state, and its specific representation (via the Hex class).
The Board class is responsible for the overall arrangement, updating, and drawing of all tiles as a whole.
Coordinate Transformation:
Instead of having each Tile know about global coordinates or the canvas, the Board can take responsibility for that. This separates the concerns and maintains the principle that Tile does not need to be aware of the canvas.
You can use a method on the Tile class to receive local coordinates relative to its position on the board, which you can compute in the Board class.
Implementation Overview
Here's a possible implementation scenario:
typescript
// Hex class to draw a hexagon
class Hex {
size: number; // Size of the hexagon
constructor(size: number) {
this.size = size;
}
draw(ctx: CanvasRenderingContext2D, x: number, y: number) {
const { size } = this;
ctx.beginPath();
for (let i = 0; i < 6; i++) {
ctx.lineTo(
x + size * Math.cos((Math.PI / 3) * i),
y + size * Math.sin((Math.PI / 3) * i)
);
}
ctx.closePath();
ctx.fill();
}
}
// Tile class with its own hexagon drawing logic
class Tile {
hex: Hex;
constructor(size: number) {
this.hex = new Hex(size);
}
draw(ctx: CanvasRenderingContext2D, x: number, y: number) {
this.hex.draw(ctx, x, y);
}
}
// Board class managing tiles
class Board {
fields: Tile[];
tileSize: number;
constructor(tileSize: number) {
this.fields = Array.from({ length: 36 }, (_, index) => new Tile(tileSize));
this.tileSize = tileSize;
}
update(delta: number) {
// Update logic for game mechanics
}
draw(ctx: CanvasRenderingContext2D) {
const hexWidth = Math.sqrt(3) * this.tileSize; // Calculate width based on hexagon properties
const hexHeight = this.tileSize * 1.5;
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 6; j++) {
const x = (i * hexWidth) + (j % 2) * (hexWidth / 2); // Adjust vertical
const y = j * (hexHeight * 0.75); // Adjust for row staggering
this.fields[i * 6 + j].draw(ctx, x, y);
}
}
}
}
Explanation:
Hex Class:
Handles drawing a hexagon given its size and the position to draw at.
Tile Class:
Contains a Hex instance. The draw() method receives the ctx (canvas context) and x, y coordinates to draw the hexagon relative to its position on the board.
Board Class:
Manages the collection of Tile instances. The draw() method calculates the correct positions for each tile based on hexagonal tiling rules and passes these coordinates to each tile's draw() method.
Benefits:
This setup keeps the responsibilities clearly separated.
It allows the Tile class to remain agnostic of where and how the hexagons are drawn.
The Board class can easily manage tile layout and coordinate transformations.
With this architecture, you can also easily extend or modify the drawing logic without major changes to the core structure of the game. For example, if you want to change how tiles are rendered or add more complex interactions, you can do so within the respective classes without impacting others.
Yes, it is perfectly fine and often a good practice to pass coordinates to the draw method rather than during construction of the object. This approach enhances flexibility and clean separation of responsibilities. Here are a few reasons why this design choice is beneficial:
Reasons to Pass Coordinates to draw() Method
Separation of Concerns:
The Tile class is responsible for its own drawing logic, while the Board class is responsible for calculating the position of each tile based on its layout. By keeping these responsibilities separate, you make your code cleaner and easier to maintain.
Dynamic Positioning:
If your game needs to change the layout of tiles dynamically (e.g., for zooming in/out, panning, or different game modes), you can simply adjust the coordinates sent to the draw() method without needing to reconstruct the tiles or change their properties.
Encapsulation:
The Hex class doesn’t need to know how to calculate the position based on a grid. It just focuses on drawing a hexagon. This adheres to the principle of encapsulation, where each class has a single responsibility.
Reduced Complexity:
If you were to pass x and y coordinates to the constructor, you’d need to create a new instance of Tile every time you want to render it in a different position. This can lead to unnecessary object creation and increased memory usage. By only passing coordinates during the draw call, you can reuse the same instance of Tile, improving performance.
Example of Usage:
Here's a simple way to illustrate:
typescript
// Usage in the drawing loop
const canvas = document.getElementById('myCanvas') as HTMLCanvasElement;
const ctx = canvas.getContext('2d');
const board = new Board(30); // Assume each tile's hexagon size is 30
function gameLoop(delta: number) {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
board.update(delta); // Update game logic
board.draw(ctx); // Draw the board with all tiles
requestAnimationFrame(gameLoop);
}
// Start the game loop
requestAnimationFrame(gameLoop);
In this example, the Board class handles the entire drawing operation by calling each Tile's draw() method with the appropriate coordinates based on the board's layout. Each Tile doesn’t need to worry about its placement—only how it should visually represent itself.
Conclusion
Passing coordinates to the draw method is a flexible and efficient approach that respects the principles of object-oriented design. It keeps your code clean, maintainable, and allows for a dynamic game environment where the layout can change without requiring significant restructuring of your objects.