Prefer composition when behaviors vary independently.
An entity identifies a thing in the world. Components hold focused data or behavior: position, health, input, sprite, or collider. Composition lets one object be assembled from the capabilities it needs rather than forced into a deep inheritance tree.
class Player {
Position position;
Health health;
InputController input;
void update(double delta) {
position.move(input.direction(), delta);
}
}
State machines make rules visible. A character might transition from GROUNDED to JUMPING only when jump input is pressed and grounded is true.
Exercises
List components for a collectible coin, enemy, and player.
Draw transitions for idle, walking, jumping, and falling.
Identify one behavior that should not be hidden inside rendering code.
Self-check
What is composition?
Why use explicit states?
What belongs in a position component?
Self-Check Quiz
1. Which design combines focused capabilities to build an object?
AnswerComposition combines components such as position, health, input, and rendering.
2. Can a player be both grounded and jumping in a simple state model?
AnswerNot if the states are mutually exclusive; the transition rules must define which state owns the condition.
Homework
Design an entity-component table for a small platform game.
Specify five legal state transitions for the player.
Implement one component with a class invariant.
Sample answerA player may have position, velocity, collider, input, health, and sprite components. A jump transition requires grounded state and jump input; update then changes vertical velocity and state to jumping. Rendering reads state but does not decide physics.