How’d They Do It? PHPSnake: Detecting Keypresses
At a recent conference in Bulgaria, there was a hackathon for which Andrew Carter created a PHP console version of the popular “snake” game.
I thought it was a really interesting concept, and since Andrew has a history of using PHP for weird things, I figured I’d demystify and explain how it was done.
The original repository is here, but we’ll build a version of it from scratch in this series so no need to clone it.
Prerequisites and Rules
As usual, I’ll be using my Homestead Improved box to get up and running instantly. You can use your own environment, just make sure it has a decent version of PHP runnable from the command line.
The snake game we’re replicating has the following features:
- a snake starts as a single on-screen character, and gets longer by one character every time it eats a piece of food.
- food is spawned randomly anywhere on the map.
- in single player mode, the snake is controlled by the arrow keys.
- in two player mode, one snake is controlled with the WSAD keys, while the other is controlled with the arrow keys.
- in single player mode, the walls are obstacles and cause a collision. Running into a wall or into yourself ends the game.
- in multi player mode, only your own snake or the enemy’s snake is an obstacle – the walls wrap around the world. Colliding will reset your snake’s length to 0. The player with the longest snake after 100 seconds have elapsed is the winner.
- it’s CLI, so does not run in the browser – it runs in the terminal window
Note that the game doesn’t work in native Windows – to run it on a Windows platform, use a good VM like Homestead Improved.
To launch a CLI (console) game, we need something similar to an
index.php file in traditional websites – a “front controller” which reads our command line input, parses it, and then launches the required classes, just like in a traditional web app. We’ll call this file
Continue reading %How’d They Do It? PHPSnake: Detecting Keypresses%
LEAVE A REPLY
You must be logged in to post a comment.