Pong-7 introduces a new state, “serve”, to our game.
What is a State Machine?
- Currently in our Pong program we’ve only talked about state a little bit. We have our “start” state, which means the game is ready for us to press “enter” so that the ball will start moving, and our “play” state, which means the game is currently underway.
- A state machine concerns itself with monitoring what is the current state and what transitions take place between possible states, such that each individual state is produced by a specific transition and has its own logic.
- In Pong-7, we allow a player to “serve” the ball by not having to defend during their first turn.
- We transition from the “play” state to the “serve” state by scoring, and from the “serve” state to the “play” state by pressing enter. The game begins in the “start” state, and transitions to the serve state by pressing enter.
Important Code
We can add our new “serve” state by making an additional condition within our update() function.
The state flow should be:
start --Enter--> serve --Enter--> playThe idea is that when a player gets scored on, they should get to serve the ball, so as to not be immediately on defense. We do this by passing the currently serving player to the ball’s reset() method so that it can set the balls new velocity according to who is serving.
We introduce a new state: “victory”, and then we set a maximum score (in our case, 10). Within update(), we modify our code that checks whether a point has been scored as follows:
if (ball.x + ball.width < 0) { servingPlayer = 2; player2Score++;
if (player2Score === VICTORY_SCORE) { winningPlayer = 2; gameState = 'victory'; } else { ball.reset( CANVAS_WIDTH / 2 - 10, CANVAS_HEIGHT / 2 - 10, servingPlayer ); gameState = 'serve'; }} else if (ball.x > CANVAS_WIDTH) { servingPlayer = 1; player1Score++;
if (player1Score === VICTORY_SCORE) { winningPlayer = 1; gameState = 'victory'; } else { ball.reset( CANVAS_WIDTH / 2 - 10, CANVAS_HEIGHT / 2 - 10, servingPlayer ); gameState = 'serve'; }}When a player reaches the maximum score, the game state transitions to “victory” and we produce a victory screen in render():
else if (gameState === 'victory') { context.fillText(`🎉 Player ${winningPlayer} wins! 🎉`, CANVAS_WIDTH / 2, CANVAS_HEIGHT / 4); context.fillText(`Press Enter to restart!`, CANVAS_WIDTH / 2, CANVAS_HEIGHT / 4 + 40);}Finally, we add logic to restart after a victory. When Enter is pressed on the victory screen, the next round should move back to a serve, clear both scores, set the server, and reset the ball.
🧩 Challenge: Add serve/victory transitions
Complete the Enter-key state transitions for start, serve, and victory so the game can begin, serve, and restart.
- Installing dependencies
- Starting Vite dev server