This is a documentation for Board Game Arena: play board games online !
BGA Studio Cookbook — разлика између измена
Нема описа измене |
|||
Ред 379: | Ред 379: | ||
* Transition to new client state | * Transition to new client state | ||
onWorker: function(e) { | onWorker: function(e) { | ||
var id = event.currentTarget.id; | |||
this.clientStateArgs.worker_id = | dojo.stopEvent(event); | ||
... // do validity checks | |||
this.clientStateArgs.worker_id = id; | |||
this.setClientState("client_playerPicksLocation", { | this.setClientState("client_playerPicksLocation", { | ||
descriptionmyturn : "${you} must select location", | descriptionmyturn : "${you} must select location", | ||
Ред 387: | Ред 389: | ||
* Have a handler for onUpdateActionButtons for client_playerPicksLocation to activate all possible locations this worker can go AND add Cancel button (see below) | * Have a handler for onUpdateActionButtons for client_playerPicksLocation to activate all possible locations this worker can go AND add Cancel button (see below) | ||
* Have a location handler which will eventually send a server request, using stored this.clientStateArgs.worker_id as worker id | * Have a location handler which will eventually send a server request, using stored this.clientStateArgs.worker_id as worker id | ||
* The cancel button should call a method to restore server state, also if you doing it for more than one state you | * The cancel button should call a method to restore server state, also if you doing it for more than one state you can add this universally using this.on_client_state check | ||
Верзија на датум 28. новембар 2017. у 13:58
This page is collection of design and implementation recipes for BGA Studio framework. For tooling and usage recipes see Tools and tips of BGA Studio. If you have your own recipes feel free to edit this page.
Visual Effects, Layout and Animation
Create pieces dynamically (using template)
Ingredients: ggg_ggg.tpl, ggg.js
Note: this method is recommended by BGA guildlines
Declared js template with variables in .tpl file, like this
<script type="text/javascript"> // Javascript HTML templates var jstpl_ipiece = '<div class="${type} ${type}_${color} inlineblock" aria-label="${name}" title="${name}"></div>'; </script>
Use it like this in .js file
div = this.format_block('jstpl_ipiece', { type : 'meeple', color : 'ff0000', name : 'Bob', });
Then you do whatever you need to do with that div, this one specifically design to go to log entries, because it has embedded title (otherwise its a picture only) and no id.
Note: you could have place this variable in js itself, but keeping it in .tpl allows you to have your js code be free of HTML. Normally it never happens but it is good to strive for it. Note: you can also use string concatenation, its less readable. You can also use dojo dom object creation api's but its brutally verbose and its more unreadable.
Create pieces dynamically (using string concatenation)
Ingredients: ggg.js
Note: Not recommended
div = "<div class='meeple "+color+"'></div>";
Create all pieces statically
Ingredients: ggg_ggg.tpl, ggg.css, ggg.view.php (optional)
- Create ALL game pieces in html template (.tpl)
- ALL pieces should have unique id, and it should be meaningful, i.e. meeple_red_1d
- Do not use inline styling
- Id of player's specific pieces should use some sort of 'color' identification, since player id cannot be used in static layout, you can use english color name, hex 6 char value, or color "number" (1,2,3...)
- Pieces should have separated class for its color, type, etc, so it can be easily styled in groups. In example below you now can style all meeples, all red meeples or all red tokens, or all "first" meeples
in .tpl file:
<div id="home_red" class="home red"> <div id="meeple_red_1" class="meeple red n1"></div> <div id="meeple_red_2" class="meeple red n2"></div> </div>
in .css file:
.meeple { width: 32px; height: 39px; background-image: url(img/78_64_stand_meeples.png); background-size: 352px; } .meeple.red { background-position: 30% 0%; }
- There should be straight forward mapping between server id and js id (or 1:1)
- You place objects in different zones of the layout, and setup css to take care of layout
.home .meeple{ display: inline-block; }
- If you need to have a temporary object that look like original you can use dojo.clone (and change id to some temp id)
- If there is lots of repetition or zone grid you can use template generator, but inject style declaration in css instead of inline style for flexibility
Note:
- If you use this model you cannot use premade js components such as Stock and Zone
- You have to use alternative methods of animation (slightly altered) since default method will leave object with inline style attributes which you don't need
Use thematic fonts
Ingredients: ggg.css
Sometime game elements use specific fonts of text, if you want to match it up you can load some specific font (from some free font source).
.css
/* latin-ext */ @font-face { font-family: 'Qwigley'; font-style: normal; font-weight: 400; src: local('Qwigley'), local('Qwigley-Regular'), url(https://fonts.gstatic.com/s/qwigley/v6/2Dy1Unur1HJoklbsg4iPJ_Y6323mHUZFJMgTvxaG2iE.woff2) format('woff2'); unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF; } /* latin */ @font-face { font-family: 'Qwigley'; font-style: normal; font-weight: normal; src: local('Qwigley'), local('Qwigley-Regular'), url(https://fonts.gstatic.com/s/qwigley/v6/gThgNuQB0o5ITpgpLi4Zpw.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000; } @font-face { font-family: 'Qwigley'; font-style: normal; font-weight: normal; src: local('Qwigley'), local('Qwigley-Regular'), url(http://ff.static.1001fonts.net/q/w/qwigley.regular.ttf) format('ttf'); } .zone_title { display: inline-block; position: absolute; font: italic 32px/32px "Qwigley", cursive; height: 32px; width: auto; }
Use player color in template
Ingredients: ggg_ggg.tpl, ggg.view.php
.view.php:
function build_page($viewArgs) { // Get players & players number $players = $this->game->loadPlayersBasicInfos(); $players_nbr = count($players); /** * ********* Place your code below: *********** */ // Set PCOLOR to the current player color hex global $g_user; $cplayer = $g_user->get_id(); if (array_key_exists($cplayer, $players)) { // may be not set if spectator $player_color = $players [$cplayer] ['player_color']; } else { $player_color = 'ffffff'; // spectator } $this->tpl ['PCOLOR'] = $player_color;
.tpl
<div id="hand" class="color_{PCOLOR}"></div>
Game Model and Database design
Database for The euro game
Lets say we have a game with workers, dice, tokens, board, resources, money and vp. Workers and dice can be placed in various zones on the board, and you can get resources, money, tokens and vp in your home zone. Also tokens can be flipped or not flipped.
Now lets try to map it, we have
- (meeple,zone)
- (die, zone, sideup)
- (resource cube/money token/vp token,player home zone)
- (token, player home zone, flip state)
We can notice that resource and money are uncountable, and don't need to be track individually so we can replace our mapping to
- (resource type/money,player home zone, count)
And vp stored already for us in player table, so we can remove it from that list.
Now when we get to encode it we can see that everything can be encoded as (object,zone,state) form, where object and zone is string and state is integer. The resource mapping is slightly different semantically so you can go with two table, or counting using same table with state been used as count for resources.
So the piece mapping for non-grid based games can be in most case represented by (string: token_key, string: location, int: state), example of such database schema can be found here: dbmodel.sql and class implementing access to it here table.game.php.
Variant 1: Minimalistic
CREATE TABLE IF NOT EXISTS `token` ( `token_key` varchar(32) NOT NULL, `token_location` varchar(32) NOT NULL, `token_state` int(10), PRIMARY KEY (`token_key`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
token_key | token_location | token_state |
---|---|---|
meeple_red_1 | home_red | 0 |
dice_black_2 | board_guard | 1 |
dice_green_1 | board_action_mayor | 3 |
bread | home_red | 5 |
Variant 2.1: Additional resource table, using same location as token table
CREATE TABLE IF NOT EXISTS `resource` ( `resource_type` varchar(32) NOT NULL, `resource_location` varchar(32) NOT NULL, `resource_count` int(10) signed NOT NULL, PRIMARY KEY (`resource_type`,`resource_location`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
resource_type | resource_location | resource_count |
---|---|---|
bread | home_red | 5 |
Variant 2.2: Additional resource table, resource count for each player id
CREATE TABLE IF NOT EXISTS `resource` ( `player_id` int(10) unsigned NOT NULL, `resource_key` varchar(32) NOT NULL, `resource_count` int(10) signed NOT NULL, PRIMARY KEY (`player_id`,`resource_key`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE resource ADD CONSTRAINT fk_player_id FOREIGN KEY (player_id) REFERENCES player(player_id);
player_id | resource_key | resource_count |
---|---|---|
123456 | bread | 5 |
Variant 3: More normalised
This version is similar to "card" table from hearts tutorial, you can also use exact cards database schema and Deck implementation for most purposes (even you not dealing with cards).
CREATE TABLE IF NOT EXISTS `token` ( `token_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `token_type` varchar(16) NOT NULL, `token_arg` int(11) NOT NULL, `token_location` varchar(32) NOT NULL, `token_state` int(10), PRIMARY KEY (`token_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
token_id | token_type | token_arg | token_location | token_state |
---|---|---|---|---|
22 | meeple | 123456 | home_123456 | 0 |
23 | dice | 2 | board_guard | 1 |
26 | dice | 1 | board_action_mayor | 3 |
49 | bread | 0 | home_123456 | 5 |
Advantages of this would be is a bit more straightforward to do some queries in db, disadvantage its hard to read (as you can compare with previous example, you cannot just look at say, ah I know what it means). Another questionable advantage is it allows you to do id randomisation, so it hard to do crafted queries to cheat, the down side of that you cannot understand it either, and handcraft db states for debugging or testing.
Database for The card game
Lets say you have a standard card game, player have hidden cards in hand, you can draw card from draw deck, play card on tableau and discard to discard pile. We have to design database for such game.
In real word to "save" the game we take a picture a play area, save cards from it, then put away draw deck, discard and hand of each player separately and mark it, also we will record current scoring (if any) and who's turn was it.
- Framework handles state machine transition, so you don't have to worry about database design for that (i.e. who's turn it is, what phase of the game we are at, you still have to design it but part of state machine step)
- Also framework supports basic player information, color, order around the table, basic scoring, etc, so you don't have to worry about it either
- The only thing you need in our database is state of the "board", which is "where each pieces is, and in what state", or (position,rotation) pair.
Lets see what we have for that:
- The card state is very simple, its usually "face up/face down", "tapped/untapped", "right side up/up side down"
- As position go we never need real coordinates x,y,z. We need to know what "zone" card was, and depending on the zone it may sometimes need an extra "z" or "x" as card order. The zone position usually static or irrelevant.
- So our model is: we have cards, which have some attributes, at any given point in time they belong to a "zone", and can also have order and state
- Now for mapping we should consider what information changes and what information is static, later is always candidate for material file
- For dynamic information we should try to reduce amount of fields we need
- we need at least a field for card, so its one
- we need to know what zone cards belong to, its 2
- and we have possibly few other fields, if you look closely at you game you may find out that most of the zone only need one attribute at a time, i.e. draw pile always have cards face down, hand always face up, also for hand and discard order does not matter at all (but for draw it does matter). So in majority of cases we can get away with one single extra integer field representing state or order
- In real database both card and zone will be integers as primary keys referring to additional tables, but in our case its total overkill, so they can be strings as easily
Variant 1: Minimalistic
CREATE TABLE IF NOT EXISTS `card` ( `card_key` varchar(32) unsigned NOT NULL, `card_location` varchar(32) NOT NULL, `card_state` int(11) NOT NULL, PRIMARY KEY (`card_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Variant 2: More normalised
This version supported by Deck php class, so unless you want to rewrite db access layer go with this one
CREATE TABLE IF NOT EXISTS `card` ( `card_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `card_type` varchar(16) NOT NULL, `card_type_arg` int(11) NOT NULL, `card_location` varchar(16) NOT NULL, `card_location_arg` int(11) NOT NULL, PRIMARY KEY (`card_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Note: if you using this schema, some zones/locations have special semantic. The 'hand' location is actually multiple locations - one per player, but player id is encoded as card_location_arg. If 'hand' in your game is ordered, visible or can have some other card states, you cannot use hand location (replacement is hand_<player_id> or hand_<color_id>)
Assorted Stuff
Multi Step Interactions: Select Worker/Place Worker - Using Client States
I don't think its documented feature but there is a way to do client-only states, which is absolutely wonderful for few reasons
- When player iteration is two step process, such as select worker, place worker, or place worker, pick one of two resources of your choice
- When multi-step process can result of impossible situation and has to be undone (by rules)
- When multi-step process is triggered from multiple states (such as you can do same thing as activated card action, pass action or main action)
So lets do Select Worker/Place Worker
Define your server state as usual, i.e. playerMainTurn -> "You must pick up a worker". Now define a client state, we only need "name" and "descriptionmyturn", lets say "client_playerPicksLocation". Always prefix names of client state with "client_" to avoid confusion. Now we have to do the following:
- Have a handler for onUpdateActionButtons for playerMainTurn to activate all possible workers he can pick
- When player clicks workers, remember the worker in one of the members of the main class, I usually use one called this.clientStateArgs.
- Transition to new client state
onWorker: function(e) { var id = event.currentTarget.id; dojo.stopEvent(event); ... // do validity checks this.clientStateArgs.worker_id = id; this.setClientState("client_playerPicksLocation", { descriptionmyturn : "${you} must select location", }); }
- Have a handler for onUpdateActionButtons for client_playerPicksLocation to activate all possible locations this worker can go AND add Cancel button (see below)
- Have a location handler which will eventually send a server request, using stored this.clientStateArgs.worker_id as worker id
- The cancel button should call a method to restore server state, also if you doing it for more than one state you can add this universally using this.on_client_state check
if (this.isCurrentPlayerActive()) { if (this.on_client_state && !$('button_cancel')) { this.addActionButton('button_cancel', _('Cancel'), dojo.hitch(this, function() { this.restoreServerGameState(); })); } }
Note: usually I call my own function call this.cancelLocalStateEffects() which will do more stuff first then call restoreServerGameState(), same function is usually needs to be called when server request has failed (i.e. invalid move)
Note: If you need more than 2 steps, you may have to do client side animation to reflect the new state, which gets trickier because you have to undo that also on cancellation.
Code is available here sharedcode.js (its using playerTurnPlayCubes and client_selectCubeLocation).