Fix Alice chess
[vchess.git] / public / javascripts / components / game.js
index 1338132..3f74fde 100644 (file)
@@ -8,10 +8,15 @@ Vue.component('my-game', {
                        start: {}, //pixels coordinates + id of starting square (click or drag)
                        selectedPiece: null, //moving piece (or clicked piece)
                        conn: null, //socket messages
-                       endofgame: "", //end of game message
+                       score: "*", //'*' means 'unfinished'
                        mode: "idle", //human, computer or idle (when not playing)
                        oppid: "", //opponent ID in case of HH game
                        oppConnected: false,
+                       seek: false,
+                       fenStart: "",
+                       incheck: [],
+                       pgnTxt: "",
+                       expert: document.cookie.length>0 ? document.cookie.substr(-1)=="1" : false,
                };
        },
        render(h) {
@@ -19,48 +24,100 @@ Vue.component('my-game', {
                // 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; });
                let elementArray = [];
-               let square00 = document.getElementById("sq-0-0");
-               let squareWidth = !!square00
-                       ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2))
-                       : 0;
+               const playingHuman = (this.mode == "human");
+               const playingComp = (this.mode == "computer");
                let actionArray = [
                        h('button',
                                {
-                                       on: { click: () => this.newGame("human") },
+                                       on: { click: this.clickGameSeek },
                                        attrs: { "aria-label": 'New game VS human' },
-                                       'class': { "tooltip":true },
+                                       'class': {
+                                               "tooltip": true,
+                                               "bottom": true, //display below
+                                               "seek": this.seek,
+                                               "playing": playingHuman,
+                                       },
                                },
                                [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
                        h('button',
                                {
-                                       on: { click: () => this.newGame("computer") },
+                                       on: { click: this.clickComputerGame },
                                        attrs: { "aria-label": 'New game VS computer' },
-                                       'class': { "tooltip":true },
+                                       'class': {
+                                               "tooltip":true,
+                                               "bottom": true,
+                                               "playing": playingComp,
+                                       },
                                },
                                [h('i', { 'class': { "material-icons": true } }, "computer")])
                ];
                if (!!this.vr)
                {
+                       const square00 = document.getElementById("sq-0-0");
+                       const squareWidth = !!square00
+                               ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2))
+                               : 0;
+                       const indicWidth = (squareWidth>0 ? squareWidth/2 : 20);
                        if (this.mode == "human")
                        {
                                let connectedIndic = h(
                                        'div',
                                        {
                                                "class": {
+                                                       "topindicator": true,
+                                                       "indic-left": true,
                                                        "connected": this.oppConnected,
                                                        "disconnected": !this.oppConnected,
                                                },
+                                               style: {
+                                                       "width": indicWidth + "px",
+                                                       "height": indicWidth + "px",
+                                               },
                                        }
                                );
                                elementArray.push(connectedIndic);
                        }
+                       let turnIndic = h(
+                               'div',
+                               {
+                                       "class": {
+                                               "topindicator": true,
+                                               "indic-right": true,
+                                               "white-turn": this.vr.turn=="w",
+                                               "black-turn": this.vr.turn=="b",
+                                       },
+                                       style: {
+                                               "width": indicWidth + "px",
+                                               "height": indicWidth + "px",
+                                       },
+                               }
+                       );
+                       elementArray.push(turnIndic);
+                       let expertSwitch = h(
+                               'button',
+                               {
+                                       on: { click: this.toggleExpertMode },
+                                       attrs: { "aria-label": 'Toggle expert mode' },
+                                       'class': {
+                                               "tooltip":true,
+                                               "topindicator": true,
+                                               "indic-right": true,
+                                               "expert-switch": true,
+                                               "expert-mode": this.expert,
+                                       },
+                               },
+                               [h('i', { 'class': { "material-icons": true } }, "remove_red_eye")]
+                       );
+                       elementArray.push(expertSwitch);
                        let choices = h('div',
                                {
                                        attrs: { "id": "choices" },
                                        'class': { 'row': true },
                                        style: {
-                                               //"position": "relative",
                                                "display": this.choices.length>0?"block":"none",
                                                "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
                                                "width": (this.choices.length * squareWidth) + "px",
@@ -78,7 +135,8 @@ Vue.component('my-game', {
                                                },
                                                [h('img',
                                                        {
-                                                               attrs: { "src": '/images/pieces/' + VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
+                                                               attrs: { "src": '/images/pieces/' +
+                                                                       VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
                                                                'class': { 'choice-piece': true, 'board': true },
                                                                on: { "click": e => { this.play(m); this.choices=[]; } },
                                                        })
@@ -112,16 +170,18 @@ Vue.component('my-game', {
                                                                                {
                                                                                        'class': {
                                                                                                'piece': true,
-                                                                                               'ghost': !!this.selectedPiece && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
+                                                                                               'ghost': !!this.selectedPiece
+                                                                                                       && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
                                                                                        },
                                                                                        attrs: {
-                                                                                               src: "/images/pieces/" + VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
+                                                                                               src: "/images/pieces/" +
+                                                                                                       VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
                                                                                        },
                                                                                }
                                                                        )
                                                                );
                                                        }
-                                                       if (hintSquares[ci][cj])
+                                                       if (!this.expert && hintSquares[ci][cj])
                                                        {
                                                                elems.push(
                                                                        h(
@@ -137,16 +197,17 @@ Vue.component('my-game', {
                                                                        )
                                                                );
                                                        }
-                                                       const lm = this.vr.lastMove; //TODO: interruptions (FEN local storage..)
-                                                       const highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj}); //&& _.isMatch(lm.start, {x:ci,y:cj})
+                                                       const lm = this.vr.lastMove;
+                                                       const highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj});
                                                        return h(
                                                                'div',
                                                                {
                                                                        'class': {
                                                                                'board': true,
-                                                                               'light-square': !highlight && (i+j)%2==0,
-                                                                               'dark-square': !highlight && (i+j)%2==1,
-                                                                               'highlight': highlight,
+                                                                               'light-square': (i+j)%2==0 && (this.expert || !highlight),
+                                                                               'dark-square': (i+j)%2==1 && (this.expert || !highlight),
+                                                                               'highlight': !this.expert && highlight,
+                                                                               'incheck': !this.expert && incheckSq[ci][cj],
                                                                        },
                                                                        attrs: {
                                                                                id: this.getSquareId({x:ci,y:cj}),
@@ -158,15 +219,21 @@ Vue.component('my-game', {
                                        );
                                }), choices]
                        );
-                       actionArray.push(
-                               h('button',
-                                       {
-                                               on: { click: this.resign },
-                                               attrs: { "aria-label": 'Resign' },
-                                               'class': { "tooltip":true },
-                                       },
-                                       [h('i', { 'class': { "material-icons": true } }, "flag")])
-                       );
+                       if (this.mode != "idle")
+                       {
+                               actionArray.push(
+                                       h('button',
+                                               {
+                                                       on: { click: this.resign },
+                                                       attrs: { "aria-label": 'Resign' },
+                                                       'class': {
+                                                               "tooltip":true,
+                                                               "bottom": true,
+                                                       },
+                                               },
+                                               [h('i', { 'class': { "material-icons": true } }, "flag")])
+                               );
+                       }
                        elementArray.push(gameDiv);
        //                      if (!!vr.reserve)
        //                      {
@@ -185,10 +252,11 @@ Vue.component('my-game', {
        //                              );
        //                              elementArray.push(reserve);
        //                      }
+                       const eogMessage = this.getEndgameMessage(this.score);
                        const modalEog = [
                                h('input',
                                        {
-                                               attrs: { "id": "modal-control", type: "checkbox" },
+                                               attrs: { "id": "modal-eog", type: "checkbox" },
                                                "class": { "modal": true },
                                        }),
                                h('div',
@@ -203,20 +271,14 @@ Vue.component('my-game', {
                                                        [
                                                                h('label',
                                                                        {
-                                                                               attrs: { "for": "modal-control" },
+                                                                               attrs: { "for": "modal-eog" },
                                                                                "class": { "modal-close": true },
                                                                        }
                                                                ),
                                                                h('h3',
                                                                        {
                                                                                "class": { "section": true },
-                                                                               domProps: { innerHTML: "End of game" },
-                                                                       }
-                                                               ),
-                                                               h('p',
-                                                                       {
-                                                                               "class": { "section": true },
-                                                                               domProps: { innerHTML: this.endofgame },
+                                                                               domProps: { innerHTML: eogMessage },
                                                                        }
                                                                )
                                                        ]
@@ -229,7 +291,7 @@ Vue.component('my-game', {
                const modalNewgame = [
                        h('input',
                                {
-                                       attrs: { "id": "modal-control2", type: "checkbox" },
+                                       attrs: { "id": "modal-newgame", type: "checkbox" },
                                        "class": { "modal": true },
                                }),
                        h('div',
@@ -244,7 +306,7 @@ Vue.component('my-game', {
                                                [
                                                        h('label',
                                                                {
-                                                                       attrs: { "id": "close-newgame", "for": "modal-control2" },
+                                                                       attrs: { "id": "close-newgame", "for": "modal-newgame" },
                                                                        "class": { "modal-close": true },
                                                                }
                                                        ),
@@ -274,6 +336,33 @@ Vue.component('my-game', {
                        actionArray
                );
                elementArray.push(actions);
+               if (this.score != "*")
+               {
+                       elementArray.push(
+                               h('div',
+                                       { attrs: { id: "pgn-div" } },
+                                       [
+                                               h('a',
+                                                       {
+                                                               attrs: {
+                                                                       id: "download",
+                                                                       href: "#",
+                                                               }
+                                                       }
+                                               ),
+                                               h('p',
+                                                       {
+                                                               attrs: { id: "pgn-game" },
+                                                               on: { click: this.download },
+                                                               domProps: {
+                                                                       innerHTML: this.pgnTxt
+                                                               }
+                                                       }
+                                               )
+                                       ]
+                               )
+                       );
+               }
                return h(
                        'div',
                        {
@@ -305,17 +394,25 @@ Vue.component('my-game', {
                        // random enough (TODO: function)
                        : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
                this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
-               this.conn.onopen = () => {
+               const socketOpenListener = () => {
                        if (continuation)
                        {
-                               // TODO: check FEN integrity with opponent
-                               this.newGame("human", localStorage.getItem("fen"),
-                                       localStorage.getItem("mycolor"), localStorage.getItem("oppid"), true);
-                               // Send ping to server, which answers pong if opponent is connected
-                               this.conn.send(JSON.stringify({code:"ping", oppid:this.oppId}));
+                               const fen = localStorage.getItem("fen");
+                               const mycolor = localStorage.getItem("mycolor");
+                               const oppid = localStorage.getItem("oppid");
+                               const moves = JSON.parse(localStorage.getItem("moves"));
+                               this.newGame("human", fen, mycolor, oppid, moves, true);
+                               // Send ping to server (answer pong if opponent is connected)
+                               this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
+                       }
+                       else if (localStorage.getItem("newgame") === variant)
+                       {
+                               // New game request has been cancelled on disconnect
+                               this.seek = true;
+                               this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
                        }
                };
-               this.conn.onmessage = msg => {
+               const socketMessageListener = msg => {
                        const data = JSON.parse(msg.data);
                        switch (data.code)
                        {
@@ -325,13 +422,51 @@ Vue.component('my-game', {
                                case "newmove": //..he played!
                                        this.play(data.move, "animate");
                                        break;
-                               case "pong": //sent when opponent stayed online after we disconnected
+                               case "pong": //received if we sent a ping (game still alive on our side)
                                        this.oppConnected = true;
+                                       const L = this.vr.moves.length;
+                                       // Send our "last state" informations to opponent
+                                       this.conn.send(JSON.stringify({
+                                               code:"lastate",
+                                               oppid:this.oppid,
+                                               lastMove:L>0?this.vr.moves[L-1]:undefined,
+                                               movesCount:L,
+                                       }));
+                                       break;
+                               case "lastate": //got opponent infos about last move (we might have resigned)
+                                       if (this.mode!="human" || this.oppid!=data.oppid)
+                                       {
+                                               // OK, we resigned
+                                               this.conn.send(JSON.stringify({
+                                                       code:"lastate",
+                                                       oppid:this.oppid,
+                                                       lastMove:undefined,
+                                                       movesCount:-1,
+                                               }));
+                                       }
+                                       else if (data.movesCount < 0)
+                                       {
+                                               // OK, he resigned
+                                               this.endGame(this.mycolor=="w"?"1-0":"0-1");
+                                       }
+                                       else if (data.movesCount < this.vr.moves.length)
+                                       {
+                                               // We must tell last move to opponent
+                                               const L = this.vr.moves.length;
+                                               this.conn.send(JSON.stringify({
+                                                       code:"lastate",
+                                                       oppid:this.oppid,
+                                                       lastMove:this.vr.moves[L-1],
+                                                       movesCount:L,
+                                               }));
+                                       }
+                                       else if (data.movesCount > this.vr.moves.length) //just got last move from him
+                                               this.play(data.lastMove, "animate");
                                        break;
                                case "resign": //..you won!
-                                       this.endGame("Victory!");
+                                       this.endGame(this.mycolor=="w"?"1-0":"0-1");
                                        break;
-                               // TODO: also use (dis)connect info to count online players
+                               // TODO: also use (dis)connect info to count online players?
                                case "connect":
                                case "disconnect":
                                        if (this.mode == "human" && this.oppid == data.id)
@@ -339,29 +474,80 @@ Vue.component('my-game', {
                                        break;
                        }
                };
+               const socketCloseListener = () => {
+                       this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
+                       this.conn.addEventListener('open', socketOpenListener);
+                       this.conn.addEventListener('message', socketMessageListener);
+                       this.conn.addEventListener('close', socketCloseListener);
+               };
+               this.conn.onopen = socketOpenListener;
+               this.conn.onmessage = socketMessageListener;
+               this.conn.onclose = socketCloseListener;
        },
        methods: {
-               endGame: function(message) {
-                       this.endofgame = message;
-                       document.getElementById("modal-control").checked = true;
+               download: function() {
+                       let content = document.getElementById("pgn-game").innerHTML;
+                       content = content.replace(/<br>/g, "\n");
+                       // Prepare and trigger download link
+                       let downloadAnchor = document.getElementById("download");
+                       downloadAnchor.setAttribute("download", "game.pgn");
+                       downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
+                       downloadAnchor.click();
+               },
+               endGame: function(score) {
+                       this.score = score;
+                       let modalBox = document.getElementById("modal-eog");
+                       modalBox.checked = true;
+                       // Variants may have special PGN structure (so next function isn't defined here)
+                       this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode);
+                       setTimeout(() => { modalBox.checked = false; }, 2000);
                        if (this.mode == "human")
                                this.clearStorage();
                        this.mode = "idle";
                        this.oppid = "";
                },
+               getEndgameMessage: function(score) {
+                       let eogMessage = "Unfinished";
+                       switch (this.score)
+                       {
+                               case "1-0":
+                                       eogMessage = "White win";
+                                       break;
+                               case "0-1":
+                                       eogMessage = "Black win";
+                                       break;
+                               case "1/2":
+                                       eogMessage = "Draw";
+                                       break;
+                       }
+                       return eogMessage;
+               },
+               toggleExpertMode: function() {
+                       this.expert = !this.expert;
+                       document.cookie = "expert=" + (this.expert ? "1" : "0");
+               },
                resign: function() {
                        if (this.mode == "human" && this.oppConnected)
-                               this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
-                       this.endGame("Try again!");
-               },
-               updateStorage: function() {
-                       if (!localStorage.getItem("myid"))
                        {
-                               localStorage.setItem("myid", this.myid);
-                               localStorage.setItem("variant", variant);
-                               localStorage.setItem("mycolor", this.mycolor);
-                               localStorage.setItem("oppid", this.oppid);
+                               try {
+                                       this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
+                               } catch (INVALID_STATE_ERR) {
+                                       return; //socket is not ready (and not yet reconnected)
+                               }
                        }
+                       this.endGame(this.mycolor=="w"?"0-1":"1-0");
+               },
+               setStorage: function() {
+                       localStorage.setItem("myid", this.myid);
+                       localStorage.setItem("variant", variant);
+                       localStorage.setItem("mycolor", this.mycolor);
+                       localStorage.setItem("oppid", this.oppid);
+                       localStorage.setItem("fenStart", this.fenStart);
+                       localStorage.setItem("moves", JSON.stringify(this.vr.moves));
+                       localStorage.setItem("fen", this.vr.getFen());
+               },
+               updateStorage: function() {
+                       localStorage.setItem("moves", JSON.stringify(this.vr.moves));
                        localStorage.setItem("fen", this.vr.getFen());
                },
                clearStorage: function() {
@@ -369,33 +555,85 @@ Vue.component('my-game', {
                        delete localStorage["myid"];
                        delete localStorage["mycolor"];
                        delete localStorage["oppid"];
+                       delete localStorage["fenStart"];
                        delete localStorage["fen"];
+                       delete localStorage["moves"];
+               },
+               clickGameSeek: function() {
+                       if (this.mode == "human")
+                               return; //no newgame while playing
+                       if (this.seek)
+                       {
+                               delete localStorage["newgame"]; //cancel game seek
+                               this.seek = false;
+                       }
+                       else
+                               this.newGame("human");
+               },
+               clickComputerGame: function() {
+                       if (this.mode == "human")
+                               return; //no newgame while playing
+                       this.newGame("computer");
                },
-               newGame: function(mode, fenInit, color, oppId, continuation) {
+               newGame: function(mode, fenInit, color, oppId, moves, continuation) {
+                       //const fen = "1n2T1n0/p2pO2p/1s1k1s2/8/3S2p1/2U2cO1/P3PuPP/3K1BR1 0100";
                        const fen = fenInit || VariantRules.GenRandInitFen();
                        console.log(fen); //DEBUG
+                       this.score = "*";
                        if (mode=="human" && !oppId)
                        {
+                               const storageVariant = localStorage.getItem("variant");
+                               if (!!storageVariant && storageVariant !== variant)
+                               {
+                                       alert("Finish your " + storageVariant + " game first!");
+                                       return;
+                               }
                                // Send game request and wait..
+                               localStorage["newgame"] = variant;
+                               this.seek = true;
                                this.clearStorage(); //in case of
-                               this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
-                               document.getElementById("modal-control2").checked = true;
+                               try {
+                                       this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
+                               } catch (INVALID_STATE_ERR) {
+                                       return; //nothing achieved
+                               }
+                               if (continuation !== "reconnect") //TODO: bad HACK...
+                               {
+                                       let modalBox = document.getElementById("modal-newgame");
+                                       modalBox.checked = true;
+                                       setTimeout(() => { modalBox.checked = false; }, 2000);
+                               }
                                return;
                        }
-                       this.vr = new VariantRules(fen);
+                       this.vr = new VariantRules(fen, moves || []);
+                       this.pgnTxt = ""; //redundant with this.score = "*", but cleaner
                        this.mode = mode;
+                       this.incheck = []; //in case of
+                       this.fenStart = continuation
+                               ? localStorage.getItem("fenStart")
+                               : fen.split(" ")[0]; //Only the position matters
                        if (mode=="human")
                        {
                                // Opponent found!
                                if (!continuation)
                                {
-                                       // Playing sound fails on game continuation:
-                                       new Audio("/sounds/newgame.mp3").play();
-                                       document.getElementById("modal-control2").checked = false;
+                                       // Not playing sound on game continuation:
+                                       new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {});
+                                       document.getElementById("modal-newgame").checked = false;
                                }
                                this.oppid = oppId;
                                this.oppConnected = true;
                                this.mycolor = color;
+                               this.seek = false;
+                               if (!!moves && moves.length > 0) //imply continuation
+                               {
+                                       const lastMove = moves[moves.length-1];
+                                       this.vr.undo(lastMove);
+                                       this.incheck = this.vr.getCheckSquares(lastMove);
+                                       this.vr.play(lastMove, "ingame");
+                               }
+                               delete localStorage["newgame"];
+                               this.setStorage(); //in case of interruptions
                        }
                        else //against computer
                        {
@@ -405,10 +643,11 @@ Vue.component('my-game', {
                        }
                },
                playComputerMove: function() {
-                       const compColor = this.mycolor=='w' ? 'b' : 'w';
-                       const compMove = this.vr.getComputerMove(compColor);
-                       // HACK: avoid selecting elements before they appear on page:
-                       setTimeout(() => this.play(compMove, "animate"), 500);
+                       const timeStart = Date.now();
+                       const compMove = this.vr.getComputerMove();
+                       // (first move) HACK: avoid selecting elements before they appear on page:
+                       const delay = Math.max(500-(Date.now()-timeStart), 0);
+                       setTimeout(() => this.play(compMove, "animate"), delay);
                },
                // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
                getSquareId: function(o) {
@@ -438,7 +677,7 @@ Vue.component('my-game', {
                                this.selectedPiece.style.display = "inline-block";
                                this.selectedPiece.style.zIndex = 3000;
                                let startSquare = this.getSquareFromId(e.target.parentNode.id);
-                               this.possibleMoves = this.vr.canIplay(this.mycolor,startSquare)
+                               this.possibleMoves = this.mode!="idle" && this.vr.canIplay(this.mycolor,startSquare)
                                        ? this.vr.getPossibleMovesFrom(startSquare)
                                        : [];
                                e.target.parentNode.appendChild(this.selectedPiece);
@@ -521,18 +760,15 @@ Vue.component('my-game', {
                                this.animateMove(move);
                                return;
                        }
+                       this.incheck = this.vr.getCheckSquares(move); //is opponent in check?
                        // Not programmatic, or animation is over
                        if (this.mode == "human" && this.vr.turn == this.mycolor)
-                       {
-                               if (!this.oppConnected)
-                                       return; //abort move if opponent is gone
                                this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
-                       }
-                       new Audio("/sounds/chessmove1.mp3").play();
+                       new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {});
                        this.vr.play(move, "ingame");
                        if (this.mode == "human")
                                this.updateStorage(); //after our moves and opponent moves
-                       const eog = this.vr.checkGameOver(this.vr.turn);
+                       const eog = this.vr.checkGameOver();
                        if (eog != "*")
                                this.endGame(eog);
                        else if (this.mode == "computer" && this.vr.turn != this.mycolor)