Alcarin Documentation

Transkrypt

Alcarin Documentation
Alcarin Documentation
Release 0.2.6
psychowico
December 28, 2013
Contents
1
Alcarin - Opowieść (pl)
1.1 Świat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 Życie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3
3
3
2
Mechanika gry
2.1 Czas . . . . . . .
2.2 Zwykli gracze . .
2.3 Substancje . . . .
2.4 System metryczny
.
.
.
.
5
5
6
6
7
3
Installation instructions
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9
9
9
4
Dev: How to?
4.1 How to define access permissions for page? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.2 How to add coffee/less files to project? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11
11
12
5
Programming
5.1 Preparing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2 Architecture design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.3 Guard configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13
13
14
14
6
AJAX programming
6.1 Urls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.2 RESTful requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17
17
17
7
Zend Framework 2 extensions
7.1 Controller Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.2 View Helpers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
19
19
19
8
Plugable game services
8.1 GameServiceContainer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.2 Custom GameObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
21
21
21
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
i
8.3
9
Common services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Logging
24
25
10 Forms
10.1 Default form fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.2 Registration custom validators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.3 Registration custom filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
27
27
27
28
11 Indices and tables
29
ii
Alcarin Documentation, Release 0.2.6
Alcarin will be a fantasy, persistent browser-based role-playing game. This documentation is divided into few parts.
I would eventually translate all docs to english, but for my convenience most parts will be only in polish until I
developing this project myself - sorry!
Contents:
Contents
1
Alcarin Documentation, Release 0.2.6
2
Contents
CHAPTER 1
Alcarin - Opowieść (pl)
Narazie wrzuc˛e tutaj troch˛e opisu świata gry i luźno powiazanych
˛
myśli, ta cz˛eść b˛edzie ważniejsza w przyszłości.
1.1 Świat
Świat w Alcarin nie przypomina naszej planety. Jest mieszanka˛ mitologii indyjskiej, ksia˛żek Tolkiena, Pratchett’a
i innych. Planeta ma kształt dysku, opiera si˛e o plecy czterech słonii, które stoja˛ na wielkich żółwiu pływajacym
˛
w przestrzeniach wszechświata. Światło i ciepło planecie daje olbrzymia latarnia znajdujaca
˛ si˛e na szczycie wielkiej
kolumny postawionej przez bogów w centrum świata. Latarnia ta pulsuje, tak że mamy atmosfer˛e podobna˛ do naszego
dnia i nocy. Jednak dzień trwa dwie nasze doby (48h), tak samo jak i noc. Z tego wynika, że pełny obrót latarnii zajmuje jej 4 doby czasu naszego świata. Na planecie nie ma wyraźnych pór roku, za to sa˛ obszary znacznie różniace
˛ si˛e
klimatem - na obrzeżach planety panuje wieczne zlodowacenie (dzi˛eki temu oceny nie “spływaja”),
˛ za to w okolicach
centrum mamy coś w rodzaju tropikalnej dżungli.
1.2 Życie
1.2.1 Rośliny
W świecie magii i pradawnych mocy czasem trudno określić, co jest roślina˛ a co zwierz˛eciem. Nie zdziw si˛e jeśli
b˛edzie zmuszony uciekać gdy w trakcie polowania spotkasz gigantyczne drzewo, któremu nie spodoba si˛e twoje
towarzystwo.
1.2.2 Zwierzeta
˛
Niektóre zwierz˛eta na tej planecie sa˛ odpowiednikiem żyjacych
˛
na ziemi, jednak spotkać można tam też wiele nieznanych nam istot. Zwierz˛eta potrafia˛ si˛e rozmnażać i czasem podróżować, ich aktywność (i co za tym idzie przykładowo szansa upolowania, albo niesione zagrożenie) może różnić si˛e zależnie od tego, czy trwa noc, czy też dzień.
1.2.3 Humanoidy
Na Alcarin można spotkać wi˛ecej niż jeden typ intelegintnych istot. Na pewno b˛eda˛ to elfy, krasnolodu i ludzie, jednak
być może potem znajdzie si˛e tego wi˛ecej.
3
Alcarin Documentation, Release 0.2.6
1.2.4 Nadprzyrodzone
Alcarin to świat magii i bogów. Chodź nie zdarza si˛e to cz˛esto, czasem można spotkać istoty wszechpot˛eżne, których
moc wydaje si˛e pochodzić od bóstw. Czasem niosace
˛ groz˛e, innym zaś razem ukojenie.
4
Chapter 1. Alcarin - Opowieść (pl)
CHAPTER 2
Mechanika gry
2.1 Czas
Pełen cykl dobowy b˛edzie trwał 24 * 4 = 96 godzin. Czyli dzień b˛edzie trwał dwie nasze doby, po którym nastapi
˛ noc,
trwajaca
˛ podobnie. Wszelkie wystapiania
˛
słowa “dzień” poniżej odnosza˛ si˛e do dnia świata gry.
W grze istnieje absolutny czas, zgodny w każdym fragmencie świata (z dokładnościa˛ do sekundy). Możemy także
określić czas lokalny - to jest zależny od pozycji w przestrzeni. Jest przydatny przykładowo przy obliczaniu oświetlenia. Godziny liczymy od 0 do 96, ale w świecie używamy określeń od 0 do 24 dniowa i od 0 do 24 nocna.
2.1.1 Współrzedne
˛
Świat używa kartezjańskiego systemu współrz˛ednych o odbitej osi Y, z punktem (0, 0) w centrum świata. Czyli Y
rośnie w dół mapy, X rośnie w jej prawa˛ stron˛e.
2.1.2 Oświetlenie
Świat Alcarin jest oświetlany przez Wielka˛ Latarni˛e (Great Lighthouse) postawiona˛ w jego centrum poprzez bogów.
Latarnia jest umiejscowiona na olbrzymim tworze skalnym o prawie płaskich ścianach, o wysokości około 5 kilometrów i szerokości przy podstawie około jednego kilometra. Jest także źródłem ciepła - tereny położone najbliżej jej
przypominaja˛ okolice równikowe na Ziemi - zaś ziemie położone najdalej - Antarktyd˛e.
Wielka Latarnia cyklicznie pulsuje, świecac
˛ przez 48h i gasnac
˛ na kolejne 48h - tworzac
˛ w ten sposób system dobowy.
Pory Dnia
Godzin˛e 0 uznajemy za poczatek
˛ dnia. Latarnia wtedy si˛e rozgrzewa, zaczyna robić si˛e jasno. Pory prezentuja˛ si˛e
nast˛epujaco:
˛
• od 44N.(nocnej) do 4D.(dziennej) mamy poranek
• od 4D. do 44D. mamy pełni˛e dnia (pełne oświetlenie)
• od 44D. do 4N. mamy wieczór
• od 4N. do 44N. mamy noc (praktyczny brak oświetlenia)
5
Alcarin Documentation, Release 0.2.6
2.2 Zwykli gracze
Zwykły gracz może stworzyć do 3 postaci. Sa˛ dwie możliwości powstania postaci:
• zamieszkanie w ciele 5-letniego dziecka (wymaga istnienia takie dziecka w świecie, prawdopodbnie b˛edzie
si˛e wiazała
˛
z długim oczekiwaniem)
• przebudzenie si˛e postaci w wieku 20 lat, w jakiś fabularny sposób, zależnie od rasy
Postacie żyja˛ normalnie około 90 dni, po czym zaczynaja˛ si˛e starzeć. W wieku 140 dni sa˛ już zupełnie słabi i podatni
na wszelkie słabości, moga˛ zginać
˛ od zadrapań etc. Gdyby jakaś postać dożyła 200 dni, od tej granicy codziennie ma
5% szans na naturalna˛ śmierć. Konsekwencja˛ starzenia jest osłabienie wszelkich zdolności(szczególnie siły fizycznej)
jednak z pami˛etanym “najwyższym” poziomem i możliwościa˛ uczenia innych według niego.
2.3 Substancje
Na poczatek
˛ mały słowniczek:
• substancja - dowolny typ obiektu, tak surowiec, jak przedmiot
• obiekt - instancja substancji
• cechy - zbiór właściwości określajacy
˛ możliwość interakcji obiektu ze światem, jak jego palność, wytrzymałość,
czy twardość. Od tego zależy, jak dobrze b˛edzie si˛e palił dany obiekt etc.
• źródło - abstrakcyjne poj˛ecie określajace
˛ zbiór substancji jakie moga˛ być pozyskiwane. źródła przypisuje si˛e do
określonych obszarów
Stwierdziliśmy, że wszelkie używalne surowce jak i szeroko rozumiane narz˛edzia b˛eda˛ należeć do tej samej grupy substancji. Można je uzyskać na jeden z dwóch sposobów: pozyskać ze źródła, lub wyprodukować (prawdopodobnie
przy użyciu innych substancji i narz˛edzi). Substancje charakteryzuja˛ si˛e nast˛epujacymi
˛
właściwościami:
• nazwa (name) - unikalna nazwa bazowa substancji (np. hammer)
• etykieta(label) - tłumaczalny ciag
˛ używany do wygenerowania nazwy substancji w grze, z użyciem jej głównego
składnika (np. “{{material}} młotek”)
• opis(description) - słowny opis wygladu
˛ i podstawowych właściwości substancji
• stan skupienia(state of matter) - stan skupienia materii, jeden z czterech:
– gazowy(gas) - przenoszony jedynie w dedykowanych pojemnikach, samoczynnie po prostu rozpływa
si˛e w powietrzu
– ciekły(liquid) - przenoszony w wi˛ekszości pojemników, samoczynnie rozlewa si˛e i zatraca
– sypki(powder) - może leżeć na ziemi w dowolnej ilości, zmienny kształt
– sztuki(units) - jako jedyny liczony w sztukach, a nie w pojemnikach (czyli niedoszacowanej obj˛etości,
sprawdź dokument “System metryczny”); może leżeć na ziemi i być noszony w pojemnikach, cz˛esto
duża obj˛etość wzgl˛edem masy
• cechy(properties) - zbiór właściwości określajacy
˛ możliwość interakcji obiektu ze światem, jak jego palność,
wytrzymałość, czy twardość. Od tego zależy, jak dobrze b˛edzie si˛e palił dany obiekt etc. Obiekty pozyskiwane
ze źródeł przyjmuja˛ wartość tych właściwość zależnie od ustawień źródła. Obiekty tworzone przez postacie
zyskuja˛ je domyślnie przy pomocy obliczania średniej ważonej substancji użytych przy wytwarzaniu danego
obiektu. Jednak ka˛żda˛ z wartości cech konkretnej substancji można nadpisać własnym wzorem, używajacym
˛
wszelkich innych cech tej substancji.
6
Chapter 2. Mechanika gry
Alcarin Documentation, Release 0.2.6
• jakość(quality)- jakość jest specjalnym typem cechy. Charakteryzuje si˛e tym, że domyślnie nie jest obliczana
jedynie przy użyciu średniej ważonej jakości użytych substancji, ale także przy uwzgl˛ednieniu staranności pracy,
umiej˛etności rzemieślnika, jakości użytych narz˛edzi.
Jako źródło substancji rozumiemy abstrakcyjny zestaw informacji który może być wykorzystany do wygenerowania
określonych substancji z określonymi cechami(jak jakość, palność), o określonymi bogactwie etc.
Źródła składaja˛ si˛e z listy generowanych substacji (cz˛esto jednej). Samo źródła posiada jedynie podstawowe właściwości:
• etykieta(label) - domyślny tłumaczalny ciag
˛ używany do wygenerowania nazwy źródła substancji w grze (np.
“Las”, “Kopalnie”). Postacie powinny mieć możliwość zapami˛etywania własnej nazwy dla każdej instancji
źródła
• opis(description) - krótki opis fabularny źródła
Każdy z wpisów na liście substancji charakteryzuje si˛e nast˛epujacymi
˛
właściwościami:
• substancja (resource) - po prostu wcześniej przygotowany typ substancji
• bogactwo(richness) - podana jako sumaryczna dost˛epna masa tuż po stworzeniu zasobu
• odnawialność(recovery) - z jaka˛ szybkościa˛ źródło b˛edzie si˛e odnawiać przy pozostawieniu odłogiem - może
być to wzór wykorzystujacy
˛ inny współczynnik (tak, by po zupełnym wykarczowaniu lasów na danym obszarze
praktycznie przestały odrastać, etc. )
• cechy(properties) - zakresy cech substancji (także jako wzory) jakie moga˛ zostać otrzymane z tego źródła
Instancja źródła(source instance) wyróżnia si˛e od typu źródła posiadaniem informacji o stopniu zużycia każdej z
generowanych substancji.
2.4 System metryczny
Mierzenie wszystkich wag w dokładnych wartościach masy - np. w gramach, jak w Cantrze, jest nienaturalne i
powoduje różne głupie sytuacje w grze. Ogranicza ludziom wyobraźni˛e dokładnościa,˛ uniemożliwia oszukiwanie itp.
Postanowiliśmy, że nasz system powinien charakteryzować sie nast˛epujacymi
˛
cechami:
• brak konieczności używania dokładnej ilości zasobów
• brak stałej, dokładnej jednostki metrycznej (ze strony graczy) - zamiast tego używanie rozmaitych miarek bazowo “szczypty” i “garści” (potem innych pojemników)
• niedokładność miarek - zależnie od dokładności wykonania ten sam typ kubka może różnić si˛e obj˛etościa˛
• po stronie serwera wszelkie instancje pojemników maja˛ tak określona˛ pojemność (obj˛etość), jak i określona˛
ilość masy jaka˛ moga˛ pomieścić. w wielu przypadkach b˛edzie to bardzo duża masa i faktyczne znaczenie
b˛edzie miała obj˛etość
Szczegóły:
• istnieja˛ dwie typy naturalnych miarek: szczypta i garść
• każda postać ma troch˛e inna˛ garść/szczypt˛e
• szczypta to ( 4ml +/- 25%, czyli 3ml-5ml ) stała dla postaci
• garść to ( 100ml +/- 15%, czyli 85ml-115ml ) stała dla postaci
Osoba b˛edzie widziała zasoby w swoim inwentarzu, czy w otoczeniu poprzez najlepiej dopasowany pojemnik jaki
ma w plecaku (niech to b˛edzie taki, którego po przeliczeniu wychodzi wielokrotność surowców nabliższa liczbie
10). Jako, że projektów, których nie znamy nie możemy “używać” i rozumieć, w projektach pokazujemy nazwy tych
przedmiotów, jakie faktycznie zostały użyte w miarkach, które posiadamy. W stanie skupienia liczonym na sztuki
2.4. System metryczny
7
Alcarin Documentation, Release 0.2.6
(units) nie używamy miarek, ale po prostu liczby. Jednostki różnia˛ si˛e rozmiarowa,˛ znajduje to odzwierciedlenie
w ich opisie. Wszystkie miarki poza szczypta˛ (wyst˛epuje tylko w całości) i garścia˛ (pół garści lub cała) moga˛ być
prezentowane także w przybliżonych cz˛eściach: pełny, trzy czwarte, pół, jedna czwarta, pusty.
8
Chapter 2. Mechanika gry
CHAPTER 3
Installation instructions
3.1 Introduction
Alcarin is a complex, browser game based on ZF2 technology. Inspiration for creating it was Cantr, old, similar game
where characters live in more real environment.
3.2 Installation
3.2.1 Using Composer
The recommended way to get a working copy of this project is to clone the repository and use composer to install
dependencies:
(The self-update directive is to ensure you have an up-to-date composer.phar available.)
In second step you should copy all “dist” configuration files to you local and reconfigure their if needed. Fastest way
on linux is:
for i in config/autoload/*.dist; do cp "$i" "${i/.dist/}"; done
Finally, if you are on UNIX system, you will probably need give change owner for you data/cache directory, for this
same like you php server use. On apache this will probably work:
sudo chown www-data data/cache
3.2.2 Persistent system
Alcarin use MongoDB as his persistent system. You should install mongo server. If you need any configuration you
should looking in config/autoload/local.php file, under the key ‘mongo’.
3.2.3 Virtual Host
Afterwards, set up a virtual host to point to the public/ directory of the project and you should be ready to go!
9
Alcarin Documentation, Release 0.2.6
3.2.4 Administration
You will probably need user with all privilages to work easy and fast. You can create one by using console script, in
project main directory:
bin/createsu [email protected] test321
First argument will be super user email address, second - password. You can use any email and password you want.
At last you should run script which will initalize mongo db instance (indexes and similar).
bin/init\ db [email protected] test321
On linux you will probably need run above commands as system administrator.
10
Chapter 3. Installation instructions
CHAPTER 4
Dev: How to?
4.1 How to define access permissions for page?
When you define new controller, nobody have access to it. You need define how kind of permissions is needed to have
access to page. You do it by edit “config/autoload/global.php” file - in config controllers_access -> controllers.
For sampe, assume you define new controller in admin page:
<?php
return array(
...
’controllers’ => array(
’invokables’ => array(
...
’Admin\Controller\Test’
=> ’Admin\Controller\TestController’,
Now this page will be unaccessible - because all pages are unaccessible by default. You need define privilages for it.
In global.php:
<?php
return array(
...
’controllers_access’ => array(
’controllers’ => array(
...
’Admin\Controller\Test’
=> [],
By define empty array you will make this controller public accesible. To controll who have access to it, you need open
Core\Permission\Resource class and define new resource type (or use exists) for you controller.
<?php
class Resource
{
...
const ADMIN_TEST = 5;
...
public static $Descriptions = [
...
’Administrative’ => [
11
Alcarin Documentation, Release 0.2.6
...
Resource::ADMIN_TEST => ["Test privilage", "This is simple, test privilage."],
]
Resource::ADMIN_TEST is a constant with resource id, that must be unique resource representation (and must
be lower than Resource::RESOURCE_LIMIT). In $Description table you define informations that are use to display
resource in player privilages admin panel (/admin/users/{id}/privilages). Now you can set this resource obligation for
you new controller:
<?php
return array(
...
’controllers_access’ => array(
’controllers’ => array(
...
’Admin\Controller\Test’
=> [Resource::ADMIN_TEST],
Now only users with “Test privilage” option checked in privilages admin panel can request you new controller.
Remember that you can more than one resources obligation for you controller.
4.2 How to add coffee/less files to project?
First, you should prepare you guard to automatically compile LESS and COFFEE files. See there for details: Guard
configuration.
Now, you should choose module where you shoud logically add you code. In this module you open (or create)
static/coffee or static/less directory. There you can create subdirectories and put .coffee/.less files. They will be
automatically compiled - results will be stored in public/js/compiled_coffee \ public/js/compiled_less, with directory
and name exactly like original file - just with new extension - .js or .css.
Good practice is to create subdirectory with you module name in your static/coffee static/less. For sample, if you
create new less to manage orbis editor view, you should probably use path:
{Admin module path}/static/less/Admin/orbis.less
When you end editing this file you, save it and let guard do work you can find results in
/public/css/compiles_less/Admin/orbis.css
Now you need register this new libraries in our project. Let open config/autoload/minifier.global.php file and add js/css
file path to suitable section. Alcarin use AssetsCompiler js/css minify system. If you want learn more, read it docs.
12
Chapter 4. Dev: How to?
CHAPTER 5
Programming
Here you can found instruction about how prepare your environment to easy work with Alcarin code and what exacly
you should know to start.
5.1 Preparing
Base introduction you can find on Installation instructions page.
Alcarin has been written in PHP language, as persistent mechanism MongoDB has been used.
If you want developing new code you should have minimum knowledge about the following technologies:
• ZF2, php framework used to create this game, if you want to learn about it there is good place to start
• MongoDB, NoSQL database system. We use mongodb-php-odm php library from colinmollenhour, it is
easy and intuitive - if you know MongoDB
• CoffeeScript, this is a little language that compiles into JavaScript. Make work with JS much easier and
enjoyable
• LESS, the dynamic stylesheet language, compiling to CSS.
• TWIG, the flexible, fast, and secure template engine for PHP
• AngularJS, HTML enhanced for web apps
• Node.js, a server-side software system designed for writing scalable Internet applications, notably web
servers
• socket.io, aims to make realtime apps possible in every browser and mobile device, blurring the differences
between the different transport mechanisms
Read about guard configuration to make you life easier with automate compile LESS, COFFEE, docs and reloading
browser when you make any changes in project.
13
Alcarin Documentation, Release 0.2.6
5.2 Architecture design
5.2.1 ZF2 - Alcarin Web Page
Web interface for Alcarin game
https://github.com/psychowico/Alcarin
-
written
in
PHP.
You
can
found
code
on
github:
Note: You should have basic understand of Zend Framework 2 to read this.
We can recognize three part of application. This will be API, Web and Dev.
API
Api code should not provide any normal views, but only logic that can used to achive any action accesible in the game.
It use JSON to communicate with clients. Thanks to this later we can create another client tool (for sample application
written in java) to play Alcarin. All API modules should be stored in module/API directory. We use RESTful standard
to write our controllers in this app part.
Web
This is the main Alcarin web page. It contains all views and use API code to call game mechanic. You can find
there specific modules - with admin, game master, guest and normal player views. In modules we have additional,
not standard, .../static directory. Inside coffee and less files are store, they will be compiled to css/js and moved to
/public/.. directory.
Dev
Additional code that is useful to debugging and developing application, for sample mongo panel to ZendDeveloperTools.
Remember to read samples code before writing anything.
5.2.2 AlcarinGameplayServer
Server application writed in Node.js and socket.io. It provide real-time event-based communication system for main
Alcarin web interface page - character page. It listening on specific port, accepting browser connections and provide
communication between logged players without database.
5.3 Guard configuration
https://github.com/guard/guard
Guard is a command line tool to easily handle events on file system modifications. If you do not want waste you
time to recompiling your coffeescript, less files, RST docs or reloading web-browser after any changes in code - it is
something that you need. You need fallow guard installation instructions. Next you should install 4 plugins:
• guard-less to automatically compiles less (like lessc –watch)
• guard-coffeescript to automatically generates your JavaScripts from your CoffeeScripts
14
Chapter 5. Programming
Alcarin Documentation, Release 0.2.6
• guard-shell to automatically runs shell commands when watched files are modified
• guard-livereload to automatically reloads your browser when ‘view’ files are modified
You will find them on guard plugins page.
If you have all installed you can simply go to Alcarin main directory and write:
guard
And it is all. All your coffeescripts, less files and docs will be automatically recompiling. If you want use livereload
too (auto reload browser when your make changes in files) you will probably need a browser plugin, related with you
client type. Check on this site.
5.3. Guard configuration
15
Alcarin Documentation, Release 0.2.6
16
Chapter 5. Programming
CHAPTER 6
AJAX programming
On alcarin programming process you will often need AJAX methods - because one of our objectives is creating rich
user interface. Instead of default jquery ajax methods you should use one of two alcarin ajax managing ways. First is
RESTful style requests, second - event style requests. Second way is prefered when you create ajax-only controllers
(what you should do in most cases).
6.1 Urls
Transfering ajax targets urls by html data attributes and others html ways is trivial, awkward and time-consuming.
To make it easier we just simple put static urls to global accesible urls object. You will find it in ..Alcarin\static\coffee\urls.coffee. When you need new urls for your ajax calls, just add it to this object and use anywhere
in code.
6.2 RESTful requests
To use RESTful requests style first you prepare default Zend Restful Controller. To make work easier, you should
consider using Core\Controller\AbstractAlcarinRestfulController instead of default AbstractRestfulController. It implement all 4 defaults restful methods, so you not must implement them all (if you need only part of it). Moreover it
give you some better errors support (in JSON mode) and two shortcuts method:
• mongo() - returing mongodb object, our wrapper for default Mongo php drivers
• gameServices() -returning GameServiceContainer instance, use with our code subsystem: Plugable game services.
To work faster with JSON responses, you should use alcarin “json()” controller plugin. Here is few samples of use it:
6.2.1 Json Example
<?php
...
public function getList()
{
//this same like:
17
Alcarin Documentation, Release 0.2.6
//return $this->json()->__invoke(...);
//it will return jsonmodel
return $this->json([’text’ => ’this is page information’]);
}
As long as we using AngularJS js framework to ajax calls you should use angular $resource module (for REST
requests) or angular $http module (if you want make not-REST requests). Check their documentations for API and
examples.
18
Chapter 6. AJAX programming
CHAPTER 7
Zend Framework 2 extensions
When working with project many specific zf2 extensions has been created. They will be described here.
7.1 Controller Plugins
http://framework.zend.com/manual/2.2/en/modules/zend.mvc.plugins.html
Fast list:
• isAllowed - check that logged user is allowed to use specific $resource
• isJson - simple plugin that checking that actual request except “json” response (in ‘accept’ header)
• json - faster json responses, check this for sample: Json Example
• redirect - additional functionality for default zf2 redirect plugin
• responses - shortcut for returning non-200 html responses
• logger - plugin helpers to have easy access to logging system
7.2 View Helpers
http://framework.zend.com/manual/2.2/en/modules/zend.view.helpers.html
Fast list:
• player - return current player game object
• isAllowed - check that logged user is allowed to use specific $resource
• helpButton - auto-create dynamic help button for admin sites
• helpButton - auto-create dynamic help button for admin sites
• uri - extension for default zf2 url plugin
19
Alcarin Documentation, Release 0.2.6
20
Chapter 7. Zend Framework 2 extensions
CHAPTER 8
Plugable game services
8.1 GameServiceContainer
One of the objectives of the game engine is api divided into logical game modules. We achieve this by our Plugable
game services system. It consists of the following elements:
• GameServiceContainer - singleton class, that our plugable system heart
• GameObject - classes inherit from \Core\GameObject class
You can get GameServiceContainer from most place in our code by getting service_manager instance and use ‘gameservices’ key:
<?php
$game_services = $service_manager->get(’game-services’)
GameServiceContainer is lighter, faster (and less functional) version of ZF2 ServiceManager. You can use it to retrieve
registered GameObject’s. For sample:
<?php
//this will get for us instance of EngineBase\GameObject\Players class.
$players
= $game_services->get(’players’);
$logged_user = $players->current();
GameServiceContainer will load required class only when it will be needed - all services are lazy loaded.
8.2 Custom GameObjects
Often you need add you own GameObject service. For sample, you create this simple class, in hypothetical module
“Test”;
<?php
namespace Test;
class RealWorldTime extends \Core\GameObject
{
public function current()
{
return time();
21
Alcarin Documentation, Release 0.2.6
}
}
Note that it inherit from \Core\GameObject. Now, to get this class from GameServiceContainer you need register it.
It can be done in two ways - first is adding configuration key to you module.config.php file.
<?php
return array(
...
’game-modules’ => array(
’TestModule’ => array(
’discription’ => ’Our testing module’,
’game-objects’ => array(
’real-world-time’ => ’Test\RealWorldTime’,
),
),
),
In our example we name our module “TestModule”. Module name should be unique - or they will be merged and
regard as one module. You can give any module description you want. ‘real-world-time’ is a key that you can use to
retrieve you GameObject from GameServiceContainer.
You can do this same by adding getGameModuleConfig() method to any of your ‘Module’ main class. For sample:
<?php
namespace Test;
class Module
{
...
public function getGameModuleConfig()
{
return array(
’TestModule’ => array(
’discription’ => ’Our testing module’,
’game-objects’ => array(
’real-world-time’ => ’Test\RealWorldTime’,
),
),
);
)
...
}
Next it is simple - you can retrieve you game object by his key.
<?php
//this will get for us instance of Test\RealWorldTime class.
$time
= $game_services->get(’real-world-time’);
$current_time = $time->current();
So let go next. We want possibility to extending our game objects from another modules. So we can, for example,
giving our plugin possibility to returning inner game time. We can do this by prepare next class with method that
returning it:
22
Chapter 8. Plugable game services
Alcarin Documentation, Release 0.2.6
<?php
namespace Test;
class RealWorldTimeExt extends \Core\GameObject
{
public function current()
{
//this only sample, not existed mongo table.
$data = $this->mongo()->gametime->findOne([]);
return $data[’current_time’];
}
}
First you should note, than our GameObject extension inherit from \Core\GameObject. It is not necessery - but give
us few benefits in form of basis methods that we can use:
• mongo() - returning \Mongo_Database class, our php mongo connection
• parent() - returing this extension parent object, null if it is root GameObject
• has($ext_name) - return true, if this game object has extension with specific name
• getServicesContainer() - returning our GameServiceConteiner object
When you done writing our class you need register it in similar way like normal GameObject. You just need use
diffrent key name:
<?php
’game-modules’ => array(
’TestModule’ => array(
’discription’ => ’Our testing module’,
’game-objects’ => array(
’real-world-time’ => ’Test\RealWorldTime’,
),
’game-objects-ext’ => array(
’Test\RealWorldTime’ => array(
’game’ => ’Test\ReadlWorldTimeExt’
),
),
),
),
This mean that you register Test\ReadlWorldTimeExt extension for GameObject Test\RealWorldTime and you call it
“game”. Now you can use it like in this example:
<?php
//this will get for us instance of Test\RealWorldTime class.
$time
= $game_services->get(’real-world-time’);
$current_time = $time->current();
$current_game_time = $time->game()->current();
If you need check game modules configuration you can retrieve it from service manager, like with all zf2 configuration
entries:
<?php
$game_modules_info = $service_manager->get(’config’)[’game-modules’];
$test_description = $game_modules_info[’TestModule’][’discription’];
echo $test_description;
8.2. Custom GameObjects
23
Alcarin Documentation, Release 0.2.6
8.3 Common services
There will described common services that can be get by GameServiceContainer. To load it call GameServiceContainer get method with lowercase module name.
8.3.1 Time
Give information about game world time. Available methods:
• timestamp() - seconds from world begining
• day() - days from world begining, remember that game day is equal to four real time days
• hour() - full hour of day (0-95)
• min() - minutes of hour (0-59)
• sec() - seconds of minute (0-59)
• freeze() - freeze game time, all events will be stoped
• unfreeze() - unfreeze game time, all events will be resume
• isFreezed() - inform about game time freeze state
8.3.2 Players
Managing players. Available methods:
• current() - current player
• get($id) - specific player
Methods returns EngineBaseGameObjectPlayer objects. It provides some basic information about player.
8.3.3 Properties
Giving some global world properties. Available methods:
• radius() - game world radius
• get($key) - get specific property value
• set($key) - set specific property value
• find() - return all properties
24
Chapter 8. Plugable game services
CHAPTER 9
Logging
Logs are needed to make developing process easier and have place where you can check critical application errors info
when you can not repeat it by youself. Zend framework 2 provide nice logging classes, you can read about it in official
zf2 manual.
In Alcarin game you can get logger class by ‘system-logger’ key.
<?php
$logger = $service_manager->get(’system-logger’);
$logger->debug(’test debug message’);
...
//in controllers you can use our controller log plugin:
$this->log()->debug(’test debug message from controller’);
You can use all standard \Zend\Log\Logger methods, like debug, info, warn etc. To configure you local log system
you should edit following lines in you local.php file:
<?php
return array(
...
’logs’ => array(
’writers’
=> array(
’mongo-log-writer’ => array(
’service’
=> ’mongo-log-writer’,
’min-priority’ => Zend\Log\Logger::ERR,
),
’stream’
=> array(
’type’
=> ’stream’,
’stream’
=> __DIR__ . ’/../../data/logs/alcarin.log’,
’min-priority’ => Zend\Log\Logger::INFO,
),
’debug-stream’
=> array(
’type’
=> ’stream’,
’stream’ => __DIR__ . ’/../../data/logs/debug.log’,
),
)
),
In this sample I added 3 logging output writers:
25
Alcarin Documentation, Release 0.2.6
• ‘mongo-log-writer’ - alcarin logger, log things to default mongo database, to “logs” table
• ‘stream’ - simple log to file, but only **information* and more priority logs
• *‘debug-stream’ - simple log to file all logs
Of course you can define you own writers, read more in zf2 docs if you want it. Remember that you php server need
write privilages to output files.
If you work on UNIX system it would make you job easier to follow all logs in realtime. If you define loggers like in
sample, you can do this by use tail unix cmd.
cd /alcarin/project/dir
tail -f data/logs/debug.log
26
Chapter 9. Logging
CHAPTER 10
Forms
In alcarin project we prefer using zf2 annotations form system instead of standard form system.
Alcarin code has prepared some facilities to make working with annotations forms easier. First, you should use
\Core\Service\AnnotationBuilderService builder class instead of zf2 default AnnotationBuilder class. You can use it
similar normal AnnotationBuilder:
<?php
$builder = $this->getServiceLocator()->get(’AnnotationBuilderService’);
$form
= $builder->createForm(new \Module\Form\MyFormName());
But it give you few additional benefits:
• default form fields
• registration custom validators
• registration custom filters
10.1 Default form fields
By default AnnotationBuilderService createForm method adding default fields to any created form.
Core\Form\DefaultFieldset class as base form. You can control this behaviour by createForm arguments:
It use
<?php
...
$submit_button_caption = ’Confirm’;
$use_default_fields = true;
$form_ann = new \Module\Form\MyFormName();
$form = $builder->createForm($form_ann, $use_default_fields, $submit_button_caption);
10.2 Registration custom validators
It is often case that you need add some custom validators to you form. You can do this by:
27
Alcarin Documentation, Release 0.2.6
<?php
...
$builder->registerCustomValidator(’CheckIt’, ’Module\Validator\MyTestValidator’);
...
//and in form class you now can add validator annotation:
/**
* @Annotation\Type("text")
* @Annotation\Validator({"name":"CheckIt"})
*/
public $username;
10.3 Registration custom filters
Registration of custom filters is similar like registration of custom validators:
<?php
$builder->registerCustomFilter(’FilterIt’, ’Module\Filter\MyTestFilter’);
28
Chapter 10. Forms
CHAPTER 11
Indices and tables
• genindex
• search
29

Podobne dokumenty