Store state of games VS computer
[vchess.git] / client / src / components / ComputerGame.vue
1 <template lang="pug">
2 BaseGame(
3 ref="basegame"
4 :game="game"
5 :vr="vr"
6 @newmove="processMove"
7 @gameover="gameOver"
8 )
9 </template>
10
11 <script>
12 import BaseGame from "@/components/BaseGame.vue";
13 import { store } from "@/store";
14 import { CompgameStorage } from "@/utils/compgameStorage";
15 import Worker from "worker-loader!@/playCompMove";
16 export default {
17 name: "my-computer-game",
18 components: {
19 BaseGame
20 },
21 // gameInfo: fen + mode + vname
22 // mode: "auto" (game comp vs comp) or "versus" (normal)
23 props: ["gameInfo"],
24 data: function() {
25 return {
26 st: store.state,
27 game: {},
28 vr: null,
29 // Web worker to play computer moves without freezing interface:
30 timeStart: undefined, //time when computer starts thinking
31 compThink: false, //avoid asking a new move while one is being searched
32 compWorker: null
33 };
34 },
35 created: function() {
36 // Computer moves web worker logic:
37 this.compWorker = new Worker();
38 this.compWorker.onmessage = e => {
39 let compMove = e.data;
40 if (!compMove) {
41 this.compThink = false;
42 this.$emit("game-stopped"); //no more moves: mate or stalemate
43 return; //after game ends, no more moves, nothing to do
44 }
45 if (!Array.isArray(compMove)) compMove = [compMove]; //potential multi-move
46 // Small delay for the bot to appear "more human"
47 const delay = Math.max(500 - (Date.now() - this.timeStart), 0);
48 setTimeout(() => {
49 if (this.currentUrl != document.location.href) return; //page change
50 // NOTE: do not animate move if special display (ShowMoves != "all")
51 const animate = V.ShowMoves == "all";
52 const animDelay = animate ? 250 : 0;
53 let moveIdx = 0;
54 let self = this;
55 (function executeMove() {
56 // NOTE: BaseGame::play() will trigger processMove() here
57 self.$refs["basegame"].play(compMove[moveIdx++], "received");
58 if (moveIdx >= compMove.length) {
59 self.compThink = false;
60 if (self.game.score != "*")
61 // User action
62 self.$emit("game-stopped");
63 } else setTimeout(executeMove, 500 + animDelay);
64 })();
65 }, delay);
66 };
67 },
68 methods: {
69 launchGame: function(game) {
70 this.compWorker.postMessage(["scripts", this.gameInfo.vname]);
71 if (!game) {
72 game = {
73 vname: this.gameInfo.vname,
74 fenStart: V.GenRandInitFen(),
75 mycolor: Math.random() < 0.5 ? "w" : "b",
76 moves: []
77 };
78 game.fen = game.fenStart;
79 if (this.gameInfo.mode == "versus")
80 CompgameStorage.add(game);
81 }
82 this.compWorker.postMessage(["init", game.fen]);
83 this.vr = new V(game.fen);
84 game.players = [{ name: "Myself" }, { name: "Computer" }];
85 if (game.myColor == "b") game.players = game.players.reverse();
86 game.score = "*"; //finished games are removed
87 this.currentUrl = document.location.href; //to avoid playing outside page
88 this.game = game;
89 this.compWorker.postMessage(["init", game.fen]);
90 if (this.gameInfo.mode == "auto" || game.mycolor != this.vr.turn)
91 this.playComputerMove();
92 },
93 // NOTE: a "goto" action could lead to an error when comp is thinking,
94 // but it's OK because from the user viewpoint the game just stops.
95 playComputerMove: function() {
96 this.timeStart = Date.now();
97 this.compThink = true;
98 this.compWorker.postMessage(["askmove"]);
99 },
100 processMove: function(move) {
101 if (this.game.score != "*") return;
102 // Send the move to web worker (including his own moves)
103 this.compWorker.postMessage(["newmove", move]);
104 // subTurn condition for Marseille (and Avalanche) rules
105 if (
106 (!this.vr.subTurn || this.vr.subTurn <= 1) &&
107 (this.gameInfo.mode == "auto" || this.vr.turn != this.game.mycolor)
108 ) {
109 this.playComputerMove();
110 }
111 // Finally, update storage:
112 if (this.gameInfo.mode == "versus") {
113 const allowed_fields = ["appear", "vanish", "start", "end"];
114 const filtered_move = Object.keys(move)
115 .filter(key => allowed_fields.includes(key))
116 .reduce((obj, key) => {
117 obj[key] = move[key];
118 return obj;
119 }, {});
120 CompgameStorage.update(this.gameInfo.vname, {
121 move: filtered_move,
122 fen: move.fen
123 });
124 }
125 },
126 gameOver: function(score, scoreMsg) {
127 this.game.score = score;
128 this.game.scoreMsg = scoreMsg;
129 if (!this.compThink) this.$emit("game-stopped"); //otherwise wait for comp
130 }
131 }
132 };
133 </script>