From 76df4eb85cadf9cf548b4aa1cc95970e1d53f48d Mon Sep 17 00:00:00 2001 From: piernov Date: Sun, 1 May 2016 14:52:43 +0200 Subject: Implement loading saved games on server --- craftmine.php | 2 ++ inc/Item.inc | 4 ++++ inc/messages.inc | 1 + inc/savegame.inc | 30 ++++++++++++++++++++++++++++++ 4 files changed, 37 insertions(+) diff --git a/craftmine.php b/craftmine.php index ac187cc..28bb49d 100644 --- a/craftmine.php +++ b/craftmine.php @@ -49,6 +49,8 @@ switch($op) { case "buyItem": buyItem(); break; case "saveGame": saveGame(); break; case "downSave": downSave(); break; + case "listSaves": listSaves(); break; + case "loadSave": loadSave(); break; default: reportBadRequest(); } diff --git a/inc/Item.inc b/inc/Item.inc index bef6d00..8e90998 100644 --- a/inc/Item.inc +++ b/inc/Item.inc @@ -20,6 +20,10 @@ class Item { $item->addChild("icon", $this->icon); $item->addChild("desc", $this->desc); } + + public static function fromXML($xml) { + return new static((string)$xml->name, +(string)$xml->cost /* convert to number */, (string)$xml->icon, (string)$xml->desc); + } } ?> diff --git a/inc/messages.inc b/inc/messages.inc index 9f3a09d..955c0a0 100644 --- a/inc/messages.inc +++ b/inc/messages.inc @@ -9,6 +9,7 @@ $messages = array( "gamesave_ok" => "Game saved.", "gamesave_error" => "An error occured when trying to save the game.", + "gamesave_not_found" => "Couldn't find the specified save file.", ); function sendMessage($type, $msg) { diff --git a/inc/savegame.inc b/inc/savegame.inc index f3b6da6..4646601 100644 --- a/inc/savegame.inc +++ b/inc/savegame.inc @@ -41,4 +41,34 @@ function downSave() { echo $save->asXML(); } +function listSaves() { + chdir(SAVEDIR); // Go to SAVEDIR folder, avoiding leading folder name in file list + echo json_encode(glob("*.save.xml")); +} + +function parseSave($xml, &$table) { // Passing $table by reference + foreach($xml as $k => $v) { + if($v->count() == 0) { // No child, treat as string + $v = (string)$v; + if(is_numeric($v)) $v = +$v; // If it is in fact a number, treat it that way using PHP unary '+' coercion + $table[$k] = $v; + } elseif($k == "inventory") { // Special case for inventory: objects need to be created + foreach($v as $item) Inventory::addItem(Item::fromXML($item)); + } else { // If nested array + $table[$k] = array(); + parseXML($v, $table[$k]); + } // Other types unsupported (unused) + } +} + +function loadSave() { + if(empty($_POST["filename"])) return; + $xml = simplexml_load_file(SAVEDIR . "/" . $_POST["filename"]); + if(empty($xml)) { + sendError("gamesave_not_found"); + return; + } + $_SESSION = array(); // drop current game + parseSave($xml, $_SESSION); +} ?> -- cgit v1.2.3-54-g00ecf