Add a game piece to the board, check that:
1. game piece doesn't already exist
2. game piece is not adjacent to non-compatible piece
return: integer of points if Success, otherwise return an error string
974162
function addGamePiece(game, gamepiece) {

    var row = gamepiece.row;
    var col = gamepiece.column;
    var points = 0;

    if (game.boardmat[row][col] !== undefined) {
        return "GamePiece already exists.";
    }

    /**
     * Helper function, to check whether it is valid to place a piece
     * param piece: the piece object being placed
     * param getAdjacent: a function that returns an adjacent GamePiece
     * return: false if valid placement, otherwise return the offending GamePiece
     */
    function _adjacentPieces(piece, getAdjacent) {
        for (var i=1; i<=6; i++) {
            adjacent = getAdjacent(i);
            if (typeof adjacent === 'undefined') {
                return false;
            } else if (i === 6) { // can't have more than 6 pieces in a valid line
                return adjacent;
            }

            var samecolor = (adjacent.piece.color === piece.color);
            var sameshape = (adjacent.piece.shape === piece.shape);

            // console.log('piece: ' + piece.color + ' ' + piece.shape +
            //             ', adjacent: ' + adjacent.piece.color + ' ' +
            //             adjacent.piece.shape);

            // either samecolor or sameshape, not both
            if ((samecolor || sameshape) && !(samecolor && sameshape)) {
                // add a point for adjacent piece, if not been played this turn
                if (!game.turn_pieces.some(function(x) {
                    return x.equals(adjacent);})) {
                    points += 1;
                }
                continue;
            }
            return adjacent;
        }
        return false;
    }

    // check if adjacent pieces are compatible
    var checkLeft = _adjacentPieces(gamepiece.piece, function(offset) {
        var _row = row-offset;
        var piece = game.boardmat[_row][col];
        return piece && new GamePiece(piece, _row, col);
    });
    var checkRight =_adjacentPieces(gamepiece.piece, function(offset) {
        var _row = row+offset;
        var piece = game.boardmat[_row][col];
        return piece && new GamePiece(piece, _row, col);
    });
    var checkUp =_adjacentPieces(gamepiece.piece, function(offset) {
        var _col = col-offset;
        var piece = game.boardmat[row][_col];
        return piece && new GamePiece(piece, row, _col);
    });
    var checkDown =_adjacentPieces(gamepiece.piece, function(offset) {
        var _col = col+offset;
        var piece = game.boardmat[row][_col];
        return piece && new GamePiece(piece, row, _col);
    });
    var badPiece = (checkLeft || checkRight || checkUp || checkDown);

    if (badPiece !== false) {
        return ("GamePiece adjacent to incompatible piece: " +
                badPiece.piece.color + " " + badPiece.piece.shape);
    }

    // check if piece played in same row or column as past pieces this turn}
    function sameRowOrCol(otherpiece) {
        return (otherpiece.row === row || otherpiece.column === col);
    }
    if (game.turn_pieces) {
        if (!game.turn_pieces.every(sameRowOrCol)) {
            return ("GamePiece must be in same row or column as others " +
                    "placed this turn.");
        }
    }

    game.turn_pieces.push(gamepiece);
    game.boardmat[row][col] = gamepiece.piece;
    game.board.push(gamepiece);

    // update board dimensions
    var dim = game.dimensions;
    if (col < dim.left) {
        dim.left = col;
    } else if (col > dim.right) {
        dim.right = col;
    }
    if (row < dim.top) {
        dim.top = row;
    } else if (row > dim.bottom) {
        dim.bottom = row;
    }

    // debug logging, print out boardmat
    // for (var i=dim.top; i<=dim.bottom; i++) {
    //  for (var j=dim.left; j<=dim.right; j++) {
    //      var piecestr = (typeof game.boardmat[i][j] == "undefined") ? " ":
    //          game.boardmat[i][j];
    //      process.stdout.write('['+piecestr+']');
    //  }
    //  console.log('');
    // }

    return points+1;  // get one point for placing a piece
}
806338
def _calc_all_possible_moves(self, input_color):
        
        for piece in self:

            # Tests if square on the board is not empty
            if piece is not None and piece.color == input_color:

                for move in piece.possible_moves(self):

                    test = cp(self)
                    test_move = Move(end_loc=move.end_loc,
                                     piece=test.piece_at_square(move.start_loc),
                                     status=move.status,
                                     start_loc=move.start_loc,
                                     promoted_to_piece=move.promoted_to_piece)
                    test.update(test_move)

                    if self.king_loc_dict is None:
                        yield move
                        continue

                    my_king = test.piece_at_square(self.king_loc_dict[input_color])

                    if my_king is None or \
                            not isinstance(my_king, King) or \
                            my_king.color != input_color:
                        self.king_loc_dict[input_color] = test.find_king(input_color)
                        my_king = test.piece_at_square(self.king_loc_dict[input_color])

                    if not my_king.in_check(test):
                        yield move
277601
def add_avatar(self, a, b=None):
        
        if self.engine._planning:
            raise NotImplementedError("Currently can't add avatars within a plan")
        if b is None:
            if not (
                    isinstance(a, Place) or
                    isinstance(a, Thing)
            ):
                raise TypeError(
                    'when called with one argument, '
                    'it must be a place or thing'
                )
            g = a.character.name
            n = a.name
        else:
            if isinstance(a, Character):
                g = a.name
            elif not isinstance(a, str):
                raise TypeError(
                    'when called with two arguments, '
                    'the first is a character or its name'
                )
            else:
                g = a
            if isinstance(b, Place) or isinstance(b, Thing):
                n = b.name
            elif not isinstance(b, str):
                raise TypeError(
                    'when called with two arguments, '
                    'the second is a thing/place or its name'
                )
            else:
                n = b
        # This will create the node if it doesn't exist. Otherwise
        # it's redundant but harmless.
        self.engine._exist_node(g, n)
        # Declare that the node is my avatar
        branch, turn, tick = self.engine._nbtt()
        self.engine._remember_avatarness(self.name, g, n, branch=branch, turn=turn, tick=tick)
627240
def add(self, point):
        

        current = self
        while True:
            check_dimensionality([point], dimensions=current.dimensions)

            # Adding has hit an empty leaf-node, add here
            if current.data is None:
                current.data = point
                return current

            # split on self.axis, recurse either left or right
            if point[current.axis] < current.data[current.axis]:
                if current.left is None:
                    current.left = current.create_subnode(point)
                    return current.left
                else:
                    current = current.left
            else:
                if current.right is None:
                    current.right = current.create_subnode(point)
                    return current.right
                else:
                    current = current.right
867549
def add_line(self, moves: Iterable[chess.Move], *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = ()) -> "GameNode":
        
        node = self

        # Add line.
        for move in moves:
            node = node.add_variation(move, starting_comment=starting_comment)
            starting_comment = ""

        # Merge comment and NAGs.
        if node.comment:
            node.comment += " " + comment
        else:
            node.comment = comment

        node.nags.update(nags)

        return node
1338070
def update(self, *args):
        

        # remove widgets that don't represent anything anymore
        Logger.debug("Board: updating")
        self.remove_absent_pawns()
        self.remove_absent_spots()
        self.remove_absent_arrows()
        # add widgets to represent new stuff
        self.add_new_spots()
        if self.arrow_cls:
            self.add_new_arrows()
        self.add_new_pawns()
        self.spotlayout.finalize_all()
        Logger.debug("Board: updated")
1232170
def add_concept(self, concept_obj):
        '''  '''
        if concept_obj is None:
            raise Exception("Concept object cannot be None")
        elif concept_obj in self.__concepts:
            raise Exception("Concept object is already inside")
        elif concept_obj.cidx in self.__concept_map:
            raise Exception("Duplicated concept ID ({})".format(concept_obj.cidx))
        self.__concepts.append(concept_obj)
        self.__concept_map[concept_obj.cidx] = concept_obj
        concept_obj.sent = self
        return concept_obj
132189
def add_table_item(self, table):
        
        if not table.is_draft_version:
            raise ValueError("Table isn't a draft version")

        self.items.append(table.latest_version)
1072638
def add(error)
      if @list.key? error.name
        raise DuplicateError, "An error named #{error.name} already exists"
      end
      @list[error.name] = error
    end
979541
def pawn_from_dummy(self, dummy):
        
        dummy.pos = self.to_local(*dummy.pos)
        for spot in self.board.spotlayout.children:
            if spot.collide_widget(dummy):
                whereat = spot
                break
        else:
            return
        whereat.add_widget(
            self.board.make_pawn(
                self.board.character.new_thing(
                    dummy.name,
                    whereat.place.name,
                    _image_paths=list(dummy.paths)
                )
            )
        )
        dummy.num += 1
217548
def support_enumeration_gen(g):
    
    try:
        N = g.N
    except:
        raise TypeError('input must be a 2-player NormalFormGame')
    if N != 2:
        raise NotImplementedError('Implemented only for 2-player games')
    return _support_enumeration_gen(g.payoff_arrays)
91676
def loc_adjacent_to_opponent_king(self, location, position):
        
        for fn in self.cardinal_directions:
            try:
                if isinstance(position.piece_at_square(fn(location)), King) and \
                        position.piece_at_square(fn(location)).color != self.color:
                    return True

            except IndexError:
                pass

        return False
775648
def add_edge(self, fr, to):
        
        if fr not in set(self.graph.vs):  # ToDo: find out why item can be in set but not dict
            raise ValueError('can not connect unknown vertices in n-partite graphs, {!r} missing'.format(fr))
        elif to not in set(self.graph.vs):
            raise ValueError('can not connect unknown vertices in n-partite graphs, {!r} missing'.format(to))
        self.graph.add_edge(fr, to)
39031
function isMyTurn(game, from) {
    if (game.score.ended)
        return false;
    from = Board.getPositionFromBoard(game.board, from);
    return isWhiteTurn(game) ? Position.hasWhitePiece(from) : Position.hasBlackPiece(from);
}
534770
def add_castle(self, position):
        
        if self.has_moved or self.in_check(position):
            return

        if self.color == color.white:
            rook_rank = 0
        else:
            rook_rank = 7

        castle_type = {
            notation_const.KING_SIDE_CASTLE: {
                "rook_file": 7,
                "direction": lambda king_square, times: king_square.shift_right(times)
            },
            notation_const.QUEEN_SIDE_CASTLE: {
                "rook_file": 0,
                "direction": lambda king_square, times: king_square.shift_left(times)
            }
        }
        for castle_key in castle_type:
            castle_dict = castle_type[castle_key]
            castle_rook = position.piece_at_square(Location(rook_rank, castle_dict["rook_file"]))
            if self._rook_legal_for_castle(castle_rook) and \
                    self._empty_not_in_check(position, castle_dict["direction"]):
                yield self.create_move(castle_dict["direction"](self.location, 2), castle_key)
449306
def add_player(player)
      raise "invalid player" unless player.class == ICU::Player
      raise "player number (#{player.num}) should be unique" if @player[player.num]
      @player[player.num] = player
    end
709310
function Game(name) {
    this.name = name;
    this.board = [];  // list representation
    this.boardmat = [];  // matrix representation
    for (var i=0; i<181; i++) {
        this.boardmat[i] = new Array(181);
    }
    this.players = {};
    this.turn_pieces = [];  // pieces played this turn
    this.chat = [];  // chat log

    // board dimensions
    this.dimensions = {'top': 90, 'right': 90, 'bottom': 90, 'left': 90};

    /* Keep track of the pieces by having a list of piece objects each with a
     * count attribute that tracks how many of that piece are left. When this
     * reaches 0, we remove the piece object from the list.
     */
    this.pieces = [];
    var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
    var shapes =  ['circle', 'star', 'diamond', 'square', 'triangle', 'clover'];
    for (var c in colors) {
        if (!colors.hasOwnProperty(c)) {
            continue;
        }
        for (var s in shapes) {
            if (!shapes.hasOwnProperty(s)) {
                continue;
            }
            this.pieces.push({'piece': new Piece(shapes[s], colors[c]), 'count': 3});
        }
    }
}