Updated themes

Updated buildings
Updated shipyard page (ships & defense)
Added Buildings building queue display & cancel build action.
Added research lab
Added navigation block structure
Removed old code
Updated registration
Added files to .gitignore

Signed-off-by: Gregory PLANCHAT <g.planchat@gmail.com>
This commit is contained in:
Gregory PLANCHAT 2011-09-13 12:54:03 +02:00
commit 8f0f7a4d46
147 changed files with 3488 additions and 2468 deletions

View file

@ -1,16 +1,89 @@
<?php
/**
* This file is part of XNova:Legacies
*
* @license http://www.gnu.org/licenses/gpl-3.0.txt
* @see http://www.xnova-ng.org/
*
* Copyright (c) 2009-Present, XNova Support Team <http://www.xnova-ng.org>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing XNova.
*
*/
/**
* Bootstrap class, used to access main and global functionalities
*
* @package Legacies
* @category core
*/
class Legacies
{
/**
* Static list of application event listeners
*
* @var array
*/
private static $_listeners = array();
/**
* Static list of all locale translators
*
* @var array
*/
private static $_translators = array();
public static $request = null;
public static $response = null;
/**
* HTTP request management object
*
* @var Legacies_Core_Controller_Request_Http
*/
protected static $_request = null;
/**
* HTTP response management object
*
* @var Legacies_Core_Controller_Response
*/
protected static $_response = null;
/**
* The current timestamp
*
* @var int
*/
protected static $_now = null;
/**
* Default locale identifier
*
* @var string
*/
protected static $_defaultLocale = 'fr_FR';
/**
* Registers an event listener to be called later in the application.
*
* @param string $event The event identifier
* @param callback $listener The event callback to be called
*/
public static function registerListener($event, $listener)
{
if (!isset(self::$_listeners[$event])) {
@ -19,11 +92,19 @@ class Legacies
self::$_listeners[$event][] = $listener;
}
/**
* Clear all event listeners
*/
public static function clearAllListeners()
{
self::$_listeners = array();
}
/**
* Clear a specific event's listeners
*
* @param unknown_type $event
*/
public static function clearEventListeners($event)
{
if (isset(self::$_listeners[$event])) {
@ -31,25 +112,44 @@ class Legacies
}
}
/**
* Dispatches an event, calls all callbacks that were previously registered
*
* @param string $event The event identifier
* @param array $params The event params
*/
public static function dispatchEvent($event, $params)
{
$eventObject = new Legacies_Core_Event($params);
if (!isset(self::$_listeners[$event])) {
return;
return $eventObject;
}
$eventObject = new Legacies_Core_Event($params);
foreach (self::$_listeners[$event] as $listener) {
call_user_func($listener, $eventObject);
}
return $eventObject;
}
/**
*
* Enter description here ...
* @param unknown_type $namespace
* @return Legacies_Core_Model_Session
*/
public static function getSession($namespace)
{
return Legacies_Core_Model_Session::factory($namespace);
}
public static function getTranslator($locale = 'fr_FR')
public static function getTranslator($locale = null)
{
if ($locale === null) {
$locale = self::getDefaultLocale();
}
if (!isset($translator[$locale])) {
$path = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'locale';
$translator[$locale] = new Legacies_Core_Model_Translator($path, $locale);
@ -67,12 +167,20 @@ class Legacies
$args = func_get_args();
array_shift($args);
return self::getTranslator(self::getLocale())->translate($message, $args);
return self::getTranslator(self::getDefaultLocale())->translateArgs($message, $args);
}
public static function getLocale()
public static function setDefaultLocale($locale)
{
return 'fr_FR';
$oldLocale = self::$_defaultLocale;
self::$_defaultLocale = $locale;
return $oldLocale;
}
public static function getDefaultLocale()
{
return self::$_defaultLocale;
}
public static function now()
@ -82,4 +190,30 @@ class Legacies
}
return self::$_now;
}
public static function getRequest()
{
if (self::$_request === null) {
self::$_request = new Legacies_Core_Controller_Request_Http();
}
return self::$_request;
}
public static function setRequest($request)
{
self::$_request = $request;
}
public static function getResponse()
{
if (self::$_response === null) {
self::$_response = new Legacies_Core_Controller_Response();
}
return self::$_response;
}
public static function setResponse($response)
{
self::$_response = $response;
}
}

View file

@ -3,4 +3,64 @@
class Legacies_Core_Block_Html_Navigation
extends Legacies_Core_Block_Template
{
public function addLink($name, $label, $title, $uri, Array $params = array(), Array $classes = array(), $template = null)
{
$explodedPath = explode('/', $name);
$baseName = array_pop($explodedPath);
$parent = $this->_getNode($explodedPath);
$child = $this->getLayout()
->createBlock('core/html.navigation.link', $this->getNameInLayout() . '.' . $baseName, array(
'url' => array(
'uri' => $uri,
'params' => $params
),
'label' => $label,
'title' => $title,
'classes' => $classes
));
$parent->setPartial($baseName, $child);
if ($template !== null) {
$child->setTemplate($template);
}
return $this;
}
public function setNodeTitle($path, $title)
{
return $this->getNode($path)->setTitle($title);
}
public function setNodeTemplate($path, $template)
{
return $this->getNode($path)->setTemplate($template);
}
public function getNode($path)
{
return $this->_getNode(explode('/', $path));
}
protected function _getNode($explodedPath)
{
$name = array_shift($explodedPath);
if ($this->hasPartial($name)) {
$child = $this->getPartial($name)->_getNode($explodedPath);
} else {
$child = $this->getLayout()
->createBlock('core/html.navigation.node', $this->getNameInLayout() . '.' . $name);
}
if ($child instanceof Legacies_Core_Block_Html_Navigation_Link) {
throw new RuntimeException('Node is a link. Could not append a child node to a link node.');
}
if (count($explodedPath) == 0) {
return $child;
}
return $child->_getNode($explodedPath);
}
}

View file

@ -0,0 +1,116 @@
<?php
class Legacies_Core_Block_Html_Navigation_Link
extends Legacies_Core_Block_Template
{
protected $_label = '';
protected $_title = '';
protected $_uri = '';
protected $_params = array();
protected $_classes = array('link');
public function getTemplate()
{
if ($this->_template !== null) {
return $this->_template;
}
return 'page/html/navigation/link.phtml';
}
public function setLabel($label)
{
$this->_label = $label;
return $this;
}
public function getLabel()
{
return $this->_label;
}
public function setTitle($title)
{
$this->_title = $title;
return $this;
}
public function getTitle()
{
return $this->_title;
}
public function setUrl($uri, $params = array())
{
$this->_uri = $uri;
$this->_params = $params;
return $this;
}
public function getLinkUrl($moreParams = array())
{
$params = array_merge($this->_params, $moreParams);
return $this->getUrl($this->_uri, $params);
}
public function addClass($class)
{
$this->_classes[] = $class;
return $this;
}
public function clearClasses()
{
$this->_classes = array();
return $this;
}
public function renderClasses($moreClasses)
{
$classes = array_merge($this->_classes, $moreClasses);
return implode(' ', $classes);
}
public function __construct(Array $data = array())
{
if (isset($data['label'])) {
$this->setLabel($data['label']);
unset($data['label']);
}
if (isset($data['title'])) {
$this->setTitle($data['title']);
unset($data['title']);
}
if (isset($data['url'])) {
if (is_array($data['url']) && isset($data['url']['uri'])) {
if (isset($data['url']['params'])) {
$this->setUrl($data['url']['uri'], $data['url']['params']);
} else {
$this->setUrl($data['url']['uri']);
}
} else {
$this->setUrl($data['url']);
}
unset($data['url']);
}
if (isset($data['classes'])) {
$classes = (array) $data['classes'];
unset($data['classes']);
foreach ($classes as $class) {
$this->set($class);
}
}
parent::__construct($data);
return $this;
}
}

View file

@ -0,0 +1,27 @@
<?php
class Legacies_Core_Block_Html_Navigation_Node
extends Legacies_Core_Block_Html_Navigation
{
protected $_title = '';
public function setTitle($title)
{
$this->_title = $title;
return $this;
}
public function getTitle()
{
return $this->_title;
}
public function getTemplate()
{
if ($this->_template !== null) {
return $this->_template;
}
return 'page/html/navigation/node.phtml';
}
}

View file

@ -3,5 +3,4 @@
class Legacies_Core_Block_Template
extends Legacies_Core_View
{
}

View file

@ -21,16 +21,16 @@ class Legacies_Core_Controller_Request_Http
if (isset($_POST[$key])) {
return $_POST[$key];
}
if (!isset($_GET[$key])) {
if (isset($_GET[$key])) {
return $_GET[$key];
}
if (!isset($_FILES[$key])) {
if (isset($_FILES[$key])) {
return $_FILES[$key];
}
if (!isset($_COOKIE[$key])) {
if (isset($_COOKIE[$key])) {
return $_COOKIE[$key];
}
if (!isset($_SERVER[$key])) {
if (isset($_SERVER[$key])) {
return $_SERVER[$key];
}
return $default;
@ -75,4 +75,12 @@ class Legacies_Core_Controller_Request_Http
}
return $_POST[$key];
}
public function getServer($key, $default = null)
{
if (!isset($_SERVER[$key])) {
return $default;
}
return $_SERVER[$key];
}
}

View file

@ -0,0 +1,32 @@
<?php
class Legacies_Core_Email
{
protected static $_defaultHeadrs = array(
);
protected $_headers = array();
public function send($to, $from, $subject, $body, Array $headers = array())
{
$this->_prepareHeaders($headers);
}
public function setHeader($name, $value)
{
$this->_headers[$name] = $value;
}
protected function _prepareHeaders($headers)
{
foreach ($headers as $name => $value) {
$this->setHeader($name, $value);
}
$this->addHeader('X-Mailer', 'PHP/' . PHP_VERSION . ' Legacies/' . VERSION);
$this->addHeader('Content-Transfer-Encoding', '7bit');
$this->addHeader('Content-Type', 'text/plain; charset=utf-8');
return $this;
}
}

View file

@ -19,6 +19,7 @@ class Legacies_Core_Layout
foreach (include $path . $layoutFile as $layoutId => $layoutConfig) {
if ($this->hasData($layoutId)) {
$declared = $this->getData($layoutId);
$layoutConfig = array_merge($declared, $layoutConfig);
}
@ -38,7 +39,6 @@ class Legacies_Core_Layout
}
$layoutConfigs = array($this->getData($layoutId));
$layoutUpdates = array();
if (isset($layoutConfigs[0]['update'])) {
$parent = $layoutConfigs[0]['update'];
@ -53,6 +53,7 @@ class Legacies_Core_Layout
}
}
$layoutUpdates = array();
$layoutConfig = array();
foreach (array_reverse($layoutConfigs) as $config) {
$layoutConfig = array_merge($layoutConfig, $config);
@ -72,12 +73,13 @@ class Legacies_Core_Layout
$type = $layoutConfig['type'];
$name = isset($layoutConfig['name']) ? $layoutConfig['name'] : 'root';
$this->_view = $this->createBlock($type, $name, $layoutConfig);
$this->_view = $this->_createBlock($type, $name, $layoutConfig);
foreach ($layoutUpdates as $block => $updates) {
if (!isset($this->_blocks[$block])) {
continue;
}
$parent = $this->_blocks[$block];
foreach ($updates as $update) {
if (isset($update['children'])) {
@ -85,11 +87,27 @@ class Legacies_Core_Layout
$type = $childConfig['type'];
$alias = isset($childConfig['alias']) ? $childConfig['alias'] : $childName;
$parent->$alias = $this->createBlock($type, $childName, $childConfig);
$parent->$alias = $this->_createBlock($type, $childName, $childConfig);
}
}
}
}
foreach ($layoutUpdates as $block => $updates) {
if (!isset($this->_blocks[$block])) {
continue;
}
foreach ($updates as $update) {
if (isset($update['actions'])) {
$this->_callActions($this->_blocks[$block], $update['actions']);
}
}
}
foreach ($this->_blocks as $block) {
$block->prepareLayout();
}
}
public function _save()
@ -119,6 +137,15 @@ class Legacies_Core_Layout
}
public function createBlock($type, $name, $config = array())
{
$instance = $this->_createBlock($type, $name, $config);
$instance->prepareLayout();
return $instance;
}
protected function _createBlock($type, $name, $config = array())
{
$className = $this->_resolveBlockClassType($type);
@ -138,6 +165,9 @@ class Legacies_Core_Layout
$instance = $reflectionClass->newInstance($config);
$this->_blocks[$name] = $instance;
$instance->setNameInLayout($name);
$instance->setLayout($this);
foreach ($children as $name => $config) {
if (isset($config['alias'])) {
@ -149,14 +179,22 @@ class Legacies_Core_Layout
if (!isset($config['type'])) {
$instance->$alias = new Legacies_Core_View($config);
} else {
$instance->$alias = $this->createBlock($config['type'], $name, $config);
$instance->$alias = $this->_createBlock($config['type'], $name, $config);
}
}
} catch (ReflectionException $e) {
var_dump($e);
return null;
}
$instance->setLayout($this);
$this->_callActions($instance, $actions);
return $instance;
}
protected function _callActions($block, $actions)
{
$reflectionClass = new ReflectionClass($block);
foreach ($actions as $action) {
if (!isset($action['method'])) {
@ -171,6 +209,7 @@ class Legacies_Core_Layout
try {
$reflectionMethod = $reflectionClass->getMethod($method);
$requiredParameterCount = $reflectionMethod->getNumberOfRequiredParameters();
$callParamaters = array();
foreach ($reflectionMethod->getParameters() as $parameter) {
$paramterName = $parameter->getName();
@ -180,24 +219,19 @@ class Legacies_Core_Layout
$callParamaters[$paramterPosition] = $params[$paramterName];
} else if ($parameter->isDefaultValueAvailable()) {
$callParamaters[$paramterPosition] = $parameter->getDefaultValue();
} else if ($parameter->isOptionnal()) {
continue;
} else {
throw RuntimeException();
//} else if (!$parameter->isOptionnal()) {
} else if ($paramterPosition <= $requiredParameterCount) {
throw new RuntimeException();
}
}
$reflectionMethod->invokeArgs($instance, $callParamaters);
$reflectionMethod->invokeArgs($block, $callParamaters);
} catch (ReflectionException $e) {
continue;
} catch (RuntimeException $e) {
continue;
}
}
$instance->prepareLayout();
return $instance;
}
public function getBlock($code)

View file

@ -29,9 +29,6 @@ class Legacies_Core_Model_Session
$reflection = new ReflectionClass(__CLASS__);
self::$_levels = array_flip($reflection->getConstants());
}
if (session_id() == '') {
session_start();
}
self::$_instances[$namespace] = new self($namespace);
}
@ -45,6 +42,14 @@ class Legacies_Core_Model_Session
public function __construct($namespace)
{
if (session_id() == '') {
session_start();
}
if (!isset($_SESSION[$namespace])) {
$_SESSION[$namespace] = array();
}
$this->_data = &$_SESSION[$namespace];
$this->_data['messages'] = array();
}

View file

@ -6,6 +6,7 @@ class Legacies_Core_View
protected $_template = null;
protected $_partials = array();
protected $_layout = null;
protected $_nameInLayout = null;
public function __construct(Array $data = array())
{
@ -27,6 +28,32 @@ class Legacies_Core_View
return Math::render($number);
}
public function renderTime($time, $unique = false)
{
if ($time >= 10) {
$seconds = $time % 60;
$minutes = (int) (($time - $seconds) / 60) % 60;
$hours = (int) ((($time - $seconds) / 60) - $minutes) / 60;
if ($hours > 24) {
$dayHours = (int) $hours % 24;
$days = (int) ($hours - $dayHours) / 24;
return $this->__('%1$d day(s) and %2$d hour(s)', $days, $dayHours);
} else if ($hours > 0) {
return $this->__('%1$d hour(s), %2$d minute(s) and %3$d second(s)', $hours, $minutes, $seconds);
} else if ($minutes > 0) {
return $this->__('%1$d minute(s) and %2$d second(s)', $minutes, $seconds);
} else {
return $this->__('%1$d second(s)', $seconds);
}
} else if (!$unique && $time > 0) {
return $this->__('%1$d per minute', 60 / $time);
} else {
return $this->__('instantaneous');
}
}
protected function escape($unescaped)
{
return htmlspecialchars($unescaped, ENT_QUOTES, 'UTF-8');
@ -37,7 +64,7 @@ class Legacies_Core_View
$args = func_get_args();
array_shift($args);
return Legacies::translate(Legacies::getLocale(), $message, $args);
return Legacies::translate(Legacies::getDefaultLocale(), $message, $args);
}
public function translate($message, $_ = null)
@ -104,12 +131,15 @@ class Legacies_Core_View
static $baseUrl = null;
if ($baseUrl === null) {
$user = Legacies_Empire_Model_User::getSingleton();
if ($user !== null && $user->getId() && ($baseUrl = $user->getSkinPath()) == '') {
if ($user !== null && $user->getId()) {
$baseUrl = $user->getSkinPath();
}
if ($baseUrl == '') {
$baseUrl = DEFAULT_SKINPATH;
}
}
return $baseUrl . $uri;
return $this->getUrl($baseUrl . $uri);
}
public function setPartial($name, $content)
@ -128,6 +158,11 @@ class Legacies_Core_View
return $this->_partials[$name];
}
public function getAllPartials()
{
return $this->_partials;
}
public function unsetPartial($name)
{
if (isset($this->_partials[$name])) {
@ -171,6 +206,10 @@ class Legacies_Core_View
return $this;
}
/**
*
* @return Legacies_Core_Layout
*/
public function getLayout()
{
return $this->_layout;
@ -183,4 +222,16 @@ class Legacies_Core_View
public function beforeToHtml()
{
}
public function setNameInLayout($name)
{
$this->_nameInLayout = $name;
return $this;
}
public function getNameInLayout()
{
return $this->_nameInLayout;
}
}

View file

@ -15,8 +15,13 @@ class Legacies_Database
$username = $config['global']['database']['options']['username'];
$password = $config['global']['database']['options']['password'];
$database = $config['global']['database']['options']['database'];
$port = 3306;
self::$_singleton = new self("mysql:dbname={$database};host={$hostname}", $username, $password, array(
if (isset($config['global']['database']['options']['port'])) {
$port = $config['global']['database']['options']['port'];
}
self::$_singleton = new self("mysql:dbname={$database};host={$hostname};port={$port}", $username, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}

View file

@ -56,6 +56,7 @@ class Legacies_Empire
const RESOURCE_MULTIPLIER = 'factor';
const RESOURCE_FORMULA = 'formule';
const RESOURCE_CLASS = 'class';
const BASE_BUILDING_TIME = 'base_time';
const SHIPS_CONSUMPTION_PRIMARY = 'consumption';
const SHIPS_CELERITY_PRIMARY = 'speed';

View file

@ -0,0 +1,118 @@
<?php
abstract class Legacies_Empire_Block_Planet_Builder_ItemAbstract
extends Legacies_Core_Block_Template
{
protected $_user = null;
protected $_planet = null;
protected $_itemId = null;
public function setUser(Legacies_Empire_Model_User $user)
{
$this->_user = $user;
return $this;
}
public function getUser()
{
if ($this->_user === null) {
$this->_user = Legacies_Empire_Model_User::getSingleton();
}
return $this->_user;
}
public function setPlanet(Legacies_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
if ($this->_planet === null) {
$this->_planet = $this->getUser()->getCurrentPlanet();
}
return $this->_planet;
}
public function setItemId($itemId)
{
$this->_itemId = $itemId;
return $this;
}
public function getItemId()
{
return $this->_itemId;
}
public function getItemInfoUrl()
{
return $this->getUrl('infos.php', array('gid' => $this->getItemId()));
}
public function getItemImageUrl()
{
// TODO : Upgrade theme
return $this->getSkinUrl('graphics/gebaeude/' . $this->getItemId() . '.gif');
}
public function getName()
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('tech');
}
if (isset($lang['tech']) && isset($lang['tech'][$this->getItemId()])) {
return $this->__($lang['tech'][$this->getItemId()]);
}
return '';
}
public function getDescription()
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('tech');
}
if (isset($lang['res']) && isset($lang['res']['descriptions']) && isset($lang['res']['descriptions'][$this->getItemId()])) {
return $this->__($lang['res']['descriptions'][$this->getItemId()]);
}
return '';
}
public function getResourceName($resourceId)
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('imperium');
}
if ($resourceId == 'cristal') {
$resourceId = 'crystal';
}
if (isset($lang[$resourceId])) {
return $this->__($lang[$resourceId]);
}
return '';
}
public function getNextLevel()
{
return $this->getQueuedLevel() + 1;
}
abstract public function getResourcesNeeded($level);
abstract public function getBuildingTime($level);
}

View file

@ -0,0 +1,22 @@
<?php
abstract class Legacies_Empire_Block_Planet_Builder_Queue_ItemAbstract
extends Legacies_Empire_Block_Planet_Builder_ItemAbstract
{
protected $_item = null;
protected $_itemIdField = null;
public function setItem(Legacies_Empire_Model_Builder_Item $item)
{
$this->_item = $item;
$this->setItemId($item->getData($this->_itemIdField));
return $this;
}
public function getItem()
{
return $this->_item;
}
}

View file

@ -0,0 +1,95 @@
<?php
abstract class Legacies_Empire_Block_Planet_Builder_QueueAbstract
extends Legacies_Core_Block_Template
{
protected $_user = null;
protected $_planet = null;
protected $_itemTemplate = null;
protected $_itemBlock = null;
public function setUser(Legacies_Empire_Model_User $user)
{
$this->_user = $user;
return $this;
}
public function getUser()
{
if ($this->_user === null) {
$this->_user = Legacies_Empire_Model_User::getSingleton();
}
return $this->_user;
}
public function setPlanet(Legacies_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
if ($this->_planet === null) {
$this->_planet = $this->getUser()->getCurrentPlanet();
}
return $this->_planet;
}
public function setItemTemplate($template)
{
$this->_itemTemplate = $template;
return $this;
}
public function getItemTemplate()
{
return $this->_itemTemplate;
}
public function setItemBlockType($blockType)
{
$this->_itemBlockType = $blockType;
return $this;
}
public function getItemBlockType()
{
return $this->_itemBlockType;
}
public function getItemBlock(Legacies_Empire_Model_Builder_Item $item)
{
$index = $item->getIndex();
$blockName = "item({$index})";
return $this->getLayout()
->createBlock($this->getItemBlockType(), $blockName)
->setTemplate($this->getItemTemplate())
->setPlanet($this->getPlanet())
->setItem($item);
}
public function prepareLayout()
{
$parentBlock = $this->getLayout()
->createBlock('core/concat', $this->getNameInLayout() . '.item-list')
;
$this->setPartial('item-list', $parentBlock);
foreach ($this->getQueue() as $item) {
$block = $this->getItemBlock($item);
$parentBlock->setPartial($block->getNameInLayout(), $block);
}
return $this;
}
abstract public function getQueue();
}

View file

@ -0,0 +1,54 @@
<?php
abstract class Legacies_Empire_Block_Planet_BuilderAbstract
extends Legacies_Core_Block_Template
{
protected $_itemTemplate = null;
protected $_itemBlock = null;
public function setItemTemplate($template)
{
$this->_itemTemplate = $template;
return $this;
}
public function getItemTemplate()
{
return $this->_itemTemplate;
}
public function setItemBlockType($blockType)
{
$this->_itemBlockType = $blockType;
return $this;
}
public function getItemBlockType()
{
return $this->_itemBlockType;
}
public function getItemBlock($itemId)
{
$blockName = "item({$itemId})";
return $this->getLayout()
->createBlock($this->getItemBlockType(), $blockName)
->setTemplate($this->getItemTemplate())
->setPlanet($this->getPlanet())
->setItemId($itemId);
}
public function prepareLayout()
{
parent::prepareLayout();
$this->_initChildBlocks();
return $this;
}
abstract protected function _initChildBlocks();
}

View file

@ -0,0 +1,46 @@
<?php
class Legacies_Empire_Block_Planet_Buildings
extends Legacies_Empire_Block_Planet_BuilderAbstract
{
protected $_planet = null;
public function setPlanet(Legacies_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
if ($this->_planet === null) {
$this->_planet = Legacies_Empire_Model_User::getSingleton()
->getCurrentPlanet()
;
}
return $this->_planet;
}
public function _initChildBlocks()
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$type = Legacies_Empire::TYPE_BUILDING_PLANET;
if ($this->getPlanet()->isMoon()) {
$type = Legacies_Empire::TYPE_BUILDING_MOON;
}
/** @var Legacies_Core_Block_Concat $parentBlock */
$parentBlock = $this->getLayout()->getBlock('item-list.items');
foreach ($types->getData($type) as $itemId) {
if (!$this->getPlanet()->checkAvailability($itemId)) {
continue;
}
$block = $this->getItemBlock($itemId);
$parentBlock->setPartial($block->getName(), $block);
}
return $this;
}
}

View file

@ -1,102 +1,56 @@
<?php
class Legacies_Empire_Block_Planet_Buildings_Item
extends Legacies_Core_Block_Template
extends Legacies_Empire_Block_Planet_Builder_ItemAbstract
{
protected $_planet = null;
protected $_itemId = null;
public function setPlanet(Legacies_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
return $this->_planet;
}
public function setItemId($itemId)
{
$this->_itemId = $itemId;
return $this;
}
public function getItemId()
{
return $this->_itemId;
}
public function getItemInfoUrl()
{
return $this->getUrl('infos.php', array('gid' => $this->getItemId()));
}
public function getItemImageUrl()
{
return $this->getSkinUrl('graphics/gebaeude/' . $this->getItemId() . '.gif');
}
public function getName()
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('tech');
}
if (isset($lang['tech']) && isset($lang['tech'][$this->getItemId()])) {
return $this->__($lang['tech'][$this->getItemId()]);
}
return '';
}
public function getDescription()
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('tech');
}
if (isset($lang['res']) && isset($lang['res']['descriptions']) && isset($lang['res']['descriptions'][$this->getItemId()])) {
return $this->__($lang['res']['descriptions'][$this->getItemId()]);
}
return '';
}
public function getResourceName($resourceId)
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('imperium');
}
if ($resourceId == 'cristal') {
$resourceId = 'crystal';
}
if (isset($lang[$resourceId])) {
return $this->__($lang[$resourceId]);
}
return '';
}
public function getLevel()
{
return $this->_planet->getElement($this->getItemId());
return $this->getPlanet()->getElement($this->getItemId());
}
public function getResourcesNeeded()
public function getResourcesNeeded($level)
{
return $this->_planet->getResourcesNeeded($this->getItemId(), 1);
return $this->getPlanet()->getResourcesNeeded($this->getItemId(), $level);
}
public function getItemTime()
public function getQueuedLevel()
{
return $this->_planet->getBuildingTime($this->getItemId(), 1);
return $this->getPlanet()->getBuildingLevelQueued($this->getItemId());
}
public function getBuildingTime($level)
{
return $this->getPlanet()->getBuildingTime($this->getItemId(), $level);
}
public function getResourcesConfigForLevel($level)
{
$resources = $this->getResourcesNeeded($level);
$resourceConfig = array();
foreach ($resources as $resourceId => $resourceValue) {
$resourceConfig[$resourceId] = new Legacies_Object(array(
'resource_id' => $resourceId,
'value' => $resourceValue
));
$amount = $this->getPlanet()->getResourceAmount($resourceId);
if (Math::comp($amount, $resourceValue) < 0) {
$resourceConfig[$resourceId]->setData('requirement', Math::sub($amount, $resourceValue));
} else {
$resourceConfig[$resourceId]->setData('overflow', Math::sub($amount, $resourceValue));
}
}
return $resourceConfig;
}
public function getResourcesConfigForNextLevel()
{
return $this->getResourcesConfigForLevel($this->getNextLevel());
}
public function getBuildingTimeForNextLevel()
{
return $this->getBuildingTime($this->getNextLevel());
}
}

View file

@ -0,0 +1,15 @@
<?php
class Legacies_Empire_Block_Planet_Buildings_Queue
extends Legacies_Empire_Block_Planet_Builder_QueueAbstract
{
public function getQueue()
{
return $this->getPlanet()->getBuildingQueue();
}
public function isEmpty()
{
return $this->getQueue()->count() == 0;
}
}

View file

@ -0,0 +1,63 @@
<?php
class Legacies_Empire_Block_Planet_Buildings_Queue_Item
extends Legacies_Empire_Block_Planet_Builder_Queue_ItemAbstract
{
protected $_itemIdField = 'building_id';
public function getLevel()
{
return $this->getPlanet()->getElement($this->getItemId());
}
public function getResourcesNeeded($level)
{
return $this->getPlanet()->getResourcesNeeded($this->getItemId(), $this->getQueuedLevel() + 1);
}
public function getItemQueuedLevel()
{
return $this->getItem()->getData('level');
}
public function getQueuedLevel()
{
return $this->getPlanet()->getBuildingLevelQueued($this->getItemId());
}
public function getBuildingTime($level)
{
return $this->getPlanet()->getBuildingTime($this->getItemId(), $level);
}
public function getResourcesConfigForLevel($level)
{
$resources = $this->getResourcesNeeded($level);
$resourceConfig = array();
foreach ($resources as $resourceId => $resourceValue) {
$resourceConfig[$resourceId] = new Legacies_Object(array(
'resource_id' => $resourceId,
'value' => $resourceValue
));
$amount = $this->getPlanet()->getResourceAmount($resourceId);
if (Math::comp($amount, $resourceValue) < 0) {
$resourceConfig[$resourceId]->setData('requirement', Math::sub($amount, $resourceValue));
} else {
$resourceConfig[$resourceId]->setData('overflow', Math::sub($amount, $resourceValue));
}
}
return $resourceConfig;
}
public function getResourcesConfigForNextLevel()
{
return $this->getResourcesConfigForLevel($this->getNextLevel());
}
public function getBuildingTimeForNextLevel()
{
return $this->getBuildingTime($this->getNextLevel());
}
}

View file

@ -0,0 +1,42 @@
<?php
class Legacies_Empire_Block_Planet_ResearchLab
extends Legacies_Empire_Block_Planet_BuilderAbstract
{
protected $_planet = null;
public function setPlanet(Legacies_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
if ($this->_planet === null) {
$this->_planet = Legacies_Empire_Model_User::getSingleton()
->getCurrentPlanet()
;
}
return $this->_planet;
}
public function _initChildBlocks()
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
/** @var Legacies_Core_Block_Concat $parentBlock */
$parentBlock = $this->getLayout()->getBlock('item-list.items');
foreach ($types->getData(Legacies_Empire::TYPE_RESEARCH) as $itemId) {
if (!$this->getPlanet()->getResearchLab()->checkAvailability($itemId)) {
continue;
}
$block = $this->getItemBlock($itemId);
$parentBlock->setPartial($block->getName(), $block);
}
return $this;
}
}

View file

@ -0,0 +1,56 @@
<?php
class Legacies_Empire_Block_Planet_ResearchLab_Item
extends Legacies_Empire_Block_Planet_Builder_ItemAbstract
{
public function getLevel()
{
return $this->getUser()->getElement($this->getItemId());
}
public function getResourcesNeeded($level)
{
return $this->getPlanet()->getResearchLab()->getResourcesNeeded($this->getItemId(), $level);
}
public function getQueuedLevel()
{
return $this->getPlanet()->getResearchLab()->getResearchLevelQueued($this->getItemId());
}
public function getBuildingTime($level)
{
return $this->getPlanet()->getResearchLab()->getResearchTime($this->getItemId(), $level);
}
public function getResourcesConfigForLevel($level)
{
$resources = $this->getResourcesNeeded($level);
$resourceConfig = array();
foreach ($resources as $resourceId => $resourceValue) {
$resourceConfig[$resourceId] = new Legacies_Object(array(
'resource_id' => $resourceId,
'value' => $resourceValue
));
$amount = $this->getPlanet()->getResourceAmount($resourceId);
if (Math::comp($amount, $resourceValue) < 0) {
$resourceConfig[$resourceId]->setData('requirement', Math::sub($amount, $resourceValue));
} else {
$resourceConfig[$resourceId]->setData('overflow', Math::sub($amount, $resourceValue));
}
}
return $resourceConfig;
}
public function getResourcesConfigForNextLevel()
{
return $this->getResourcesConfigForLevel($this->getNextLevel());
}
public function getBuildingTimeForNextLevel()
{
return $this->getBuildingTime($this->getNextLevel());
}
}

View file

@ -0,0 +1,15 @@
<?php
class Legacies_Empire_Block_Planet_ResearchLab_Queue
extends Legacies_Empire_Block_Planet_Builder_QueueAbstract
{
public function getQueue()
{
return $this->getPlanet()->getResearchLab()->getBuilder();
}
public function isEmpty()
{
return $this->getQueue()->count() == 0;
}
}

View file

@ -0,0 +1,63 @@
<?php
class Legacies_Empire_Block_Planet_ResearchLab_Queue_Item
extends Legacies_Empire_Block_Planet_Builder_Queue_ItemAbstract
{
protected $_itemIdField = 'research_id';
public function getLevel()
{
return $this->getUser()->getElement($this->getItemId());
}
public function getResourcesNeeded($level)
{
return $this->getPlanet()->getResearchLab()->getResourcesNeeded($this->getItemId(), $this->getQueuedLevel() + 1);
}
public function getItemQueuedLevel()
{
return $this->getItem()->getData('level');
}
public function getQueuedLevel()
{
return $this->getPlanet()->getResearchLab()->getResearchLevelQueued($this->getItemId());
}
public function getBuildingTime($level)
{
return $this->getPlanet()->getResearchLab()->getBuildingTime($this->getItemId(), $level);
}
public function getResourcesConfigForLevel($level)
{
$resources = $this->getResourcesNeeded($level);
$resourceConfig = array();
foreach ($resources as $resourceId => $resourceValue) {
$resourceConfig[$resourceId] = new Legacies_Object(array(
'resource_id' => $resourceId,
'value' => $resourceValue
));
$amount = $this->getPlanet()->getResourceAmount($resourceId);
if (Math::comp($amount, $resourceValue) < 0) {
$resourceConfig[$resourceId]->setData('requirement', Math::sub($amount, $resourceValue));
} else {
$resourceConfig[$resourceId]->setData('overflow', Math::sub($amount, $resourceValue));
}
}
return $resourceConfig;
}
public function getResourcesConfigForNextLevel()
{
return $this->getResourcesConfigForLevel($this->getNextLevel());
}
public function getBuildingTimeForNextLevel()
{
return $this->getBuildingTime($this->getNextLevel());
}
}

View file

@ -0,0 +1,82 @@
<?php
class Legacies_Empire_Block_Planet_Shipyard
extends Legacies_Empire_Block_Planet_BuilderAbstract
{
protected $_planet = null;
protected $_type = Legacies_Empire::TYPE_SHIP;
protected $_allowedTypes = array(
Legacies_Empire::TYPE_SHIP,
Legacies_Empire::TYPE_DEFENSE
);
public function setPlanet(Legacies_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
if ($this->_planet === null) {
$this->_planet = Legacies_Empire_Model_User::getSingleton()
->getCurrentPlanet()
;
}
return $this->_planet;
}
public function setAllowedTypes($types)
{
if (is_array($types)) {
$this->_allowedTypes = $types;
}
return $this;
}
public function addAllowedType($type)
{
if (!in_array($type, $this->_allowedTypes)) {
$this->_allowedTypes[] = $type;
}
return $this;
}
public function getAllowedTypes()
{
return $this->_allowedTypes;
}
public function setType($type)
{
if (in_array($type, $this->_allowedTypes)) {
$this->_type = $type;
}
return $this;
}
public function getType()
{
return $this->_type;
}
public function _initChildBlocks()
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
/** @var Legacies_Core_Block_Concat $parentBlock */
$parentBlock = $this->getLayout()->getBlock('item-list.items');
foreach ($types->getData($this->getType()) as $itemId) {
if (!$this->getPlanet()->getShipyard()->checkAvailability($itemId)) {
continue;
}
$block = $this->getItemBlock($itemId);
$parentBlock->setPartial($block->getName(), $block);
}
return $this;
}
}

View file

@ -1,109 +1,46 @@
<?php
class Legacies_Empire_Block_Planet_Shipyard_Item
extends Legacies_Core_Block_Template
extends Legacies_Empire_Block_Planet_Builder_ItemAbstract
{
protected $_planet = null;
protected $_shipyard = null;
protected $_itemId = null;
public function setPlanet(Legacies_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
$this->_shipyard = $this->_planet->getShipyard();
return $this;
}
public function getPlanet()
{
return $this->_planet;
}
public function setItemId($shipId)
{
$this->_itemId = $shipId;
return $this;
}
public function getItemId()
{
return $this->_itemId;
}
public function getItemInfoUrl()
{
return $this->getUrl('infos.php', array('gid' => $this->getItemId()));
}
public function getItemImageUrl()
{
return $this->getSkinUrl('graphics/gebaeude/' . $this->getItemId() . '.gif');
}
public function getName()
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('tech');
}
if (isset($lang['tech']) && isset($lang['tech'][$this->getItemId()])) {
return $this->__($lang['tech'][$this->getItemId()]);
}
return '';
}
public function getDescription()
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('tech');
}
if (isset($lang['res']) && isset($lang['res']['descriptions']) && isset($lang['res']['descriptions'][$this->getItemId()])) {
return $this->__($lang['res']['descriptions'][$this->getItemId()]);
}
return '';
}
public function getResourceName($resourceId)
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('imperium');
}
if ($resourceId == 'cristal') {
$resourceId = 'crystal';
}
if (isset($lang[$resourceId])) {
return $this->__($lang[$resourceId]);
}
return '';
}
public function getQty()
{
return $this->_planet->getElement($this->getItemId());
return $this->getPlanet()->getElement($this->getItemId());
}
public function getResourcesNeeded()
public function getResourcesNeeded($qty)
{
return $this->_shipyard->getResourcesNeeded($this->getItemId(), 1);
return $this->getPlanet()->getShipyard()->getResourcesNeeded($this->getItemId(), $qty);
}
public function getBuildingTime()
public function getBuildingTime($qty)
{
return $this->_shipyard->getBuildingTime($this->getItemId(), 1);
return $this->getPlanet()->getShipyard()->getBuildingTime($this->getItemId(), $qty);
}
public function getMaximumBuildableElementsCount()
{
return $this->_shipyard->getMaximumBuildableElementsCount($this->getItemId());
return $this->getPlanet()->getShipyard()->getMaximumBuildableElementsCount($this->getItemId());
}
public function getResourcesConfigForQty($qty)
{
$resources = $this->getResourcesNeeded($qty);
$resourceConfig = array();
foreach ($resources as $resourceId => $resourceValue) {
$resourceConfig[$resourceId] = new Legacies_Object(array(
'resource_id' => $resourceId,
'value' => $resourceValue
));
$amount = $this->getPlanet()->getResourceAmount($resourceId);
if (Math::comp($amount, $resourceValue) < 0) {
$resourceConfig[$resourceId]->setData('requirement', Math::sub($amount, $resourceValue));
} else {
$resourceConfig[$resourceId]->setData('overflow', Math::sub($amount, $resourceValue));
}
}
return $resourceConfig;
}
}

View file

@ -0,0 +1,15 @@
<?php
class Legacies_Empire_Block_Planet_Shipyard_Queue
extends Legacies_Empire_Block_Planet_Builder_QueueAbstract
{
public function getQueue()
{
return $this->getPlanet()->getShipyard()->getQueue();
}
public function isEmpty()
{
return $this->getQueue()->count() == 0;
}
}

View file

@ -19,7 +19,7 @@ abstract class Legacies_Empire_Model_BuilderAbstract
* construction queue
* @var array
*/
private $_queue = null;
protected $_queue = null;
/**
* construction queue
@ -27,12 +27,6 @@ abstract class Legacies_Empire_Model_BuilderAbstract
*/
protected $_itemClass = 'Legacies_Empire_Model_Builder_Item';
/**
* construction queue
* @var array
*/
protected $_index = 0;
/**
*
* @param Legacies_Empire_Model_Planet $currentPlanet
@ -48,25 +42,36 @@ abstract class Legacies_Empire_Model_BuilderAbstract
abstract public function init();
abstract protected function _initItem();
abstract protected function _initItem(Array $params);
public function enqueue()
public function enqueue($params, $index = null)
{
$params = func_get_args();
$item = call_user_func_array(array($this, '_initItem'), $params);
$item->setIndex($this->_index);
$this->_queue[$this->_index++] = $item;
$item = $this->_initItem($params);
if ($item === null) {
return $this;
}
if ($index === null) {
$index = $this->_generateIndex();
}
$item->setIndex($index);
$this->_queue[$index] = $item;
return $this;
}
public function dequeue($item)
{
unset($this->_queue[(int) $item->getIndex()]);
unset($this->_queue[$item->getIndex()]);
return $this;
}
protected function _generateIndex()
{
return uniqid();
}
public function getItem($itemIndex)
{
if (isset($this->_queue[$itemIndex])) {
@ -79,8 +84,8 @@ abstract class Legacies_Empire_Model_BuilderAbstract
protected function _serializeQueue()
{
$serialize = array();
foreach ($this->_queue as $item) {
$serialize[] = $item->getAllDatas();
foreach ($this->_queue as $itemIndex => $itemInstance) {
$serialize[$itemIndex] = $itemInstance->getAllDatas();
}
return serialize($serialize);
}
@ -95,8 +100,8 @@ abstract class Legacies_Empire_Model_BuilderAbstract
return $this;
}
foreach ($unserialized as $itemData) {
call_user_func_array(array($this, 'enqueue'), $itemData);
foreach ($unserialized as $itemIndex => $itemData) {
$this->enqueue($itemData, $itemIndex);
}
return $this;
@ -222,7 +227,7 @@ abstract class Legacies_Empire_Model_BuilderAbstract
protected function _calculateResourceRemainingAmounts($resourceNeeded)
{
$resourceAmounts = array();
foreach ($resourcesNeeded as $resourceId => $resourceAmount) {
foreach ($resourceNeeded as $resourceId => $resourceAmount) {
$resourceAmounts[$resourceId] = Math::sub($this->_currentPlanet[$resourceId], $resourceAmount);
if (Math::isNegative($resourceAmounts[$resourceId])) {
return false;
@ -230,4 +235,13 @@ abstract class Legacies_Empire_Model_BuilderAbstract
}
return $resourceAmounts;
}
protected function _calculateResourceReclaimedAmounts($resourceNeeded)
{
$resourceAmounts = array();
foreach ($resourceNeeded as $resourceId => $resourceAmount) {
$resourceAmounts[$resourceId] = Math::add($this->_currentPlanet[$resourceId], $resourceAmount);
}
return $resourceAmounts;
}
}

View file

@ -8,4 +8,25 @@ class Legacies_Empire_Model_Galaxy_Position
$this->_tableName = 'galaxy';
$this->_idFieldNames = array('id_planet');
}
static function initPlanetListerner($eventData)
{
if (!isset($eventData['planet'])) {
return;
}
$planet = $eventData['planet'];
if (!$planet->isPlanet()) {
return;
}
$galaxy = new self();
$galaxy
->setData('galaxy', $planet->getGalaxy())
->setData('system', $planet->getSystem())
->setData('planet', $planet->getPosition())
->setData('id_planet', $planet->getId())
->save()
;
}
}

View file

@ -70,15 +70,6 @@ class Legacies_Empire_Model_Planet
$this->_idFieldName = 'id';
}
public function _afterLoad()
{
parent::_afterLoad();
$this->getBuildingQueue()->init();
return $this;
}
public function getLastUpdate()
{
return $this->getData('last_update');
@ -119,10 +110,15 @@ class Legacies_Empire_Model_Planet
//$officerEnhancement = (.5 * $this->getUser()->getData('rpg_stockeur')) + 1;
$officerEnhancement = 1;
$storageEnhancementFactor = Math::floor(Math::pow(1.6, $this[Legacies_Empire::getFieldName($resourceData['storage'])]));
$storageEnhancement = Math::mul(BASE_STORAGE_SIZE / 2, $storageEnhancementFactor);
if ($this->getElement($resourceData['storage'])) {
$storageEnhancementFactor = Math::floor(Math::pow(1.6, $this->getElement($resourceData['storage'])));
$storageEnhancement = Math::mul(BASE_STORAGE_SIZE / 2, $storageEnhancementFactor);
} else {
$storageEnhancement = 0;
}
$value = Math::mul(MAX_OVERFLOW, Math::mul($officerEnhancement, Math::add(BASE_STORAGE_SIZE, $storageEnhancement)));
$this->setData($resourceData['storage_field'], Math::floor($value));
}
Math::setPrecision();
@ -619,9 +615,9 @@ class Legacies_Empire_Model_Planet
));
if ($destroy === false) {
$level = $this->getElement($buildingId) + 1;
$level = $this->getBuildingLevelQueued($buildingId) + 1;
} else {
$level = max($this->getElement($buildingId) - 1, 0);
$level = max($this->getBuildingLevelQueued($buildingId) - 1, 0);
}
$this->getBuildingQueue()->appendQueue($buildingId, $level, $time);
@ -664,6 +660,19 @@ class Legacies_Empire_Model_Planet
return $this;
}
public function getBuildingLevelQueued($buildingId)
{
$level = $this->getElement($buildingId);
foreach ($this->_builder as $item) {
if ($item->getData('building_id') != $buildingId) {
continue;
}
$level = $item->getData('level');
}
return $level;
}
/**
*
* @return Legacies_Empire_Model_Planet_Builder
@ -691,6 +700,18 @@ class Legacies_Empire_Model_Planet
return $this;
}
/**
*
* Enter description here ...
* @return Legacies_Empire_Model_Planet
*/
public function dequeueItem($itemId)
{
$this->getBuildingQueue()->dequeueItem($itemId);
return $this;
}
/**
* Check if a building is actually buildable on the current planet,
* depending on the technology and buildings requirements.
@ -743,60 +764,33 @@ class Legacies_Empire_Model_Planet
{
if (isset($eventData['user'])) {
$user = $eventData['user'];
$request = $eventData['request'];
if ($user === null || !$user instanceof Legacies_Empire_Model_User || $user->getId()) {
return;
}
if ($request === null || !$request instanceof Legacies_Core_Controller_Request) {
if ($user === null || !$user instanceof Legacies_Empire_Model_User || !$user->getId()) {
return;
}
$collection = new Legacies_Core_Collection('planets');
$collection
->column(array(
'galaxy' => 'planet.galaxy',
'system' => 'planet.system',
'count' => 'COUNT(planet.id)'
))
->group('planet.galaxy')
->group('planet.system')
->where('planet.planet_type=1')
->order('COUNT(planet.id)', 'ASC')
->order('RAND()', 'ASC')
->limit(1)
;
$params = array();
$galaxy = $request->getParam('system');
if ($galaxy !== null) {
$collection->where('planet.galaxy=:galaxy');
$params['galaxy'] = $galaxy;
$systems = explode(',', $request->getParam('system'));
if (is_array($systems) && count($systems) == 2 && is_int($systems[0]) && is_int($systems[1])) {
$collection->where('planet.system IN(' . implode(', ', range($systems[0], $systems[1])) . ')');
}
}
$collection->load($params);
$collection = self::_searchMostFreeSystems();
$collection->limit(1)->load();
if ($collection->count() == 0) {
throw new Exception('No planet to colonize there!'); // FIXME
throw new Exception('No more planet to colonize!'); // Oops, no more free place
}
$systemInfo = $collection->current();
if ($systemInfo->getData('count') >= MAX_PLANET_IN_SYSTEM) {
throw new Exception('No planet to colonize there!'); // FIXME
throw new Exception('No more planet to colonize!'); // Oops, no more free place
}
$system = $systemInfo->getData('system');
$galaxy = $systemInfo->getData('galaxy');
$collection = new Legacies_Core_Collection('planets');
$collection = new Legacies_Core_Collection(array('planet' => 'planets'));
$collection
->column(array('position' => 'planet.position'))
->column(array('position' => 'planet.planet'))
->where('planet.planet_type=1')
->where('planet.planet_type=:system')
->load()
->where('planet.galaxy=:galaxy')
->where('planet.system=:system')
->load(array(
'galaxy' => $systemInfo->getData('galaxy'),
'system' => $systemInfo->getData('system'),
))
;
$positions = range(1, MAX_PLANET_IN_SYSTEM);
foreach ($collection as $planet) {
@ -808,14 +802,29 @@ class Legacies_Empire_Model_Planet
$key = array_rand($positions, 1);
$finalPosition = $positions[$key];
$config = Legacies_Core_Model_Config::getSingleton();
$planet = new self();
$planet
->setData('id_owner', $user->getId())
->setData('name', $request->getParam('planet'))
->setData('galaxy', $galaxy)
->setData('system', $system)
->setData('position', $finalPosition)
->setData('name', Legacies::getRequest()->getParam('planet'))
->setData('galaxy', $systemInfo->getData('galaxy'))
->setData('system', $systemInfo->getData('system'))
->setData('planet', $finalPosition)
->setData('planet_type', 1)
->setData('field_max', $config->getData('initial_fields'))
->setData('field_current', 0)
->setData('metal', 500) // TODO: use config
->setData('cristal', 500) // TODO: use config
;
$planet->save();
$user
->setData('id_planet', $planet->getId())
->setData('current_planet', $planet->getId())
->setData('galaxy', $planet->getGalaxy())
->setData('system', $planet->getSystem())
->setData('planet', $planet->getPosition())
;
Legacies::dispatchEvent('planet.init', array(
@ -823,19 +832,61 @@ class Legacies_Empire_Model_Planet
'user' => $user
));
$planet
->setData('field_max', 163)
->setData('field_current', 0)
->save()
;
$user
->setData('id_planet', $planet->getId())
->setData('current_planet', $planet->getId())
;
//$planet->save();
}
}
protected static function _searchMostFreeSystems($galaxyList = null, $systemList = null)
{
$collection = new Legacies_Core_Collection(array('planet' => 'planets'));
$collection
->column(array(
'galaxy' => 'planet.galaxy',
'system' => 'planet.system',
'count' => 'COUNT(planet.id)'
))
->group('planet.galaxy')
->group('planet.system')
->where('planet.planet_type=1')
;
$config = Legacies_Core_Model_Config::getSingleton();
if ($galaxyList === null && $config->hasData('user/registration/galaxy_list')) {
$galaxyList = explode(',', $config->getData('user/registration/galaxy_list'));
}
if ($galaxyList !== null) {
array_walk($galaxyList, array(__CLASS__, '_cleanItemRanges'));
$collection->where('planet.galaxy IN(' . implode(', ', $galaxyList) . ')');
}
if ($systemList === null && $config->hasData('user/registration/system_list')) {
$systemList = explode(',', $config->getData('user/registration/system_list'));
}
if ($systemList !== null) {
array_walk($systemList, array(__CLASS__, '_cleanItemRanges'));
$collection->where('planet.system IN(' . implode(', ', $systemList) . ')');
}
$orders = array(
"1.5 / COUNT(planet.id)",
"ABS(planet.galaxy - CEIL({$collection->quote(MAX_GALAXY_IN_WORLD)} / 2))",
"ABS(planet.system - CEIL({$collection->quote(MAX_SYSTEM_IN_GALAXY)} / 2))"
);
$collection
->order('((' . implode(') * (', $orders) . '))', 'ASC')
->order('RAND()', 'ASC');
return $collection;
}
private static function _cleanItemRanges(&$value, $index, $userdata = null)
{
return intval($value);
}
public static function planetUpdateListener($eventData)
{
if (isset($eventData['planet'])) {

View file

@ -9,21 +9,41 @@ class Legacies_Empire_Model_Planet_Builder
}
/**
* @param int $buildingId
* @param int $level
* @param int $time
* @param array $params
*/
public function _initItem()
protected function _initItem(Array $params)
{
$buildingId = func_get_arg(0);
$level = func_get_arg(1);
$time = func_get_arg(2);
if (!isset($params['building_id']) || !isset($params['level'])) {
return null;
}
$buildingId = $params['building_id'];
$level = $params['level'];
if (!isset($params['created_at'])) {
$createdAt = time();
} else {
$createdAt = $params['created_at'];
}
if (!isset($params['started_at'])) {
$startedAt = 0;
} else {
$startedAt = $params['started_at'];
}
if (!isset($params['updated_at'])) {
$updatedAt = $createdAt;
} else {
$updatedAt = $params['updated_at'];
}
return new Legacies_Empire_Model_Planet_Builder_Item(array(
'building_id' => $buildingId,
'level' => $level,
'created_at' => $time,
'updated_at' => $time
'created_at' => $createdAt,
'started_at' => $startedAt,
'updated_at' => $updatedAt
));
}
@ -42,12 +62,34 @@ class Legacies_Empire_Model_Planet_Builder
return true;
}
return $this->checkAvailability($buildingId);
return false;
}
public function getBuildingTime($buildingId, $level)
{
return 0;
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
$gameConfig = Legacies_Core_Model_Config::getSingleton();
Math::setPrecision(50);
$firstLevelTime = $prices[$buildingId][Legacies_Empire::BASE_BUILDING_TIME];
$partialLevelTime = Math::mul($firstLevelTime, Math::pow($prices[$buildingId][Legacies_Empire::RESOURCE_MULTIPLIER], $level));
$levelTime = Math::sub($partialLevelTime, $firstLevelTime);
$speedFactor = $gameConfig->getData('game_speed');
$baseTime = $levelTime / $speedFactor * 3600;
Math::setPrecision();
$event = Legacies::dispatchEvent('planet.building.building-time', array(
'time' => $baseTime,
'base_time' => $baseTime,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser,
'building_id' => $buildingId,
'level' => $level
));
return $event->getData('time');
}
public function getResourcesNeeded($buildingId, $level)
@ -65,8 +107,7 @@ class Legacies_Empire_Model_Planet_Builder
}
if (Math::isPositive($prices[$buildingId][$resourceId])) {
$firstLevelCost = $prices[$buildingId][$resourceId];
$partialLevelCost = Math::mul($firstLevelCost, Math::pow($prices[$buildingId][Legacies_Empire::RESOURCE_MULTIPLIER], $level));
$resourcesNeeded[$resourceId] = Math::sub($partialLevelCost, $firstLevelCost);
$resourcesNeeded[$resourceId] = Math::mul($firstLevelCost, Math::pow($prices[$buildingId][Legacies_Empire::RESOURCE_MULTIPLIER], $level));
}
}
@ -82,12 +123,20 @@ class Legacies_Empire_Model_Planet_Builder
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
$elapsedTime = $time - $this->_currentPlanet->getData('b_building');
$startingTime = $this->_currentPlanet->getData('b_building');
foreach ($this->getQueue() as $element) {
$buildingId = $element->getData('building_id');
$elementTime = $element->getData('started_at');
if ($elementTime == 0) {
$element->setData('started_at', $startingTime);
$elementTime = $startingTime;
}
$level = $element->getData('level');
$buildTime = $this->getBuildingTime($buildingId, $level); // FIXME: consider total time, not only the construction time
$buildingId = $element->getData('building_id');
$buildTime = $this->getBuildingTime($buildingId, $level);
$elapsedTime = $time - $elementTime;
if ($elapsedTime >= $buildTime) {
$this->_currentPlanet->updateResources($time - $elapsedTime);
@ -95,6 +144,7 @@ class Legacies_Empire_Model_Planet_Builder
$this->_currentPlanet->updateResourceProduction($time - $elapsedTime);
$this->_currentPlanet->updateStorages($time - $elapsedTime);
$this->_currentPlanet->updateBuildingFields();
$this->dequeue($element);
Legacies::dispatchEvent('planet.building.level-update', array(
@ -105,15 +155,16 @@ class Legacies_Empire_Model_Planet_Builder
'level' => $level
));
$elapsedTime -= $buildTime;
$startingTime = $elementTime + $buildTime;
continue;
}
$element->setData('updated_at', $time);
break;
}
$this->_currentPlanet->setData('b_building_id', $this->serialize());
$this->_currentPlanet->setData('b_building', $time);
$this->_currentPlanet->setData('b_building', $startingTime);
return $this;
}
@ -148,7 +199,11 @@ class Legacies_Empire_Model_Planet_Builder
return $this;
}
$this->enqueue($buildingId, $level, $time);
$this->enqueue(array(
'building_id' => $buildingId,
'level' => $level,
'created_at' => $time
));
$this->_currentPlanet->setData('b_building_id', $this->serialize());
foreach ($remainingAmounts as $resourceId => $resourceAmount) {
@ -159,22 +214,52 @@ class Legacies_Empire_Model_Planet_Builder
}
/**
* Append items to build to the construction list
* Dequeues the first item to build to the construction list and removes all
* its successors of the same type.
*
* @param int $buildingId
* @param int|string $level
* @return Legacies_Empire_Model_Planet_Building_Shipyard
* @return Legacies_Empire_Model_Planet_Builder
*/
public function dequeueFirstItem($time)
public function dequeueFirstItem()
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
$this->rewind();
$item = $this->current();
if (!Math::isPositive($level)) {
return $this->dequeueItem($item->getIndex());
}
/**
* Dequeues an item to build to the construction list and removes all its
* successors of the same type.
*
* @param string $itemId
* @return Legacies_Empire_Model_Planet_Builder
*/
public function dequeueItem($itemId)
{
$item = $this->getItem($itemId);
if (!$item) {
return $this;
}
$buildingId = $item->getData('building_id');
// FIXME
$keys = array_keys($this->_queue);
$size = count($keys);
$start = array_search($item->getIndex(), $keys);
for ($i = $start; $i < $size; $i++) {
$index = $keys[$i];
if ($this->_queue[$index]->getData('building_id') != $buildingId) {
continue;
}
$resourcesNeeded = $this->getResourcesNeeded($buildingId, $this->_queue[$index]->getData('level'));
$reclaimedAmounts = $this->_calculateResourceReclaimedAmounts($resourcesNeeded);
$this->dequeue($this->_queue[$index]);
foreach ($reclaimedAmounts as $resourceId => $resourceAmount) {
$this->_currentPlanet[$resourceId] = $resourceAmount;
}
}
$this->_currentPlanet->setData('b_building_id', $this->serialize());

View file

@ -0,0 +1,19 @@
<?php
class Legacies_Empire_Model_Planet_Building_NaniteFactory
implements Legacies_Empire_Model_Planet_BuildingInterface
{
public static function buildingTimeListener($event)
{
$planet = $event->getData('planet');
if (!$planet->getId() || ($level = $planet->getElement(Legacies_Empire::ID_BUILDING_NANITE_FACTORY)) <= 0) {
return;
}
$time = $event->getData('time');
$speedFactor = pow(2, $level);
$event->setData('time', $time / $speedFactor);
}
}

View file

@ -206,12 +206,12 @@ class Legacies_Empire_Model_Planet_Building_ResearchLab
* @param int $resourceId
* @return bool
*/
public function checkAvailability($resourceId)
public function checkAvailability($researchId)
{
try {
// Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'check-availability', array(
'research_id' => $resourceId,
'research_id' => $researchId,
'laboratory' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
@ -220,17 +220,30 @@ class Legacies_Empire_Model_Planet_Building_ResearchLab
return false;
}
return $this->_builder->checkAvailability($resourceId);
return $this->_builder->checkAvailability($researchId);
}
public function getResourcesNeeded($resourceId, $level)
public function getResourcesNeeded($researchId, $level)
{
return $this->_builder->getResourcesNeeded($resourceId, $level);
return $this->_builder->getResourcesNeeded($researchId, $level);
}
public function getBuildingTime($resourceId, $level)
public function getResearchTime($researchId, $level)
{
$this->_builder->getBuildingTime($resourceId, $level);
$this->_builder->getBuildingTime($researchId, $level);
}
public function getResearchLevelQueued($researchId)
{
$level = $this->_currentUser->getElement($researchId);
foreach ($this->_builder as $item) {
if ($item->getData('research_id') != $researchId) {
continue;
}
$level = $item->getData('level');
}
return $level;
}
public static function planetUpdateListener($eventData)

View file

@ -18,17 +18,30 @@ class Legacies_Empire_Model_Planet_Building_ResearchLab_Builder
* @param int $level
* @param int $time
*/
public function _initItem()
protected function _initItem(Array $params)
{
$technologyId = func_get_arg(0);
$level = func_get_arg(1);
$time = func_get_arg(2);
if (!isset($params['technology_id']) || !isset($params['level'])) {
return null;
}
$technologyId = $params['technology_id'];
$level = $params['level'];
if (!isset($params['created_at'])) {
$createdAt = time();
} else {
$createdAt = $params['created_at'];
}
if (!isset($params['updated_at'])) {
$updatedAt = $createdAt;
} else {
$updatedAt = $params['updated_at'];
}
return new Legacies_Empire_Model_Planet_Building_ResearchLab_Item(array(
'technology_id' => $technologyId,
'level' => $level,
'created_at' => $time,
'updated_at' => $time
'created_at' => $createdAt,
'updated_at' => $updatedAt
));
}

View file

@ -0,0 +1,19 @@
<?php
class Legacies_Empire_Model_Planet_Building_RoboticFactory
implements Legacies_Empire_Model_Planet_BuildingInterface
{
public static function buildingTimeListener($event)
{
$planet = $event->getData('planet');
if (!$planet->getId() || ($level = $planet->getElement(Legacies_Empire::ID_BUILDING_ROBOTIC_FACTORY)) <= 0) {
return;
}
$time = $event->getData('time');
$speedFactor = 1 + $level;
$event->setData('time', $time / $speedFactor);
}
}

View file

@ -259,7 +259,7 @@ class Legacies_Empire_Model_Planet_Building_Shipyard
public function getBuildingTime($shipId, $qty)
{
$this->_builder->getBuildingTime($shipId, $qty);
return $this->_builder->getBuildingTime($shipId, $qty);
}
public static function planetUpdateListener($eventData)

View file

@ -18,17 +18,30 @@ class Legacies_Empire_Model_Planet_Building_Shipyard_Builder
* @param int $qty
* @param int $time
*/
public function _initItem()
protected function _initItem(Array $params)
{
$shipId = func_get_arg(0);
$qty = func_get_arg(1);
$time = func_get_arg(2);
if (!isset($params['ship_id']) || !isset($params['qty'])) {
return null;
}
$shipId = $params['ship_id'];
$qty = $params['qty'];
if (!isset($params['created_at'])) {
$createdAt = time();
} else {
$createdAt = $params['created_at'];
}
if (!isset($params['updated_at'])) {
$updatedAt = $createdAt;
} else {
$updatedAt = $params['updated_at'];
}
return new Legacies_Empire_Model_Planet_Building_Shipyard_Item(array(
'ship_id' => $shipId,
'qty' => $qty,
'created_at' => $time,
'updated_at' => $time
'created_at' => $createdAt,
'updated_at' => $updatedAt
));
}
@ -108,7 +121,7 @@ class Legacies_Empire_Model_Planet_Building_Shipyard_Builder
);
if (in_array($shipId, array_keys($limitedElementsQty))) {
foreach ($this->_queue as $element) {
foreach ($this->getQueue() as $element) {
if ($element['ship_id'] != $shipId) {
continue;
}
@ -138,36 +151,26 @@ class Legacies_Empire_Model_Planet_Building_Shipyard_Builder
public function getBuildingTime($shipId, $qty)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$gameConfig = Legacies_Core_Model_Config::getSingleton();
Math::setPrecision(50);
$buildingTime = Math::mul($prices[$shipId][Legacies_Empire::BASE_BUILDING_TIME], $qty);
// FIXME: Resource dependency
$totalCost = Math::mul(Math::add($prices[$shipId][Legacies_Empire::RESOURCE_METAL], $prices[$shipId][Legacies_Empire::RESOURCE_CRISTAL]), $qty);
$speedFactor = $gameConfig->getData('game_speed');
// FIXME: Building dependency
$shipyardSpeedup = Math::div(1, Math::add($this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_SHIPYARD]], 1));
$naniteSpeedup = Math::pow(.5, $this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_NANITE_FACTORY]]);
$structuresSpeedup = Math::mul($shipyardSpeedup, $naniteSpeedup);
// FIXME: officers
$officerSpeedup = 1;
if ($types->is($shipId, Legacies_Empire::TYPE_SHIP)) {
$officerSpeedup = 1 - ($this->_currentUser['rpg_technocrate'] * .05);
} else if ($types->is($shipId, Legacies_Empire::TYPE_SPECIAL)) {
$officerSpeedup = 1 - ($this->_currentUser['rpg_technocrate'] * .05);
} else if ($types->is($shipId, Legacies_Empire::TYPE_DEFENSE)) {
$officerSpeedup = 1 - ($this->_currentUser['rpg_defenseur'] * .375);
}
$baseTime = Math::div($buildingTime, $speedFactor);
Math::setPrecision();
$baseTime = ($totalCost / $speedFactor) * $structuresSpeedup;
$event = Legacies::dispatchEvent('planet.shipyard.building-time', array(
'time' => $baseTime,
'base_time' => $baseTime,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser,
'ship_id' => $shipId,
'qty' => $qty
));
return (int) Math::floor($baseTime * $officerSpeedup * 3600);
return $event->getData('time');
}
/**

View file

@ -19,6 +19,9 @@ class Legacies_Empire_Model_User
public static $hashCallback = 'md5';
protected $_homePlanet = null;
protected $_currentPlanet = null;
const SESSION_KEY = 'user';
const COOKIE_NAME = 'legacies';
const COOKIE_LIFETIME = 2592000;
@ -56,7 +59,7 @@ class Legacies_Empire_Model_User
$session = Legacies::getSession(self::SESSION_KEY);
if ($session->hasData('user_id')) {
$id = intval($session->getData('user_id'));
} else if (Legacies::$request !== null && ($cookie = Legacies::$request->getCookie(self::$_cookieName)) !== null) {
} else if (Legacies::getRequest() !== null && ($cookie = Legacies::getRequest()->getCookie(self::$_cookieName)) !== null) {
$cookieData = unserialize(stripslashes($cookie));
if (is_array($cookieData)) {
$collection = new Legacies_Core_Collection(array('user' => 'users'));
@ -164,7 +167,7 @@ class Legacies_Empire_Model_User
if (intval($login['login_success']) == 1) {
if ($login['banaday'] != 0) {
if($login['banaday'] <= time() && $login['banaday'] != '0') {
if($login['banaday'] <= time()) {
$user->setData('banaday', 0)
->setData('bana', 0)
->setData('urlaubs_modus', 0)
@ -176,7 +179,7 @@ class Legacies_Empire_Model_User
}
}
if (isset($_POST["rememberme"]) && Legacies::$request !== null) {
if (isset($_POST["rememberme"]) && Legacies::getRequest() !== null) {
Legacies::$response->setCookie(self::$_cookieName, array('id' => $login['id'], 'key' => $login['login_rememberme']), self::COOKIE_LIFETIME);
}
@ -195,11 +198,18 @@ class Legacies_Empire_Model_User
public static function register($username, $email, $password)
{
try {
$request = Legacies::getRequest();
$user = new self(array(
'username' => $username,
'password' => md5($password),
'email' => $email,
'email_2' => $email
'email_2' => $email,
'register_time' => Legacies::now(),
'onlinetime' => Legacies::now(),
'ip_at_reg' => $request->getServer('REMOTE_ADDR'),
'user_lastip' => $request->getServer('REMOTE_ADDR'),
'user_agent' => $request->getServer('HTTP_USER_AGENT')
));
$user->save();
@ -210,6 +220,7 @@ class Legacies_Empire_Model_User
$user->save();
} catch (Legacies_Core_Model_Exception $e) {
echo $e->getTraceAsString();
$session->addError($e->getMessage());
return null;
}
@ -225,7 +236,7 @@ class Legacies_Empire_Model_User
public function updateCurrentPlanet($planet)
{
if (!$planetId instanceof Legacies_Empire_Model_Planet) {
$planetColelction = $this->_preparePlanetCollection()->where('id=:id');
$planetCollection = $this->_preparePlanetCollection()->where('id=:id');
$planetCollection->load(array(
'id' => $planet,
@ -248,6 +259,23 @@ class Legacies_Empire_Model_User
return $this;
}
/**
*
* Enter description here ...
* @param Legacies_Empire_Model_Planet $planet
*/
public function setHomePlanet(Legacies_Empire_Model_Planet $planet)
{
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return $this;
}
$this->setData('id_planet', $planet->getId());
$this->_homePlanet = $planet;
return $this;
}
/**
*
* Enter description here ...
@ -260,6 +288,7 @@ class Legacies_Empire_Model_User
}
$this->setData('current_planet', $planet->getId());
$this->_currentPlanet = $planet;
return $this;
}
@ -271,15 +300,19 @@ class Legacies_Empire_Model_User
*/
public function getHomePlanet()
{
$planetId = $this->getData('id_planet');
if (!$planetId) {
return null;
}
if ($this->_homePlanet === null) {
$planetId = $this->getData('id_planet');
if (!$planetId) {
return null;
}
$planet = Legacies_Empire_Model_Planet::factory($planetId);
$planet = Legacies_Empire_Model_Planet::factory($planetId);
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return null;
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return null;
}
$this->_homePlanet = $planet;
}
return $planet;
@ -292,22 +325,29 @@ class Legacies_Empire_Model_User
*/
public function getCurrentPlanet()
{
$planetId = $this->getData('current_planet');
if ($this->_currentPlanet === null) {
$planetId = $this->getData('current_planet');
if (!$planetId) {
$planet = $this->getHomePlanet();
$this->setData('current_planet', $planet->getId())->save();
if (!$planetId) {
$this->_currentPlanet = $this->getHomePlanet();
$this->setData('current_planet', $this->_currentPlanet->getId())->save();
return $planet;
return $this->_currentPlanet;
}
$planet = Legacies_Empire_Model_Planet::factory($planetId);
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
$this->_currentPlanet = $this->getHomePlanet();
$this->setData('current_planet', $this->_currentPlanet->getId())->save();
return $this->_currentPlanet;
}
$this->_currentPlanet = $planet;
}
$planet = Legacies_Empire_Model_Planet::factory($planetId);
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return null;
}
return $planet;
return $this->_currentPlanet;
}
protected function _preparePlanetCollection()

View file

@ -0,0 +1,237 @@
<?php
/**
* Test class for Legacies_Object.
* Generated by PHPUnit on 2011-09-01 at 11:24:52.
*/
class Test_Legacies_Empire_Model_BuilderTest extends PHPUnit_Framework_TestCase
{
/**
* @var Legacies_Empire_Model_Planet
*/
protected $_planet = null;
/**
* @var Legacies_Empire_Model_User
*/
protected $_user = null;
protected $_class = 'Legacies_Empire_Model_BuilderAbstract';
protected $_queueItemsData = null;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->_planet = new Legacies_Empire_Model_Planet(array(
'id' => 1,
'id_owner' => 1
));
$this->_user = new Legacies_Empire_Model_User(array(
'id' => 1
));
$this->_planet->setUser($this->_user);
$this->_user->setCurrentPlanet($this->_planet);
$this->_user->setHomePlanet($this->_planet);
$this->_queueItemsData = array(
'IDX0001' => array(
'item_id' => 1,
'level' => 1,
'created_at' => 0,
'updated_at' => 0
),
'IDX0002' => array(
'item_id' => 1,
'level' => 2,
'created_at' => 100,
'updated_at' => 100
),
'IDX0003' => array(
'item_id' => 1,
'level' => 3,
'created_at' => 150,
'updated_at' => 150
)
);
}
protected function _getMockedInstance($planet, $user, $methods = array())
{
$reflector = new ReflectionClass($this->_class);
foreach ($reflector->getMethods() as $method) {
if ($method->isAbstract()) {
$methods[] = $method->getName();
}
}
if (empty($methods)) {
$methods = null;
}
return $this->getMock($this->_class, $methods, array($planet, $user));
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
public function testInit()
{
$stub = $this->getMockBuilder('Legacies_Empire_Model_BuilderAbstract')
->disableOriginalConstructor()
->setMethods(array('init', '_initItem', 'updateQueue', 'appendQueue', 'getResourcesNeeded', 'getBuildingTime'))
->getMock();
$stub->expects($this->once())
->method('init')
->will($this->returnValue($stub));
$stub->expects($this->never())
->method('_serializeQueue')
->will($this->returnValue($stub));
$stub->expects($this->never())
->method('_unserializeQueue')
->will($this->returnValue($stub));
$stub->__construct($this->_planet, $this->_user);
}
public function testSerializingQueue()
{
$items = array(
'IDX0001' => array(
'item_id' => 1,
'level' => 1,
'created_at' => 0,
'updated_at' => 0
),
'IDX0002' => array(
'item_id' => 1,
'level' => 2,
'created_at' => 100,
'updated_at' => 100
),
'IDX0003' => array(
'item_id' => 1,
'level' => 3,
'created_at' => 150,
'updated_at' => 150
)
);
$stub = $this->_getMockedInstance($this->_planet, $this->_user, array('_generateIndex'));
$stub->expects($this->exactly(3))
->method('_initItem')
->will($this->onConsecutiveCalls(
new Legacies_Empire_Model_Builder_Item($this->_queueItemsData['IDX0001']),
new Legacies_Empire_Model_Builder_Item($this->_queueItemsData['IDX0002']),
new Legacies_Empire_Model_Builder_Item($this->_queueItemsData['IDX0003'])
));
$stub->expects($this->exactly(3))
->method('_generateIndex')
->will($this->onConsecutiveCalls(
'IDX0001',
'IDX0002',
'IDX0003'
));
$stub->enqueue($this->_queueItemsData['IDX0001']);
$stub->enqueue($this->_queueItemsData['IDX0002']);
$stub->enqueue($this->_queueItemsData['IDX0003']);
$this->assertEquals(serialize($this->_queueItemsData), $stub->serialize());
}
public function testUnSerializingQueue()
{
$serializedData = serialize($this->_queueItemsData);
$stub = $this->_getMockedInstance($this->_planet, $this->_user, array('_generateIndex'));
$stub->expects($this->exactly(3))
->method('_initItem')
->will($this->onConsecutiveCalls(
new Legacies_Empire_Model_Builder_Item($this->_queueItemsData['IDX0001']),
new Legacies_Empire_Model_Builder_Item($this->_queueItemsData['IDX0002']),
new Legacies_Empire_Model_Builder_Item($this->_queueItemsData['IDX0003'])
));
$stub->expects($this->never())
->method('_generateIndex');
$stub->unserialize($serializedData);
$this->assertAttributeNotEmpty('_queue', $stub);
$this->assertEquals(serialize($this->_queueItemsData), $stub->serialize());
}
public function testUnSerializingQueueWithInvalidData()
{
$serializedData = '';
$stub = $this->_getMockedInstance($this->_planet, $this->_user, array('_generateIndex'));
$stub->expects($this->never())
->method('_initItem');
$stub->expects($this->never())
->method('_generateIndex');
$stub->unserialize($serializedData);
$this->assertAttributeEmpty('_queue', $stub);
$this->assertEquals('a:0:{}', $stub->serialize());
}
public function testInitItemReturningNull()
{
$serializedData = serialize($this->_queueItemsData);
$stub = $this->_getMockedInstance($this->_planet, $this->_user, array('_generateIndex'));
$stub->expects($this->exactly(3))
->method('_initItem')
->will($this->returnValue(null));
$stub->unserialize($serializedData);
$this->assertAttributeEmpty('_queue', $stub);
$this->assertEquals('a:0:{}', $stub->serialize());
}
public function testCheckAvailability()
{
$serializedData = serialize($this->_queueItemsData);
$stub = $this->_getMockedInstance($this->_planet, $this->_user, array('_generateIndex'));
$stub->expects($this->any())
->method('_initItem')
->will($this->onConsecutiveCalls(
new Legacies_Empire_Model_Builder_Item($this->_queueItemsData['IDX0001'])
));
$this->assertTrue($stub->checkAvailability(Legacies_Empire::ID_BUILDING_METAL_MINE));
$this->assertTrue($stub->checkAvailability(Legacies_Empire::ID_BUILDING_CRISTAL_MINE));
$this->assertTrue($stub->checkAvailability(Legacies_Empire::ID_BUILDING_DEUTERIUM_SYNTHETISER));
$this->assertTrue($stub->checkAvailability(Legacies_Empire::ID_BUILDING_FUSION_REACTOR));
}
}

View file

@ -0,0 +1,205 @@
<?php
/**
* Test class for Legacies_Object.
* Generated by PHPUnit on 2011-09-01 at 11:24:52.
*/
class Test_Legacies_ObjectTest extends PHPUnit_Framework_TestCase
{
/**
* @var Legacies_Object
*/
protected $_object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->_object = new Legacies_Object();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
/**
* @todo Implement testSetData().
*/
public function testSetData()
{
$this->assertAttributeEmpty('_data', $this->_object);
$this->_object->setData('test', true);
$expected = array('test' => true);
$this->assertAttributeEquals($expected, '_data', $this->_object);
$this->_object->setData('test', 'testing');
$expected = array('test' => 'testing');
$this->assertAttributeEquals($expected, '_data', $this->_object);
}
/**
* @requires testSetData
*/
public function testGetData()
{
$this->_object->setData('test', 'testing');
$this->assertEquals('testing', $this->_object->getData('test'));
$this->_object->setData('test', true);
$this->assertTrue($this->_object->getData('test'));
$this->assertNull($this->_object->getData('testing'));
}
/**
* @requires testSetData
* @requires testGetData
*/
public function testGetAllDatas()
{
$this->_object->setData('test', 'testing');
$expected = array('test' => 'testing');
$this->assertEquals($expected, $this->_object->getAllDatas());
$this->_object->setData('test', true);
$expected = array('test' => true);
$this->assertEquals($expected, $this->_object->getAllDatas());
}
/**
* @requires testSetData
* @requires testGetData
*/
public function testHasData()
{
$this->_object->setData('test', 'testing');
$this->assertTrue($this->_object->hasData('test'));
$this->assertFalse($this->_object->hasData('testing'));
}
/**
* @requires testSetData
*/
public function testAddData()
{
$this->_object->setData('test', 'testing');
$expected = array(
'test' => 'testing',
'testing' => true,
'legacies' => false
);
$this->_object->addData(array(
'testing' => true,
'legacies' => false
));
$this->assertAttributeEquals($expected, '_data', $this->_object);
$expected = array(
'test' => 'legacies',
'testing' => false,
'legacies' => 'Legacies_Object'
);
$this->_object->addData($expected);
$this->assertAttributeEquals($expected, '_data', $this->_object);
}
/**
* @requires testSetData
*/
public function testUnsetData()
{
$this->_object->setData('test', 'testing');
$this->_object->setData('testing', true);
$this->_object->setData('removed', 'me!');
$this->_object->setData('legacies', false);
$expected = array(
'test' => 'testing',
'testing' => true,
'legacies' => false
);
$this->_object->unsetData('removed');
$this->assertAttributeEquals($expected, '_data', $this->_object);
}
/**
* @todo Implement testClearData().
*/
public function testClearData()
{
$this->_object->setData('test', 'testing');
$this->_object->setData('testing', true);
$this->_object->setData('removed', 'me!');
$this->_object->setData('legacies', false);
$expected = array(
'test' => 'testing',
'testing' => true,
'legacies' => false
);
$this->_object->clearData();
$this->assertAttributeEmpty('_data', $this->_object);
}
/**
* @requires testSetData
* @requires testHasData
*/
public function testOffsetExists()
{
$this->_object->setData('test', 'testing');
$this->assertTrue(isset($this->_object['test']));
}
/**
* @requires testSetData
* @requires testGetData
*/
public function testOffsetGet()
{
$this->_object->setData('test', 'testing');
$this->assertEquals('testing', $this->_object['test']);
}
/**
* @requires testGetData
* @requires testSetData
*/
public function testOffsetSet()
{
$this->_object['test'] = 'testing';
$this->assertEquals('testing', $this->_object->getData('test'));
}
/**
* @requires testSetData
* @requires testGetData
*/
public function testOffsetUnset()
{
$this->_object->setData('test', 'testing');
unset($this->_object['test']);
$this->assertAttributeEmpty('_data', $this->_object);
$this->assertNull($this->_object->getData('test'));
}
}

View file

@ -0,0 +1,119 @@
<?php
class Test_LegaciesTest
extends PHPUnit_Framework_TestCase
{
protected function tearDown()
{
Legacies::clearAllListeners();
}
public function nonStaticListener($observer)
{
$observer->setData('success', true);
}
public static function staticListener($observer)
{
$observer->setData('success', true);
}
public function testRegisteringNonStaticEvent()
{
Legacies::registerListener('testing', array($this, 'nonStaticListener'));
$observer = Legacies::dispatchEvent('testing', array('success' => false));
$this->assertInstanceOf('Legacies_Core_Event', $observer);
$this->assertTrue($observer->getData('success'));
}
public function testRegisteringStaticEvent()
{
Legacies::registerListener('testing', array(get_class($this), 'staticListener'));
$observer = Legacies::dispatchEvent('testing', array('success' => false));
$this->assertInstanceOf('Legacies_Core_Event', $observer);
$this->assertTrue($observer->getData('success'));
}
public function testDispatchNonExistingEvent()
{
$observer = Legacies::dispatchEvent('testing', array('success' => true));
$this->assertInstanceOf('Legacies_Core_Event', $observer);
$this->assertTrue($observer->getData('success'));
}
/**
* @depends testRegisteringNonStaticEvent
*/
public function testUnregisteringNonStaticEvent()
{
Legacies::registerListener('testing', array($this, 'nonStaticListener'));
Legacies::clearEventListeners('testing');
$observer = Legacies::dispatchEvent('testing', array('success' => false));
$this->assertInstanceOf('Legacies_Core_Event', $observer);
$this->assertFalse($observer->getData('success'));
}
/**
* @depends testRegisteringStaticEvent
*/
public function testUnregisteringStaticEvent()
{
Legacies::registerListener('testing', array(get_class($this), 'staticListener'));
Legacies::clearEventListeners('testing');
$observer = Legacies::dispatchEvent('testing', array('success' => false));
$this->assertInstanceOf('Legacies_Core_Event', $observer);
$this->assertFalse($observer->getData('success'));
}
public function testGetSession()
{
$this->markTestSkipped('Sessions could not be tested in CLI.');
$this->assertInstanceOf('Legacies_Core_Model_Session', Legacies::getSession('test'));
}
public function testGetTranslator()
{
$this->assertInstanceOf('Legacies_Core_Model_Translator', Legacies::getTranslator('test'));
$this->assertInstanceOf('Legacies_Core_Model_Translator', Legacies::getTranslator());
}
public function testTranslate()
{
$this->assertEquals('My testing message!', Legacies::translate('test', 'My %s message!', array('testing')));
}
public function testTranslateGettextStyle()
{
$this->assertEquals('My testing message!', Legacies::__('My %s message!', 'testing'));
}
public function testSetDefaultLocale()
{
Legacies::setDefaultLocale('test');
$this->assertAttributeEquals('test', '_defaultLocale', 'Legacies');
}
/**
*
* @requires testSetDefaultLocale
*/
public function testGetDefaultLocale()
{
Legacies::setDefaultLocale('test');
$this->assertEquals('test', Legacies::getDefaultLocale());
}
}

View file

@ -0,0 +1,66 @@
<?php
set_include_path(implode(PATH_SEPARATOR, array(
dirname(__DIR__),
get_include_path()
)));
function frameworkAutoload($class) {
include_once str_replace('_', '/', $class) . '.php';
}
spl_autoload_register('frameworkAutoload');
include 'vfsStream/vfsStream.php';
vfsStream::create(array(
'includes' => array(
'application' => array(
'code' => array(
'community' => array(),
'core' => array(),
'libraries' => array(),
'local' => array(),
),
'design' => array(
'layouts' => array(),
'scripts' => array()
)
),
'data' => array(
'combat.php' => '<?php echo ' . var_export(array(), true),
'events.php' => '<?php echo ' . var_export(array(), true),
'fields-alias.php' => '<?php echo ' . var_export(array(), true),
'prices.php' => '<?php echo ' . var_export(array(), true),
'production.php' => '<?php echo ' . var_export(array(), true),
'requirements.php' => '<?php echo ' . var_export(array(), true),
'resources.php' => '<?php echo ' . var_export(array(), true),
'types.php' => '<?php echo ' . var_export(array(), true),
)
),
'config.php' => '<?php echo ' . var_export(array(
'global' => array(
'date' => array(
'timezone' => 'Europe/Paris'
),
'database' => array(
'engine' => 'mysql',
'options' => array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db_xnova'
),
'table_prefix' => 'game_',
),
'layout' => array(
'page' => 'page.php',
'empire' => 'empire.php'
)
)
), true) . ';'
), 'root', 644);
define('ROOT_PATH', vfsStream::url(''));
define('APPLICATION_PATH', vfsStream::url('includes/application'));