Fix games vs comp + auto
[vchess.git] / client / src / components / ComputerGame.vue
1 <template lang="pug">
2 .row
3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
4 BaseGame(:game="game" :vr="vr" ref="basegame"
5 @newmove="processMove" @gameover="gameOver")
6 </template>
7
8 <script>
9 import BaseGame from "@/components/BaseGame.vue";
10 import { store } from "@/store";
11 import Worker from "worker-loader!@/playCompMove";
12
13 export default {
14 name: "my-computer-game",
15 components: {
16 BaseGame,
17 },
18 // gameInfo: fen + mode + vname
19 // mode: "auto" (game comp vs comp), "versus" (normal) or "analyze"
20 props: ["gameInfo"],
21 data: function() {
22 return {
23 st: store.state,
24 game: {},
25 vr: null,
26 // Web worker to play computer moves without freezing interface:
27 timeStart: undefined, //time when computer starts thinking
28 compThink: false, //avoid asking a new move while one is being searched
29 compWorker: null,
30 };
31 },
32 watch: {
33 "gameInfo.fen": function() {
34 this.launchGame();
35 },
36 "gameInfo.score": function(newScore) {
37 if (newScore != "*")
38 {
39 this.game.score = newScore; //user action
40 this.game.mode = "analyze";
41 if (!this.compThink)
42 this.$emit("game-stopped"); //otherwise wait for comp
43 }
44 },
45 },
46 // Modal end of game, and then sub-components
47 created: function() {
48 // Computer moves web worker logic:
49 this.compWorker = new Worker();
50 this.compWorker.onmessage = e => {
51 let compMove = e.data;
52 if (!compMove)
53 return; //after game ends, no more moves, nothing to do
54 if (!Array.isArray(compMove))
55 compMove = [compMove]; //to deal with MarseilleRules
56 // Small delay for the bot to appear "more human"
57 const delay = Math.max(500-(Date.now()-this.timeStart), 0);
58 setTimeout(() => {
59 // NOTE: Dark and 2-moves are incompatible
60 const animate = (this.gameInfo.vname != "Dark");
61 const animDelay = (animate ? 250 : 0);
62 let moveIdx = 0;
63 let self = this;
64 (function executeMove() {
65 self.$refs.basegame.play(compMove[moveIdx++], animate);
66 if (moveIdx >= compMove.length)
67 {
68 self.compThink = false;
69 if (self.game.score != "*") //user action
70 self.$emit("game-stopped");
71 }
72 else
73 setTimeout(executeMove, 500 + animDelay);
74 })();
75 }, delay);
76 }
77 if (!!this.gameInfo.fen)
78 this.launchGame();
79 },
80 // dans variant.js (plutôt room.js) conn gère aussi les challenges
81 // et les chats dans chat.js. Puis en webRTC, repenser tout ça.
82 methods: {
83 launchGame: async function() {
84 const vModule = await import("@/variants/" + this.gameInfo.vname + ".js");
85 window.V = vModule.VariantRules;
86 this.compWorker.postMessage(["scripts",this.gameInfo.vname]);
87 this.compWorker.postMessage(["init",this.gameInfo.fen]);
88 this.vr = new V(this.gameInfo.fen);
89 const mycolor = (Math.random() < 0.5 ? "w" : "b");
90 let players = [{name:"Myself"},{name:"Computer"}];
91 if (mycolor == "b")
92 players = players.reverse();
93 // NOTE: fen and fenStart are redundant in game object
94 this.game = Object.assign({},
95 this.gameInfo,
96 {
97 fenStart: this.gameInfo.fen,
98 players: players,
99 mycolor: mycolor,
100 score: "*",
101 });
102 this.compWorker.postMessage(["init",this.gameInfo.fen]);
103 if (mycolor != "w" || this.gameInfo.mode == "auto")
104 this.playComputerMove();
105 },
106 playComputerMove: function() {
107 this.timeStart = Date.now();
108 this.compThink = true;
109 this.compWorker.postMessage(["askmove"]);
110 },
111 processMove: function(move) {
112 // Send the move to web worker (including his own moves)
113 this.compWorker.postMessage(["newmove",move]);
114 // subTurn condition for Marseille (and Avalanche) rules
115 if ((!this.vr.subTurn || this.vr.subTurn <= 1)
116 && (this.gameInfo.mode == "auto" || this.vr.turn != this.game.mycolor))
117 {
118 this.playComputerMove();
119 }
120 },
121 gameOver: function(score) {
122 this.game.score = score;
123 this.game.mode = "analyze";
124 this.$emit("game-over", score); //bubble up to Rules.vue
125 },
126 },
127 };
128 </script>