Creating A Game With PHP Part 4: Side Scrolling Shooter

10th March 2021 - 12 minutes read time

As another step up from the game of snake I created in my last post I decided to try my hand at creating a side scrolling shooter. Just like my other posts, this is an ASCII based game played on the command line.

A side scrolling shooter, if you didn't already know, moves a scene from right to left across the screen with enemies moving with the scene towards the player's ship, which is on the left hand side of the scene. The player can fire bullets towards the enemies so remove them from the scene.

In order to create a side scrolling shooter we need to define a few elements.

  • The player's ship.
  • The enemies for the player to avoid.
  • The bullets that the player's ship shoots.

All of these items will be positioned in the scene using x,y coordinates so to simplify things a base class of Entity can be created. This will encapsulate the position of each of the entities in the scene.

  1. class Entity {
  2. public $positionX = 0;
  3. public $positionY = 0;
  4.  
  5. public function __construct($x, $y) {
  6. $this->positionX = $x;
  7. $this->positionY = $y;
  8. }
  9. }

By extending this base Entity class we can create the components needed for the game. The Spaceship needs a couple more properties to allow it to move around the scene and to fire towards the enemies.

  1. class Spaceship extends Entity {
  2. public $movementX = 0;
  3. public $movementY = 0;
  4. public $fire = FALSE;
  5. }
  6.  
  7. class Enemy extends Entity {}
  8.  
  9. class Bullet extends Entity {}

The main game is controlled via a single Scene class. This class stores all of the components needed for the game and allows the game to be controlled by the player. The constructor of the class stores the dimensions of the game scene and then creates the player's ship object. The ship is placed in the middle height of the scene 2 squares from the left hand side.

  1. class Scene {
  2. public $height;
  3. public $width;
  4.  
  5. public $ship;
  6. public $enemies = [];
  7. public $bullets = [];
  8. public $score = 0;
  9.  
  10. public function __construct($width, $height) {
  11. $this->width = $width;
  12. $this->height = $height;
  13. $this->ship = new Spaceship(2, round($this->height / 2));
  14. }
  15. }

In order to move the ship around a moveShip() method is used. This will take the current movement x,y and apply it to the position properties of the ship. Some logic is applied to the movements to prevent the player from going beyond the bounds of the scene and to stop the ship when it reaches the half way point.

  1. public function moveShip() {
  2. $this->ship->positionX += $this->ship->movementX;
  3. $this->ship->positionY += $this->ship->movementY;
  4.  
  5. $this->ship->movementX = 0;
  6. $this->ship->movementY = 0;
  7.  
  8. if ($this->ship->positionX < 0) {
  9. $this->ship->positionX = 0;
  10. }
  11. if ($this->ship->positionX >= $this->height) {
  12. $this->ship->positionX = $this->height - 1;
  13. }
  14. if ($this->ship->positionY < 0) {
  15. $this->ship->positionY = 0;
  16. }
  17. if ($this->ship->positionY > $this->width / 4) {
  18. $this->ship->positionY = $this->width / 4;
  19. }
  20. }

As well as moving the ship we also want the ship to shoot bullets. When the ship is in 'fire' mode a new bullet object is created, using the position that the ship is in as a basis for the position of the bullet. Once a bullet has been fired we turn off the fire state for the ship, which means that we only fire one bullet at a time.

  1. public function shoot() {
  2. if ($this->ship->fire == TRUE) {
  3. $this->bullets[] = new Bullet($this->ship->positionX, $this->ship->positionY + 1);
  4. $this->ship->fire = FALSE;
  5. }
  6. }

With the ship movement and shoot methods in place we need to listen to the player's input and apply those actions to the ship. This uses the same key detection logic that we used in the previous posts, including the buttons to fire bullets and a the Esc button to quit the game.

  1. public function action($stdin) {
  2. // Listen to the button being pressed.
  3. $key = fgets($stdin);
  4. if ($key) {
  5. $key = $this->translateKeypress($key);
  6. switch ($key) {
  7. case "UP":
  8. $this->ship->movementX = -1;
  9. $this->ship->movementY = 0;
  10. break;
  11. case "DOWN":
  12. $this->ship->movementX = 1;
  13. $this->ship->movementY = 0;
  14. break;
  15. case "RIGHT":
  16. $this->ship->movementX = 0;
  17. $this->ship->movementY = 1;
  18. break;
  19. case "LEFT":
  20. $this->ship->movementX = 0;
  21. $this->ship->movementY = -1;
  22. break;
  23. case "ENTER":
  24. case "SPACE":
  25. $this->ship->fire = TRUE;
  26. break;
  27. case "ESC":
  28. die();
  29. }
  30. }
  31. }
  32.  
  33. private function translateKeypress($string) {
  34. switch ($string) {
  35. case "\033[A":
  36. return "UP";
  37. case "\033[B":
  38. return "DOWN";
  39. case "\033[C":
  40. return "RIGHT";
  41. case "\033[D":
  42. return "LEFT";
  43. case "\n":
  44. return "ENTER";
  45. case " ":
  46. return "SPACE";
  47. case "\e":
  48. return "ESC";
  49. }
  50. return $string;
  51. }

Moving the bullets across the scene is quite simple, we just increment the y position of each bullet in the scene. This moves the bullets in a horizontal manner towards the right hand side of the scene.

  1. public function moveBullets() {
  2. foreach ($this->bullets as $bullet) {
  3. $bullet->positionY++;
  4. }
  5. }

We need something for the player to shoot at so let's create a method to spawn enemies. This function will ensure that a minimum of 15 enemies are on the screen at any one time. We call this method every time we move the scene so if the player shoots one of the enemies then another will spawn in. The spawning of enemies will be done at a random position outside of the right hand side of game 'screen' so that they are decently placed before they are moved into the scene.

  1. public function spawnEnemies() {
  2. if (count($this->enemies) < 15) {
  3. $y = rand($this->width, $this->width * 2);
  4. $x = rand(0, $this->height - 1);
  5. $this->enemies[] = new Enemy($x, $y);
  6. }
  7. }

Moving the enemies in the scene is slightly move involved as we also need to detect if the enemy needs to be removed. If and enemy has gone beyond the left hand side of the scene then it can be removed from the scene without incident. If the enemy is in the same spot as a bullet then both are removed and the player receives a +1 to their score. This just takes a little bit of position matching to ensure that the enemies are in the right place before removing them.

  1. public function moveEnemies() {
  2. foreach ($this->enemies as $enemyId => $enemy) {
  3. $enemy->positionY--;
  4. if ($enemy->positionY == 0) {
  5. // Remove the enemy if it goes beyond the left hand side of the scene.
  6. unset($this->enemies[$enemyId]);
  7. continue;
  8. }
  9. foreach ($this->bullets as $bulletId => $bullet) {
  10. if ($bullet->positionX == $enemy->positionX && ($bullet->positionY == $enemy->positionY || $bullet->positionY == $enemy->positionY - 1)) {
  11. unset($this->enemies[$enemyId]);
  12. unset($this->bullets[$bulletId]);
  13. $this->score++;
  14. }
  15. }
  16. }
  17. }

The final step here is to add a 'game over' scenario. This happens if an enemy reaches the same x,y position of the player's ship. We just kill the entire program here and print the game over message to the output.

  1. public function gameOver() {
  2. foreach ($this->enemies as $enemy) {
  3. if ($this->ship->positionX == $enemy->positionX && $this->ship->positionY == $enemy->positionY) {
  4. die('dead :(');
  5. }
  6. }
  7. }

With all of those elements in place the game scene can now be rendered. This rendering method loops through the height and width of the scene and prints out each of the elements within the scene. I've treated each x,y coordinate here as a cell in a grid to make things easier to understand. The ship is represented as a greater than symbol, the enemies by the letter x and the bullets as a dash. Everything else on the scene is blank.

  1. public function renderGame() {
  2. $output = '';
  3.  
  4. for ($i = 0; $i < $this->height; $i++) {
  5. for ($j = 0; $j < $this->width; $j++) {
  6. if ($this->ship->positionX == $i && $this->ship->positionY == $j) {
  7. $cell = '>';
  8. }
  9. else {
  10. $cell = ' ';
  11. }
  12. foreach ($this->enemies as $enemy) {
  13. if ($enemy->positionX == $i && $enemy->positionY == $j) {
  14. $cell = 'X';
  15. }
  16. }
  17. foreach ($this->bullets as $bullet) {
  18. if ($bullet->positionX == $i && $bullet->positionY == $j) {
  19. $cell = '-';
  20. }
  21. }
  22. $output .= $cell;
  23. }
  24. $output .= PHP_EOL;
  25. }
  26.  
  27. $output .= PHP_EOL;
  28.  
  29. $output .= 'Score:' . $this->score . PHP_EOL;
  30.  
  31. return $output;
  32. }

To run the game we just need to instantiate the Scene object with a given height and width, set up the stream listening system to detect the user's input and then run the game loop. The game loop is an infinite loop that will call the methods I have outlined above over and over again (at least until the game ends). The order of the methods is important here as we need to listen to the user's action before moving and shooting the ship. After this we call the methods to move the bullets and enemies in the scene.

  1. $scene = new Scene(50, 10);
  2.  
  3. system('stty cbreak -echo');
  4. $stdin = fopen('php://stdin', 'r');
  5. stream_set_blocking($stdin, 0);
  6.  
  7. while (1) {
  8. system('clear');
  9. $scene->action($stdin);
  10. $scene->moveShip();
  11. $scene->shoot();
  12. $scene->moveEnemies();
  13. $scene->moveBullets();
  14. echo $scene->renderGame();
  15. $scene->gameOver();
  16. $scene->spawnEnemies();
  17. usleep(100000);
  18. }

Running this code displays the scene with the player's ship in it. After a couple of seconds enemies start to appear and we can shoot at them using the space bar. If a bullet reaches an enemy then the enemy is removed and we get a +1 to the score.

  1. - X X
  2. X
  3. > - X X X
  4. X X
  5.  
  6. X X
  7.  
  8. X
  9. X
  10.  
  11. Score:2

I have also created a gif of the game in action.

via GIPHY

As an addition to this it is also possible to add a call to srand() to set a seed for the random values that the enemies are created with. By adding a seed to the randomness we can set spawning of the enemies to be more predictable every time the game is played. It's not entirely predictable as the player removing enemies from the scene will change how more enemies are spawned in, but the initial condition of the game are always the same. I've written about using random seeds in PHP before if you want to know more. This function just needs to be placed at the start of the script.

srand(1);

There is a lot of code here, but this works really well. In fact, I'm actually surprised how well it works given that it's written in PHP and is running only on the command line. It's no R-Type or Silkworm, but for a simple script I'm very pleased. The scene in the gif above is only 50 wide and 10 high, but I have had it working well with 150 wide and 30 high. It should even be possible to set a level of difficulty by increasing the number of enemies spawned onto the scene at any given moment. I have added the whole side scrolling shooter PHP script to a gist if you want to take a look. Feel free to give it a go and let me know your high scores!

Add new comment

The content of this field is kept private and will not be shown publicly.