<html><form method="POST" action="<?=$SCRIPT_NAME?>"> <!-- it's where it all starts -->
<?
// reading and parsing input: no need to do anything since it's automatically done by PHP
// retrieve state: no need to do anything since it's coming from the client as input
if ($message) { // do you have a state?
process($arg); // if you do, process it
} else { // no state: create a new one
$message = "Welcome."; // initialize it
$acc = 0;
$turn = "user";
?> State has been initialized. <p> <? // notice the specific way of "printing"...
}
?>
<!-- store state: be careful how you print the values; we use expressions. -->
<input type="hidden" name="message" value="<?=$message?>">
<input type="hidden" name="acc" value="<?=$acc?>">
<input type="hidden" name="turn" value="<?=$turn?>">
<?
printState(); // print state so the user can see what's going on...
?>
<!-- prepare for new input -->
<p> Enter number: <input type="text" name="arg">
<p> </form>
<? // notice the specific way of defining functions
function printMessage() { // no param
global $message; // but $message must be declared global to be accessible
?> <?=$message?> <p> <? // printing is also done in its own specific way...
}
function showAccumulator() { // same observations as with printMessage
global $acc;
?> Current accumulator: <?=$acc?> <p> <?
}
function showTurn() { // same as printMessage and showAccumulator
global $turn;
?> The <?=$turn?> moves. <p> <?
}
function printState() {
// global $turn, $message, $acc; // not really needed, you see?...
printMessage();
showAccumulator();
showTurn();
}
function process($arg) {
global $turn, $message, $acc; // as specific as local ($arg) = @_ if you want...
if ($arg >= 1 && $arg <= 10) { // the rest is basically unchanged, as can be noticed
change($arg);
showAccumulator();
showTurn();
if ($acc == 0) { } // game has ended!...
else {
$comp = rand(1, 10);
echo "Computer is adding: " . $comp . "<p>";
change($comp);
}
} else {
?> Sorry, <?=$arg?> not a valid input value. <p> <?
}
}
function change($arg) { // arg is the input, state is this
global $turn, $message, $acc; // again, the only php-specific thing here...
$acc += $arg; // check for legal moves elsewhere (in process, for example)
if ($acc >= 100) {
$message = "The " . $turn . " has won.\nNew game, enter number.";
$acc = 0;
$turn = "user"; // new game
} else {
$message = "Game is in progress...";
if ($turn == "user") { $turn = "computer"; }
else { $turn = "user"; }
}
} // so the transformation is essentially extremely easy (and effective)...