Space shooter strategy is a tiny game designed to demonstrate the strategy pattern.
Move and shoot to prevent the asteroids from destroying your ship. Get upgrades for your ship's gun to help you destroy any asteroids that may hit you.
Table of contents
Let’s begin with a quick definition:
- The strategy pattern defines a set of encapsulated and interchangeable algorithms.
- Each algorithm represents a strategy.
- All strategies can be used and interchanged at runtime by one or more clients.
- To make sure strategies are interchangeable, every one of them will have to implement the same interface.
So, in our example:
- Each gun behavior we defined (simple, double, bubble) is a strategy. So we’ll encapsulate the behavior in a separate class.
- We’ll also have a
GunStrategy
interface that each gun will implement. - Our
Ship
class will define agunStrategy
field where we can set the currently selected strategy.
└───src/
├───game-objects/ Our game objects
│ ├───Asteroid.ts Handles the asteroids' texture and movement
│ ├───Bullet.ts Represents any type of bullet
│ ├───GunUpgrade.ts Represents upgrades for the gun
│ └───ShipCharacter.ts Our main character logic (movement, shooting, etc.)
│
├───gun-strategy/ The strategies algorithms are implemented here
│ ├───BubbleGun.ts Strategy for the bubble gun
│ ├───DoubleGun.ts Strategy for the double gun
│ ├───GunStrategy.ts Strategy interface
│ └───SimpleGun.ts Strategy for the simple gun (the default)
│
├───scenes/ The game's scenes
│ ├───GameOverScene.ts Scene that is displayed when the player gets hit
│ ├───GameScene.ts The game's main logic
│ └───PreloaderScene.ts Loader for the assets
│
└───Main.ts
- Navigate to this project's root folder:
cd strategy-pattern-space-shooter
- Install dependencies: Run the following command:
npm install
- Start the local development server:
npm start
- Go to your browser and navigate to http://localhost:8000.
That's it! You should see the game running in your browser.