aboutsummaryrefslogtreecommitdiffstats
path: root/inc
diff options
context:
space:
mode:
authorpiernov <piernov@piernov.org>2016-05-01 14:52:43 +0200
committerpiernov <piernov@piernov.org>2016-05-01 14:52:43 +0200
commit76df4eb85cadf9cf548b4aa1cc95970e1d53f48d (patch)
tree8c4ef775860e6d5349b2a5e56b622c1ab6f9c7be /inc
parentcaf62cfe0e439fc13f7c297954c4aeb21112a2ec (diff)
downloadcandybox-76df4eb85cadf9cf548b4aa1cc95970e1d53f48d.tar.gz
candybox-76df4eb85cadf9cf548b4aa1cc95970e1d53f48d.tar.bz2
candybox-76df4eb85cadf9cf548b4aa1cc95970e1d53f48d.tar.xz
candybox-76df4eb85cadf9cf548b4aa1cc95970e1d53f48d.zip
Implement loading saved games on server
Diffstat (limited to 'inc')
-rw-r--r--inc/Item.inc4
-rw-r--r--inc/messages.inc1
-rw-r--r--inc/savegame.inc30
3 files changed, 35 insertions, 0 deletions
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);
+}
?>