This is a documentation for Board Game Arena: play board games online !

BGA Studio Cookbook

Từ Board Game Arena
Bước tới điều hướng Bước tới tìm kiếm

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).

Dragonline font.png

.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;


Inject images and styled html in the log

Ingredients: ggg.js, ggg.game.php

So you want nice pictures in the game log, what do you do? First idea that come to mind is to send html from php in notifications. This is bad idea for many reasons

  • Its bad architecture, ui elements leak into server now you have to manage ui in many places
  • If you decided to change something in ui in future version, old games reply and tutorials may not work, since they use stored notifications
  • When you read log preview for old games its unreadable (this is log before you enter the game reply, useful for troubleshooting or game analysis)
  • Its more data to transfer and store in db
  • Its nightmare for translators

So what else can you do? I use this recipe which I is client side log injection. I intercept log arguments and replace them by html on my client side.

Clientloginjection.png

ggg.js

 

        /** Override this function to inject html for log items  */

        /* @Override */
        format_string_recursive : function(log, args) {
            try {
                if (log && args && !args.processed) {
                    args.processed = true;
                    args.You = this.divYou(); // will replace ${You} with colored version

                    // list of other known variables
                    var keys = ['place_name','token_name'];
                    
                  
                    for ( var i in keys) {
                        var key = keys[i];
                        if (typeof args[key] == 'string') {
                           args[key] = this.getTokenDiv(key, args);                            
                        }
                    }
                }
            } catch (e) {
                console.error(log,args,"Exception thrown", e.stack);
            }
            return this.inherited(arguments);
        },

        /* Implementation of proper colored You with background in case of white or light colors  */

        divYou : function() {
            var color = this.gamedatas.players[this.player_id].color;
            var color_bg = "";
            if (this.gamedatas.players[this.player_id] && this.gamedatas.players[this.player_id].color_back) {
                color_bg = "background-color:#" + this.gamedatas.players[this.player_id].color_back + ";";
            }
            var you = "<span style=\"font-weight:bold;color:#" + color + ";" + color_bg + "\">" + __("lang_mainsite", "You") + "</span>";
            return you;
        },



        getTokenDiv : function(key, args) {
            // ... implement whatever html you want here, example from sharedcode.js
            var token_id = args[key];
            var item_type = getPart(token_id,0);
            var logid = "log" + (this.globalid++) + "_" + token_id;
            switch (item_type) {
                case 'wcube':
                    var tokenDiv = this.format_block('jstpl_resource_log', {
                        "id" : logid,
                        "type" : "wcube",
                        "color" : getPart(token_id,1),
                    });
                    return tokenDiv;
                    break;
                case 'meeple':
                    if ($(token_id)) {
                        var clone = dojo.clone($(token_id));
    
                        dojo.attr(clone, "id", logid);
                        this.stripPosition(clone);
                        dojo.addClass(clone, "logitem");
                        return clone.outerHTML;
                    }
                    break;
     
                default:
                    break;
            }

            return "'" + this.clienttranslate_string(this.getTokenName(token_id)) + "'";
       },
       getTokenName : function(key) {
           return this.gamedatas.token_types[key].name; // get name for the key, from static table for example
       },

Note in this case server simply injects token_id as name, and client substitutes it for the real translated name or the picture

ggg.game.php:

          $this->notifyPlayer($player_id,'playerLog',clienttranslate('${You} moved cube'),['You'=>'You']);

ggg.game.php:

          $this->notifyAllPlayers('playerLog',clienttranslate('Game moves ${token_name}'),['token_name'=>$token_id]);

Now if you don't like raw log containing id instead of name but want name, and want substitution, you can use another parameter as id. The problem with that, it will work at first, but if you reload game using F5 you will loose your additional parameters, why? Because when game reloads it does not actually send same notifications, it sends special "hitstorical_log" notification where all parameters not listed in the "log" are removed. There is a hack (feature) to circumvent that, called recursive parameters. I.e. you can send stuff like this:

            $this->notifyAllPlayers('playerLog',clienttranslate('Game moves ${token_name_rec}'),
                   ['token_name_rec'=>['log'=>'${token_name}',
                                       'args'=> ['token_name'=>clienttranslate('Boo'), 'token_id'=>$token_id, 'i18n'=>['token_name'] ]
                                      ]
                   ]);

and in format_log_recursive

            var key = 'token_name';
            if (typeof args[key] == 'string' && typeof args['token_id'] == 'string') {
                args[key] = this.getTokenDiv('token_id', args);                            
            }

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.

Madeira board.png


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
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

Now how we represent resource counters such as bread? Using same table from we simply add special counter token for bread and use state to indicate the count. Note to keep first column unique we have to add player identification for that counter, i.e. ff0000 is red player.

token
token_key token_location token_state
bread_ff0000 tableau_ff0000 5


Variant 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);
resource
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
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

Ingredients: ggg.js

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).


Multi Step Interactions: Action Stack - Using Client States

Ingredients: ggg.js, ggg.game.php, material.inc.php

  • We have euro game where game actions consist of series of mini-actions, which can be triggered by multiple sources
  • Example: Russian RailRoads have multiple source of actions, such as worker slots, triggered advantages, triggered factory rewards, etc. Each of the consist of series of small action, such as "advance black rail + advance marker", once you start executing it, more mini-actions are triggered and added to the stack (in case of RRR its not a stack but a random access list but whatever)
  • Implementing such game with server states is rather difficult because
    • it require lots of states
    • require stack on the state machine to support return to the state we originated substate from
    • series can result in invalid game state (i.e. not allowed by rules), which it hard to roll back over multiple states
    • without undo it would be rather frustrating for the player, and undo is hard to implement

So this is how to implemented it using action stack and client states

Encode all mini-actions as identifier or a letter, I use letters personally

For each action, trigger, etc, define a "rules" of that game element using mini-action encoding and store in material.inc.php so both server and client have access to it, no need to store it in database, rules are not going to change during the game.

material.inc.php:

$this->token_types = array(
 ...
'slot_action_14' => array(
 'name' => clienttranslate("Industry Advancement"),
 'rules'=>"i",
),
'slot_action_15' => array(
 'name' => clienttranslate("2 Industry Advancements"),
 'rules'=>"ii",
),
'slot_action_16' => array(
 'name' => clienttranslate("Industry and Black Track Advancement"),
 'rules'=>"ib",
),
);


In game.php you send this to client ggg.game.php:

   protected function getAllDatas() {
       ...
       // this is material fields
       $result ['token_types'] = $this->token_types;
       ...
  }

In .js when client selects original action, you read this field and push actions into stack, something like

        this.pushOperations(this.gamedatas.token_types[action_id].rules);
        this.processAction();

And processAction() will allow user to deal with possible actions. If this is truly a stack you could have done something like

   processAction: function() {
        var op = this.popOperation();
        switch (op) {
             case 'i': 
               this.setClientState("client_playerTurnSelectAdvantageToken", {
                              descriptionmyturn : "${you} must select industry marker to move",
                          });
               break;
            ...
        }
   }

In Russian Railroads its unordered list, so it has to offer user all possible choices driven by current unprocessed operations, then determine what operation was that from the list based on what they clicked, i.e.

       onMoveable : function(event) {
                           ...
                           else if (id.startsWith('ind')) {
                               if (!this.commitOperation('i', id, place_id)) return;
                           }
                           this.gamedatas_local.tokens[id] = place_id; // alter local model
                           this.placeToken(id, place_id); // client side animation
                           if (this.checkAchievementMoveable(new_state, old_state, id)) { // that will check if something is triggered, so we can push more stuff on the stack
                              this.processAction();
                           }
        }

During client states data is collected and pushed into client array of performed operations, we also do client side animation and alter model, since we don't send intermediate steps to server.

In example above we check if we client on industry marker, we will "commit" "i" operation with selected id of the marker and place_id. The commit is just pushing this data into an array.

All this operations later are send to server, usually when user clicks Done. The data will be encoded for server to read into a string, i.e. i__ind2__indslot15, means move industry marker number 2 into slot 15 of industry track. And multiple operations can be separated by a space for example.

At anytime during client states user can click Cancel which will restore last server state and undo all client animation back to last stored state.

The only disadvantage of this method is you have to implement a lot of functionality two times - on server and client.