Code simplification + a few fixes
[vchess.git] / public / javascripts / components / rules.js
1 // Load rules on variant page
2 Vue.component('my-rules', {
3 data: function() {
4 return { content: "" };
5 },
6 template: `<div v-html="content" class="section-content"></div>`,
7 mounted: function() {
8 // AJAX request to get rules content (plain text, HTML)
9 let xhr = new XMLHttpRequest();
10 let self = this;
11 xhr.onreadystatechange = function() {
12 if (this.readyState == 4 && this.status == 200)
13 {
14 let replaceByDiag = (match, p1, p2) => { return self.drawDiag(p2); };
15 self.content = xhr.responseText.replace(/(fen:)([^:]*):/g, replaceByDiag);
16 }
17 };
18 xhr.open("GET", "/rules/" + variant, true);
19 xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest");
20 xhr.send();
21 },
22 methods: {
23 drawDiag: function(fen) {
24 let [sizeX,sizeY] = [V.size.x,V.size.y];
25 let fenParts = fen.split(" ");
26 // Obtain array of pieces images names
27 let board = VariantRules.GetBoard(fenParts[0]);
28 let orientation = "w";
29 if (fenParts.length >= 2)
30 orientation = fenParts[1];
31 let markArray = [];
32 if (fenParts.length >= 3)
33 {
34 let marks_str = fenParts[2];
35 // Turn (human) marks into coordinates
36 markArray = doubleArray(sizeX, sizeY, false);
37 let marks = marks_str.split(",");
38 for (let i=0; i<marks.length; i++)
39 {
40 var res = /^([a-z]+)([0-9]+)$/i.exec(marks[i]);
41 let x = sizeX - parseInt(res[2]); //white at bottom, so counting is reversed
42 let y = res[1].charCodeAt(0)-97; //always one char: max 26, big enough
43 markArray[x][y] = true;
44 }
45 }
46 let boardDiv = "";
47 let [startX,startY,inc] = orientation == 'w'
48 ? [0, 0, 1]
49 : [sizeX-1, sizeY-1, -1];
50 for (let i=startX; i>=0 && i<sizeX; i+=inc)
51 {
52 boardDiv += "<div class='row'>";
53 for (let j=startY; j>=0 && j<sizeY; j+=inc)
54 {
55 boardDiv += "<div class='board board" + sizeY + " " +
56 ((i+j)%2==0 ? "light-square-diag" : "dark-square-diag") + "'>";
57 if (board[i][j] != VariantRules.EMPTY)
58 {
59 boardDiv += "<img src='/images/pieces/" +
60 VariantRules.getPpath(board[i][j]) + ".svg' class='piece'/>";
61 }
62 if (markArray.length>0 && markArray[i][j])
63 boardDiv += "<img src='/images/mark.svg' class='mark-square'/>";
64 boardDiv += "</div>";
65 }
66 boardDiv += "</div>";
67 }
68 return boardDiv;
69 },
70 },
71 })