Skip to content

Instantly share code, notes, and snippets.

@philipnorton42
Created November 8, 2020 19:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipnorton42/577ae0b17201be7f9052d8d908e49637 to your computer and use it in GitHub Desktop.
Save philipnorton42/577ae0b17201be7f9052d8d908e49637 to your computer and use it in GitHub Desktop.
Creating A Game With PHP Part 1: Detecting Key Input (see https://www.hashbangcode.com/article/creating-game-php-part-1-detecting-key-input)
<?php
function translateKeypress($string) {
switch ($string) {
case "\033[A":
return "UP";
case "\033[B":
return "DOWN";
case "\033[C":
return "RIGHT";
case "\033[D":
return "LEFT";
case "\n":
return "ENTER";
case " ":
return "SPACE";
case "\010":
case "\177":
return "BACKSPACE";
case "\t":
return "TAB";
case "\e":
return "ESC";
}
return $string;
}
$stdin = fopen('php://stdin', 'r');
stream_set_blocking($stdin, 0);
system('stty cbreak -echo');
while (1) {
$line = fgets($stdin);
if ($line) {
echo 'Key pressed: ' . translateKeypress($line) . PHP_EOL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment