blob: 73d82c84ce11dbb67b24982b83bd01041a9c67ab (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
<?php
/**
* Represent the player's Inventory.
* Implemented as a singleton in the session.
*
* @package inc\Inventory.inc
* @author Alexandre Renoux
* @author Pierre-Emmanuel Novac
*/
class Inventory {
/**
* Arrays of array with Item and Item's count
*/
public $items = array();
/**
* Checks if the Inventory was already created in the session
*
* @return boolean true if Inventory was already created, false otherwise
*/
public static function created() {
return !empty($_SESSION["inventory"]);
}
/**
* Returns the Inventory's content from the session.
*
* @return array array of Items and number
*/
public static function sendContent() {
return self::get()->items;
}
/**
* Returns the Inventory from the session.
* Implements the singleton pattern.
*
* @return Inventory the Inventory object
*/
public static function get() {
if(!self::created()) {
$_SESSION["inventory"] = new Inventory();
}
return $_SESSION["inventory"];
}
/**
* Adds an Item object to the Inventory, incrementing the Item's count if it was already present.
*
* @param Item $item Item to add to the Inventory
* @return array Item and Item's count
*/
private function _addItem($item) {
foreach($this->items as $k => $object){
if($object[0] == $item){
$this->items[$k][1]++;
return $this->items[$k];
}
}
$tab = array($item,1);
$this->items[] = $tab;
return $tab;
}
/**
* Adds an Item object to the singleton's Inventory from session.
*
* @param Item $item Item to add to the Inventory
* @return array Item and Item's count
*/
public static function addItem($item) {
$inv = self::get();
$tab = $inv->_addItem($item);
return $tab;
}
private function _removeItem($item) {
foreach($this->items as $k => $object) {
if($object[0] == $item) {
unset($this->items[$k]);
return;
}
}
}
public static function removeItem($item) {
$inv = self::get();
$inv->_removeItem($item);
}
private function _useItem($item) {
foreach($this->items as $k => $object){
if($object[0] == $item) {
$nb = $this->items[$k][1];
if($nb > 0) {
$this->items[$k][0]->consume();
$this->items[$k][1]--;
}
if($nb-1 <= 0) $this->_removeItem($item);
return array($object[0], $nb-1);
}
}
return false;
}
public static function useItem($item) {
$inv = self::get();
$it = $inv->_useItem($item);
return $it;
}
public function addToXML($root) {
foreach($this->items as $item)
$item[0]->addToXML($root, $item[1]);
}
}
?>
|