Remember that Grid game back in tutorial 025? In this tutorial, I convert it to a Command Line Interface game instead of a web server game with a session. This tutorial has 3 parts and goes over the application of the past things I have gone over.
Saving a game through serialization Part 2
Saving a game through serialization Part 3
Here are the sources used in this tutorial:
tacos.txt
a:2:{s:1:"x";i:0;s:1:"y";i:7;}
tut031.php
<?php //PHP Tut 031 A game that saves through serialization //get info from user in CLI http://www.php.net/manual/en/features.commandline.php error_reporting(E_ERROR); $grid = array(); $width = 20; $height = 10; function grid() { global $grid, $height, $width; $grid = array(); for ($x = 0; $x < $width; $x++) { for ($y = 0; $y < $height; $y++) { $grid[$x][] = "_"; } } } grid(); if (!isset($player['x'])) { $player['x'] = (int)($width / 2); } if (!isset($player['y'])) { $player['y'] = (int)($height / 2); } //Determine new location based on relative location and given direction function getdirection($getNew = 0) { global $direction, $status; if ($getNew) { $line = trim(fgets(STDIN)); if (strlen($line) > 0) { $direction = strtolower(substr($line, 0, 1)); } else { return - 1; } if ($direction == "e") { $status = -1; } if ($direction == "s") { savegame(); } if ($direction == "a") { loadgame(); } } return $direction; } function savegame(){ global $player; echo "\n what file name would you like to save under?\n"; $line = trim(fgets(STDIN)); file_put_contents($line, serialize($player)); } function loadgame(){ global $player; echo "\n what file name would you like to load?\n"; $line = trim(fgets(STDIN)); $player = unserialize(file_get_contents($line)); } $status = 0; while ($status != -1) { if ($status >= 1) { for($t = 0; $t < 9; $t++){ echo "\n"; } echo "Hello, you can say l for left, r for right, u up, and d for down.\nIf you want to exit, say e.\nAlso, if you want to save say s, and for load, use a."; if (getdirection(1) != -1) { grid(); //they gave us a direction so now we will process it. if (getdirection() == "l" && $player['x'] > 0) { $player['x'] -= 1; } if (getdirection() == "r" && $player['x'] < $width - 1) { $player['x'] += 1; } if (getdirection() == "d" && $player['y'] < $height - 1) { $player['y'] += 1; } if (getdirection() == "u" && $player['y'] > 0) { $player['y'] -= 1; } //the opposite $error = "you bonked your head, therefore you are dead.(not really.)"; if (getdirection() == "l" && $player['x'] <= 0) { echo $error; } if (getdirection() == "r" && $player['x'] >= $width - 1) { echo $error; } if (getdirection() == "d" && $player['y'] >= $height - 1) { echo $error; } if (getdirection() == "u" && $player['y'] <= 0) { echo $error; } } } echo "\n"; echo "\n"; echo "\n"; echo "\n"; $grid[$player['x']][$player['y']] = "X"; for ($y = 0; $y < $height; $y++) { for ($x = 0; $x < $width; $x++) { echo $grid[$x][$y]; } echo "\n"; } if ($status == 0) { $status = 1; } } ?>