Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.