Pong-4 behaves exactly like Pong-3. The biggest advantage we gain from this update is in the design of our code. Open up Pong-4 to take a look at how we’ve reorganized the code using classes and objects.
TypeScript Modules
It is important to understand that all of the TypeScript we are writing here is client-side. This means that the code is executed within your web browser. This is different than last semester in Web II where we wrote our code server-side which meant that the code was executed within the NodeJS runtime. Despite this, we can still use ES6 modules in our client-side source code using the import and export keywords:
export default class Ball { ... }import Ball from './Ball';Now, we can instantiate an object of type Ball in main.ts!
Important Code
The main takeaway from this update is that we now have abstracted away from main.ts the logic relevant to paddle and ball mechanics. These are now in their own classes, so you’ll see a few new files in the project directory. Ball.ts contains all the logic specific to the ball, while Paddle.ts contains all the logic specific to each paddle.
This not only gives us greater flexibility moving forward, it also makes our main.ts file cleaner and more readable.
🧩 Challenge: Render through class methods
Use each object’s own render method so the ball and both paddles draw themselves. The starter code has already created the objects for you; your job is to call the right public method on each one and pass in the canvas rendering context.
- Installing dependencies
- Starting Vite dev server