WGo.js javascript library for game of go

WGo.js API reference

Global constants

WGo.version

Actual version of WGo player


WGo.about

Information text about WGo


WGo.B

Constant for black color.


WGo.W

Constant for white color.


WGo.DIR

Directory of WGo.js file.


WGo.opera

True if current browser is Opera.


WGo.webkit

True if current browser is Webkit browser.


WGo.mozilla

True if current browser is Firefox.


WGo.msie

True if current browser is IE.


WGo.lang

Language of the WGo. Default is en. You can change this variable, but WGo.i18n[WGo.lang] should exist.


WGo.i18n

Object with terms. Its structure is like this: {en: {key1: term1, ... , keyN: termN}}. All output texts should be saved in this object in order to be translated. If you want to add support of your language you can extend this object.


Global properties

WGo.ERROR_REPORT boolean

If set true users will see all errors, otherwise they stay hidden. Actually it does nothing in standalone WGo.js, however WGo.js Player use this constant. Default: true.

Global functions

WGo.extendClass(parent, child)

Helper function for class inheritance.

Arguments
  • parent Function
    Constructor of parent class.
  • child Function
    Constructor of child class - this class inherits methods from parent class.
Return
Function Child constructor.

WGo.clone(obj)

Helper function for deep copy of simple JSON-like objects.

Arguments
  • obj Object
    Object to be cloned.
Return
Object Clone of the object.

WGo.filterHTML(html)

Escapes html tags in text. To avoid XSS.

Arguments
  • html string
    HTML text to be filtered.
Return
string Safe text.

WGo.t(key[, arg1, ..., argN])

Function for output. It returns appropriate term in currently active language.

Arguments
  • key String
    Key of the term.
  • args String
    Additional arguments. If specified, characters $ in target term will be replaced by arguments. First $ is replaced with arg1, second $ with arg2 etc.
Return
string Appropriate term. At first variable WGo.i18n[WGo.lang][key] is checked, then WGo.i18n.en[key]. If both variables are undefined it returns argument key.

WGo.Board

WGo.Board is a class that produces HTML5 canvas go board. Through its interface you can add and remove objects like stones on the board.

Board consists of 3 canvas layers. Bottom layer contains a grid, second layer is for stone's shadows and finally the topmost layer is for stones and other objects. However you can add your own layer for your own purposes, just extend Board.CanvasLayer class.

In the documentation I use 2 coordinates system:
  • relative coordinates - they serve for location of fields. On common board of size 19 coordinates 0:0 means top left field (A19 in common notation), 18:0 means top right field (T19), 0:18 is bottom left field (A1) and 18:18 is bottom right filed (T1).
  • absolute coordinates - for locating single pixels on canvas. Coordinates 0:0 are coordinates of left and topmost pixel of board's canvases.

Constructor

WGo.Board(element, config)

Constructor - creates instance of WGo.Board class.

Arguments
  • element HTMLElement
    Target HTML element for the board.
  • config Object
    Configuration object of the board. It is simple JSON with structure: {key1: value1, ..., keyN: valueN}. All configurations are optional. Possible configurations are:
    • size number Size of the board (default: 19)
    • width number Width of the board (default: 0)
    • height number Height of the board (default: 0)
    • font string Font of board writings (default: "Calibri")
    • lineWidth number Line width of board drawings (default: 1)
    • starPoints Object Star points coordinates, defined for various board sizes. Look in source code at Board.default for object structure.
    • stoneHandler WGo.Board.DrawHandler Stone drawing handler (default: WGo.Board.DrawHandlers.NORMAL)
    • starSize number Size of star points (default: 1). Radius of stars is dynamic, however you can modify it by given constant.
    • stoneSize number Size of stone (default: 1). Radius of stone is dynamic, however you can modify it by given constant.
    • shadowSize number Size of stone shadow (default: 1). Radius of shadow is dynamic, however you can modify it by given constant.
    • section Object It defines a section of board to be displayed. You can set a number of rows (or cols) to be skipped on each side. Numbers can be negative, in that case there will be more empty space. In default all values are zeros. Object has structure: {top: number, right: number, bottom: number, left: number}
    • background string Background of the board, it can be either color (#RRGGBB) or path to image. Empty string means no background will be applied. (default: WGo.DIR+"wood1.jpg")

Public properties

These properties can be changed without calling any method. However you will probably need to redraw board after any changes. In this documentation I use variable board as instance of WGo.Board class.

board.font string

Font used in board drawings.


board.lineWidth number

Line width use in some objects (eg circle marker).


board.stoneHandler WGo.Board.DrawHandler

Draw handler used for stones.


board.starSize number

Final size of star points in pixels is computed according to field size, however it is multiplied with this constant.


board.stoneSize number

Final size of stones (and other common objects) in pixels is computed according to field size, however it is multiplied with this constant. It shouldn't be greater than 1.


board.shadowSize number

Final size of shadows in pixels is computed according to field size, however it is multiplied with this constant. It shouldn't be greater than 1.


board.stoneRadius number

Size of stone radius in pixels. It shouldn't be changed.


board.element HTMLElement

Main HTML element of the board. You shouldn't change it, however you can alter it - for example change style.


Public methods

board.init()

Initialization method, it is called in constructor. You shouldn't call it, but you can alter it.


board.setWidth(width)

Sets new width of board and redraws it, height is computed to keep correct aspect ratio.

Arguments
  • width number
    New width of board.

board.setHeight(height)

Sets new height of board and redraws it, width is computed to keep correct aspect ratio.

Arguments
  • height number
    New height of board.

board.setDimensions(width, height)

Sets both dimensions, aspect ratio is not kept.

Arguments
  • width number
    New width of board.
  • height number
    New height of board.

board.setSection(section)

Sets section of the board to be displayed.

Arguments
  • section Object You can set a number of rows (or cols) to be skipped on each side. Numbers can be negative, in that case there will be more empty space. In default all values are zeros. Object has structure: {top: number, right: number, bottom: number, left: number}

board.setSize(size)

Sets size of the board. Most common values are 19, 13 and 9. All objects on the board's fields will be removed.

Arguments
  • size number New size of the board.

board.getSection()

Returns currently visible section of the board.

Return

Object Section of the board.


board.redraw()

Redraws board and every object on it.


board.getX(x)

Returns absolute coordinates of column.

Arguments
  • x number
    Relative x coordinate. It should be not negative number less than board's size. Normally 0-18.
Return

number X coordinate in pixels.


board.getY(y)

Returns absolute coordinates of row.

Arguments
  • y number
    Relative y coordinate. It should be not negative number less than board's size. Normally 0-18.
Return

number Y coordinate in pixels.


board.addLayer(layer, weight)

Adds layer to the board. It is meant to be only for canvas layers.

Arguments
  • layer WGo.Board.CanvasLayer
    Layer to be added.
  • weight number
    Layers with bigger weights are on top.

board.removeLayer(layer)

Removes layer from the board.

Arguments
  • layer WGo.Board.CanvasLayer
    Layer to be removed.

board.addObject(object)

Adds object on given coordinates of the board. Object should occupy only one board's field, otherwise they won't be properly painted. This method is meant for stones and markers.

Arguments
  • object Object Array
    Object or array objects to be added. Object has this structure {x: number, y: number, type: WGo.Board.DrawHandler|string|undefined}. X and Y coordinates are required, you must use relative coordinates. Object's type can be WGo.Board.DrawHandler or name of predefined handler, in that case WGo.Board.DrawHandlers[name] must be valid handler. If you omit object's type, default stone handler will be used. Object can have additional paarmeters which are passed to draw handler.
Example

Adding a black stone with label.

board.addObject([
    {x: 3, y: 3, c: WGo.B},
    {x: 3, y: 3, type: "LB", text: "A"}
]);

board.removeObject(object)

Removes object from the board.

Arguments
  • object Object Array
    Object or array objects to be removed. Objects should be specified by coordinates and type.

board.removeObjectsAt(x, y)

Remove all objects on given coordinates.

Arguments
  • x number
    Relative x coordinate. It should be not negative number less than board's size. Normally 0-18.
  • y number
    Relative y coordinate. It should be not negative number less than board's size. Normally 0-18.

board.removeAllObjects()

Remove all objects on the board. This method won't remove custom objects.


board.addCustomObject(handler, args)

Adds custom object on the board.

Arguments
  • handler WGo.Board.DrawHandler
    Draw handler for object being added.
  • args Object
    Configuration object which is passed to draw handler.

board.removeCustomObject(handler, args)

Removes custom object from the board.

Arguments
  • handler WGo.Board.DrawHandler
    Draw handler for object being removed.
  • args Object
    Configuration object which is passed to draw handler.

board.addEventListener(name, callback)

Adds event listener to the board. It should be mouse event listener. It is attached to board's main HTML element.

Arguments
  • name String
    Type of event listener. For example: click, mousemove, mouseout etc.
  • callback Function
    Function to be called when event is triggered. It is called in this way: callback(x, y, event) where x and y are relative board's coordinates of mouse pointer and event is original event object.

board.removeEventListener(name, callback)

Removes event listener from the board.

Arguments
  • name String
    Type of event listener. For example: click, mousemove, mouseout etc.
  • callback Function
    Listener's callback to be removed.

board.getState()

Get current board state (all objects on the board). It actually returns deep copy of the state.

Return

Object State object of the board. It is composed of two objects: {objects: Array, custom: Array}, in variable objects they are stored normal objects, in array custom they are stored custom objects.


board.restoreState(state)

Restores state from board's state object and redraws board.

Arguments
  • state Object
    State object of the board you can retrieve from board.getState(). It may contain only one component (objects or custom), in that case the omitted component won't be affected.


WGo.Board.CanvasLayer

This class creates HTML5 canvas element.

Constructor

WGo.Board.CanvasLayer()

Constructor - creates instance of WGo.Board.CanvasLayer class.


Public properties

canvasLayer.element HTMLCanvasElement

HTML canvas element of the layer. You shouldn't change it, however you can work with it.


canvasLayer.context CanvasRenderingContext2D

Canvas context used for drawing.


Public methods

canvasLayer.setDimensions(width, height)

Sets dimensions of the canvas.

Arguments
  • width number
    New width of the canvas.
  • height number
    New height of the canvas.

canvasLayer.draw(board)

Draws something on the canvas. This method is called by board at the beginnig of drawing. CanvasLayer itself draw nothing.

Arguments
  • board WGo.Board
    Board the canvas is part of.

canvasLayer.clear()

Clears the canvas.


WGo.Board.GridLayer inherits from WGo.Board.CanvasLayer

This canvas layer serves for board's grid. It makes sure the grid is properly painted.


WGo.Board.ShadowLayer inherits from WGo.Board.CanvasLayer

This canvas layer serves for stone's shadows. It assures correct transformation of shadows.


WGo.Board.DrawHandler

Actually this is not a class but interface. Objects that implement this interface can be used for painting on any board's layer.

DrawHandler object has this structure: {stone: DrawObject, shadow: DrawObject, grid: DrawObject}. All properties are optional. Property 'stone' is for painting on stone layer, property 'shadow' is for painting on shadow layer and finally property 'grid' is for painting on grid layer.

DrawObject defines the drawing, it has this interface: {draw: Function, clear: Function}.

  • draw - this function should make drawing on the layer. It has these arguments: args Object arguments of drawing, board WGo.Board full board object. This function is required.
  • clear - this function should clear drawing produced by draw function. It has the same arguments as function above. If this function is ommited, default clearing function is used instead. It clears exactly one field specified in args.
Both functions are called in CanvasRenderingContext2D context of given layer.

Example:

DrawHandler of default stone.

var stone = {
    // draw handler for stone layer
    stone: {
        // drawing function - args object contain info about drawing object, board is main board object
        // this function is called from canvas2D context
        draw: function(args, board) {
            var xr = board.getX(args.x),
                yr = board.getY(args.y),
                sr = board.stoneRadius,
                radgrad;
            
            // set stone texture
            if(args.c == WGo.W) {
                radgrad = this.createRadialGradient(xr-2*sr/5,yr-2*sr/5,2,xr-sr/5,yr-sr/5,4*sr/5);
                radgrad.addColorStop(0, '#fff');
                radgrad.addColorStop(1, '#d4d4d4');
            }
            else {
                radgrad = this.createRadialGradient(xr-2*sr/5,yr-2*sr/5,1,xr-sr/5,yr-sr/5,4*sr/5);
                radgrad.addColorStop(0, '#666');
                radgrad.addColorStop(1, '#000');
            }
            
            // paint stone
            this.beginPath();
            this.fillStyle = radgrad;
            this.arc(xr-0.5, yr-0.5, sr-0.5, 0, 2*Math.PI, true);
            this.fill();
        }
    },
	
    // adding shadow handler
    shadow: {
        draw: function(args, board) {
            var xr = board.getX(args.x),
                yr = board.getY(args.y),
                sr = board.stoneRadius;
            
            this.beginPath();
            this.fillStyle = 'rgba(32,32,32,0.5)';
            this.arc(xr-0.5, yr-0.5, sr-0.5, 0, 2*Math.PI, true);
            this.fill();
        }
    }
};

WGo.Board.drawHandlers

Static object with predefined draw handlers. It contains these items:

  • NORMAL - default stone
  • PAINTED - painted stone
  • GlOW - glowing stone
  • MONO - monochromatic stone
  • CR - circle marker
  • LB - lable marker (lable is specified by parameter text)
  • SQ - square marker
  • TR - triangle
  • MA - X marker
  • SL - filled square marker
  • outline - it draws outline of object specified in parameter stoneStyle
  • mini - it draws a miniature of object specified in parameter stoneStyle

WGo.Position

Simple helper class for storing game's position. Class was initially created for storing stone's colors: WGo.W|WGo.B|0, however it can be used for storing any values.

Constructor

WGo.Position([size])

Constructor - creates an empty position.

Arguments
  • size number
    Size of the position. Only square positions are supported. If omitted size will be 19.

Public properties

position.size number

Size of the position. It cannot be changed.


Public methods

position.get(x, y)

Returns specified field of position.

Arguments
  • x number
    X coordinate of field.
  • y number
    Y coordinate of field.
Return
mixed Value of field. Empty fields return 0.

position.set(x, y, value)

Sets new value of specified field of position.

Arguments
  • x number
    X coordinate of field.
  • y number
    Y coordinate of field.
  • value mixed
    New value of field.

position.clear()

Clears the whole position by filling each field with 0.


position.clone()

Creates shallow copy of the position.

Return
WGo.Position Cloned position.

WGo.Game

This class implements game logic. It basically analyses and saves given moves and returns captured stones. WGo.Game also stores every position from the beginning, so it has ability to check repeating positions and it can effectively restore old positions.

Constructor

WGo.Game([size[, repeat]])

Constructor - creates an Game's class instance.

Arguments
  • size number
    Size for the game. If omitted size will be 19.
  • repeat string
    Defines how to handle repeated position. Supported options are:
    • KO - ko is properly handled - new position cannot be same as previous position.
    • ALL - same position cannot be repeated at all - e.g. it forbids triple ko.
    • NONE - positions can be repeated.

Public properties

game.size number

Size of the game. It cannot be changed.


game.repeating string

Defines how to handle repeated position. More info in the constructor.


game.turn WGo.B|WGo.W

What color should be played next.


Public methods

game.getPosition()

Returns current position - the position on the top of the stack.

Return
WGo.Position Current position object.

game.play(x, y[, color[, noplay]])

Plays a move. It also creates a new position and puts it on the top of the stack.

Arguments
  • x number
    X coordinate of move.
  • y number
    Y coordinate of move.
  • color WGo.B|WGo.W
    Color of move. If omitted, inversed color of the last move is used.
  • noplay boolean
    If true, move isn't played neither saved. Used internally.
Return
Array number If move is valid method returns array of captured stones saved as objects: {x: number, y: number}. If move is invalid method returns error code:
  • 1 - given coordinates are not on board.
  • 2 - on given coordinates already is a stone.
  • 3 - suicide (currently they are forbbiden).
  • 4 - repeated position.

game.pass([color])

Plays a pass. It also clones a position and puts it on the top of the stack.

Arguments
  • color WGo.B|WGo.W
    Color of passing player. If omitted, inversed color of the last move is used.

game.isValid(x, y[, color])

Checks validity of given move

Arguments
  • x number
    X coordinate of move.
  • y number
    Y coordinate of move.
  • color WGo.B|WGo.W
    Color of move. If omitted, inversed color of the last move is used.
Return
boolean True if move is valid and can be played.

game.isOnBoard(x, y)

Checks if given coordinates lie on the board

Arguments
  • x number
    X coordinate.
  • y number
    Y coordinate.
Return
boolean True if coordinates lie on the board.

game.addStone(x, y, color)

Adds stone into the current position. If field isn't empty, stone won't be added. It can be used for setting of position.

Arguments
  • x number
    X coordinate of stone.
  • y number
    Y coordinate of stone.
  • color WGo.B|WGo.W
    Color of stone.
Return
boolean True if stone is successfully added.

game.removeStone(x, y, color)

Removes stone from the current position. It can be used for setting of position.

Arguments
  • x number
    X coordinate of stone.
  • y number
    Y coordinate of stone.
Return
boolean True if stone was removed.

game.setStone(x, y, color)

Sets stone in the current position. It can be used for setting of position.

Arguments
  • x number
    X coordinate of stone.
  • y number
    Y coordinate of stone.
  • color WGo.B|WGo.W
    Color of stone.
Return
boolean True if stone is successfully set.

game.getStone(x, y)

Returns stone on given position.

Arguments
  • x number
    X coordinate of stone.
  • y number
    Y coordinate of stone.
Return
WGo.B|WGo.W|0 Stone's color. 0 means an empty field.

game.pushPosition([position])

Adds given position on the top of the stack.

Arguments
  • position WGo.Position
    Position to be added. If argument is omitted, current position is cloned and used instead.
In positions there are counts of captured stones stored in this form position.capCount = {black: number, white: number}, so if you are creating your own position you should add this property to the position object.

game.popPosition()

Removes position from the top of the stack.

Return
WGo.Position Removed position.

game.firstPosition()

Removes all positions.


game.getCaptureCount(color)

Returns actual number of captured stones of given player.

Arguments
  • color WGo.B|WGo.W Color of the player.
Return

number Count of captured stones.


game.validatePosition(color)

Validate actual position. Position is tested from 0:0 to size-1:size-1 field by field. If there are some moves, that should be captured, they will be removed. You can use this, after insertion of more stones.

Return

Array Array of removed stones in form: {x: number, y: number}.