-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathJsonToPgnParser.php
executable file
·113 lines (91 loc) · 2.48 KB
/
JsonToPgnParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**
* Created by IntelliJ IDEA.
* User: alfmagne1
* Date: 13/03/2017
* Time: 19:00
*/
class JsonToPgnParser
{
private $games;
public function __construct()
{
$this->games = array();
}
/**
* @param string $jsonString
*/
public function addGame($jsonString)
{
$this->addGameObject(json_decode($jsonString, true));
}
/**
* @param array $json
*/
public function addGameObject($json)
{
$this->games[] = $json;
}
public function asPgn()
{
$ret = array();
foreach ($this->games as $game) {
$ret[] = $this->gameToPgn($game);
}
return implode("\n\n", $ret);
}
private function gameToPgn($game)
{
$moves = array();
$metadata = array();
foreach ($game as $key => $value) {
switch ($key) {
case "moves":
$moves = $this->movesToPgn($value, $this->getStartMove($game));
break;
default:
if (is_string($value)) {
$metadata[] = '[' . ucfirst($key) . ' "' . $value . '"]';
}
}
}
return implode("\n", $metadata) . "\n\n" . $moves;
}
private function getStartMove($game)
{
if (empty($game["fen"])) return 1;
$tokens = explode(" ", $game["fen"]);
$ret = array_pop($tokens);
if ($tokens[1] == "b") $ret += .5;
return $ret;
}
private function movesToPgn($moves, $startMove)
{
$ret = array();
if ($startMove != floor($startMove)) {
$ret[] = floor($startMove) . "...";
}
foreach ($moves as $move) {
if(!empty($move["m"])){
if ($startMove == floor($startMove)) {
$ret[] = $startMove . ".";
}
$ret[] = str_replace("..", "", $move["m"]);
}
if (!empty($move["comment"])) {
$ret[] = '{' . $move["comment"] . "}";
}
if(!empty($move["variations"])){
foreach($move["variations"] as $variation){
if(!empty($variation)){
$ret[] = "(" . $this->movesToPgn($variation, $startMove);
}
}
}
if(!empty($move["m"])) {
$startMove += .5;
}
}
return implode(" ", $ret);
}
}