Computer mode in rules section almost OK
[vchess.git] / public / javascripts / components / board.js
index 2861cf7..5a75f29 100644 (file)
@@ -1,3 +1,11 @@
+Vue.component('my-board', {
+       // Last move cannot be guessed from here, and is required to highlight squares
+       // vr: object to check moves, print board...
+       // mode: HH, HC or analyze
+       // userColor: for mode HH or HC
+       props: ["vr","lastMove","mode","orientation","userColor"],
+       data: function () {
+               return {
                        hints: (!localStorage["hints"] ? true : localStorage["hints"] === "1"),
                        bcolor: localStorage["bcolor"] || "lichess", //lichess, chesscom or chesstempo
                        possibleMoves: [], //filled after each valid click/dragstart
                        selectedPiece: null, //moving piece (or clicked piece)
                        incheck: [],
                        start: {}, //pixels coordinates + id of starting square (click or drag)
-                       vr: null, //object to check moves, store them, FEN..
-       orientation: "w", //useful if click on "flip board"     
-       
-
-// TODO: watch for property change "fen"
-// send event after each move, to notify what was played
-       
-       const [sizeX,sizeY] = [V.size.x,V.size.y];
+               };
+       },
+       render(h) {
+               if (!this.vr)
+                       return;
+               const [sizeX,sizeY] = [V.size.x,V.size.y];
                // Precompute hints squares to facilitate rendering
                let hintSquares = doubleArray(sizeX, sizeY, false);
                this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
                // Also precompute in-check squares
                let incheckSq = doubleArray(sizeX, sizeY, false);
                this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
-                       const choices = h('div',
-                               {
-                                       attrs: { "id": "choices" },
-                                       'class': { 'row': true },
-                                       style: {
-                                               "display": this.choices.length>0?"block":"none",
-                                               "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
-                                               "width": (this.choices.length * squareWidth) + "px",
-                                               "height": squareWidth + "px",
-                                       },
+               const squareWidth = 40; //TODO: compute this
+               const choices = h(
+                       'div',
+                       {
+                               attrs: { "id": "choices" },
+                               'class': { 'row': true },
+                               style: {
+                                       "display": this.choices.length>0?"block":"none",
+                                       "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
+                                       "width": (this.choices.length * squareWidth) + "px",
+                                       "height": squareWidth + "px",
                                },
-                               this.choices.map( m => { //a "choice" is a move
-                                       return h('div',
-                                               {
-                                                       'class': {
-                                                               'board': true,
-                                                               ['board'+sizeY]: true,
-                                                       },
-                                                       style: {
-                                                               'width': (100/this.choices.length) + "%",
-                                                               'padding-bottom': (100/this.choices.length) + "%",
-                                                       },
+                       },
+                       this.choices.map(m => { //a "choice" is a move
+                               return h('div',
+                                       {
+                                               'class': {
+                                                       'board': true,
+                                                       ['board'+sizeY]: true,
+                                               },
+                                               style: {
+                                                       'width': (100/this.choices.length) + "%",
+                                                       'padding-bottom': (100/this.choices.length) + "%",
                                                },
-                                               [h('img',
-                                                       {
-                                                               attrs: { "src": '/images/pieces/' +
-                                                                       VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
-                                                               'class': { 'choice-piece': true },
-                                                               on: {
-                                                                       "click": e => { this.play(m); this.choices=[]; },
-                                                                       // NOTE: add 'touchstart' event to fix a problem on smartphones
-                                                                       "touchstart": e => { this.play(m); this.choices=[]; },
-                                                               },
-                                                       })
-                                               ]
-                                       );
-                               })
-                       );
-                       // Create board element (+ reserves if needed by variant or mode)
-                       const lm = this.vr.lastMove;
-                       const showLight = this.hints && variant.name!="Dark" &&
-                               (this.mode != "idle" ||
-                                       (this.vr.moves.length > 0 && this.cursor==this.vr.moves.length));
-                       const gameDiv = h('div',
-                               {
-                                       'class': {
-                                               'game': true,
-                                               'clearer': true,
                                        },
-                               },
-                               [_.range(sizeX).map(i => {
-                                       let ci = (this.mycolor=='w' ? i : sizeX-i-1);
-                                       return h(
-                                               'div',
+                                       [h('img',
                                                {
-                                                       'class': {
-                                                               'row': true,
+                                                       attrs: { "src": '/images/pieces/' +
+                                                               V.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
+                                                       'class': { 'choice-piece': true },
+                                                       on: {
+                                                               "click": e => { this.play(m); this.choices=[]; },
+                                                               // NOTE: add 'touchstart' event to fix a problem on smartphones
+                                                               "touchstart": e => { this.play(m); this.choices=[]; },
                                                        },
-                                                       style: { 'opacity': this.choices.length>0?"0.5":"1" },
-                                               },
-                                               _.range(sizeY).map(j => {
-                                                       let cj = (this.mycolor=='w' ? j : sizeY-j-1);
-                                                       let elems = [];
-                                                       if (this.vr.board[ci][cj] != VariantRules.EMPTY && (variant.name!="Dark"
-                                                               || this.score!="*" || this.vr.enlightened[this.mycolor][ci][cj]))
-                                                       {
-                                                               elems.push(
-                                                                       h(
-                                                                               'img',
-                                                                               {
-                                                                                       'class': {
-                                                                                               'piece': true,
-                                                                                               'ghost': !!this.selectedPiece
-                                                                                                       && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
-                                                                                       },
-                                                                                       attrs: {
-                                                                                               src: "/images/pieces/" +
-                                                                                                       VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
-                                                                                       },
-                                                                               }
-                                                                       )
-                                                               );
-                                                       }
-                                                       if (this.hints && hintSquares[ci][cj])
-                                                       {
-                                                               elems.push(
-                                                                       h(
-                                                                               'img',
-                                                                               {
-                                                                                       'class': {
-                                                                                               'mark-square': true,
-                                                                                       },
-                                                                                       attrs: {
-                                                                                               src: "/images/mark.svg",
-                                                                                       },
-                                                                               }
-                                                                       )
-                                                               );
-                                                       }
-                                                       return h(
-                                                               'div',
-                                                               {
-                                                                       'class': {
-                                                                               'board': true,
-                                                                               ['board'+sizeY]: true,
-                                                                               'light-square': (i+j)%2==0,
-                                                                               'dark-square': (i+j)%2==1,
-                                                                               [this.bcolor]: true,
-                                                                               'in-shadow': variant.name=="Dark" && this.score=="*"
-                                                                                       && !this.vr.enlightened[this.mycolor][ci][cj],
-                                                                               'highlight': showLight && !!lm && _.isMatch(lm.end, {x:ci,y:cj}),
-                                                                               'incheck': showLight && incheckSq[ci][cj],
-                                                                       },
-                                                                       attrs: {
-                                                                               id: this.getSquareId({x:ci,y:cj}),
-                                                                       },
-                                                               },
-                                                               elems
-                                                       );
                                                })
-                                       );
-                               }), choices]
-                       );
-                       if (!!this.vr.reserve)
+                                       ]
+                               );
+                       })
+               );
+               // Create board element (+ reserves if needed by variant or mode)
+               const lm = this.lastMove;
+               const showLight = this.hints && variant.name != "Dark";
+               const gameDiv = h(
+                       'div',
                        {
-                               const shiftIdx = (this.mycolor=="w" ? 0 : 1);
-                               let myReservePiecesArray = [];
-                               for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
-                               {
-                                       myReservePiecesArray.push(h('div',
+                               'class': {
+                                       'game': true,
+                                       'clearer': true,
+                               },
+                       },
+                       [_.range(sizeX).map(i => {
+                               let ci = (this.orientation=='w' ? i : sizeX-i-1);
+                               return h(
+                                       'div',
                                        {
-                                               'class': {'board':true, ['board'+sizeY]:true},
-                                               attrs: { id: this.getSquareId({x:sizeX+shiftIdx,y:i}) }
+                                               'class': {
+                                                       'row': true,
+                                               },
+                                               style: { 'opacity': this.choices.length>0?"0.5":"1" },
                                        },
-                                       [
-                                               h('img',
+                                       _.range(sizeY).map(j => {
+                                               let cj = (this.orientation=='w' ? j : sizeY-j-1);
+                                               let elems = [];
+                                               if (this.vr.board[ci][cj] != V.EMPTY && (variant.name!="Dark"
+                                                       || this.gameOver || this.mode == "analyze"
+                                                       || this.vr.enlightened[this.userColor][ci][cj]))
                                                {
-                                                       'class': {"piece":true, "reserve":true},
-                                                       attrs: {
-                                                               "src": "/images/pieces/" +
-                                                                       this.vr.getReservePpath(this.mycolor,i) + ".svg",
-                                                       }
-                                               }),
-                                               h('sup',
-                                                       {"class": { "reserve-count": true } },
-                                                       [ this.vr.reserve[this.mycolor][VariantRules.RESERVE_PIECES[i]] ]
-                                               )
-                                       ]));
-                               }
-                               let oppReservePiecesArray = [];
-                               const oppCol = this.vr.getOppCol(this.mycolor);
-                               for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
-                               {
-                                       oppReservePiecesArray.push(h('div',
-                                       {
-                                               'class': {'board':true, ['board'+sizeY]:true},
-                                               attrs: { id: this.getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
-                                       },
-                                       [
-                                               h('img',
+                                                       elems.push(
+                                                               h(
+                                                                       'img',
+                                                                       {
+                                                                               'class': {
+                                                                                       'piece': true,
+                                                                                       'ghost': !!this.selectedPiece
+                                                                                               && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
+                                                                               },
+                                                                               attrs: {
+                                                                                       src: "/images/pieces/" +
+                                                                                               V.getPpath(this.vr.board[ci][cj]) + ".svg",
+                                                                               },
+                                                                       }
+                                                               )
+                                                       );
+                                               }
+                                               if (this.hints && hintSquares[ci][cj])
                                                {
-                                                       'class': {"piece":true, "reserve":true},
-                                                       attrs: {
-                                                               "src": "/images/pieces/" +
-                                                                       this.vr.getReservePpath(oppCol,i) + ".svg",
-                                                       }
-                                               }),
-                                               h('sup',
-                                                       {"class": { "reserve-count": true } },
-                                                       [ this.vr.reserve[oppCol][VariantRules.RESERVE_PIECES[i]] ]
-                                               )
-                                       ]));
-                               }
-                               let reserves = h('div',
-                                       {
-                                               'class':{
-                                                       'game': true,
-                                                       "reserve-div": true,
-                                               },
-                                       },
-                                       [
-                                               h('div',
+                                                       elems.push(
+                                                               h(
+                                                                       'img',
+                                                                       {
+                                                                               'class': {
+                                                                                       'mark-square': true,
+                                                                               },
+                                                                               attrs: {
+                                                                                       src: "/images/mark.svg",
+                                                                               },
+                                                                       }
+                                                               )
+                                                       );
+                                               }
+                                               return h(
+                                                       'div',
                                                        {
                                                                'class': {
-                                                                       'row': true,
-                                                                       "reserve-row-1": true,
+                                                                       'board': true,
+                                                                       ['board'+sizeY]: true,
+                                                                       'light-square': (i+j)%2==0,
+                                                                       'dark-square': (i+j)%2==1,
+                                                                       [this.bcolor]: true,
+                                                                       'in-shadow': variant.name=="Dark" && !this.gameOver
+                                                                               && this.mode != "analyze"
+                                                                               && !this.vr.enlightened[this.userColor][ci][cj],
+                                                                       'highlight': showLight && !!lm && _.isMatch(lm.end, {x:ci,y:cj}),
+                                                                       'incheck': showLight && incheckSq[ci][cj],
+                                                               },
+                                                               attrs: {
+                                                                       id: getSquareId({x:ci,y:cj}),
                                                                },
                                                        },
-                                                       myReservePiecesArray
-                                               ),
-                                               h('div',
-                                                       { 'class': { 'row': true }},
-                                                       oppReservePiecesArray
-                                               )
-                                       ]
+                                                       elems
+                                               );
+                                       })
                                );
-                               elementArray.push(reserves);
+                       }), choices]
+               );
+               let elementArray = [choices, gameDiv];
+               if (!!this.vr.reserve)
+               {
+                       const shiftIdx = (this.userColor=="w" ? 0 : 1);
+                       let myReservePiecesArray = [];
+                       for (let i=0; i<V.RESERVE_PIECES.length; i++)
+                       {
+                               myReservePiecesArray.push(h('div',
+                               {
+                                       'class': {'board':true, ['board'+sizeY]:true},
+                                       attrs: { id: getSquareId({x:sizeX+shiftIdx,y:i}) }
+                               },
+                               [
+                                       h('img',
+                                       {
+                                               'class': {"piece":true, "reserve":true},
+                                               attrs: {
+                                                       "src": "/images/pieces/" +
+                                                               this.vr.getReservePpath(this.userColor,i) + ".svg",
+                                               }
+                                       }),
+                                       h('sup',
+                                               {"class": { "reserve-count": true } },
+                                               [ this.vr.reserve[this.userColor][V.RESERVE_PIECES[i]] ]
+                                       )
+                               ]));
+                       }
+                       let oppReservePiecesArray = [];
+                       const oppCol = V.GetOppCol(this.userColor);
+                       for (let i=0; i<V.RESERVE_PIECES.length; i++)
+                       {
+                               oppReservePiecesArray.push(h('div',
+                               {
+                                       'class': {'board':true, ['board'+sizeY]:true},
+                                       attrs: { id: getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
+                               },
+                               [
+                                       h('img',
+                                       {
+                                               'class': {"piece":true, "reserve":true},
+                                               attrs: {
+                                                       "src": "/images/pieces/" +
+                                                               this.vr.getReservePpath(oppCol,i) + ".svg",
+                                               }
+                                       }),
+                                       h('sup',
+                                               {"class": { "reserve-count": true } },
+                                               [ this.vr.reserve[oppCol][V.RESERVE_PIECES[i]] ]
+                                       )
+                               ]));
                        }
-                               // Show current FEN (just below board, lower right corner)
-// (if mode != Dark ...)
-                               elementArray.push(
+                       let reserves = h('div',
+                               {
+                                       'class':{
+                                               'game': true,
+                                               "reserve-div": true,
+                                       },
+                               },
+                               [
                                        h('div',
                                                {
-                                                       attrs: { id: "fen-div" },
-                                                       "class": { "section-content": true },
+                                                       'class': {
+                                                               'row': true,
+                                                               "reserve-row-1": true,
+                                                       },
                                                },
-                                               [
-                                                       h('p',
-                                                               {
-                                                                       attrs: { id: "fen-string" },
-                                                                       domProps: { innerHTML: this.vr.getBaseFen() },
-                                                                       "class": { "text-center": true },
-                                                               }
-                                                       )
-                                               ]
+                                               myReservePiecesArray
+                                       ),
+                                       h('div',
+                                               { 'class': { 'row': true }},
+                                               oppReservePiecesArray
                                        )
-                               );
+                               ]
+                       );
+                       elementArray.push(reserves);
+               }
+               return h(
+                       'div',
+                       {
+                               'class': {
+                                       "col-sm-12":true,
+                                       "col-md-10":true,
+                                       "col-md-offset-1":true,
+                                       "col-lg-8":true,
+                                       "col-lg-offset-2":true,
+                               },
+                               // NOTE: click = mousedown + mouseup
                                on: {
                                        mousedown: this.mousedown,
                                        mousemove: this.mousemove,
                                        touchmove: this.mousemove,
                                        touchend: this.mouseup,
                                },
-
-
-               // TODO: "chessground-like" component
-               // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
-               getSquareId: function(o) {
-                       // NOTE: a separator is required to allow any size of board
-                       return  "sq-" + o.x + "-" + o.y;
-               },
-               // Inverse function
-               getSquareFromId: function(id) {
-                       let idParts = id.split('-');
-                       return [parseInt(idParts[1]), parseInt(idParts[2])];
-               },
+                       },
+                       elementArray
+               );
+       },
+       methods: {
                mousedown: function(e) {
                        e = e || window.event;
                        let ingame = false;
                                this.selectedPiece.style.top = 0;
                                this.selectedPiece.style.display = "inline-block";
                                this.selectedPiece.style.zIndex = 3000;
-                               const startSquare = this.getSquareFromId(e.target.parentNode.id);
+                               const startSquare = getSquareFromId(e.target.parentNode.id);
                                this.possibleMoves = [];
-                               if (this.score == "*")
-                               {
-
-// TODO: essentially adapt this (all other things do not change much)
-// if inside a real game, mycolor should be provided ? (simplest way)
-
-                                       const color = ["friend","problem"].includes(this.mode)
-                                               ? this.vr.turn
-                                               : this.mycolor;
-                                       if (this.vr.canIplay(color,startSquare))
-                                               this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
-                               }
+                               const color = this.mode=="analyze" || this.gameOver
+                                       ? this.vr.turn
+                                       : this.userColor;
+                               if (this.vr.canIplay(color,startSquare))
+                                       this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
                                // Next line add moving piece just after current image
                                // (required for Crazyhouse reserve)
                                e.target.parentNode.insertBefore(this.selectedPiece, e.target.nextSibling);
                                return;
                        }
                        // OK: process move attempt
-                       let endSquare = this.getSquareFromId(landing.id);
+                       let endSquare = getSquareFromId(landing.id);
                        let moves = this.findMatchingMoves(endSquare);
                        this.possibleMoves = [];
                        if (moves.length > 1)
                        });
                        return moves;
                },
-               animateMove: function(move) {
-                       let startSquare = document.getElementById(this.getSquareId(move.start));
-                       let endSquare = document.getElementById(this.getSquareId(move.end));
-                       let rectStart = startSquare.getBoundingClientRect();
-                       let rectEnd = endSquare.getBoundingClientRect();
-                       let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
-                       let movingPiece =
-                               document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
-                       // HACK for animation (with positive translate, image slides "under background")
-                       // Possible improvement: just alter squares on the piece's way...
-                       squares = document.getElementsByClassName("board");
-                       for (let i=0; i<squares.length; i++)
-                       {
-                               let square = squares.item(i);
-                               if (square.id != this.getSquareId(move.start))
-                                       square.style.zIndex = "-1";
-                       }
-                       movingPiece.style.transform = "translate(" + translation.x + "px," +
-                               translation.y + "px)";
-                       movingPiece.style.transitionDuration = "0.2s";
-                       movingPiece.style.zIndex = "3000";
-                       setTimeout( () => {
-                               for (let i=0; i<squares.length; i++)
-                                       squares.item(i).style.zIndex = "auto";
-                               movingPiece.style = {}; //required e.g. for 0-0 with KR swap
-                               this.play(move);
-                       }, 250);
+               play: function(move) {
+                       this.$emit('play-move', move);
                },
+       },
+})