There's one critical element missing from our game. Right now, once the game starts, it keeps going until the player exits the program. We need a win condition, and to indicate when that win condition has been reached.
First let's create two separate components - one that holds information about the victory, and one that counts down to when the game should return to the title screen.
```ts
import { Component } from "encompass-ecs";
export class WinDisplayComponent extends Component {
public player_index: number;
}
```
```ts
import { Component } from "encompass-ecs";
export class FinishGameTimerComponent extends Component {
public time_remaining: number;
}
```
Now we'll create an engine that checks the game score and emits a message if one player has reached that score.
```ts
import { Emits, Engine } from "encompass-ecs";
import { GoalOneComponent } from "game/components/goal_one";
import { GoalTwoComponent } from "game/components/goal_two";
import { ScoreComponent } from "game/components/score";
import { WinDisplayComponent } from "game/components/win_display";
import { WinMessage } from "game/messages/win";
@Emits(WinMessage)
export class CheckScoreEngine extends Engine {
private winning_score: number;
public initialize(winning_score: number) {
this.winning_score = winning_score;
}
public update() {
if (this.read_component(WinDisplayComponent)) { return; }
Let's also make it so the ball stops spawning if the game is over. In our BallSpawnTimerEngine component loop:
```ts
...
if (this.read_component(WinDisplayComponent)) {
this.get_entity(component.entity_id)!.destroy();
continue;
}
...
```
Finally, we're going to need some logic to take us back to the title screen. We _could_ just pass the Game state to a FinishGameEngine... but then we would have a circular dependency. This is a prime candidate for an Interface.
Let's create a new folder, **game/interfaces** and a new file, **game/interfaces/finishable.ts**:
if (finish_game_timer_component.time_remaining <= 0) {
this.game_state.finished = true;
}
}
}
}
```
This is pretty straightforward. Once the timer expires we change the game state to let the rest of the program know the state is finished. Now we can use this in our main loop. In **main.ts**:
```ts
love.update = (dt) => {
if (current_state === title) {
if (love.keyboard.isDown("space")) {
current_state = game;
}
} else if (current_state === game) {
if (game.finished) {
game = new Game();
game.load();
current_state = title;
}
}
current_state.update(dt);
};
```
Now when the game is finished, it creates a new Game and switches the current state back to the title menu.
Don't forget to add our new Engines to the WorldBuilder.