Write Royalrace rules
[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 moves: []
76 };
77 game.fen = game.fenStart;
78 if (this.gameInfo.mode == "versus")
79 CompgameStorage.add(game);
80 }
81 if (this.gameInfo.mode == "versus" && !game.mycolor)
82 game.mycolor = Math.random() < 0.5 ? "w" : "b";
83 this.compWorker.postMessage(["init", game.fen]);
84 this.vr = new V(game.fen);
85 game.players = [{ name: "Myself" }, { name: "Computer" }];
86 if (game.myColor == "b") game.players = game.players.reverse();
87 game.score = "*"; //finished games are removed
88 this.currentUrl = document.location.href; //to avoid playing outside page
89 this.game = game;
90 this.compWorker.postMessage(["init", game.fen]);
91 if (this.gameInfo.mode == "auto" || game.mycolor != this.vr.turn)
92 this.playComputerMove();
93 },
94 // NOTE: a "goto" action could lead to an error when comp is thinking,
95 // but it's OK because from the user viewpoint the game just stops.
96 playComputerMove: function() {
97 this.timeStart = Date.now();
98 this.compThink = true;
99 this.compWorker.postMessage(["askmove"]);
100 },
101 processMove: function(move) {
102 if (this.game.score != "*") return;
103 // Send the move to web worker (including his own moves)
104 this.compWorker.postMessage(["newmove", move]);
105 // subTurn condition for Marseille (and Avalanche) rules
106 if (
107 (!this.vr.subTurn || this.vr.subTurn <= 1) &&
108 (this.gameInfo.mode == "auto" || this.vr.turn != this.game.mycolor)
109 ) {
110 this.playComputerMove();
111 }
112 // Finally, update storage:
113 if (this.gameInfo.mode == "versus") {
114 const allowed_fields = ["appear", "vanish", "start", "end"];
115 const filtered_move = Object.keys(move)
116 .filter(key => allowed_fields.includes(key))
117 .reduce((obj, key) => {
118 obj[key] = move[key];
119 return obj;
120 }, {});
121 CompgameStorage.update(this.gameInfo.vname, {
122 move: filtered_move,
123 fen: move.fen
124 });
125 }
126 },
127 gameOver: function(score, scoreMsg) {
128 this.game.score = score;
129 this.game.scoreMsg = scoreMsg;
130 if (!this.compThink) this.$emit("game-stopped"); //otherwise wait for comp
131 }
132 }
133 };
134 </script>