How to make a simple Interactive PHP Console Dice Game

Let's practice some basics together ... like text output, assigning values to variables and executing parts of our code based on conditions.

To not make things overly complicated, we're going to keep this very simple.

  • we expect the player to either input a number between 1-3
  • or the x character to exit the game
  • if the number is guessed correctly the player wins, otherwise the player looses
  • after exiting the game, we display the total wins and losses

The example below shows all the code we need for this. The only new thing's here are the three function's rand(), trim(),fgets(), and this weird uppercase constant STDIN.

Welcome to our little dice game =)
Press [x] to quit the game

<?php
$wins = $losses = 0;

do {
    $dice = rand(1, 3);

    echo "\nEnter a number between 1-3: ";

    $input = trim(fgets(STDIN));

    if ($input == 'x') {
        break;
    } elseif ($input == $dice) {
        $wins++;
        echo "winner!\n";
    } else {
        $losses++;
        echo "looser!\n";
    }
} while ($input != 'x');
?>

You have won <?= $wins ?> times and lost <?= $losses ?> times.
Welcome to our little dice game =)
Press [x] to quit the game

Enter a number between 1-3: