3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

第3話 持ち物

3
Last updated at Posted at 2016-02-02

朝、持っていくものは確認するように!

いろんな事件に巻き込まれる太郎と次郎は普段から十分に準備が必要と考えたことをコード化しようとしているところです。

こんな感じはどうだろう...

Item.php
class Item implements JsonSerializable {
    private $properties;
    function __construct($param = []) {
        $this->properties = $param;
    }
    function __set($name, $value) {
        $this->properties[$name] = $value;
    }
    function __get($name) {
        return $this->properties[$name];
    }
        function toArray() {
        return $this->properties;
    }
    function jsonSerialize() {
        return $this->toArray();
    }
}

いろいろな属性を持った持ち物があるので、例えば

yomple.php
$bat = new Item();
$bat->name = '金属バット';
$bat->type = 'Weapon';
$bat->attackPoint = '3d6';

$nabe = new Item();
$nabe->name = 'アルミの鍋';
$nabe->type = 'Helmet';
$nabe->defencePoint = 3;

$coke = new Item();
$coke->name = '黒い炭酸水';
$coke->type = 'Drink';
$coke->recoveryPoint = 7;

みたいな感じで作っておいて、データベースに格納してみる。思いつきで、属性を増やしてみたりしそうだし、この性質上、MySQL的なRDB向きではないと思われる。なのでMongoDB使ってみる(実は初めて使うw)

mongolian_chop.php
$mongo = new MongoClient();
$db = $mongo->test;
$col = $db->item;
$col->insert($bat->toArray());
$col->insert($nabe->toArray());
$col->insert($coke->toArray());

※例外処理とか書いてません(見ればわかる)
ついでに、ちゃんとデータベースに登録できたかを確認してみた。

yondemiru.php
abstract class UsableItem {
    protected $item;
    function __construct($item = null) {
        $this->item = $item;
    }
    function doAction() {
    }
}

class Weapon extends UsableItem {
    function doAction() {
        echo $this->item->name."を振り回して".dice($this->item->attackPoint)."のダメージを与えた<br>";
    }
}

class Helmet extends UsableItem {
    function doAction() {
        echo $this->item->name."を深くかぶり、".$this->item->defencePoint."のダメージを防いだ<br>";
    }
}

class Drink extends UsableItem {
    function doAction() {
        echo $this->item->name."を一気に飲み干して、体力が".$this->item->recoveryPoint."回復した<br>";
    }
}

$cur = $col->find();
foreach ($cur as $item) {
    $tmp = new Item($item);
    $class = $tmp->type;
    $use = new $class($tmp);
    $use->doAction();
}

ちゃんと登録できてた。なんか、こういうのに使えそう。
しかしながら、ぅ~ん...一意キーとかないし、もうちょっと考えたほうがいいw

とりあえず、アイデアをコード化(備忘メモ)したものですw

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?