├── LICENSE ├── README.md ├── chrome ├── background.js ├── chess.js ├── icons │ ├── anarchy-chess128.png │ ├── anarchy-chess16.png │ ├── anarchy-chess32.png │ └── anarchy-chess48.png ├── manifest.json ├── src │ ├── popup.css │ ├── popup.html │ ├── popup.js │ └── script.js └── util.js └── firefox ├── background.js ├── chess.js ├── icons ├── anarchy-chess128.png ├── anarchy-chess16.png ├── anarchy-chess32.png └── anarchy-chess48.png ├── manifest.json ├── src ├── popup.css ├── popup.html ├── popup.js └── script.js └── util.js /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # auto-en-passant-extension 2 | A chrome/firefox extension that automatically plays en passant if it's avaliable 3 | 4 | Chrome: https://chrome.google.com/webstore/detail/auto-en-passant/egcfjkjbfiffcoebkejbhdbgohfbgbch 5 | 6 | Firefox: https://addons.mozilla.org/en-US/firefox/addon/auto-en-passant/ 7 | 8 | This includes the [chess.js library](https://github.com/jhlywa/chess.js/) by jhlywa because browsers seem to get very angry when you try to run code from an external source via an extension 9 | 10 | This was made for [r/AnarchyChess](https://www.reddit.com/r/AnarchyChess/) via this [post](https://www.reddit.com/r/AnarchyChess/comments/vf7blc/fuck_you_auto_en_passant/?utm_source=share&utm_medium=web2x&context=3) 11 | -------------------------------------------------------------------------------- /chrome/background.js: -------------------------------------------------------------------------------- 1 | import { hasEnPassant, getCurrentGame } from './util.js' 2 | 3 | let API_KEY = "" 4 | let toggle = false 5 | 6 | chrome.storage.sync.get(['API_KEY'], (result) => { 7 | API_KEY = result.API_KEY 8 | }) 9 | 10 | chrome.storage.sync.get(['toggle'], (result) => { 11 | toggle = result.toggle 12 | }) 13 | 14 | chrome.storage.onChanged.addListener((changes, areaName) => { 15 | if (changes.API_KEY) {API_KEY = changes.API_KEY.newValue} 16 | if (changes.toggle) {toggle = changes.toggle.newValue} 17 | }) 18 | 19 | // Gets the moves from script.js and checks for the funny 20 | chrome.runtime.onMessage.addListener((moves, sender) => { 21 | console.log(toggle) 22 | if (moves !== null && toggle) { 23 | const game = getCurrentGame(moves) 24 | const move = hasEnPassant(game) 25 | if (move !== null) { 26 | fetch('https://lichess.org/api/board/game/' + sender.url.split('/')[3] + '/move/' + move.from + move.to, { 27 | method: "post", 28 | headers: { 29 | "Authorization": "Bearer " + API_KEY 30 | } 31 | }) 32 | } 33 | } 34 | 35 | }) 36 | 37 | chrome.webNavigation.onCompleted.addListener((details) => { 38 | if (details.frameId == 0) { 39 | chrome.scripting.executeScript({ 40 | target: { tabId: details.tabId }, 41 | files: ['src/script.js'] 42 | }) 43 | } 44 | }) 45 | -------------------------------------------------------------------------------- /chrome/chess.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, Jeff Hlywa (jhlywa@gmail.com) 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * 8 | * 1. Redistributions of source code must retain the above copyright notice, 9 | * this list of conditions and the following disclaimer. 10 | * 2. Redistributions in binary form must reproduce the above copyright notice, 11 | * this list of conditions and the following disclaimer in the documentation 12 | * and/or other materials provided with the distribution. 13 | * 14 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 18 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | * POSSIBILITY OF SUCH DAMAGE. 25 | * 26 | *----------------------------------------------------------------------------*/ 27 | 28 | const SYMBOLS = 'pnbrqkPNBRQK' 29 | 30 | const DEFAULT_POSITION = 31 | 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1' 32 | 33 | const TERMINATION_MARKERS = ['1-0', '0-1', '1/2-1/2', '*'] 34 | 35 | const PAWN_OFFSETS = { 36 | b: [16, 32, 17, 15], 37 | w: [-16, -32, -17, -15], 38 | } 39 | 40 | const PIECE_OFFSETS = { 41 | n: [-18, -33, -31, -14, 18, 33, 31, 14], 42 | b: [-17, -15, 17, 15], 43 | r: [-16, 1, 16, -1], 44 | q: [-17, -16, -15, 1, 17, 16, 15, -1], 45 | k: [-17, -16, -15, 1, 17, 16, 15, -1], 46 | } 47 | 48 | // prettier-ignore 49 | const ATTACKS = [ 50 | 20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0,20, 0, 51 | 0,20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0,20, 0, 0, 52 | 0, 0,20, 0, 0, 0, 0, 24, 0, 0, 0, 0,20, 0, 0, 0, 53 | 0, 0, 0,20, 0, 0, 0, 24, 0, 0, 0,20, 0, 0, 0, 0, 54 | 0, 0, 0, 0,20, 0, 0, 24, 0, 0,20, 0, 0, 0, 0, 0, 55 | 0, 0, 0, 0, 0,20, 2, 24, 2,20, 0, 0, 0, 0, 0, 0, 56 | 0, 0, 0, 0, 0, 2,53, 56, 53, 2, 0, 0, 0, 0, 0, 0, 57 | 24,24,24,24,24,24,56, 0, 56,24,24,24,24,24,24, 0, 58 | 0, 0, 0, 0, 0, 2,53, 56, 53, 2, 0, 0, 0, 0, 0, 0, 59 | 0, 0, 0, 0, 0,20, 2, 24, 2,20, 0, 0, 0, 0, 0, 0, 60 | 0, 0, 0, 0,20, 0, 0, 24, 0, 0,20, 0, 0, 0, 0, 0, 61 | 0, 0, 0,20, 0, 0, 0, 24, 0, 0, 0,20, 0, 0, 0, 0, 62 | 0, 0,20, 0, 0, 0, 0, 24, 0, 0, 0, 0,20, 0, 0, 0, 63 | 0,20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0,20, 0, 0, 64 | 20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0,20 65 | ]; 66 | 67 | // prettier-ignore 68 | const RAYS = [ 69 | 17, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 15, 0, 70 | 0, 17, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 15, 0, 0, 71 | 0, 0, 17, 0, 0, 0, 0, 16, 0, 0, 0, 0, 15, 0, 0, 0, 72 | 0, 0, 0, 17, 0, 0, 0, 16, 0, 0, 0, 15, 0, 0, 0, 0, 73 | 0, 0, 0, 0, 17, 0, 0, 16, 0, 0, 15, 0, 0, 0, 0, 0, 74 | 0, 0, 0, 0, 0, 17, 0, 16, 0, 15, 0, 0, 0, 0, 0, 0, 75 | 0, 0, 0, 0, 0, 0, 17, 16, 15, 0, 0, 0, 0, 0, 0, 0, 76 | 1, 1, 1, 1, 1, 1, 1, 0, -1, -1, -1,-1, -1, -1, -1, 0, 77 | 0, 0, 0, 0, 0, 0,-15,-16,-17, 0, 0, 0, 0, 0, 0, 0, 78 | 0, 0, 0, 0, 0,-15, 0,-16, 0,-17, 0, 0, 0, 0, 0, 0, 79 | 0, 0, 0, 0,-15, 0, 0,-16, 0, 0,-17, 0, 0, 0, 0, 0, 80 | 0, 0, 0,-15, 0, 0, 0,-16, 0, 0, 0,-17, 0, 0, 0, 0, 81 | 0, 0,-15, 0, 0, 0, 0,-16, 0, 0, 0, 0,-17, 0, 0, 0, 82 | 0,-15, 0, 0, 0, 0, 0,-16, 0, 0, 0, 0, 0,-17, 0, 0, 83 | -15, 0, 0, 0, 0, 0, 0,-16, 0, 0, 0, 0, 0, 0,-17 84 | ]; 85 | 86 | const SHIFTS = { p: 0, n: 1, b: 2, r: 3, q: 4, k: 5 } 87 | 88 | const BITS = { 89 | NORMAL: 1, 90 | CAPTURE: 2, 91 | BIG_PAWN: 4, 92 | EP_CAPTURE: 8, 93 | PROMOTION: 16, 94 | KSIDE_CASTLE: 32, 95 | QSIDE_CASTLE: 64, 96 | } 97 | 98 | const RANK_1 = 7 99 | const RANK_2 = 6 100 | const RANK_3 = 5 101 | const RANK_4 = 4 102 | const RANK_5 = 3 103 | const RANK_6 = 2 104 | const RANK_7 = 1 105 | const RANK_8 = 0 106 | 107 | // prettier-ignore 108 | const SQUARE_MAP = { 109 | a8: 0, b8: 1, c8: 2, d8: 3, e8: 4, f8: 5, g8: 6, h8: 7, 110 | a7: 16, b7: 17, c7: 18, d7: 19, e7: 20, f7: 21, g7: 22, h7: 23, 111 | a6: 32, b6: 33, c6: 34, d6: 35, e6: 36, f6: 37, g6: 38, h6: 39, 112 | a5: 48, b5: 49, c5: 50, d5: 51, e5: 52, f5: 53, g5: 54, h5: 55, 113 | a4: 64, b4: 65, c4: 66, d4: 67, e4: 68, f4: 69, g4: 70, h4: 71, 114 | a3: 80, b3: 81, c3: 82, d3: 83, e3: 84, f3: 85, g3: 86, h3: 87, 115 | a2: 96, b2: 97, c2: 98, d2: 99, e2: 100, f2: 101, g2: 102, h2: 103, 116 | a1: 112, b1: 113, c1: 114, d1: 115, e1: 116, f1: 117, g1: 118, h1: 119 117 | }; 118 | 119 | const ROOKS = { 120 | w: [ 121 | { square: SQUARE_MAP.a1, flag: BITS.QSIDE_CASTLE }, 122 | { square: SQUARE_MAP.h1, flag: BITS.KSIDE_CASTLE }, 123 | ], 124 | b: [ 125 | { square: SQUARE_MAP.a8, flag: BITS.QSIDE_CASTLE }, 126 | { square: SQUARE_MAP.h8, flag: BITS.KSIDE_CASTLE }, 127 | ], 128 | } 129 | 130 | const PARSER_STRICT = 0 131 | const PARSER_SLOPPY = 1 132 | 133 | /* this function is used to uniquely identify ambiguous moves */ 134 | function get_disambiguator(move, moves) { 135 | var from = move.from 136 | var to = move.to 137 | var piece = move.piece 138 | 139 | var ambiguities = 0 140 | var same_rank = 0 141 | var same_file = 0 142 | 143 | for (var i = 0, len = moves.length; i < len; i++) { 144 | var ambig_from = moves[i].from 145 | var ambig_to = moves[i].to 146 | var ambig_piece = moves[i].piece 147 | 148 | /* if a move of the same piece type ends on the same to square, we'll 149 | * need to add a disambiguator to the algebraic notation 150 | */ 151 | if (piece === ambig_piece && from !== ambig_from && to === ambig_to) { 152 | ambiguities++ 153 | 154 | if (rank(from) === rank(ambig_from)) { 155 | same_rank++ 156 | } 157 | 158 | if (file(from) === file(ambig_from)) { 159 | same_file++ 160 | } 161 | } 162 | } 163 | 164 | if (ambiguities > 0) { 165 | /* if there exists a similar moving piece on the same rank and file as 166 | * the move in question, use the square as the disambiguator 167 | */ 168 | if (same_rank > 0 && same_file > 0) { 169 | return algebraic(from) 170 | } else if (same_file > 0) { 171 | /* if the moving piece rests on the same file, use the rank symbol as the 172 | * disambiguator 173 | */ 174 | return algebraic(from).charAt(1) 175 | } else { 176 | /* else use the file symbol */ 177 | return algebraic(from).charAt(0) 178 | } 179 | } 180 | 181 | return '' 182 | } 183 | 184 | function infer_piece_type(san) { 185 | var piece_type = san.charAt(0) 186 | if (piece_type >= 'a' && piece_type <= 'h') { 187 | var matches = san.match(/[a-h]\d.*[a-h]\d/) 188 | if (matches) { 189 | return undefined 190 | } 191 | return PAWN 192 | } 193 | piece_type = piece_type.toLowerCase() 194 | if (piece_type === 'o') { 195 | return KING 196 | } 197 | return piece_type 198 | } 199 | 200 | // parses all of the decorators out of a SAN string 201 | function stripped_san(move) { 202 | return move.replace(/=/, '').replace(/[+#]?[?!]*$/, '') 203 | } 204 | 205 | /***************************************************************************** 206 | * UTILITY FUNCTIONS 207 | ****************************************************************************/ 208 | function rank(i) { 209 | return i >> 4 210 | } 211 | 212 | function file(i) { 213 | return i & 15 214 | } 215 | 216 | function algebraic(i) { 217 | var f = file(i), 218 | r = rank(i) 219 | return 'abcdefgh'.substring(f, f + 1) + '87654321'.substring(r, r + 1) 220 | } 221 | 222 | function swap_color(c) { 223 | return c === WHITE ? BLACK : WHITE 224 | } 225 | 226 | function is_digit(c) { 227 | return '0123456789'.indexOf(c) !== -1 228 | } 229 | 230 | function clone(obj) { 231 | var dupe = obj instanceof Array ? [] : {} 232 | 233 | for (var property in obj) { 234 | if (typeof property === 'object') { 235 | dupe[property] = clone(obj[property]) 236 | } else { 237 | dupe[property] = obj[property] 238 | } 239 | } 240 | 241 | return dupe 242 | } 243 | 244 | function trim(str) { 245 | return str.replace(/^\s+|\s+$/g, '') 246 | } 247 | 248 | /*************************************************************************** 249 | * PUBLIC CONSTANTS 250 | **************************************************************************/ 251 | 252 | export const BLACK = 'b' 253 | export const WHITE = 'w' 254 | 255 | export const EMPTY = -1 256 | 257 | export const PAWN = 'p' 258 | export const KNIGHT = 'n' 259 | export const BISHOP = 'b' 260 | export const ROOK = 'r' 261 | export const QUEEN = 'q' 262 | export const KING = 'k' 263 | 264 | export const SQUARES = (function () { 265 | /* from the ECMA-262 spec (section 12.6.4): 266 | * "The mechanics of enumerating the properties ... is 267 | * implementation dependent" 268 | * so: for (var sq in SQUARES) { keys.push(sq); } might not be 269 | * ordered correctly 270 | */ 271 | var keys = [] 272 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 273 | if (i & 0x88) { 274 | i += 7 275 | continue 276 | } 277 | keys.push(algebraic(i)) 278 | } 279 | return keys 280 | })() 281 | 282 | export const FLAGS = { 283 | NORMAL: 'n', 284 | CAPTURE: 'c', 285 | BIG_PAWN: 'b', 286 | EP_CAPTURE: 'e', 287 | PROMOTION: 'p', 288 | KSIDE_CASTLE: 'k', 289 | QSIDE_CASTLE: 'q', 290 | } 291 | 292 | export const Chess = function (fen) { 293 | var board = new Array(128) 294 | var kings = { w: EMPTY, b: EMPTY } 295 | var turn = WHITE 296 | var castling = { w: 0, b: 0 } 297 | var ep_square = EMPTY 298 | var half_moves = 0 299 | var move_number = 1 300 | var history = [] 301 | var header = {} 302 | var comments = {} 303 | 304 | /* if the user passes in a fen string, load it, else default to 305 | * starting position 306 | */ 307 | if (typeof fen === 'undefined') { 308 | load(DEFAULT_POSITION) 309 | } else { 310 | load(fen) 311 | } 312 | 313 | function clear(keep_headers) { 314 | if (typeof keep_headers === 'undefined') { 315 | keep_headers = false 316 | } 317 | 318 | board = new Array(128) 319 | kings = { w: EMPTY, b: EMPTY } 320 | turn = WHITE 321 | castling = { w: 0, b: 0 } 322 | ep_square = EMPTY 323 | half_moves = 0 324 | move_number = 1 325 | history = [] 326 | if (!keep_headers) header = {} 327 | comments = {} 328 | update_setup(generate_fen()) 329 | } 330 | 331 | function prune_comments() { 332 | var reversed_history = [] 333 | var current_comments = {} 334 | var copy_comment = function (fen) { 335 | if (fen in comments) { 336 | current_comments[fen] = comments[fen] 337 | } 338 | } 339 | while (history.length > 0) { 340 | reversed_history.push(undo_move()) 341 | } 342 | copy_comment(generate_fen()) 343 | while (reversed_history.length > 0) { 344 | make_move(reversed_history.pop()) 345 | copy_comment(generate_fen()) 346 | } 347 | comments = current_comments 348 | } 349 | 350 | function reset() { 351 | load(DEFAULT_POSITION) 352 | } 353 | 354 | function load(fen, keep_headers) { 355 | if (typeof keep_headers === 'undefined') { 356 | keep_headers = false 357 | } 358 | 359 | var tokens = fen.split(/\s+/) 360 | var position = tokens[0] 361 | var square = 0 362 | 363 | if (!validate_fen(fen).valid) { 364 | return false 365 | } 366 | 367 | clear(keep_headers) 368 | 369 | for (var i = 0; i < position.length; i++) { 370 | var piece = position.charAt(i) 371 | 372 | if (piece === '/') { 373 | square += 8 374 | } else if (is_digit(piece)) { 375 | square += parseInt(piece, 10) 376 | } else { 377 | var color = piece < 'a' ? WHITE : BLACK 378 | put({ type: piece.toLowerCase(), color: color }, algebraic(square)) 379 | square++ 380 | } 381 | } 382 | 383 | turn = tokens[1] 384 | 385 | if (tokens[2].indexOf('K') > -1) { 386 | castling.w |= BITS.KSIDE_CASTLE 387 | } 388 | if (tokens[2].indexOf('Q') > -1) { 389 | castling.w |= BITS.QSIDE_CASTLE 390 | } 391 | if (tokens[2].indexOf('k') > -1) { 392 | castling.b |= BITS.KSIDE_CASTLE 393 | } 394 | if (tokens[2].indexOf('q') > -1) { 395 | castling.b |= BITS.QSIDE_CASTLE 396 | } 397 | 398 | ep_square = tokens[3] === '-' ? EMPTY : SQUARE_MAP[tokens[3]] 399 | half_moves = parseInt(tokens[4], 10) 400 | move_number = parseInt(tokens[5], 10) 401 | 402 | update_setup(generate_fen()) 403 | 404 | return true 405 | } 406 | 407 | /* TODO: this function is pretty much crap - it validates structure but 408 | * completely ignores content (e.g. doesn't verify that each side has a king) 409 | * ... we should rewrite this, and ditch the silly error_number field while 410 | * we're at it 411 | */ 412 | function validate_fen(fen) { 413 | var errors = { 414 | 0: 'No errors.', 415 | 1: 'FEN string must contain six space-delimited fields.', 416 | 2: '6th field (move number) must be a positive integer.', 417 | 3: '5th field (half move counter) must be a non-negative integer.', 418 | 4: '4th field (en-passant square) is invalid.', 419 | 5: '3rd field (castling availability) is invalid.', 420 | 6: '2nd field (side to move) is invalid.', 421 | 7: "1st field (piece positions) does not contain 8 '/'-delimited rows.", 422 | 8: '1st field (piece positions) is invalid [consecutive numbers].', 423 | 9: '1st field (piece positions) is invalid [invalid piece].', 424 | 10: '1st field (piece positions) is invalid [row too large].', 425 | 11: 'Illegal en-passant square', 426 | } 427 | 428 | /* 1st criterion: 6 space-seperated fields? */ 429 | var tokens = fen.split(/\s+/) 430 | if (tokens.length !== 6) { 431 | return { valid: false, error_number: 1, error: errors[1] } 432 | } 433 | 434 | /* 2nd criterion: move number field is a integer value > 0? */ 435 | if (isNaN(tokens[5]) || parseInt(tokens[5], 10) <= 0) { 436 | return { valid: false, error_number: 2, error: errors[2] } 437 | } 438 | 439 | /* 3rd criterion: half move counter is an integer >= 0? */ 440 | if (isNaN(tokens[4]) || parseInt(tokens[4], 10) < 0) { 441 | return { valid: false, error_number: 3, error: errors[3] } 442 | } 443 | 444 | /* 4th criterion: 4th field is a valid e.p.-string? */ 445 | if (!/^(-|[abcdefgh][36])$/.test(tokens[3])) { 446 | return { valid: false, error_number: 4, error: errors[4] } 447 | } 448 | 449 | /* 5th criterion: 3th field is a valid castle-string? */ 450 | if (!/^(KQ?k?q?|Qk?q?|kq?|q|-)$/.test(tokens[2])) { 451 | return { valid: false, error_number: 5, error: errors[5] } 452 | } 453 | 454 | /* 6th criterion: 2nd field is "w" (white) or "b" (black)? */ 455 | if (!/^(w|b)$/.test(tokens[1])) { 456 | return { valid: false, error_number: 6, error: errors[6] } 457 | } 458 | 459 | /* 7th criterion: 1st field contains 8 rows? */ 460 | var rows = tokens[0].split('/') 461 | if (rows.length !== 8) { 462 | return { valid: false, error_number: 7, error: errors[7] } 463 | } 464 | 465 | /* 8th criterion: every row is valid? */ 466 | for (var i = 0; i < rows.length; i++) { 467 | /* check for right sum of fields AND not two numbers in succession */ 468 | var sum_fields = 0 469 | var previous_was_number = false 470 | 471 | for (var k = 0; k < rows[i].length; k++) { 472 | if (!isNaN(rows[i][k])) { 473 | if (previous_was_number) { 474 | return { valid: false, error_number: 8, error: errors[8] } 475 | } 476 | sum_fields += parseInt(rows[i][k], 10) 477 | previous_was_number = true 478 | } else { 479 | if (!/^[prnbqkPRNBQK]$/.test(rows[i][k])) { 480 | return { valid: false, error_number: 9, error: errors[9] } 481 | } 482 | sum_fields += 1 483 | previous_was_number = false 484 | } 485 | } 486 | if (sum_fields !== 8) { 487 | return { valid: false, error_number: 10, error: errors[10] } 488 | } 489 | } 490 | 491 | if ( 492 | (tokens[3][1] == '3' && tokens[1] == 'w') || 493 | (tokens[3][1] == '6' && tokens[1] == 'b') 494 | ) { 495 | return { valid: false, error_number: 11, error: errors[11] } 496 | } 497 | 498 | /* everything's okay! */ 499 | return { valid: true, error_number: 0, error: errors[0] } 500 | } 501 | 502 | function generate_fen() { 503 | var empty = 0 504 | var fen = '' 505 | 506 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 507 | if (board[i] == null) { 508 | empty++ 509 | } else { 510 | if (empty > 0) { 511 | fen += empty 512 | empty = 0 513 | } 514 | var color = board[i].color 515 | var piece = board[i].type 516 | 517 | fen += color === WHITE ? piece.toUpperCase() : piece.toLowerCase() 518 | } 519 | 520 | if ((i + 1) & 0x88) { 521 | if (empty > 0) { 522 | fen += empty 523 | } 524 | 525 | if (i !== SQUARE_MAP.h1) { 526 | fen += '/' 527 | } 528 | 529 | empty = 0 530 | i += 8 531 | } 532 | } 533 | 534 | var cflags = '' 535 | if (castling[WHITE] & BITS.KSIDE_CASTLE) { 536 | cflags += 'K' 537 | } 538 | if (castling[WHITE] & BITS.QSIDE_CASTLE) { 539 | cflags += 'Q' 540 | } 541 | if (castling[BLACK] & BITS.KSIDE_CASTLE) { 542 | cflags += 'k' 543 | } 544 | if (castling[BLACK] & BITS.QSIDE_CASTLE) { 545 | cflags += 'q' 546 | } 547 | 548 | /* do we have an empty castling flag? */ 549 | cflags = cflags || '-' 550 | var epflags = ep_square === EMPTY ? '-' : algebraic(ep_square) 551 | 552 | return [fen, turn, cflags, epflags, half_moves, move_number].join(' ') 553 | } 554 | 555 | function set_header(args) { 556 | for (var i = 0; i < args.length; i += 2) { 557 | if (typeof args[i] === 'string' && typeof args[i + 1] === 'string') { 558 | header[args[i]] = args[i + 1] 559 | } 560 | } 561 | return header 562 | } 563 | 564 | /* called when the initial board setup is changed with put() or remove(). 565 | * modifies the SetUp and FEN properties of the header object. if the FEN is 566 | * equal to the default position, the SetUp and FEN are deleted 567 | * the setup is only updated if history.length is zero, ie moves haven't been 568 | * made. 569 | */ 570 | function update_setup(fen) { 571 | if (history.length > 0) return 572 | 573 | if (fen !== DEFAULT_POSITION) { 574 | header['SetUp'] = '1' 575 | header['FEN'] = fen 576 | } else { 577 | delete header['SetUp'] 578 | delete header['FEN'] 579 | } 580 | } 581 | 582 | function get(square) { 583 | var piece = board[SQUARE_MAP[square]] 584 | return piece ? { type: piece.type, color: piece.color } : null 585 | } 586 | 587 | function put(piece, square) { 588 | /* check for valid piece object */ 589 | if (!('type' in piece && 'color' in piece)) { 590 | return false 591 | } 592 | 593 | /* check for piece */ 594 | if (SYMBOLS.indexOf(piece.type.toLowerCase()) === -1) { 595 | return false 596 | } 597 | 598 | /* check for valid square */ 599 | if (!(square in SQUARE_MAP)) { 600 | return false 601 | } 602 | 603 | var sq = SQUARE_MAP[square] 604 | 605 | /* don't let the user place more than one king */ 606 | if ( 607 | piece.type == KING && 608 | !(kings[piece.color] == EMPTY || kings[piece.color] == sq) 609 | ) { 610 | return false 611 | } 612 | 613 | board[sq] = { type: piece.type, color: piece.color } 614 | if (piece.type === KING) { 615 | kings[piece.color] = sq 616 | } 617 | 618 | update_setup(generate_fen()) 619 | 620 | return true 621 | } 622 | 623 | function remove(square) { 624 | var piece = get(square) 625 | board[SQUARE_MAP[square]] = null 626 | if (piece && piece.type === KING) { 627 | kings[piece.color] = EMPTY 628 | } 629 | 630 | update_setup(generate_fen()) 631 | 632 | return piece 633 | } 634 | 635 | function build_move(board, from, to, flags, promotion) { 636 | var move = { 637 | color: turn, 638 | from: from, 639 | to: to, 640 | flags: flags, 641 | piece: board[from].type, 642 | } 643 | 644 | if (promotion) { 645 | move.flags |= BITS.PROMOTION 646 | move.promotion = promotion 647 | } 648 | 649 | if (board[to]) { 650 | move.captured = board[to].type 651 | } else if (flags & BITS.EP_CAPTURE) { 652 | move.captured = PAWN 653 | } 654 | return move 655 | } 656 | 657 | function generate_moves(options) { 658 | function add_move(board, moves, from, to, flags) { 659 | /* if pawn promotion */ 660 | if ( 661 | board[from].type === PAWN && 662 | (rank(to) === RANK_8 || rank(to) === RANK_1) 663 | ) { 664 | var pieces = [QUEEN, ROOK, BISHOP, KNIGHT] 665 | for (var i = 0, len = pieces.length; i < len; i++) { 666 | moves.push(build_move(board, from, to, flags, pieces[i])) 667 | } 668 | } else { 669 | moves.push(build_move(board, from, to, flags)) 670 | } 671 | } 672 | 673 | var moves = [] 674 | var us = turn 675 | var them = swap_color(us) 676 | var second_rank = { b: RANK_7, w: RANK_2 } 677 | 678 | var first_sq = SQUARE_MAP.a8 679 | var last_sq = SQUARE_MAP.h1 680 | var single_square = false 681 | 682 | /* do we want legal moves? */ 683 | var legal = 684 | typeof options !== 'undefined' && 'legal' in options 685 | ? options.legal 686 | : true 687 | 688 | var piece_type = 689 | typeof options !== 'undefined' && 690 | 'piece' in options && 691 | typeof options.piece === 'string' 692 | ? options.piece.toLowerCase() 693 | : true 694 | 695 | /* are we generating moves for a single square? */ 696 | if (typeof options !== 'undefined' && 'square' in options) { 697 | if (options.square in SQUARE_MAP) { 698 | first_sq = last_sq = SQUARE_MAP[options.square] 699 | single_square = true 700 | } else { 701 | /* invalid square */ 702 | return [] 703 | } 704 | } 705 | 706 | for (var i = first_sq; i <= last_sq; i++) { 707 | /* did we run off the end of the board */ 708 | if (i & 0x88) { 709 | i += 7 710 | continue 711 | } 712 | 713 | var piece = board[i] 714 | if (piece == null || piece.color !== us) { 715 | continue 716 | } 717 | 718 | if (piece.type === PAWN && (piece_type === true || piece_type === PAWN)) { 719 | /* single square, non-capturing */ 720 | var square = i + PAWN_OFFSETS[us][0] 721 | if (board[square] == null) { 722 | add_move(board, moves, i, square, BITS.NORMAL) 723 | 724 | /* double square */ 725 | var square = i + PAWN_OFFSETS[us][1] 726 | if (second_rank[us] === rank(i) && board[square] == null) { 727 | add_move(board, moves, i, square, BITS.BIG_PAWN) 728 | } 729 | } 730 | 731 | /* pawn captures */ 732 | for (j = 2; j < 4; j++) { 733 | var square = i + PAWN_OFFSETS[us][j] 734 | if (square & 0x88) continue 735 | 736 | if (board[square] != null && board[square].color === them) { 737 | add_move(board, moves, i, square, BITS.CAPTURE) 738 | } else if (square === ep_square) { 739 | add_move(board, moves, i, ep_square, BITS.EP_CAPTURE) 740 | } 741 | } 742 | } else if (piece_type === true || piece_type === piece.type) { 743 | for (var j = 0, len = PIECE_OFFSETS[piece.type].length; j < len; j++) { 744 | var offset = PIECE_OFFSETS[piece.type][j] 745 | var square = i 746 | 747 | while (true) { 748 | square += offset 749 | if (square & 0x88) break 750 | 751 | if (board[square] == null) { 752 | add_move(board, moves, i, square, BITS.NORMAL) 753 | } else { 754 | if (board[square].color === us) break 755 | add_move(board, moves, i, square, BITS.CAPTURE) 756 | break 757 | } 758 | 759 | /* break, if knight or king */ 760 | if (piece.type === 'n' || piece.type === 'k') break 761 | } 762 | } 763 | } 764 | } 765 | 766 | /* check for castling if: a) we're generating all moves, or b) we're doing 767 | * single square move generation on the king's square 768 | */ 769 | if (piece_type === true || piece_type === KING) { 770 | if (!single_square || last_sq === kings[us]) { 771 | /* king-side castling */ 772 | if (castling[us] & BITS.KSIDE_CASTLE) { 773 | var castling_from = kings[us] 774 | var castling_to = castling_from + 2 775 | 776 | if ( 777 | board[castling_from + 1] == null && 778 | board[castling_to] == null && 779 | !attacked(them, kings[us]) && 780 | !attacked(them, castling_from + 1) && 781 | !attacked(them, castling_to) 782 | ) { 783 | add_move(board, moves, kings[us], castling_to, BITS.KSIDE_CASTLE) 784 | } 785 | } 786 | 787 | /* queen-side castling */ 788 | if (castling[us] & BITS.QSIDE_CASTLE) { 789 | var castling_from = kings[us] 790 | var castling_to = castling_from - 2 791 | 792 | if ( 793 | board[castling_from - 1] == null && 794 | board[castling_from - 2] == null && 795 | board[castling_from - 3] == null && 796 | !attacked(them, kings[us]) && 797 | !attacked(them, castling_from - 1) && 798 | !attacked(them, castling_to) 799 | ) { 800 | add_move(board, moves, kings[us], castling_to, BITS.QSIDE_CASTLE) 801 | } 802 | } 803 | } 804 | } 805 | 806 | /* return all pseudo-legal moves (this includes moves that allow the king 807 | * to be captured) 808 | */ 809 | if (!legal) { 810 | return moves 811 | } 812 | 813 | /* filter out illegal moves */ 814 | var legal_moves = [] 815 | for (var i = 0, len = moves.length; i < len; i++) { 816 | make_move(moves[i]) 817 | if (!king_attacked(us)) { 818 | legal_moves.push(moves[i]) 819 | } 820 | undo_move() 821 | } 822 | 823 | return legal_moves 824 | } 825 | 826 | /* convert a move from 0x88 coordinates to Standard Algebraic Notation 827 | * (SAN) 828 | * 829 | * @param {boolean} sloppy Use the sloppy SAN generator to work around over 830 | * disambiguation bugs in Fritz and Chessbase. See below: 831 | * 832 | * r1bqkbnr/ppp2ppp/2n5/1B1pP3/4P3/8/PPPP2PP/RNBQK1NR b KQkq - 2 4 833 | * 4. ... Nge7 is overly disambiguated because the knight on c6 is pinned 834 | * 4. ... Ne7 is technically the valid SAN 835 | */ 836 | function move_to_san(move, moves) { 837 | var output = '' 838 | 839 | if (move.flags & BITS.KSIDE_CASTLE) { 840 | output = 'O-O' 841 | } else if (move.flags & BITS.QSIDE_CASTLE) { 842 | output = 'O-O-O' 843 | } else { 844 | if (move.piece !== PAWN) { 845 | var disambiguator = get_disambiguator(move, moves) 846 | output += move.piece.toUpperCase() + disambiguator 847 | } 848 | 849 | if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) { 850 | if (move.piece === PAWN) { 851 | output += algebraic(move.from)[0] 852 | } 853 | output += 'x' 854 | } 855 | 856 | output += algebraic(move.to) 857 | 858 | if (move.flags & BITS.PROMOTION) { 859 | output += '=' + move.promotion.toUpperCase() 860 | } 861 | } 862 | 863 | make_move(move) 864 | if (in_check()) { 865 | if (in_checkmate()) { 866 | output += '#' 867 | } else { 868 | output += '+' 869 | } 870 | } 871 | undo_move() 872 | 873 | return output 874 | } 875 | 876 | function attacked(color, square) { 877 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 878 | /* did we run off the end of the board */ 879 | if (i & 0x88) { 880 | i += 7 881 | continue 882 | } 883 | 884 | /* if empty square or wrong color */ 885 | if (board[i] == null || board[i].color !== color) continue 886 | 887 | var piece = board[i] 888 | var difference = i - square 889 | var index = difference + 119 890 | 891 | if (ATTACKS[index] & (1 << SHIFTS[piece.type])) { 892 | if (piece.type === PAWN) { 893 | if (difference > 0) { 894 | if (piece.color === WHITE) return true 895 | } else { 896 | if (piece.color === BLACK) return true 897 | } 898 | continue 899 | } 900 | 901 | /* if the piece is a knight or a king */ 902 | if (piece.type === 'n' || piece.type === 'k') return true 903 | 904 | var offset = RAYS[index] 905 | var j = i + offset 906 | 907 | var blocked = false 908 | while (j !== square) { 909 | if (board[j] != null) { 910 | blocked = true 911 | break 912 | } 913 | j += offset 914 | } 915 | 916 | if (!blocked) return true 917 | } 918 | } 919 | 920 | return false 921 | } 922 | 923 | function king_attacked(color) { 924 | return attacked(swap_color(color), kings[color]) 925 | } 926 | 927 | function in_check() { 928 | return king_attacked(turn) 929 | } 930 | 931 | function in_checkmate() { 932 | return in_check() && generate_moves().length === 0 933 | } 934 | 935 | function in_stalemate() { 936 | return !in_check() && generate_moves().length === 0 937 | } 938 | 939 | function insufficient_material() { 940 | var pieces = {} 941 | var bishops = [] 942 | var num_pieces = 0 943 | var sq_color = 0 944 | 945 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 946 | sq_color = (sq_color + 1) % 2 947 | if (i & 0x88) { 948 | i += 7 949 | continue 950 | } 951 | 952 | var piece = board[i] 953 | if (piece) { 954 | pieces[piece.type] = piece.type in pieces ? pieces[piece.type] + 1 : 1 955 | if (piece.type === BISHOP) { 956 | bishops.push(sq_color) 957 | } 958 | num_pieces++ 959 | } 960 | } 961 | 962 | /* k vs. k */ 963 | if (num_pieces === 2) { 964 | return true 965 | } else if ( 966 | /* k vs. kn .... or .... k vs. kb */ 967 | num_pieces === 3 && 968 | (pieces[BISHOP] === 1 || pieces[KNIGHT] === 1) 969 | ) { 970 | return true 971 | } else if (num_pieces === pieces[BISHOP] + 2) { 972 | /* kb vs. kb where any number of bishops are all on the same color */ 973 | var sum = 0 974 | var len = bishops.length 975 | for (var i = 0; i < len; i++) { 976 | sum += bishops[i] 977 | } 978 | if (sum === 0 || sum === len) { 979 | return true 980 | } 981 | } 982 | 983 | return false 984 | } 985 | 986 | function in_threefold_repetition() { 987 | /* TODO: while this function is fine for casual use, a better 988 | * implementation would use a Zobrist key (instead of FEN). the 989 | * Zobrist key would be maintained in the make_move/undo_move functions, 990 | * avoiding the costly that we do below. 991 | */ 992 | var moves = [] 993 | var positions = {} 994 | var repetition = false 995 | 996 | while (true) { 997 | var move = undo_move() 998 | if (!move) break 999 | moves.push(move) 1000 | } 1001 | 1002 | while (true) { 1003 | /* remove the last two fields in the FEN string, they're not needed 1004 | * when checking for draw by rep */ 1005 | var fen = generate_fen().split(' ').slice(0, 4).join(' ') 1006 | 1007 | /* has the position occurred three or move times */ 1008 | positions[fen] = fen in positions ? positions[fen] + 1 : 1 1009 | if (positions[fen] >= 3) { 1010 | repetition = true 1011 | } 1012 | 1013 | if (!moves.length) { 1014 | break 1015 | } 1016 | make_move(moves.pop()) 1017 | } 1018 | 1019 | return repetition 1020 | } 1021 | 1022 | function push(move) { 1023 | history.push({ 1024 | move: move, 1025 | kings: { b: kings.b, w: kings.w }, 1026 | turn: turn, 1027 | castling: { b: castling.b, w: castling.w }, 1028 | ep_square: ep_square, 1029 | half_moves: half_moves, 1030 | move_number: move_number, 1031 | }) 1032 | } 1033 | 1034 | function make_move(move) { 1035 | var us = turn 1036 | var them = swap_color(us) 1037 | push(move) 1038 | 1039 | board[move.to] = board[move.from] 1040 | board[move.from] = null 1041 | 1042 | /* if ep capture, remove the captured pawn */ 1043 | if (move.flags & BITS.EP_CAPTURE) { 1044 | if (turn === BLACK) { 1045 | board[move.to - 16] = null 1046 | } else { 1047 | board[move.to + 16] = null 1048 | } 1049 | } 1050 | 1051 | /* if pawn promotion, replace with new piece */ 1052 | if (move.flags & BITS.PROMOTION) { 1053 | board[move.to] = { type: move.promotion, color: us } 1054 | } 1055 | 1056 | /* if we moved the king */ 1057 | if (board[move.to].type === KING) { 1058 | kings[board[move.to].color] = move.to 1059 | 1060 | /* if we castled, move the rook next to the king */ 1061 | if (move.flags & BITS.KSIDE_CASTLE) { 1062 | var castling_to = move.to - 1 1063 | var castling_from = move.to + 1 1064 | board[castling_to] = board[castling_from] 1065 | board[castling_from] = null 1066 | } else if (move.flags & BITS.QSIDE_CASTLE) { 1067 | var castling_to = move.to + 1 1068 | var castling_from = move.to - 2 1069 | board[castling_to] = board[castling_from] 1070 | board[castling_from] = null 1071 | } 1072 | 1073 | /* turn off castling */ 1074 | castling[us] = '' 1075 | } 1076 | 1077 | /* turn off castling if we move a rook */ 1078 | if (castling[us]) { 1079 | for (var i = 0, len = ROOKS[us].length; i < len; i++) { 1080 | if ( 1081 | move.from === ROOKS[us][i].square && 1082 | castling[us] & ROOKS[us][i].flag 1083 | ) { 1084 | castling[us] ^= ROOKS[us][i].flag 1085 | break 1086 | } 1087 | } 1088 | } 1089 | 1090 | /* turn off castling if we capture a rook */ 1091 | if (castling[them]) { 1092 | for (var i = 0, len = ROOKS[them].length; i < len; i++) { 1093 | if ( 1094 | move.to === ROOKS[them][i].square && 1095 | castling[them] & ROOKS[them][i].flag 1096 | ) { 1097 | castling[them] ^= ROOKS[them][i].flag 1098 | break 1099 | } 1100 | } 1101 | } 1102 | 1103 | /* if big pawn move, update the en passant square */ 1104 | if (move.flags & BITS.BIG_PAWN) { 1105 | if (turn === 'b') { 1106 | ep_square = move.to - 16 1107 | } else { 1108 | ep_square = move.to + 16 1109 | } 1110 | } else { 1111 | ep_square = EMPTY 1112 | } 1113 | 1114 | /* reset the 50 move counter if a pawn is moved or a piece is captured */ 1115 | if (move.piece === PAWN) { 1116 | half_moves = 0 1117 | } else if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) { 1118 | half_moves = 0 1119 | } else { 1120 | half_moves++ 1121 | } 1122 | 1123 | if (turn === BLACK) { 1124 | move_number++ 1125 | } 1126 | turn = swap_color(turn) 1127 | } 1128 | 1129 | function undo_move() { 1130 | var old = history.pop() 1131 | if (old == null) { 1132 | return null 1133 | } 1134 | 1135 | var move = old.move 1136 | kings = old.kings 1137 | turn = old.turn 1138 | castling = old.castling 1139 | ep_square = old.ep_square 1140 | half_moves = old.half_moves 1141 | move_number = old.move_number 1142 | 1143 | var us = turn 1144 | var them = swap_color(turn) 1145 | 1146 | board[move.from] = board[move.to] 1147 | board[move.from].type = move.piece // to undo any promotions 1148 | board[move.to] = null 1149 | 1150 | if (move.flags & BITS.CAPTURE) { 1151 | board[move.to] = { type: move.captured, color: them } 1152 | } else if (move.flags & BITS.EP_CAPTURE) { 1153 | var index 1154 | if (us === BLACK) { 1155 | index = move.to - 16 1156 | } else { 1157 | index = move.to + 16 1158 | } 1159 | board[index] = { type: PAWN, color: them } 1160 | } 1161 | 1162 | if (move.flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE)) { 1163 | var castling_to, castling_from 1164 | if (move.flags & BITS.KSIDE_CASTLE) { 1165 | castling_to = move.to + 1 1166 | castling_from = move.to - 1 1167 | } else if (move.flags & BITS.QSIDE_CASTLE) { 1168 | castling_to = move.to - 2 1169 | castling_from = move.to + 1 1170 | } 1171 | 1172 | board[castling_to] = board[castling_from] 1173 | board[castling_from] = null 1174 | } 1175 | 1176 | return move 1177 | } 1178 | 1179 | // convert a move from Standard Algebraic Notation (SAN) to 0x88 coordinates 1180 | function move_from_san(move, sloppy) { 1181 | // strip off any move decorations: e.g Nf3+?! becomes Nf3 1182 | var clean_move = stripped_san(move) 1183 | 1184 | // the move parsers is a 2-step state 1185 | for (var parser = 0; parser < 2; parser++) { 1186 | if (parser == PARSER_SLOPPY) { 1187 | // only run the sloppy parse if explicitly requested 1188 | if (!sloppy) { 1189 | return null 1190 | } 1191 | 1192 | // The sloppy parser allows the user to parse non-standard chess 1193 | // notations. This parser is opt-in (by specifying the 1194 | // '{ sloppy: true }' setting) and is only run after the Standard 1195 | // Algebraic Notation (SAN) parser has failed. 1196 | // 1197 | // When running the sloppy parser, we'll run a regex to grab the piece, 1198 | // the to/from square, and an optional promotion piece. This regex will 1199 | // parse common non-standard notation like: Pe2-e4, Rc1c4, Qf3xf7, 1200 | // f7f8q, b1c3 1201 | 1202 | // NOTE: Some positions and moves may be ambiguous when using the 1203 | // sloppy parser. For example, in this position: 1204 | // 6k1/8/8/B7/8/8/8/BN4K1 w - - 0 1, the move b1c3 may be interpreted 1205 | // as Nc3 or B1c3 (a disambiguated bishop move). In these cases, the 1206 | // sloppy parser will default to the most most basic interpretation 1207 | // (which is b1c3 parsing to Nc3). 1208 | 1209 | // FIXME: these var's are hoisted into function scope, this will need 1210 | // to change when switching to const/let 1211 | 1212 | var overly_disambiguated = false 1213 | 1214 | var matches = clean_move.match( 1215 | /([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnQRBN])?/ 1216 | ) 1217 | if (matches) { 1218 | var piece = matches[1] 1219 | var from = matches[2] 1220 | var to = matches[3] 1221 | var promotion = matches[4] 1222 | 1223 | if (from.length == 1) { 1224 | overly_disambiguated = true 1225 | } 1226 | } else { 1227 | // The [a-h]?[1-8]? portion of the regex below handles moves that may 1228 | // be overly disambiguated (e.g. Nge7 is unnecessary and non-standard 1229 | // when there is one legal knight move to e7). In this case, the value 1230 | // of 'from' variable will be a rank or file, not a square. 1231 | var matches = clean_move.match( 1232 | /([pnbrqkPNBRQK])?([a-h]?[1-8]?)x?-?([a-h][1-8])([qrbnQRBN])?/ 1233 | ) 1234 | 1235 | if (matches) { 1236 | var piece = matches[1] 1237 | var from = matches[2] 1238 | var to = matches[3] 1239 | var promotion = matches[4] 1240 | 1241 | if (from.length == 1) { 1242 | var overly_disambiguated = true 1243 | } 1244 | } 1245 | } 1246 | } 1247 | 1248 | var piece_type = infer_piece_type(clean_move) 1249 | var moves = generate_moves({ 1250 | legal: true, 1251 | piece: piece ? piece : piece_type, 1252 | }) 1253 | 1254 | for (var i = 0, len = moves.length; i < len; i++) { 1255 | switch (parser) { 1256 | case PARSER_STRICT: { 1257 | if (clean_move === stripped_san(move_to_san(moves[i], moves))) { 1258 | return moves[i] 1259 | } 1260 | break 1261 | } 1262 | case PARSER_SLOPPY: { 1263 | if (matches) { 1264 | // hand-compare move properties with the results from our sloppy 1265 | // regex 1266 | if ( 1267 | (!piece || piece.toLowerCase() == moves[i].piece) && 1268 | SQUARE_MAP[from] == moves[i].from && 1269 | SQUARE_MAP[to] == moves[i].to && 1270 | (!promotion || promotion.toLowerCase() == moves[i].promotion) 1271 | ) { 1272 | return moves[i] 1273 | } else if (overly_disambiguated) { 1274 | // SPECIAL CASE: we parsed a move string that may have an 1275 | // unneeded rank/file disambiguator (e.g. Nge7). The 'from' 1276 | // variable will 1277 | var square = algebraic(moves[i].from) 1278 | if ( 1279 | (!piece || piece.toLowerCase() == moves[i].piece) && 1280 | SQUARE_MAP[to] == moves[i].to && 1281 | (from == square[0] || from == square[1]) && 1282 | (!promotion || promotion.toLowerCase() == moves[i].promotion) 1283 | ) { 1284 | return moves[i] 1285 | } 1286 | } 1287 | } 1288 | } 1289 | } 1290 | } 1291 | } 1292 | 1293 | return null 1294 | } 1295 | 1296 | /* pretty = external move object */ 1297 | function make_pretty(ugly_move) { 1298 | var move = clone(ugly_move) 1299 | move.san = move_to_san(move, generate_moves({ legal: true })) 1300 | move.to = algebraic(move.to) 1301 | move.from = algebraic(move.from) 1302 | 1303 | var flags = '' 1304 | 1305 | for (var flag in BITS) { 1306 | if (BITS[flag] & move.flags) { 1307 | flags += FLAGS[flag] 1308 | } 1309 | } 1310 | move.flags = flags 1311 | 1312 | return move 1313 | } 1314 | 1315 | /***************************************************************************** 1316 | * DEBUGGING UTILITIES 1317 | ****************************************************************************/ 1318 | function perft(depth) { 1319 | var moves = generate_moves({ legal: false }) 1320 | var nodes = 0 1321 | var color = turn 1322 | 1323 | for (var i = 0, len = moves.length; i < len; i++) { 1324 | make_move(moves[i]) 1325 | if (!king_attacked(color)) { 1326 | if (depth - 1 > 0) { 1327 | var child_nodes = perft(depth - 1) 1328 | nodes += child_nodes 1329 | } else { 1330 | nodes++ 1331 | } 1332 | } 1333 | undo_move() 1334 | } 1335 | 1336 | return nodes 1337 | } 1338 | 1339 | return { 1340 | /*************************************************************************** 1341 | * PUBLIC API 1342 | **************************************************************************/ 1343 | load: function (fen) { 1344 | return load(fen) 1345 | }, 1346 | 1347 | reset: function () { 1348 | return reset() 1349 | }, 1350 | 1351 | moves: function (options) { 1352 | /* The internal representation of a chess move is in 0x88 format, and 1353 | * not meant to be human-readable. The code below converts the 0x88 1354 | * square coordinates to algebraic coordinates. It also prunes an 1355 | * unnecessary move keys resulting from a verbose call. 1356 | */ 1357 | 1358 | var ugly_moves = generate_moves(options) 1359 | var moves = [] 1360 | 1361 | for (var i = 0, len = ugly_moves.length; i < len; i++) { 1362 | /* does the user want a full move object (most likely not), or just 1363 | * SAN 1364 | */ 1365 | if ( 1366 | typeof options !== 'undefined' && 1367 | 'verbose' in options && 1368 | options.verbose 1369 | ) { 1370 | moves.push(make_pretty(ugly_moves[i])) 1371 | } else { 1372 | moves.push( 1373 | move_to_san(ugly_moves[i], generate_moves({ legal: true })) 1374 | ) 1375 | } 1376 | } 1377 | 1378 | return moves 1379 | }, 1380 | 1381 | in_check: function () { 1382 | return in_check() 1383 | }, 1384 | 1385 | in_checkmate: function () { 1386 | return in_checkmate() 1387 | }, 1388 | 1389 | in_stalemate: function () { 1390 | return in_stalemate() 1391 | }, 1392 | 1393 | in_draw: function () { 1394 | return ( 1395 | half_moves >= 100 || 1396 | in_stalemate() || 1397 | insufficient_material() || 1398 | in_threefold_repetition() 1399 | ) 1400 | }, 1401 | 1402 | insufficient_material: function () { 1403 | return insufficient_material() 1404 | }, 1405 | 1406 | in_threefold_repetition: function () { 1407 | return in_threefold_repetition() 1408 | }, 1409 | 1410 | game_over: function () { 1411 | return ( 1412 | half_moves >= 100 || 1413 | in_checkmate() || 1414 | in_stalemate() || 1415 | insufficient_material() || 1416 | in_threefold_repetition() 1417 | ) 1418 | }, 1419 | 1420 | validate_fen: function (fen) { 1421 | return validate_fen(fen) 1422 | }, 1423 | 1424 | fen: function () { 1425 | return generate_fen() 1426 | }, 1427 | 1428 | board: function () { 1429 | var output = [], 1430 | row = [] 1431 | 1432 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 1433 | if (board[i] == null) { 1434 | row.push(null) 1435 | } else { 1436 | row.push({ 1437 | square: algebraic(i), 1438 | type: board[i].type, 1439 | color: board[i].color, 1440 | }) 1441 | } 1442 | if ((i + 1) & 0x88) { 1443 | output.push(row) 1444 | row = [] 1445 | i += 8 1446 | } 1447 | } 1448 | 1449 | return output 1450 | }, 1451 | 1452 | pgn: function (options) { 1453 | /* using the specification from http://www.chessclub.com/help/PGN-spec 1454 | * example for html usage: .pgn({ max_width: 72, newline_char: "
" }) 1455 | */ 1456 | var newline = 1457 | typeof options === 'object' && typeof options.newline_char === 'string' 1458 | ? options.newline_char 1459 | : '\n' 1460 | var max_width = 1461 | typeof options === 'object' && typeof options.max_width === 'number' 1462 | ? options.max_width 1463 | : 0 1464 | var result = [] 1465 | var header_exists = false 1466 | 1467 | /* add the PGN header headerrmation */ 1468 | for (var i in header) { 1469 | /* TODO: order of enumerated properties in header object is not 1470 | * guaranteed, see ECMA-262 spec (section 12.6.4) 1471 | */ 1472 | result.push('[' + i + ' "' + header[i] + '"]' + newline) 1473 | header_exists = true 1474 | } 1475 | 1476 | if (header_exists && history.length) { 1477 | result.push(newline) 1478 | } 1479 | 1480 | var append_comment = function (move_string) { 1481 | var comment = comments[generate_fen()] 1482 | if (typeof comment !== 'undefined') { 1483 | var delimiter = move_string.length > 0 ? ' ' : '' 1484 | move_string = `${move_string}${delimiter}{${comment}}` 1485 | } 1486 | return move_string 1487 | } 1488 | 1489 | /* pop all of history onto reversed_history */ 1490 | var reversed_history = [] 1491 | while (history.length > 0) { 1492 | reversed_history.push(undo_move()) 1493 | } 1494 | 1495 | var moves = [] 1496 | var move_string = '' 1497 | 1498 | /* special case of a commented starting position with no moves */ 1499 | if (reversed_history.length === 0) { 1500 | moves.push(append_comment('')) 1501 | } 1502 | 1503 | /* build the list of moves. a move_string looks like: "3. e3 e6" */ 1504 | while (reversed_history.length > 0) { 1505 | move_string = append_comment(move_string) 1506 | var move = reversed_history.pop() 1507 | 1508 | /* if the position started with black to move, start PGN with 1. ... */ 1509 | if (!history.length && move.color === 'b') { 1510 | move_string = move_number + '. ...' 1511 | } else if (move.color === 'w') { 1512 | /* store the previous generated move_string if we have one */ 1513 | if (move_string.length) { 1514 | moves.push(move_string) 1515 | } 1516 | move_string = move_number + '.' 1517 | } 1518 | 1519 | move_string = 1520 | move_string + ' ' + move_to_san(move, generate_moves({ legal: true })) 1521 | make_move(move) 1522 | } 1523 | 1524 | /* are there any other leftover moves? */ 1525 | if (move_string.length) { 1526 | moves.push(append_comment(move_string)) 1527 | } 1528 | 1529 | /* is there a result? */ 1530 | if (typeof header.Result !== 'undefined') { 1531 | moves.push(header.Result) 1532 | } 1533 | 1534 | /* history should be back to what it was before we started generating PGN, 1535 | * so join together moves 1536 | */ 1537 | if (max_width === 0) { 1538 | return result.join('') + moves.join(' ') 1539 | } 1540 | 1541 | var strip = function () { 1542 | if (result.length > 0 && result[result.length - 1] === ' ') { 1543 | result.pop() 1544 | return true 1545 | } 1546 | return false 1547 | } 1548 | 1549 | /* NB: this does not preserve comment whitespace. */ 1550 | var wrap_comment = function (width, move) { 1551 | for (var token of move.split(' ')) { 1552 | if (!token) { 1553 | continue 1554 | } 1555 | if (width + token.length > max_width) { 1556 | while (strip()) { 1557 | width-- 1558 | } 1559 | result.push(newline) 1560 | width = 0 1561 | } 1562 | result.push(token) 1563 | width += token.length 1564 | result.push(' ') 1565 | width++ 1566 | } 1567 | if (strip()) { 1568 | width-- 1569 | } 1570 | return width 1571 | } 1572 | 1573 | /* wrap the PGN output at max_width */ 1574 | var current_width = 0 1575 | for (var i = 0; i < moves.length; i++) { 1576 | if (current_width + moves[i].length > max_width) { 1577 | if (moves[i].includes('{')) { 1578 | current_width = wrap_comment(current_width, moves[i]) 1579 | continue 1580 | } 1581 | } 1582 | /* if the current move will push past max_width */ 1583 | if (current_width + moves[i].length > max_width && i !== 0) { 1584 | /* don't end the line with whitespace */ 1585 | if (result[result.length - 1] === ' ') { 1586 | result.pop() 1587 | } 1588 | 1589 | result.push(newline) 1590 | current_width = 0 1591 | } else if (i !== 0) { 1592 | result.push(' ') 1593 | current_width++ 1594 | } 1595 | result.push(moves[i]) 1596 | current_width += moves[i].length 1597 | } 1598 | 1599 | return result.join('') 1600 | }, 1601 | 1602 | load_pgn: function (pgn, options) { 1603 | // allow the user to specify the sloppy move parser to work around over 1604 | // disambiguation bugs in Fritz and Chessbase 1605 | var sloppy = 1606 | typeof options !== 'undefined' && 'sloppy' in options 1607 | ? options.sloppy 1608 | : false 1609 | 1610 | function mask(str) { 1611 | return str.replace(/\\/g, '\\') 1612 | } 1613 | 1614 | function parse_pgn_header(header, options) { 1615 | var newline_char = 1616 | typeof options === 'object' && 1617 | typeof options.newline_char === 'string' 1618 | ? options.newline_char 1619 | : '\r?\n' 1620 | var header_obj = {} 1621 | var headers = header.split(new RegExp(mask(newline_char))) 1622 | var key = '' 1623 | var value = '' 1624 | 1625 | for (var i = 0; i < headers.length; i++) { 1626 | var regex = /^\s*\[([A-Za-z]+)\s*"(.*)"\s*\]\s*$/ 1627 | key = headers[i].replace(regex, '$1') 1628 | value = headers[i].replace(regex, '$2') 1629 | if (trim(key).length > 0) { 1630 | header_obj[key] = value 1631 | } 1632 | } 1633 | 1634 | return header_obj 1635 | } 1636 | 1637 | // strip whitespace from head/tail of PGN block 1638 | pgn = pgn.trim() 1639 | 1640 | var newline_char = 1641 | typeof options === 'object' && typeof options.newline_char === 'string' 1642 | ? options.newline_char 1643 | : '\r?\n' 1644 | 1645 | // RegExp to split header. Takes advantage of the fact that header and movetext 1646 | // will always have a blank line between them (ie, two newline_char's). 1647 | // With default newline_char, will equal: /^(\[((?:\r?\n)|.)*\])(?:\s*\r?\n){2}/ 1648 | var header_regex = new RegExp( 1649 | '^(\\[((?:' + 1650 | mask(newline_char) + 1651 | ')|.)*\\])' + 1652 | '(?:\\s*' + 1653 | mask(newline_char) + 1654 | '){2}' 1655 | ) 1656 | 1657 | // If no header given, begin with moves. 1658 | var header_string = header_regex.test(pgn) 1659 | ? header_regex.exec(pgn)[1] 1660 | : '' 1661 | 1662 | // Put the board in the starting position 1663 | reset() 1664 | 1665 | /* parse PGN header */ 1666 | var headers = parse_pgn_header(header_string, options) 1667 | var fen = '' 1668 | 1669 | for (var key in headers) { 1670 | // check to see user is including fen (possibly with wrong tag case) 1671 | if (key.toLowerCase() === 'fen') { 1672 | fen = headers[key] 1673 | } 1674 | set_header([key, headers[key]]) 1675 | } 1676 | 1677 | /* sloppy parser should attempt to load a fen tag, even if it's 1678 | * the wrong case and doesn't include a corresponding [SetUp "1"] tag */ 1679 | if (sloppy) { 1680 | if (fen) { 1681 | if (!load(fen, true)) { 1682 | return false 1683 | } 1684 | } 1685 | } else { 1686 | /* strict parser - load the starting position indicated by [Setup '1'] 1687 | * and [FEN position] */ 1688 | if (headers['SetUp'] === '1') { 1689 | if (!('FEN' in headers && load(headers['FEN'], true))) { 1690 | // second argument to load: don't clear the headers 1691 | return false 1692 | } 1693 | } 1694 | } 1695 | 1696 | /* NB: the regexes below that delete move numbers, recursive 1697 | * annotations, and numeric annotation glyphs may also match 1698 | * text in comments. To prevent this, we transform comments 1699 | * by hex-encoding them in place and decoding them again after 1700 | * the other tokens have been deleted. 1701 | * 1702 | * While the spec states that PGN files should be ASCII encoded, 1703 | * we use {en,de}codeURIComponent here to support arbitrary UTF8 1704 | * as a convenience for modern users */ 1705 | 1706 | var to_hex = function (string) { 1707 | return Array.from(string) 1708 | .map(function (c) { 1709 | /* encodeURI doesn't transform most ASCII characters, 1710 | * so we handle these ourselves */ 1711 | return c.charCodeAt(0) < 128 1712 | ? c.charCodeAt(0).toString(16) 1713 | : encodeURIComponent(c).replace(/\%/g, '').toLowerCase() 1714 | }) 1715 | .join('') 1716 | } 1717 | 1718 | var from_hex = function (string) { 1719 | return string.length == 0 1720 | ? '' 1721 | : decodeURIComponent('%' + string.match(/.{1,2}/g).join('%')) 1722 | } 1723 | 1724 | var encode_comment = function (string) { 1725 | string = string.replace(new RegExp(mask(newline_char), 'g'), ' ') 1726 | return `{${to_hex(string.slice(1, string.length - 1))}}` 1727 | } 1728 | 1729 | var decode_comment = function (string) { 1730 | if (string.startsWith('{') && string.endsWith('}')) { 1731 | return from_hex(string.slice(1, string.length - 1)) 1732 | } 1733 | } 1734 | 1735 | /* delete header to get the moves */ 1736 | var ms = pgn 1737 | .replace(header_string, '') 1738 | .replace( 1739 | /* encode comments so they don't get deleted below */ 1740 | new RegExp(`(\{[^}]*\})+?|;([^${mask(newline_char)}]*)`, 'g'), 1741 | function (match, bracket, semicolon) { 1742 | return bracket !== undefined 1743 | ? encode_comment(bracket) 1744 | : ' ' + encode_comment(`{${semicolon.slice(1)}}`) 1745 | } 1746 | ) 1747 | .replace(new RegExp(mask(newline_char), 'g'), ' ') 1748 | 1749 | /* delete recursive annotation variations */ 1750 | var rav_regex = /(\([^\(\)]+\))+?/g 1751 | while (rav_regex.test(ms)) { 1752 | ms = ms.replace(rav_regex, '') 1753 | } 1754 | 1755 | /* delete move numbers */ 1756 | ms = ms.replace(/\d+\.(\.\.)?/g, '') 1757 | 1758 | /* delete ... indicating black to move */ 1759 | ms = ms.replace(/\.\.\./g, '') 1760 | 1761 | /* delete numeric annotation glyphs */ 1762 | ms = ms.replace(/\$\d+/g, '') 1763 | 1764 | /* trim and get array of moves */ 1765 | var moves = trim(ms).split(new RegExp(/\s+/)) 1766 | 1767 | /* delete empty entries */ 1768 | moves = moves.join(',').replace(/,,+/g, ',').split(',') 1769 | var move = '' 1770 | 1771 | var result = '' 1772 | 1773 | for (var half_move = 0; half_move < moves.length; half_move++) { 1774 | var comment = decode_comment(moves[half_move]) 1775 | if (comment !== undefined) { 1776 | comments[generate_fen()] = comment 1777 | continue 1778 | } 1779 | 1780 | move = move_from_san(moves[half_move], sloppy) 1781 | 1782 | /* invalid move */ 1783 | if (move == null) { 1784 | /* was the move an end of game marker */ 1785 | if (TERMINATION_MARKERS.indexOf(moves[half_move]) > -1) { 1786 | result = moves[half_move] 1787 | } else { 1788 | return false 1789 | } 1790 | } else { 1791 | /* reset the end of game marker if making a valid move */ 1792 | result = '' 1793 | make_move(move) 1794 | } 1795 | } 1796 | 1797 | /* Per section 8.2.6 of the PGN spec, the Result tag pair must match 1798 | * match the termination marker. Only do this when headers are present, 1799 | * but the result tag is missing 1800 | */ 1801 | if (result && Object.keys(header).length && !header['Result']) { 1802 | set_header(['Result', result]) 1803 | } 1804 | 1805 | return true 1806 | }, 1807 | 1808 | header: function () { 1809 | return set_header(arguments) 1810 | }, 1811 | 1812 | turn: function () { 1813 | return turn 1814 | }, 1815 | 1816 | move: function (move, options) { 1817 | /* The move function can be called with in the following parameters: 1818 | * 1819 | * .move('Nxb7') <- where 'move' is a case-sensitive SAN string 1820 | * 1821 | * .move({ from: 'h7', <- where the 'move' is a move object (additional 1822 | * to :'h8', fields are ignored) 1823 | * promotion: 'q', 1824 | * }) 1825 | */ 1826 | 1827 | // allow the user to specify the sloppy move parser to work around over 1828 | // disambiguation bugs in Fritz and Chessbase 1829 | var sloppy = 1830 | typeof options !== 'undefined' && 'sloppy' in options 1831 | ? options.sloppy 1832 | : false 1833 | 1834 | var move_obj = null 1835 | 1836 | if (typeof move === 'string') { 1837 | move_obj = move_from_san(move, sloppy) 1838 | } else if (typeof move === 'object') { 1839 | var moves = generate_moves() 1840 | 1841 | /* convert the pretty move object to an ugly move object */ 1842 | for (var i = 0, len = moves.length; i < len; i++) { 1843 | if ( 1844 | move.from === algebraic(moves[i].from) && 1845 | move.to === algebraic(moves[i].to) && 1846 | (!('promotion' in moves[i]) || 1847 | move.promotion === moves[i].promotion) 1848 | ) { 1849 | move_obj = moves[i] 1850 | break 1851 | } 1852 | } 1853 | } 1854 | 1855 | /* failed to find move */ 1856 | if (!move_obj) { 1857 | return null 1858 | } 1859 | 1860 | /* need to make a copy of move because we can't generate SAN after the 1861 | * move is made 1862 | */ 1863 | var pretty_move = make_pretty(move_obj) 1864 | 1865 | make_move(move_obj) 1866 | 1867 | return pretty_move 1868 | }, 1869 | 1870 | undo: function () { 1871 | var move = undo_move() 1872 | return move ? make_pretty(move) : null 1873 | }, 1874 | 1875 | clear: function () { 1876 | return clear() 1877 | }, 1878 | 1879 | put: function (piece, square) { 1880 | return put(piece, square) 1881 | }, 1882 | 1883 | get: function (square) { 1884 | return get(square) 1885 | }, 1886 | 1887 | ascii() { 1888 | var s = ' +------------------------+\n' 1889 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 1890 | /* display the rank */ 1891 | if (file(i) === 0) { 1892 | s += ' ' + '87654321'[rank(i)] + ' |' 1893 | } 1894 | 1895 | /* empty piece */ 1896 | if (board[i] == null) { 1897 | s += ' . ' 1898 | } else { 1899 | var piece = board[i].type 1900 | var color = board[i].color 1901 | var symbol = 1902 | color === WHITE ? piece.toUpperCase() : piece.toLowerCase() 1903 | s += ' ' + symbol + ' ' 1904 | } 1905 | 1906 | if ((i + 1) & 0x88) { 1907 | s += '|\n' 1908 | i += 8 1909 | } 1910 | } 1911 | s += ' +------------------------+\n' 1912 | s += ' a b c d e f g h' 1913 | 1914 | return s 1915 | }, 1916 | 1917 | remove: function (square) { 1918 | return remove(square) 1919 | }, 1920 | 1921 | perft: function (depth) { 1922 | return perft(depth) 1923 | }, 1924 | 1925 | square_color: function (square) { 1926 | if (square in SQUARE_MAP) { 1927 | var sq_0x88 = SQUARE_MAP[square] 1928 | return (rank(sq_0x88) + file(sq_0x88)) % 2 === 0 ? 'light' : 'dark' 1929 | } 1930 | 1931 | return null 1932 | }, 1933 | 1934 | history: function (options) { 1935 | var reversed_history = [] 1936 | var move_history = [] 1937 | var verbose = 1938 | typeof options !== 'undefined' && 1939 | 'verbose' in options && 1940 | options.verbose 1941 | 1942 | while (history.length > 0) { 1943 | reversed_history.push(undo_move()) 1944 | } 1945 | 1946 | while (reversed_history.length > 0) { 1947 | var move = reversed_history.pop() 1948 | if (verbose) { 1949 | move_history.push(make_pretty(move)) 1950 | } else { 1951 | move_history.push(move_to_san(move, generate_moves({ legal: true }))) 1952 | } 1953 | make_move(move) 1954 | } 1955 | 1956 | return move_history 1957 | }, 1958 | 1959 | get_comment: function () { 1960 | return comments[generate_fen()] 1961 | }, 1962 | 1963 | set_comment: function (comment) { 1964 | comments[generate_fen()] = comment.replace('{', '[').replace('}', ']') 1965 | }, 1966 | 1967 | delete_comment: function () { 1968 | var comment = comments[generate_fen()] 1969 | delete comments[generate_fen()] 1970 | return comment 1971 | }, 1972 | 1973 | get_comments: function () { 1974 | prune_comments() 1975 | return Object.keys(comments).map(function (fen) { 1976 | return { fen: fen, comment: comments[fen] } 1977 | }) 1978 | }, 1979 | 1980 | delete_comments: function () { 1981 | prune_comments() 1982 | return Object.keys(comments).map(function (fen) { 1983 | var comment = comments[fen] 1984 | delete comments[fen] 1985 | return { fen: fen, comment: comment } 1986 | }) 1987 | }, 1988 | } 1989 | } 1990 | -------------------------------------------------------------------------------- /chrome/icons/anarchy-chess128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phazejeff/auto-en-passant-extension/0fefcaf8ab83869e9135b16c415d08fba3b21822/chrome/icons/anarchy-chess128.png -------------------------------------------------------------------------------- /chrome/icons/anarchy-chess16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phazejeff/auto-en-passant-extension/0fefcaf8ab83869e9135b16c415d08fba3b21822/chrome/icons/anarchy-chess16.png -------------------------------------------------------------------------------- /chrome/icons/anarchy-chess32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phazejeff/auto-en-passant-extension/0fefcaf8ab83869e9135b16c415d08fba3b21822/chrome/icons/anarchy-chess32.png -------------------------------------------------------------------------------- /chrome/icons/anarchy-chess48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phazejeff/auto-en-passant-extension/0fefcaf8ab83869e9135b16c415d08fba3b21822/chrome/icons/anarchy-chess48.png -------------------------------------------------------------------------------- /chrome/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 3, 3 | "name": "Auto En Passant", 4 | "version": "0.1", 5 | "description": "anti brick", 6 | "background": { 7 | "service_worker": "background.js", 8 | "type": "module" 9 | }, 10 | "permissions": ["storage", "scripting", "webNavigation"], 11 | "host_permissions": ["https://*.lichess.org/"], 12 | "action": { 13 | "default_popup": "src/popup.html", 14 | "default_icon": { 15 | "16": "/icons/anarchy-chess16.png", 16 | "32": "/icons/anarchy-chess32.png", 17 | "48": "/icons/anarchy-chess48.png", 18 | "128": "/icons/anarchy-chess128.png" 19 | } 20 | }, 21 | "icons": { 22 | "16": "/icons/anarchy-chess16.png", 23 | "32": "/icons/anarchy-chess32.png", 24 | "48": "/icons/anarchy-chess48.png", 25 | "128": "/icons/anarchy-chess128.png" 26 | } 27 | } -------------------------------------------------------------------------------- /chrome/src/popup.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #262421; 3 | text-align: center; 4 | } 5 | 6 | #piss { 7 | color: #bababa; 8 | font-family: 'Noto Sans', Sans-Serif; 9 | font-size: calc( 20px + 2 * ((100vw - 320px) / 880)); 10 | text-align: center; 11 | } 12 | 13 | .api-key { 14 | color: #3692E7; 15 | font-family: 'Noto Sans', Sans-Serif; 16 | font-size: calc( 12px + 2 * ((100vw - 320px) / 880)); 17 | text-align: center; 18 | text-decoration: none; 19 | } 20 | 21 | .api-key-box { 22 | color: #bababa; 23 | background-color: #404040; 24 | font-family: 'Noto Sans', Sans-Serif; 25 | text-align: center; 26 | border: none; 27 | } 28 | 29 | /* The switch - the box around the slider */ 30 | .switch { 31 | position: relative; 32 | display: inline-block; 33 | width: 60px; 34 | height: 34px; 35 | } 36 | 37 | /* Hide default HTML checkbox */ 38 | .switch input { 39 | opacity: 0; 40 | width: 0; 41 | height: 0; 42 | } 43 | 44 | /* The slider */ 45 | .slider { 46 | position: absolute; 47 | cursor: pointer; 48 | top: 0; 49 | left: 0; 50 | right: 0; 51 | bottom: 0; 52 | background-color: #999; 53 | -webkit-transition: .4s; 54 | transition: .4s; 55 | } 56 | 57 | .slider:before { 58 | position: absolute; 59 | content: ""; 60 | height: 26px; 61 | width: 26px; 62 | left: 4px; 63 | bottom: 4px; 64 | background-color: #404040; 65 | -webkit-transition: .4s; 66 | transition: .4s; 67 | } 68 | 69 | input:checked + .slider { 70 | background-color: #629924; 71 | } 72 | 73 | input:focus + .slider { 74 | box-shadow: 0 0 1px #629924; 75 | } 76 | 77 | input:checked + .slider:before { 78 | -webkit-transform: translateX(26px); 79 | -ms-transform: translateX(26px); 80 | transform: translateX(26px); 81 | } 82 | 83 | /* Rounded sliders */ 84 | .slider.round { 85 | border-radius: 34px; 86 | } 87 | 88 | .slider.round:before { 89 | border-radius: 50%; 90 | } -------------------------------------------------------------------------------- /chrome/src/popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Auto En Passant 5 | 6 | 7 |

Auto En Passant

8 | 12 |

13 |

Get API Key

14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /chrome/src/popup.js: -------------------------------------------------------------------------------- 1 | function checkKey(API_KEY) { 2 | fetch('https://lichess.org/api/account', { 3 | headers: { 4 | Authorization: "Bearer " + API_KEY, 5 | Accept: "application/x-ndjson" 6 | } 7 | }).then(r => { 8 | if (r.status !== 200) { 9 | document.getElementById('checkbox-switch').disabled = true 10 | document.getElementById('span-switch').style.cursor = "not-allowed" 11 | document.getElementById('span-switch').style.title = "Invalid API Key" 12 | } else { 13 | document.getElementById('checkbox-switch').disabled = false 14 | document.getElementById('span-switch').style.cursor = "pointer" 15 | document.getElementById('span-switch').style.title = null 16 | } 17 | }) 18 | } 19 | 20 | // API Key 21 | chrome.storage.sync.get(['API_KEY'], (result) => { 22 | if (result.API_KEY == null) { 23 | document.getElementById('api-key').value = "" 24 | } else { 25 | document.getElementById('api-key').value = result.API_KEY 26 | } 27 | 28 | checkKey(result.API_KEY) 29 | }) 30 | 31 | document.getElementById('api-key').addEventListener('change', (key) => { 32 | chrome.storage.sync.set({API_KEY: key.target.value}) 33 | checkKey(key.target.value) 34 | }) 35 | 36 | 37 | // Toggles 38 | chrome.storage.sync.get(['toggle'], (result) => { 39 | if (result.toggle == true) { 40 | document.getElementById('checkbox-switch').checked = true 41 | } else { 42 | document.getElementById('checkbox-switch').checked = false 43 | } 44 | }) 45 | 46 | document.getElementById('checkbox-switch').addEventListener('change', (e) => { 47 | chrome.storage.sync.set({toggle: e.target.checked}) 48 | }) -------------------------------------------------------------------------------- /chrome/src/script.js: -------------------------------------------------------------------------------- 1 | var API_KEY = "" 2 | 3 | // https://gist.github.com/ornicar/a097406810939cf7be1df8ea30e94f3e 4 | const readStream = processLine => response => { 5 | const stream = response.body.getReader(); 6 | const matcher = /\r?\n/; 7 | const decoder = new TextDecoder(); 8 | let buf = ''; 9 | 10 | const loop = () => 11 | stream.read().then(({ done, value }) => { 12 | if (done) { 13 | if (buf.length > 0) processLine(JSON.parse(buf)); 14 | } else { 15 | const chunk = decoder.decode(value, { 16 | stream: true 17 | }); 18 | buf += chunk; 19 | 20 | const parts = buf.split(matcher); 21 | buf = parts.pop(); 22 | for (const i of parts.filter(p => p)) processLine(JSON.parse(i)); 23 | return loop(); 24 | } 25 | }); 26 | 27 | return loop(); 28 | } 29 | 30 | chrome.storage.sync.get(['API_KEY'], (result) => { 31 | API_KEY = result.API_KEY 32 | 33 | function main() { 34 | // Actual shit starts here 35 | const gameId = window.location.href.split('/')[3] 36 | const boardStream = fetch('https://lichess.org/api/board/game/stream/' + gameId, { 37 | headers: { 38 | Authorization: "Bearer " + API_KEY, 39 | Accept: "application/x-ndjson" 40 | } 41 | }) 42 | 43 | boardStream.then(readStream(game => { 44 | let moves 45 | if (game.type == "gameFull") { moves = game.state.moves.split(' ') } 46 | else if (game.type == "gameState") { moves = game.moves.split(' ') } 47 | 48 | chrome.runtime.sendMessage(moves) // Sends to background process because browser can't import the chess library for whatever reason 49 | })) 50 | } 51 | 52 | chrome.storage.onChanged.addListener((changes, areaName) => { 53 | API_KEY = changes.API_KEY.newValue 54 | main() 55 | }) 56 | 57 | main() 58 | }) -------------------------------------------------------------------------------- /chrome/util.js: -------------------------------------------------------------------------------- 1 | import { Chess } from './chess.js' 2 | 3 | // Gets current lichess game 4 | export function getCurrentGame(moves) { 5 | const chess = new Chess() 6 | 7 | for (let i=0; i < moves.length; i++) { 8 | chess.move({from: moves[i].substring(0,2), to: moves[i].substring(2,4)}) 9 | } 10 | 11 | return chess 12 | } 13 | 14 | // Returns the chess.move for en passant, or null if none avaliable 15 | export function hasEnPassant(game) { 16 | const moves = game.moves({ verbose: true }) 17 | for (let i=0; i < moves.length; i++) { 18 | if (moves[i].flags.includes('e')) { return moves[i] } 19 | } 20 | return null 21 | } -------------------------------------------------------------------------------- /firefox/background.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | let API_KEY = "" 4 | let toggle = false 5 | 6 | browser.storage.sync.get(['API_KEY'], (result) => { 7 | API_KEY = result.API_KEY 8 | }) 9 | 10 | browser.storage.sync.get(['toggle'], (result) => { 11 | toggle = result.toggle 12 | }) 13 | 14 | browser.storage.onChanged.addListener((changes, areaName) => { 15 | if (changes.API_KEY) {API_KEY = changes.API_KEY.newValue} 16 | if (changes.toggle) {toggle = changes.toggle.newValue} 17 | }) 18 | 19 | // Gets the moves from script.js and checks for the funny 20 | browser.runtime.onMessage.addListener((moves, sender) => { 21 | if (moves !== null && toggle) { 22 | const game = getCurrentGame(moves) 23 | const move = hasEnPassant(game) 24 | if (move !== null) { 25 | fetch('https://lichess.org/api/board/game/' + sender.url.split('/')[3] + '/move/' + move.from + move.to, { 26 | method: "post", 27 | headers: { 28 | "Authorization": "Bearer " + API_KEY 29 | } 30 | }) 31 | } 32 | } 33 | 34 | }) 35 | 36 | browser.webNavigation.onCompleted.addListener((details) => { 37 | if (details.frameId == 0) { 38 | browser.tabs.executeScript({ 39 | file: 'src/script.js' 40 | }) 41 | } 42 | }) 43 | -------------------------------------------------------------------------------- /firefox/chess.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, Jeff Hlywa (jhlywa@gmail.com) 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * 8 | * 1. Redistributions of source code must retain the above copyright notice, 9 | * this list of conditions and the following disclaimer. 10 | * 2. Redistributions in binary form must reproduce the above copyright notice, 11 | * this list of conditions and the following disclaimer in the documentation 12 | * and/or other materials provided with the distribution. 13 | * 14 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 18 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | * POSSIBILITY OF SUCH DAMAGE. 25 | * 26 | *----------------------------------------------------------------------------*/ 27 | 28 | const SYMBOLS = 'pnbrqkPNBRQK' 29 | 30 | const DEFAULT_POSITION = 31 | 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1' 32 | 33 | const TERMINATION_MARKERS = ['1-0', '0-1', '1/2-1/2', '*'] 34 | 35 | const PAWN_OFFSETS = { 36 | b: [16, 32, 17, 15], 37 | w: [-16, -32, -17, -15], 38 | } 39 | 40 | const PIECE_OFFSETS = { 41 | n: [-18, -33, -31, -14, 18, 33, 31, 14], 42 | b: [-17, -15, 17, 15], 43 | r: [-16, 1, 16, -1], 44 | q: [-17, -16, -15, 1, 17, 16, 15, -1], 45 | k: [-17, -16, -15, 1, 17, 16, 15, -1], 46 | } 47 | 48 | // prettier-ignore 49 | const ATTACKS = [ 50 | 20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0,20, 0, 51 | 0,20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0,20, 0, 0, 52 | 0, 0,20, 0, 0, 0, 0, 24, 0, 0, 0, 0,20, 0, 0, 0, 53 | 0, 0, 0,20, 0, 0, 0, 24, 0, 0, 0,20, 0, 0, 0, 0, 54 | 0, 0, 0, 0,20, 0, 0, 24, 0, 0,20, 0, 0, 0, 0, 0, 55 | 0, 0, 0, 0, 0,20, 2, 24, 2,20, 0, 0, 0, 0, 0, 0, 56 | 0, 0, 0, 0, 0, 2,53, 56, 53, 2, 0, 0, 0, 0, 0, 0, 57 | 24,24,24,24,24,24,56, 0, 56,24,24,24,24,24,24, 0, 58 | 0, 0, 0, 0, 0, 2,53, 56, 53, 2, 0, 0, 0, 0, 0, 0, 59 | 0, 0, 0, 0, 0,20, 2, 24, 2,20, 0, 0, 0, 0, 0, 0, 60 | 0, 0, 0, 0,20, 0, 0, 24, 0, 0,20, 0, 0, 0, 0, 0, 61 | 0, 0, 0,20, 0, 0, 0, 24, 0, 0, 0,20, 0, 0, 0, 0, 62 | 0, 0,20, 0, 0, 0, 0, 24, 0, 0, 0, 0,20, 0, 0, 0, 63 | 0,20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0,20, 0, 0, 64 | 20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0,20 65 | ]; 66 | 67 | // prettier-ignore 68 | const RAYS = [ 69 | 17, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 15, 0, 70 | 0, 17, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 15, 0, 0, 71 | 0, 0, 17, 0, 0, 0, 0, 16, 0, 0, 0, 0, 15, 0, 0, 0, 72 | 0, 0, 0, 17, 0, 0, 0, 16, 0, 0, 0, 15, 0, 0, 0, 0, 73 | 0, 0, 0, 0, 17, 0, 0, 16, 0, 0, 15, 0, 0, 0, 0, 0, 74 | 0, 0, 0, 0, 0, 17, 0, 16, 0, 15, 0, 0, 0, 0, 0, 0, 75 | 0, 0, 0, 0, 0, 0, 17, 16, 15, 0, 0, 0, 0, 0, 0, 0, 76 | 1, 1, 1, 1, 1, 1, 1, 0, -1, -1, -1,-1, -1, -1, -1, 0, 77 | 0, 0, 0, 0, 0, 0,-15,-16,-17, 0, 0, 0, 0, 0, 0, 0, 78 | 0, 0, 0, 0, 0,-15, 0,-16, 0,-17, 0, 0, 0, 0, 0, 0, 79 | 0, 0, 0, 0,-15, 0, 0,-16, 0, 0,-17, 0, 0, 0, 0, 0, 80 | 0, 0, 0,-15, 0, 0, 0,-16, 0, 0, 0,-17, 0, 0, 0, 0, 81 | 0, 0,-15, 0, 0, 0, 0,-16, 0, 0, 0, 0,-17, 0, 0, 0, 82 | 0,-15, 0, 0, 0, 0, 0,-16, 0, 0, 0, 0, 0,-17, 0, 0, 83 | -15, 0, 0, 0, 0, 0, 0,-16, 0, 0, 0, 0, 0, 0,-17 84 | ]; 85 | 86 | const SHIFTS = { p: 0, n: 1, b: 2, r: 3, q: 4, k: 5 } 87 | 88 | const BITS = { 89 | NORMAL: 1, 90 | CAPTURE: 2, 91 | BIG_PAWN: 4, 92 | EP_CAPTURE: 8, 93 | PROMOTION: 16, 94 | KSIDE_CASTLE: 32, 95 | QSIDE_CASTLE: 64, 96 | } 97 | 98 | const RANK_1 = 7 99 | const RANK_2 = 6 100 | const RANK_3 = 5 101 | const RANK_4 = 4 102 | const RANK_5 = 3 103 | const RANK_6 = 2 104 | const RANK_7 = 1 105 | const RANK_8 = 0 106 | 107 | // prettier-ignore 108 | const SQUARE_MAP = { 109 | a8: 0, b8: 1, c8: 2, d8: 3, e8: 4, f8: 5, g8: 6, h8: 7, 110 | a7: 16, b7: 17, c7: 18, d7: 19, e7: 20, f7: 21, g7: 22, h7: 23, 111 | a6: 32, b6: 33, c6: 34, d6: 35, e6: 36, f6: 37, g6: 38, h6: 39, 112 | a5: 48, b5: 49, c5: 50, d5: 51, e5: 52, f5: 53, g5: 54, h5: 55, 113 | a4: 64, b4: 65, c4: 66, d4: 67, e4: 68, f4: 69, g4: 70, h4: 71, 114 | a3: 80, b3: 81, c3: 82, d3: 83, e3: 84, f3: 85, g3: 86, h3: 87, 115 | a2: 96, b2: 97, c2: 98, d2: 99, e2: 100, f2: 101, g2: 102, h2: 103, 116 | a1: 112, b1: 113, c1: 114, d1: 115, e1: 116, f1: 117, g1: 118, h1: 119 117 | }; 118 | 119 | const ROOKS = { 120 | w: [ 121 | { square: SQUARE_MAP.a1, flag: BITS.QSIDE_CASTLE }, 122 | { square: SQUARE_MAP.h1, flag: BITS.KSIDE_CASTLE }, 123 | ], 124 | b: [ 125 | { square: SQUARE_MAP.a8, flag: BITS.QSIDE_CASTLE }, 126 | { square: SQUARE_MAP.h8, flag: BITS.KSIDE_CASTLE }, 127 | ], 128 | } 129 | 130 | const PARSER_STRICT = 0 131 | const PARSER_SLOPPY = 1 132 | 133 | /* this function is used to uniquely identify ambiguous moves */ 134 | function get_disambiguator(move, moves) { 135 | var from = move.from 136 | var to = move.to 137 | var piece = move.piece 138 | 139 | var ambiguities = 0 140 | var same_rank = 0 141 | var same_file = 0 142 | 143 | for (var i = 0, len = moves.length; i < len; i++) { 144 | var ambig_from = moves[i].from 145 | var ambig_to = moves[i].to 146 | var ambig_piece = moves[i].piece 147 | 148 | /* if a move of the same piece type ends on the same to square, we'll 149 | * need to add a disambiguator to the algebraic notation 150 | */ 151 | if (piece === ambig_piece && from !== ambig_from && to === ambig_to) { 152 | ambiguities++ 153 | 154 | if (rank(from) === rank(ambig_from)) { 155 | same_rank++ 156 | } 157 | 158 | if (file(from) === file(ambig_from)) { 159 | same_file++ 160 | } 161 | } 162 | } 163 | 164 | if (ambiguities > 0) { 165 | /* if there exists a similar moving piece on the same rank and file as 166 | * the move in question, use the square as the disambiguator 167 | */ 168 | if (same_rank > 0 && same_file > 0) { 169 | return algebraic(from) 170 | } else if (same_file > 0) { 171 | /* if the moving piece rests on the same file, use the rank symbol as the 172 | * disambiguator 173 | */ 174 | return algebraic(from).charAt(1) 175 | } else { 176 | /* else use the file symbol */ 177 | return algebraic(from).charAt(0) 178 | } 179 | } 180 | 181 | return '' 182 | } 183 | 184 | function infer_piece_type(san) { 185 | var piece_type = san.charAt(0) 186 | if (piece_type >= 'a' && piece_type <= 'h') { 187 | var matches = san.match(/[a-h]\d.*[a-h]\d/) 188 | if (matches) { 189 | return undefined 190 | } 191 | return PAWN 192 | } 193 | piece_type = piece_type.toLowerCase() 194 | if (piece_type === 'o') { 195 | return KING 196 | } 197 | return piece_type 198 | } 199 | 200 | // parses all of the decorators out of a SAN string 201 | function stripped_san(move) { 202 | return move.replace(/=/, '').replace(/[+#]?[?!]*$/, '') 203 | } 204 | 205 | /***************************************************************************** 206 | * UTILITY FUNCTIONS 207 | ****************************************************************************/ 208 | function rank(i) { 209 | return i >> 4 210 | } 211 | 212 | function file(i) { 213 | return i & 15 214 | } 215 | 216 | function algebraic(i) { 217 | var f = file(i), 218 | r = rank(i) 219 | return 'abcdefgh'.substring(f, f + 1) + '87654321'.substring(r, r + 1) 220 | } 221 | 222 | function swap_color(c) { 223 | return c === WHITE ? BLACK : WHITE 224 | } 225 | 226 | function is_digit(c) { 227 | return '0123456789'.indexOf(c) !== -1 228 | } 229 | 230 | function clone(obj) { 231 | var dupe = obj instanceof Array ? [] : {} 232 | 233 | for (var property in obj) { 234 | if (typeof property === 'object') { 235 | dupe[property] = clone(obj[property]) 236 | } else { 237 | dupe[property] = obj[property] 238 | } 239 | } 240 | 241 | return dupe 242 | } 243 | 244 | function trim(str) { 245 | return str.replace(/^\s+|\s+$/g, '') 246 | } 247 | 248 | /*************************************************************************** 249 | * PUBLIC CONSTANTS 250 | **************************************************************************/ 251 | 252 | const BLACK = 'b' 253 | const WHITE = 'w' 254 | 255 | const EMPTY = -1 256 | 257 | const PAWN = 'p' 258 | const KNIGHT = 'n' 259 | const BISHOP = 'b' 260 | const ROOK = 'r' 261 | const QUEEN = 'q' 262 | const KING = 'k' 263 | 264 | const SQUARES = (function () { 265 | /* from the ECMA-262 spec (section 12.6.4): 266 | * "The mechanics of enumerating the properties ... is 267 | * implementation dependent" 268 | * so: for (var sq in SQUARES) { keys.push(sq); } might not be 269 | * ordered correctly 270 | */ 271 | var keys = [] 272 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 273 | if (i & 0x88) { 274 | i += 7 275 | continue 276 | } 277 | keys.push(algebraic(i)) 278 | } 279 | return keys 280 | })() 281 | 282 | const FLAGS = { 283 | NORMAL: 'n', 284 | CAPTURE: 'c', 285 | BIG_PAWN: 'b', 286 | EP_CAPTURE: 'e', 287 | PROMOTION: 'p', 288 | KSIDE_CASTLE: 'k', 289 | QSIDE_CASTLE: 'q', 290 | } 291 | 292 | const Chess = function (fen) { 293 | var board = new Array(128) 294 | var kings = { w: EMPTY, b: EMPTY } 295 | var turn = WHITE 296 | var castling = { w: 0, b: 0 } 297 | var ep_square = EMPTY 298 | var half_moves = 0 299 | var move_number = 1 300 | var history = [] 301 | var header = {} 302 | var comments = {} 303 | 304 | /* if the user passes in a fen string, load it, else default to 305 | * starting position 306 | */ 307 | if (typeof fen === 'undefined') { 308 | load(DEFAULT_POSITION) 309 | } else { 310 | load(fen) 311 | } 312 | 313 | function clear(keep_headers) { 314 | if (typeof keep_headers === 'undefined') { 315 | keep_headers = false 316 | } 317 | 318 | board = new Array(128) 319 | kings = { w: EMPTY, b: EMPTY } 320 | turn = WHITE 321 | castling = { w: 0, b: 0 } 322 | ep_square = EMPTY 323 | half_moves = 0 324 | move_number = 1 325 | history = [] 326 | if (!keep_headers) header = {} 327 | comments = {} 328 | update_setup(generate_fen()) 329 | } 330 | 331 | function prune_comments() { 332 | var reversed_history = [] 333 | var current_comments = {} 334 | var copy_comment = function (fen) { 335 | if (fen in comments) { 336 | current_comments[fen] = comments[fen] 337 | } 338 | } 339 | while (history.length > 0) { 340 | reversed_history.push(undo_move()) 341 | } 342 | copy_comment(generate_fen()) 343 | while (reversed_history.length > 0) { 344 | make_move(reversed_history.pop()) 345 | copy_comment(generate_fen()) 346 | } 347 | comments = current_comments 348 | } 349 | 350 | function reset() { 351 | load(DEFAULT_POSITION) 352 | } 353 | 354 | function load(fen, keep_headers) { 355 | if (typeof keep_headers === 'undefined') { 356 | keep_headers = false 357 | } 358 | 359 | var tokens = fen.split(/\s+/) 360 | var position = tokens[0] 361 | var square = 0 362 | 363 | if (!validate_fen(fen).valid) { 364 | return false 365 | } 366 | 367 | clear(keep_headers) 368 | 369 | for (var i = 0; i < position.length; i++) { 370 | var piece = position.charAt(i) 371 | 372 | if (piece === '/') { 373 | square += 8 374 | } else if (is_digit(piece)) { 375 | square += parseInt(piece, 10) 376 | } else { 377 | var color = piece < 'a' ? WHITE : BLACK 378 | put({ type: piece.toLowerCase(), color: color }, algebraic(square)) 379 | square++ 380 | } 381 | } 382 | 383 | turn = tokens[1] 384 | 385 | if (tokens[2].indexOf('K') > -1) { 386 | castling.w |= BITS.KSIDE_CASTLE 387 | } 388 | if (tokens[2].indexOf('Q') > -1) { 389 | castling.w |= BITS.QSIDE_CASTLE 390 | } 391 | if (tokens[2].indexOf('k') > -1) { 392 | castling.b |= BITS.KSIDE_CASTLE 393 | } 394 | if (tokens[2].indexOf('q') > -1) { 395 | castling.b |= BITS.QSIDE_CASTLE 396 | } 397 | 398 | ep_square = tokens[3] === '-' ? EMPTY : SQUARE_MAP[tokens[3]] 399 | half_moves = parseInt(tokens[4], 10) 400 | move_number = parseInt(tokens[5], 10) 401 | 402 | update_setup(generate_fen()) 403 | 404 | return true 405 | } 406 | 407 | /* TODO: this function is pretty much crap - it validates structure but 408 | * completely ignores content (e.g. doesn't verify that each side has a king) 409 | * ... we should rewrite this, and ditch the silly error_number field while 410 | * we're at it 411 | */ 412 | function validate_fen(fen) { 413 | var errors = { 414 | 0: 'No errors.', 415 | 1: 'FEN string must contain six space-delimited fields.', 416 | 2: '6th field (move number) must be a positive integer.', 417 | 3: '5th field (half move counter) must be a non-negative integer.', 418 | 4: '4th field (en-passant square) is invalid.', 419 | 5: '3rd field (castling availability) is invalid.', 420 | 6: '2nd field (side to move) is invalid.', 421 | 7: "1st field (piece positions) does not contain 8 '/'-delimited rows.", 422 | 8: '1st field (piece positions) is invalid [consecutive numbers].', 423 | 9: '1st field (piece positions) is invalid [invalid piece].', 424 | 10: '1st field (piece positions) is invalid [row too large].', 425 | 11: 'Illegal en-passant square', 426 | } 427 | 428 | /* 1st criterion: 6 space-seperated fields? */ 429 | var tokens = fen.split(/\s+/) 430 | if (tokens.length !== 6) { 431 | return { valid: false, error_number: 1, error: errors[1] } 432 | } 433 | 434 | /* 2nd criterion: move number field is a integer value > 0? */ 435 | if (isNaN(tokens[5]) || parseInt(tokens[5], 10) <= 0) { 436 | return { valid: false, error_number: 2, error: errors[2] } 437 | } 438 | 439 | /* 3rd criterion: half move counter is an integer >= 0? */ 440 | if (isNaN(tokens[4]) || parseInt(tokens[4], 10) < 0) { 441 | return { valid: false, error_number: 3, error: errors[3] } 442 | } 443 | 444 | /* 4th criterion: 4th field is a valid e.p.-string? */ 445 | if (!/^(-|[abcdefgh][36])$/.test(tokens[3])) { 446 | return { valid: false, error_number: 4, error: errors[4] } 447 | } 448 | 449 | /* 5th criterion: 3th field is a valid castle-string? */ 450 | if (!/^(KQ?k?q?|Qk?q?|kq?|q|-)$/.test(tokens[2])) { 451 | return { valid: false, error_number: 5, error: errors[5] } 452 | } 453 | 454 | /* 6th criterion: 2nd field is "w" (white) or "b" (black)? */ 455 | if (!/^(w|b)$/.test(tokens[1])) { 456 | return { valid: false, error_number: 6, error: errors[6] } 457 | } 458 | 459 | /* 7th criterion: 1st field contains 8 rows? */ 460 | var rows = tokens[0].split('/') 461 | if (rows.length !== 8) { 462 | return { valid: false, error_number: 7, error: errors[7] } 463 | } 464 | 465 | /* 8th criterion: every row is valid? */ 466 | for (var i = 0; i < rows.length; i++) { 467 | /* check for right sum of fields AND not two numbers in succession */ 468 | var sum_fields = 0 469 | var previous_was_number = false 470 | 471 | for (var k = 0; k < rows[i].length; k++) { 472 | if (!isNaN(rows[i][k])) { 473 | if (previous_was_number) { 474 | return { valid: false, error_number: 8, error: errors[8] } 475 | } 476 | sum_fields += parseInt(rows[i][k], 10) 477 | previous_was_number = true 478 | } else { 479 | if (!/^[prnbqkPRNBQK]$/.test(rows[i][k])) { 480 | return { valid: false, error_number: 9, error: errors[9] } 481 | } 482 | sum_fields += 1 483 | previous_was_number = false 484 | } 485 | } 486 | if (sum_fields !== 8) { 487 | return { valid: false, error_number: 10, error: errors[10] } 488 | } 489 | } 490 | 491 | if ( 492 | (tokens[3][1] == '3' && tokens[1] == 'w') || 493 | (tokens[3][1] == '6' && tokens[1] == 'b') 494 | ) { 495 | return { valid: false, error_number: 11, error: errors[11] } 496 | } 497 | 498 | /* everything's okay! */ 499 | return { valid: true, error_number: 0, error: errors[0] } 500 | } 501 | 502 | function generate_fen() { 503 | var empty = 0 504 | var fen = '' 505 | 506 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 507 | if (board[i] == null) { 508 | empty++ 509 | } else { 510 | if (empty > 0) { 511 | fen += empty 512 | empty = 0 513 | } 514 | var color = board[i].color 515 | var piece = board[i].type 516 | 517 | fen += color === WHITE ? piece.toUpperCase() : piece.toLowerCase() 518 | } 519 | 520 | if ((i + 1) & 0x88) { 521 | if (empty > 0) { 522 | fen += empty 523 | } 524 | 525 | if (i !== SQUARE_MAP.h1) { 526 | fen += '/' 527 | } 528 | 529 | empty = 0 530 | i += 8 531 | } 532 | } 533 | 534 | var cflags = '' 535 | if (castling[WHITE] & BITS.KSIDE_CASTLE) { 536 | cflags += 'K' 537 | } 538 | if (castling[WHITE] & BITS.QSIDE_CASTLE) { 539 | cflags += 'Q' 540 | } 541 | if (castling[BLACK] & BITS.KSIDE_CASTLE) { 542 | cflags += 'k' 543 | } 544 | if (castling[BLACK] & BITS.QSIDE_CASTLE) { 545 | cflags += 'q' 546 | } 547 | 548 | /* do we have an empty castling flag? */ 549 | cflags = cflags || '-' 550 | var epflags = ep_square === EMPTY ? '-' : algebraic(ep_square) 551 | 552 | return [fen, turn, cflags, epflags, half_moves, move_number].join(' ') 553 | } 554 | 555 | function set_header(args) { 556 | for (var i = 0; i < args.length; i += 2) { 557 | if (typeof args[i] === 'string' && typeof args[i + 1] === 'string') { 558 | header[args[i]] = args[i + 1] 559 | } 560 | } 561 | return header 562 | } 563 | 564 | /* called when the initial board setup is changed with put() or remove(). 565 | * modifies the SetUp and FEN properties of the header object. if the FEN is 566 | * equal to the default position, the SetUp and FEN are deleted 567 | * the setup is only updated if history.length is zero, ie moves haven't been 568 | * made. 569 | */ 570 | function update_setup(fen) { 571 | if (history.length > 0) return 572 | 573 | if (fen !== DEFAULT_POSITION) { 574 | header['SetUp'] = '1' 575 | header['FEN'] = fen 576 | } else { 577 | delete header['SetUp'] 578 | delete header['FEN'] 579 | } 580 | } 581 | 582 | function get(square) { 583 | var piece = board[SQUARE_MAP[square]] 584 | return piece ? { type: piece.type, color: piece.color } : null 585 | } 586 | 587 | function put(piece, square) { 588 | /* check for valid piece object */ 589 | if (!('type' in piece && 'color' in piece)) { 590 | return false 591 | } 592 | 593 | /* check for piece */ 594 | if (SYMBOLS.indexOf(piece.type.toLowerCase()) === -1) { 595 | return false 596 | } 597 | 598 | /* check for valid square */ 599 | if (!(square in SQUARE_MAP)) { 600 | return false 601 | } 602 | 603 | var sq = SQUARE_MAP[square] 604 | 605 | /* don't let the user place more than one king */ 606 | if ( 607 | piece.type == KING && 608 | !(kings[piece.color] == EMPTY || kings[piece.color] == sq) 609 | ) { 610 | return false 611 | } 612 | 613 | board[sq] = { type: piece.type, color: piece.color } 614 | if (piece.type === KING) { 615 | kings[piece.color] = sq 616 | } 617 | 618 | update_setup(generate_fen()) 619 | 620 | return true 621 | } 622 | 623 | function remove(square) { 624 | var piece = get(square) 625 | board[SQUARE_MAP[square]] = null 626 | if (piece && piece.type === KING) { 627 | kings[piece.color] = EMPTY 628 | } 629 | 630 | update_setup(generate_fen()) 631 | 632 | return piece 633 | } 634 | 635 | function build_move(board, from, to, flags, promotion) { 636 | var move = { 637 | color: turn, 638 | from: from, 639 | to: to, 640 | flags: flags, 641 | piece: board[from].type, 642 | } 643 | 644 | if (promotion) { 645 | move.flags |= BITS.PROMOTION 646 | move.promotion = promotion 647 | } 648 | 649 | if (board[to]) { 650 | move.captured = board[to].type 651 | } else if (flags & BITS.EP_CAPTURE) { 652 | move.captured = PAWN 653 | } 654 | return move 655 | } 656 | 657 | function generate_moves(options) { 658 | function add_move(board, moves, from, to, flags) { 659 | /* if pawn promotion */ 660 | if ( 661 | board[from].type === PAWN && 662 | (rank(to) === RANK_8 || rank(to) === RANK_1) 663 | ) { 664 | var pieces = [QUEEN, ROOK, BISHOP, KNIGHT] 665 | for (var i = 0, len = pieces.length; i < len; i++) { 666 | moves.push(build_move(board, from, to, flags, pieces[i])) 667 | } 668 | } else { 669 | moves.push(build_move(board, from, to, flags)) 670 | } 671 | } 672 | 673 | var moves = [] 674 | var us = turn 675 | var them = swap_color(us) 676 | var second_rank = { b: RANK_7, w: RANK_2 } 677 | 678 | var first_sq = SQUARE_MAP.a8 679 | var last_sq = SQUARE_MAP.h1 680 | var single_square = false 681 | 682 | /* do we want legal moves? */ 683 | var legal = 684 | typeof options !== 'undefined' && 'legal' in options 685 | ? options.legal 686 | : true 687 | 688 | var piece_type = 689 | typeof options !== 'undefined' && 690 | 'piece' in options && 691 | typeof options.piece === 'string' 692 | ? options.piece.toLowerCase() 693 | : true 694 | 695 | /* are we generating moves for a single square? */ 696 | if (typeof options !== 'undefined' && 'square' in options) { 697 | if (options.square in SQUARE_MAP) { 698 | first_sq = last_sq = SQUARE_MAP[options.square] 699 | single_square = true 700 | } else { 701 | /* invalid square */ 702 | return [] 703 | } 704 | } 705 | 706 | for (var i = first_sq; i <= last_sq; i++) { 707 | /* did we run off the end of the board */ 708 | if (i & 0x88) { 709 | i += 7 710 | continue 711 | } 712 | 713 | var piece = board[i] 714 | if (piece == null || piece.color !== us) { 715 | continue 716 | } 717 | 718 | if (piece.type === PAWN && (piece_type === true || piece_type === PAWN)) { 719 | /* single square, non-capturing */ 720 | var square = i + PAWN_OFFSETS[us][0] 721 | if (board[square] == null) { 722 | add_move(board, moves, i, square, BITS.NORMAL) 723 | 724 | /* double square */ 725 | var square = i + PAWN_OFFSETS[us][1] 726 | if (second_rank[us] === rank(i) && board[square] == null) { 727 | add_move(board, moves, i, square, BITS.BIG_PAWN) 728 | } 729 | } 730 | 731 | /* pawn captures */ 732 | for (j = 2; j < 4; j++) { 733 | var square = i + PAWN_OFFSETS[us][j] 734 | if (square & 0x88) continue 735 | 736 | if (board[square] != null && board[square].color === them) { 737 | add_move(board, moves, i, square, BITS.CAPTURE) 738 | } else if (square === ep_square) { 739 | add_move(board, moves, i, ep_square, BITS.EP_CAPTURE) 740 | } 741 | } 742 | } else if (piece_type === true || piece_type === piece.type) { 743 | for (var j = 0, len = PIECE_OFFSETS[piece.type].length; j < len; j++) { 744 | var offset = PIECE_OFFSETS[piece.type][j] 745 | var square = i 746 | 747 | while (true) { 748 | square += offset 749 | if (square & 0x88) break 750 | 751 | if (board[square] == null) { 752 | add_move(board, moves, i, square, BITS.NORMAL) 753 | } else { 754 | if (board[square].color === us) break 755 | add_move(board, moves, i, square, BITS.CAPTURE) 756 | break 757 | } 758 | 759 | /* break, if knight or king */ 760 | if (piece.type === 'n' || piece.type === 'k') break 761 | } 762 | } 763 | } 764 | } 765 | 766 | /* check for castling if: a) we're generating all moves, or b) we're doing 767 | * single square move generation on the king's square 768 | */ 769 | if (piece_type === true || piece_type === KING) { 770 | if (!single_square || last_sq === kings[us]) { 771 | /* king-side castling */ 772 | if (castling[us] & BITS.KSIDE_CASTLE) { 773 | var castling_from = kings[us] 774 | var castling_to = castling_from + 2 775 | 776 | if ( 777 | board[castling_from + 1] == null && 778 | board[castling_to] == null && 779 | !attacked(them, kings[us]) && 780 | !attacked(them, castling_from + 1) && 781 | !attacked(them, castling_to) 782 | ) { 783 | add_move(board, moves, kings[us], castling_to, BITS.KSIDE_CASTLE) 784 | } 785 | } 786 | 787 | /* queen-side castling */ 788 | if (castling[us] & BITS.QSIDE_CASTLE) { 789 | var castling_from = kings[us] 790 | var castling_to = castling_from - 2 791 | 792 | if ( 793 | board[castling_from - 1] == null && 794 | board[castling_from - 2] == null && 795 | board[castling_from - 3] == null && 796 | !attacked(them, kings[us]) && 797 | !attacked(them, castling_from - 1) && 798 | !attacked(them, castling_to) 799 | ) { 800 | add_move(board, moves, kings[us], castling_to, BITS.QSIDE_CASTLE) 801 | } 802 | } 803 | } 804 | } 805 | 806 | /* return all pseudo-legal moves (this includes moves that allow the king 807 | * to be captured) 808 | */ 809 | if (!legal) { 810 | return moves 811 | } 812 | 813 | /* filter out illegal moves */ 814 | var legal_moves = [] 815 | for (var i = 0, len = moves.length; i < len; i++) { 816 | make_move(moves[i]) 817 | if (!king_attacked(us)) { 818 | legal_moves.push(moves[i]) 819 | } 820 | undo_move() 821 | } 822 | 823 | return legal_moves 824 | } 825 | 826 | /* convert a move from 0x88 coordinates to Standard Algebraic Notation 827 | * (SAN) 828 | * 829 | * @param {boolean} sloppy Use the sloppy SAN generator to work around over 830 | * disambiguation bugs in Fritz and Chessbase. See below: 831 | * 832 | * r1bqkbnr/ppp2ppp/2n5/1B1pP3/4P3/8/PPPP2PP/RNBQK1NR b KQkq - 2 4 833 | * 4. ... Nge7 is overly disambiguated because the knight on c6 is pinned 834 | * 4. ... Ne7 is technically the valid SAN 835 | */ 836 | function move_to_san(move, moves) { 837 | var output = '' 838 | 839 | if (move.flags & BITS.KSIDE_CASTLE) { 840 | output = 'O-O' 841 | } else if (move.flags & BITS.QSIDE_CASTLE) { 842 | output = 'O-O-O' 843 | } else { 844 | if (move.piece !== PAWN) { 845 | var disambiguator = get_disambiguator(move, moves) 846 | output += move.piece.toUpperCase() + disambiguator 847 | } 848 | 849 | if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) { 850 | if (move.piece === PAWN) { 851 | output += algebraic(move.from)[0] 852 | } 853 | output += 'x' 854 | } 855 | 856 | output += algebraic(move.to) 857 | 858 | if (move.flags & BITS.PROMOTION) { 859 | output += '=' + move.promotion.toUpperCase() 860 | } 861 | } 862 | 863 | make_move(move) 864 | if (in_check()) { 865 | if (in_checkmate()) { 866 | output += '#' 867 | } else { 868 | output += '+' 869 | } 870 | } 871 | undo_move() 872 | 873 | return output 874 | } 875 | 876 | function attacked(color, square) { 877 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 878 | /* did we run off the end of the board */ 879 | if (i & 0x88) { 880 | i += 7 881 | continue 882 | } 883 | 884 | /* if empty square or wrong color */ 885 | if (board[i] == null || board[i].color !== color) continue 886 | 887 | var piece = board[i] 888 | var difference = i - square 889 | var index = difference + 119 890 | 891 | if (ATTACKS[index] & (1 << SHIFTS[piece.type])) { 892 | if (piece.type === PAWN) { 893 | if (difference > 0) { 894 | if (piece.color === WHITE) return true 895 | } else { 896 | if (piece.color === BLACK) return true 897 | } 898 | continue 899 | } 900 | 901 | /* if the piece is a knight or a king */ 902 | if (piece.type === 'n' || piece.type === 'k') return true 903 | 904 | var offset = RAYS[index] 905 | var j = i + offset 906 | 907 | var blocked = false 908 | while (j !== square) { 909 | if (board[j] != null) { 910 | blocked = true 911 | break 912 | } 913 | j += offset 914 | } 915 | 916 | if (!blocked) return true 917 | } 918 | } 919 | 920 | return false 921 | } 922 | 923 | function king_attacked(color) { 924 | return attacked(swap_color(color), kings[color]) 925 | } 926 | 927 | function in_check() { 928 | return king_attacked(turn) 929 | } 930 | 931 | function in_checkmate() { 932 | return in_check() && generate_moves().length === 0 933 | } 934 | 935 | function in_stalemate() { 936 | return !in_check() && generate_moves().length === 0 937 | } 938 | 939 | function insufficient_material() { 940 | var pieces = {} 941 | var bishops = [] 942 | var num_pieces = 0 943 | var sq_color = 0 944 | 945 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 946 | sq_color = (sq_color + 1) % 2 947 | if (i & 0x88) { 948 | i += 7 949 | continue 950 | } 951 | 952 | var piece = board[i] 953 | if (piece) { 954 | pieces[piece.type] = piece.type in pieces ? pieces[piece.type] + 1 : 1 955 | if (piece.type === BISHOP) { 956 | bishops.push(sq_color) 957 | } 958 | num_pieces++ 959 | } 960 | } 961 | 962 | /* k vs. k */ 963 | if (num_pieces === 2) { 964 | return true 965 | } else if ( 966 | /* k vs. kn .... or .... k vs. kb */ 967 | num_pieces === 3 && 968 | (pieces[BISHOP] === 1 || pieces[KNIGHT] === 1) 969 | ) { 970 | return true 971 | } else if (num_pieces === pieces[BISHOP] + 2) { 972 | /* kb vs. kb where any number of bishops are all on the same color */ 973 | var sum = 0 974 | var len = bishops.length 975 | for (var i = 0; i < len; i++) { 976 | sum += bishops[i] 977 | } 978 | if (sum === 0 || sum === len) { 979 | return true 980 | } 981 | } 982 | 983 | return false 984 | } 985 | 986 | function in_threefold_repetition() { 987 | /* TODO: while this function is fine for casual use, a better 988 | * implementation would use a Zobrist key (instead of FEN). the 989 | * Zobrist key would be maintained in the make_move/undo_move functions, 990 | * avoiding the costly that we do below. 991 | */ 992 | var moves = [] 993 | var positions = {} 994 | var repetition = false 995 | 996 | while (true) { 997 | var move = undo_move() 998 | if (!move) break 999 | moves.push(move) 1000 | } 1001 | 1002 | while (true) { 1003 | /* remove the last two fields in the FEN string, they're not needed 1004 | * when checking for draw by rep */ 1005 | var fen = generate_fen().split(' ').slice(0, 4).join(' ') 1006 | 1007 | /* has the position occurred three or move times */ 1008 | positions[fen] = fen in positions ? positions[fen] + 1 : 1 1009 | if (positions[fen] >= 3) { 1010 | repetition = true 1011 | } 1012 | 1013 | if (!moves.length) { 1014 | break 1015 | } 1016 | make_move(moves.pop()) 1017 | } 1018 | 1019 | return repetition 1020 | } 1021 | 1022 | function push(move) { 1023 | history.push({ 1024 | move: move, 1025 | kings: { b: kings.b, w: kings.w }, 1026 | turn: turn, 1027 | castling: { b: castling.b, w: castling.w }, 1028 | ep_square: ep_square, 1029 | half_moves: half_moves, 1030 | move_number: move_number, 1031 | }) 1032 | } 1033 | 1034 | function make_move(move) { 1035 | var us = turn 1036 | var them = swap_color(us) 1037 | push(move) 1038 | 1039 | board[move.to] = board[move.from] 1040 | board[move.from] = null 1041 | 1042 | /* if ep capture, remove the captured pawn */ 1043 | if (move.flags & BITS.EP_CAPTURE) { 1044 | if (turn === BLACK) { 1045 | board[move.to - 16] = null 1046 | } else { 1047 | board[move.to + 16] = null 1048 | } 1049 | } 1050 | 1051 | /* if pawn promotion, replace with new piece */ 1052 | if (move.flags & BITS.PROMOTION) { 1053 | board[move.to] = { type: move.promotion, color: us } 1054 | } 1055 | 1056 | /* if we moved the king */ 1057 | if (board[move.to].type === KING) { 1058 | kings[board[move.to].color] = move.to 1059 | 1060 | /* if we castled, move the rook next to the king */ 1061 | if (move.flags & BITS.KSIDE_CASTLE) { 1062 | var castling_to = move.to - 1 1063 | var castling_from = move.to + 1 1064 | board[castling_to] = board[castling_from] 1065 | board[castling_from] = null 1066 | } else if (move.flags & BITS.QSIDE_CASTLE) { 1067 | var castling_to = move.to + 1 1068 | var castling_from = move.to - 2 1069 | board[castling_to] = board[castling_from] 1070 | board[castling_from] = null 1071 | } 1072 | 1073 | /* turn off castling */ 1074 | castling[us] = '' 1075 | } 1076 | 1077 | /* turn off castling if we move a rook */ 1078 | if (castling[us]) { 1079 | for (var i = 0, len = ROOKS[us].length; i < len; i++) { 1080 | if ( 1081 | move.from === ROOKS[us][i].square && 1082 | castling[us] & ROOKS[us][i].flag 1083 | ) { 1084 | castling[us] ^= ROOKS[us][i].flag 1085 | break 1086 | } 1087 | } 1088 | } 1089 | 1090 | /* turn off castling if we capture a rook */ 1091 | if (castling[them]) { 1092 | for (var i = 0, len = ROOKS[them].length; i < len; i++) { 1093 | if ( 1094 | move.to === ROOKS[them][i].square && 1095 | castling[them] & ROOKS[them][i].flag 1096 | ) { 1097 | castling[them] ^= ROOKS[them][i].flag 1098 | break 1099 | } 1100 | } 1101 | } 1102 | 1103 | /* if big pawn move, update the en passant square */ 1104 | if (move.flags & BITS.BIG_PAWN) { 1105 | if (turn === 'b') { 1106 | ep_square = move.to - 16 1107 | } else { 1108 | ep_square = move.to + 16 1109 | } 1110 | } else { 1111 | ep_square = EMPTY 1112 | } 1113 | 1114 | /* reset the 50 move counter if a pawn is moved or a piece is captured */ 1115 | if (move.piece === PAWN) { 1116 | half_moves = 0 1117 | } else if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) { 1118 | half_moves = 0 1119 | } else { 1120 | half_moves++ 1121 | } 1122 | 1123 | if (turn === BLACK) { 1124 | move_number++ 1125 | } 1126 | turn = swap_color(turn) 1127 | } 1128 | 1129 | function undo_move() { 1130 | var old = history.pop() 1131 | if (old == null) { 1132 | return null 1133 | } 1134 | 1135 | var move = old.move 1136 | kings = old.kings 1137 | turn = old.turn 1138 | castling = old.castling 1139 | ep_square = old.ep_square 1140 | half_moves = old.half_moves 1141 | move_number = old.move_number 1142 | 1143 | var us = turn 1144 | var them = swap_color(turn) 1145 | 1146 | board[move.from] = board[move.to] 1147 | board[move.from].type = move.piece // to undo any promotions 1148 | board[move.to] = null 1149 | 1150 | if (move.flags & BITS.CAPTURE) { 1151 | board[move.to] = { type: move.captured, color: them } 1152 | } else if (move.flags & BITS.EP_CAPTURE) { 1153 | var index 1154 | if (us === BLACK) { 1155 | index = move.to - 16 1156 | } else { 1157 | index = move.to + 16 1158 | } 1159 | board[index] = { type: PAWN, color: them } 1160 | } 1161 | 1162 | if (move.flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE)) { 1163 | var castling_to, castling_from 1164 | if (move.flags & BITS.KSIDE_CASTLE) { 1165 | castling_to = move.to + 1 1166 | castling_from = move.to - 1 1167 | } else if (move.flags & BITS.QSIDE_CASTLE) { 1168 | castling_to = move.to - 2 1169 | castling_from = move.to + 1 1170 | } 1171 | 1172 | board[castling_to] = board[castling_from] 1173 | board[castling_from] = null 1174 | } 1175 | 1176 | return move 1177 | } 1178 | 1179 | // convert a move from Standard Algebraic Notation (SAN) to 0x88 coordinates 1180 | function move_from_san(move, sloppy) { 1181 | // strip off any move decorations: e.g Nf3+?! becomes Nf3 1182 | var clean_move = stripped_san(move) 1183 | 1184 | // the move parsers is a 2-step state 1185 | for (var parser = 0; parser < 2; parser++) { 1186 | if (parser == PARSER_SLOPPY) { 1187 | // only run the sloppy parse if explicitly requested 1188 | if (!sloppy) { 1189 | return null 1190 | } 1191 | 1192 | // The sloppy parser allows the user to parse non-standard chess 1193 | // notations. This parser is opt-in (by specifying the 1194 | // '{ sloppy: true }' setting) and is only run after the Standard 1195 | // Algebraic Notation (SAN) parser has failed. 1196 | // 1197 | // When running the sloppy parser, we'll run a regex to grab the piece, 1198 | // the to/from square, and an optional promotion piece. This regex will 1199 | // parse common non-standard notation like: Pe2-e4, Rc1c4, Qf3xf7, 1200 | // f7f8q, b1c3 1201 | 1202 | // NOTE: Some positions and moves may be ambiguous when using the 1203 | // sloppy parser. For example, in this position: 1204 | // 6k1/8/8/B7/8/8/8/BN4K1 w - - 0 1, the move b1c3 may be interpreted 1205 | // as Nc3 or B1c3 (a disambiguated bishop move). In these cases, the 1206 | // sloppy parser will default to the most most basic interpretation 1207 | // (which is b1c3 parsing to Nc3). 1208 | 1209 | // FIXME: these var's are hoisted into function scope, this will need 1210 | // to change when switching to const/let 1211 | 1212 | var overly_disambiguated = false 1213 | 1214 | var matches = clean_move.match( 1215 | /([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnQRBN])?/ 1216 | ) 1217 | if (matches) { 1218 | var piece = matches[1] 1219 | var from = matches[2] 1220 | var to = matches[3] 1221 | var promotion = matches[4] 1222 | 1223 | if (from.length == 1) { 1224 | overly_disambiguated = true 1225 | } 1226 | } else { 1227 | // The [a-h]?[1-8]? portion of the regex below handles moves that may 1228 | // be overly disambiguated (e.g. Nge7 is unnecessary and non-standard 1229 | // when there is one legal knight move to e7). In this case, the value 1230 | // of 'from' variable will be a rank or file, not a square. 1231 | var matches = clean_move.match( 1232 | /([pnbrqkPNBRQK])?([a-h]?[1-8]?)x?-?([a-h][1-8])([qrbnQRBN])?/ 1233 | ) 1234 | 1235 | if (matches) { 1236 | var piece = matches[1] 1237 | var from = matches[2] 1238 | var to = matches[3] 1239 | var promotion = matches[4] 1240 | 1241 | if (from.length == 1) { 1242 | var overly_disambiguated = true 1243 | } 1244 | } 1245 | } 1246 | } 1247 | 1248 | var piece_type = infer_piece_type(clean_move) 1249 | var moves = generate_moves({ 1250 | legal: true, 1251 | piece: piece ? piece : piece_type, 1252 | }) 1253 | 1254 | for (var i = 0, len = moves.length; i < len; i++) { 1255 | switch (parser) { 1256 | case PARSER_STRICT: { 1257 | if (clean_move === stripped_san(move_to_san(moves[i], moves))) { 1258 | return moves[i] 1259 | } 1260 | break 1261 | } 1262 | case PARSER_SLOPPY: { 1263 | if (matches) { 1264 | // hand-compare move properties with the results from our sloppy 1265 | // regex 1266 | if ( 1267 | (!piece || piece.toLowerCase() == moves[i].piece) && 1268 | SQUARE_MAP[from] == moves[i].from && 1269 | SQUARE_MAP[to] == moves[i].to && 1270 | (!promotion || promotion.toLowerCase() == moves[i].promotion) 1271 | ) { 1272 | return moves[i] 1273 | } else if (overly_disambiguated) { 1274 | // SPECIAL CASE: we parsed a move string that may have an 1275 | // unneeded rank/file disambiguator (e.g. Nge7). The 'from' 1276 | // variable will 1277 | var square = algebraic(moves[i].from) 1278 | if ( 1279 | (!piece || piece.toLowerCase() == moves[i].piece) && 1280 | SQUARE_MAP[to] == moves[i].to && 1281 | (from == square[0] || from == square[1]) && 1282 | (!promotion || promotion.toLowerCase() == moves[i].promotion) 1283 | ) { 1284 | return moves[i] 1285 | } 1286 | } 1287 | } 1288 | } 1289 | } 1290 | } 1291 | } 1292 | 1293 | return null 1294 | } 1295 | 1296 | /* pretty = external move object */ 1297 | function make_pretty(ugly_move) { 1298 | var move = clone(ugly_move) 1299 | move.san = move_to_san(move, generate_moves({ legal: true })) 1300 | move.to = algebraic(move.to) 1301 | move.from = algebraic(move.from) 1302 | 1303 | var flags = '' 1304 | 1305 | for (var flag in BITS) { 1306 | if (BITS[flag] & move.flags) { 1307 | flags += FLAGS[flag] 1308 | } 1309 | } 1310 | move.flags = flags 1311 | 1312 | return move 1313 | } 1314 | 1315 | /***************************************************************************** 1316 | * DEBUGGING UTILITIES 1317 | ****************************************************************************/ 1318 | function perft(depth) { 1319 | var moves = generate_moves({ legal: false }) 1320 | var nodes = 0 1321 | var color = turn 1322 | 1323 | for (var i = 0, len = moves.length; i < len; i++) { 1324 | make_move(moves[i]) 1325 | if (!king_attacked(color)) { 1326 | if (depth - 1 > 0) { 1327 | var child_nodes = perft(depth - 1) 1328 | nodes += child_nodes 1329 | } else { 1330 | nodes++ 1331 | } 1332 | } 1333 | undo_move() 1334 | } 1335 | 1336 | return nodes 1337 | } 1338 | 1339 | return { 1340 | /*************************************************************************** 1341 | * PUBLIC API 1342 | **************************************************************************/ 1343 | load: function (fen) { 1344 | return load(fen) 1345 | }, 1346 | 1347 | reset: function () { 1348 | return reset() 1349 | }, 1350 | 1351 | moves: function (options) { 1352 | /* The internal representation of a chess move is in 0x88 format, and 1353 | * not meant to be human-readable. The code below converts the 0x88 1354 | * square coordinates to algebraic coordinates. It also prunes an 1355 | * unnecessary move keys resulting from a verbose call. 1356 | */ 1357 | 1358 | var ugly_moves = generate_moves(options) 1359 | var moves = [] 1360 | 1361 | for (var i = 0, len = ugly_moves.length; i < len; i++) { 1362 | /* does the user want a full move object (most likely not), or just 1363 | * SAN 1364 | */ 1365 | if ( 1366 | typeof options !== 'undefined' && 1367 | 'verbose' in options && 1368 | options.verbose 1369 | ) { 1370 | moves.push(make_pretty(ugly_moves[i])) 1371 | } else { 1372 | moves.push( 1373 | move_to_san(ugly_moves[i], generate_moves({ legal: true })) 1374 | ) 1375 | } 1376 | } 1377 | 1378 | return moves 1379 | }, 1380 | 1381 | in_check: function () { 1382 | return in_check() 1383 | }, 1384 | 1385 | in_checkmate: function () { 1386 | return in_checkmate() 1387 | }, 1388 | 1389 | in_stalemate: function () { 1390 | return in_stalemate() 1391 | }, 1392 | 1393 | in_draw: function () { 1394 | return ( 1395 | half_moves >= 100 || 1396 | in_stalemate() || 1397 | insufficient_material() || 1398 | in_threefold_repetition() 1399 | ) 1400 | }, 1401 | 1402 | insufficient_material: function () { 1403 | return insufficient_material() 1404 | }, 1405 | 1406 | in_threefold_repetition: function () { 1407 | return in_threefold_repetition() 1408 | }, 1409 | 1410 | game_over: function () { 1411 | return ( 1412 | half_moves >= 100 || 1413 | in_checkmate() || 1414 | in_stalemate() || 1415 | insufficient_material() || 1416 | in_threefold_repetition() 1417 | ) 1418 | }, 1419 | 1420 | validate_fen: function (fen) { 1421 | return validate_fen(fen) 1422 | }, 1423 | 1424 | fen: function () { 1425 | return generate_fen() 1426 | }, 1427 | 1428 | board: function () { 1429 | var output = [], 1430 | row = [] 1431 | 1432 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 1433 | if (board[i] == null) { 1434 | row.push(null) 1435 | } else { 1436 | row.push({ 1437 | square: algebraic(i), 1438 | type: board[i].type, 1439 | color: board[i].color, 1440 | }) 1441 | } 1442 | if ((i + 1) & 0x88) { 1443 | output.push(row) 1444 | row = [] 1445 | i += 8 1446 | } 1447 | } 1448 | 1449 | return output 1450 | }, 1451 | 1452 | pgn: function (options) { 1453 | /* using the specification from http://www.chessclub.com/help/PGN-spec 1454 | * example for html usage: .pgn({ max_width: 72, newline_char: "
" }) 1455 | */ 1456 | var newline = 1457 | typeof options === 'object' && typeof options.newline_char === 'string' 1458 | ? options.newline_char 1459 | : '\n' 1460 | var max_width = 1461 | typeof options === 'object' && typeof options.max_width === 'number' 1462 | ? options.max_width 1463 | : 0 1464 | var result = [] 1465 | var header_exists = false 1466 | 1467 | /* add the PGN header headerrmation */ 1468 | for (var i in header) { 1469 | /* TODO: order of enumerated properties in header object is not 1470 | * guaranteed, see ECMA-262 spec (section 12.6.4) 1471 | */ 1472 | result.push('[' + i + ' "' + header[i] + '"]' + newline) 1473 | header_exists = true 1474 | } 1475 | 1476 | if (header_exists && history.length) { 1477 | result.push(newline) 1478 | } 1479 | 1480 | var append_comment = function (move_string) { 1481 | var comment = comments[generate_fen()] 1482 | if (typeof comment !== 'undefined') { 1483 | var delimiter = move_string.length > 0 ? ' ' : '' 1484 | move_string = `${move_string}${delimiter}{${comment}}` 1485 | } 1486 | return move_string 1487 | } 1488 | 1489 | /* pop all of history onto reversed_history */ 1490 | var reversed_history = [] 1491 | while (history.length > 0) { 1492 | reversed_history.push(undo_move()) 1493 | } 1494 | 1495 | var moves = [] 1496 | var move_string = '' 1497 | 1498 | /* special case of a commented starting position with no moves */ 1499 | if (reversed_history.length === 0) { 1500 | moves.push(append_comment('')) 1501 | } 1502 | 1503 | /* build the list of moves. a move_string looks like: "3. e3 e6" */ 1504 | while (reversed_history.length > 0) { 1505 | move_string = append_comment(move_string) 1506 | var move = reversed_history.pop() 1507 | 1508 | /* if the position started with black to move, start PGN with 1. ... */ 1509 | if (!history.length && move.color === 'b') { 1510 | move_string = move_number + '. ...' 1511 | } else if (move.color === 'w') { 1512 | /* store the previous generated move_string if we have one */ 1513 | if (move_string.length) { 1514 | moves.push(move_string) 1515 | } 1516 | move_string = move_number + '.' 1517 | } 1518 | 1519 | move_string = 1520 | move_string + ' ' + move_to_san(move, generate_moves({ legal: true })) 1521 | make_move(move) 1522 | } 1523 | 1524 | /* are there any other leftover moves? */ 1525 | if (move_string.length) { 1526 | moves.push(append_comment(move_string)) 1527 | } 1528 | 1529 | /* is there a result? */ 1530 | if (typeof header.Result !== 'undefined') { 1531 | moves.push(header.Result) 1532 | } 1533 | 1534 | /* history should be back to what it was before we started generating PGN, 1535 | * so join together moves 1536 | */ 1537 | if (max_width === 0) { 1538 | return result.join('') + moves.join(' ') 1539 | } 1540 | 1541 | var strip = function () { 1542 | if (result.length > 0 && result[result.length - 1] === ' ') { 1543 | result.pop() 1544 | return true 1545 | } 1546 | return false 1547 | } 1548 | 1549 | /* NB: this does not preserve comment whitespace. */ 1550 | var wrap_comment = function (width, move) { 1551 | for (var token of move.split(' ')) { 1552 | if (!token) { 1553 | continue 1554 | } 1555 | if (width + token.length > max_width) { 1556 | while (strip()) { 1557 | width-- 1558 | } 1559 | result.push(newline) 1560 | width = 0 1561 | } 1562 | result.push(token) 1563 | width += token.length 1564 | result.push(' ') 1565 | width++ 1566 | } 1567 | if (strip()) { 1568 | width-- 1569 | } 1570 | return width 1571 | } 1572 | 1573 | /* wrap the PGN output at max_width */ 1574 | var current_width = 0 1575 | for (var i = 0; i < moves.length; i++) { 1576 | if (current_width + moves[i].length > max_width) { 1577 | if (moves[i].includes('{')) { 1578 | current_width = wrap_comment(current_width, moves[i]) 1579 | continue 1580 | } 1581 | } 1582 | /* if the current move will push past max_width */ 1583 | if (current_width + moves[i].length > max_width && i !== 0) { 1584 | /* don't end the line with whitespace */ 1585 | if (result[result.length - 1] === ' ') { 1586 | result.pop() 1587 | } 1588 | 1589 | result.push(newline) 1590 | current_width = 0 1591 | } else if (i !== 0) { 1592 | result.push(' ') 1593 | current_width++ 1594 | } 1595 | result.push(moves[i]) 1596 | current_width += moves[i].length 1597 | } 1598 | 1599 | return result.join('') 1600 | }, 1601 | 1602 | load_pgn: function (pgn, options) { 1603 | // allow the user to specify the sloppy move parser to work around over 1604 | // disambiguation bugs in Fritz and Chessbase 1605 | var sloppy = 1606 | typeof options !== 'undefined' && 'sloppy' in options 1607 | ? options.sloppy 1608 | : false 1609 | 1610 | function mask(str) { 1611 | return str.replace(/\\/g, '\\') 1612 | } 1613 | 1614 | function parse_pgn_header(header, options) { 1615 | var newline_char = 1616 | typeof options === 'object' && 1617 | typeof options.newline_char === 'string' 1618 | ? options.newline_char 1619 | : '\r?\n' 1620 | var header_obj = {} 1621 | var headers = header.split(new RegExp(mask(newline_char))) 1622 | var key = '' 1623 | var value = '' 1624 | 1625 | for (var i = 0; i < headers.length; i++) { 1626 | var regex = /^\s*\[([A-Za-z]+)\s*"(.*)"\s*\]\s*$/ 1627 | key = headers[i].replace(regex, '$1') 1628 | value = headers[i].replace(regex, '$2') 1629 | if (trim(key).length > 0) { 1630 | header_obj[key] = value 1631 | } 1632 | } 1633 | 1634 | return header_obj 1635 | } 1636 | 1637 | // strip whitespace from head/tail of PGN block 1638 | pgn = pgn.trim() 1639 | 1640 | var newline_char = 1641 | typeof options === 'object' && typeof options.newline_char === 'string' 1642 | ? options.newline_char 1643 | : '\r?\n' 1644 | 1645 | // RegExp to split header. Takes advantage of the fact that header and movetext 1646 | // will always have a blank line between them (ie, two newline_char's). 1647 | // With default newline_char, will equal: /^(\[((?:\r?\n)|.)*\])(?:\s*\r?\n){2}/ 1648 | var header_regex = new RegExp( 1649 | '^(\\[((?:' + 1650 | mask(newline_char) + 1651 | ')|.)*\\])' + 1652 | '(?:\\s*' + 1653 | mask(newline_char) + 1654 | '){2}' 1655 | ) 1656 | 1657 | // If no header given, begin with moves. 1658 | var header_string = header_regex.test(pgn) 1659 | ? header_regex.exec(pgn)[1] 1660 | : '' 1661 | 1662 | // Put the board in the starting position 1663 | reset() 1664 | 1665 | /* parse PGN header */ 1666 | var headers = parse_pgn_header(header_string, options) 1667 | var fen = '' 1668 | 1669 | for (var key in headers) { 1670 | // check to see user is including fen (possibly with wrong tag case) 1671 | if (key.toLowerCase() === 'fen') { 1672 | fen = headers[key] 1673 | } 1674 | set_header([key, headers[key]]) 1675 | } 1676 | 1677 | /* sloppy parser should attempt to load a fen tag, even if it's 1678 | * the wrong case and doesn't include a corresponding [SetUp "1"] tag */ 1679 | if (sloppy) { 1680 | if (fen) { 1681 | if (!load(fen, true)) { 1682 | return false 1683 | } 1684 | } 1685 | } else { 1686 | /* strict parser - load the starting position indicated by [Setup '1'] 1687 | * and [FEN position] */ 1688 | if (headers['SetUp'] === '1') { 1689 | if (!('FEN' in headers && load(headers['FEN'], true))) { 1690 | // second argument to load: don't clear the headers 1691 | return false 1692 | } 1693 | } 1694 | } 1695 | 1696 | /* NB: the regexes below that delete move numbers, recursive 1697 | * annotations, and numeric annotation glyphs may also match 1698 | * text in comments. To prevent this, we transform comments 1699 | * by hex-encoding them in place and decoding them again after 1700 | * the other tokens have been deleted. 1701 | * 1702 | * While the spec states that PGN files should be ASCII encoded, 1703 | * we use {en,de}codeURIComponent here to support arbitrary UTF8 1704 | * as a convenience for modern users */ 1705 | 1706 | var to_hex = function (string) { 1707 | return Array.from(string) 1708 | .map(function (c) { 1709 | /* encodeURI doesn't transform most ASCII characters, 1710 | * so we handle these ourselves */ 1711 | return c.charCodeAt(0) < 128 1712 | ? c.charCodeAt(0).toString(16) 1713 | : encodeURIComponent(c).replace(/\%/g, '').toLowerCase() 1714 | }) 1715 | .join('') 1716 | } 1717 | 1718 | var from_hex = function (string) { 1719 | return string.length == 0 1720 | ? '' 1721 | : decodeURIComponent('%' + string.match(/.{1,2}/g).join('%')) 1722 | } 1723 | 1724 | var encode_comment = function (string) { 1725 | string = string.replace(new RegExp(mask(newline_char), 'g'), ' ') 1726 | return `{${to_hex(string.slice(1, string.length - 1))}}` 1727 | } 1728 | 1729 | var decode_comment = function (string) { 1730 | if (string.startsWith('{') && string.endsWith('}')) { 1731 | return from_hex(string.slice(1, string.length - 1)) 1732 | } 1733 | } 1734 | 1735 | /* delete header to get the moves */ 1736 | var ms = pgn 1737 | .replace(header_string, '') 1738 | .replace( 1739 | /* encode comments so they don't get deleted below */ 1740 | new RegExp(`(\{[^}]*\})+?|;([^${mask(newline_char)}]*)`, 'g'), 1741 | function (match, bracket, semicolon) { 1742 | return bracket !== undefined 1743 | ? encode_comment(bracket) 1744 | : ' ' + encode_comment(`{${semicolon.slice(1)}}`) 1745 | } 1746 | ) 1747 | .replace(new RegExp(mask(newline_char), 'g'), ' ') 1748 | 1749 | /* delete recursive annotation variations */ 1750 | var rav_regex = /(\([^\(\)]+\))+?/g 1751 | while (rav_regex.test(ms)) { 1752 | ms = ms.replace(rav_regex, '') 1753 | } 1754 | 1755 | /* delete move numbers */ 1756 | ms = ms.replace(/\d+\.(\.\.)?/g, '') 1757 | 1758 | /* delete ... indicating black to move */ 1759 | ms = ms.replace(/\.\.\./g, '') 1760 | 1761 | /* delete numeric annotation glyphs */ 1762 | ms = ms.replace(/\$\d+/g, '') 1763 | 1764 | /* trim and get array of moves */ 1765 | var moves = trim(ms).split(new RegExp(/\s+/)) 1766 | 1767 | /* delete empty entries */ 1768 | moves = moves.join(',').replace(/,,+/g, ',').split(',') 1769 | var move = '' 1770 | 1771 | var result = '' 1772 | 1773 | for (var half_move = 0; half_move < moves.length; half_move++) { 1774 | var comment = decode_comment(moves[half_move]) 1775 | if (comment !== undefined) { 1776 | comments[generate_fen()] = comment 1777 | continue 1778 | } 1779 | 1780 | move = move_from_san(moves[half_move], sloppy) 1781 | 1782 | /* invalid move */ 1783 | if (move == null) { 1784 | /* was the move an end of game marker */ 1785 | if (TERMINATION_MARKERS.indexOf(moves[half_move]) > -1) { 1786 | result = moves[half_move] 1787 | } else { 1788 | return false 1789 | } 1790 | } else { 1791 | /* reset the end of game marker if making a valid move */ 1792 | result = '' 1793 | make_move(move) 1794 | } 1795 | } 1796 | 1797 | /* Per section 8.2.6 of the PGN spec, the Result tag pair must match 1798 | * match the termination marker. Only do this when headers are present, 1799 | * but the result tag is missing 1800 | */ 1801 | if (result && Object.keys(header).length && !header['Result']) { 1802 | set_header(['Result', result]) 1803 | } 1804 | 1805 | return true 1806 | }, 1807 | 1808 | header: function () { 1809 | return set_header(arguments) 1810 | }, 1811 | 1812 | turn: function () { 1813 | return turn 1814 | }, 1815 | 1816 | move: function (move, options) { 1817 | /* The move function can be called with in the following parameters: 1818 | * 1819 | * .move('Nxb7') <- where 'move' is a case-sensitive SAN string 1820 | * 1821 | * .move({ from: 'h7', <- where the 'move' is a move object (additional 1822 | * to :'h8', fields are ignored) 1823 | * promotion: 'q', 1824 | * }) 1825 | */ 1826 | 1827 | // allow the user to specify the sloppy move parser to work around over 1828 | // disambiguation bugs in Fritz and Chessbase 1829 | var sloppy = 1830 | typeof options !== 'undefined' && 'sloppy' in options 1831 | ? options.sloppy 1832 | : false 1833 | 1834 | var move_obj = null 1835 | 1836 | if (typeof move === 'string') { 1837 | move_obj = move_from_san(move, sloppy) 1838 | } else if (typeof move === 'object') { 1839 | var moves = generate_moves() 1840 | 1841 | /* convert the pretty move object to an ugly move object */ 1842 | for (var i = 0, len = moves.length; i < len; i++) { 1843 | if ( 1844 | move.from === algebraic(moves[i].from) && 1845 | move.to === algebraic(moves[i].to) && 1846 | (!('promotion' in moves[i]) || 1847 | move.promotion === moves[i].promotion) 1848 | ) { 1849 | move_obj = moves[i] 1850 | break 1851 | } 1852 | } 1853 | } 1854 | 1855 | /* failed to find move */ 1856 | if (!move_obj) { 1857 | return null 1858 | } 1859 | 1860 | /* need to make a copy of move because we can't generate SAN after the 1861 | * move is made 1862 | */ 1863 | var pretty_move = make_pretty(move_obj) 1864 | 1865 | make_move(move_obj) 1866 | 1867 | return pretty_move 1868 | }, 1869 | 1870 | undo: function () { 1871 | var move = undo_move() 1872 | return move ? make_pretty(move) : null 1873 | }, 1874 | 1875 | clear: function () { 1876 | return clear() 1877 | }, 1878 | 1879 | put: function (piece, square) { 1880 | return put(piece, square) 1881 | }, 1882 | 1883 | get: function (square) { 1884 | return get(square) 1885 | }, 1886 | 1887 | ascii() { 1888 | var s = ' +------------------------+\n' 1889 | for (var i = SQUARE_MAP.a8; i <= SQUARE_MAP.h1; i++) { 1890 | /* display the rank */ 1891 | if (file(i) === 0) { 1892 | s += ' ' + '87654321'[rank(i)] + ' |' 1893 | } 1894 | 1895 | /* empty piece */ 1896 | if (board[i] == null) { 1897 | s += ' . ' 1898 | } else { 1899 | var piece = board[i].type 1900 | var color = board[i].color 1901 | var symbol = 1902 | color === WHITE ? piece.toUpperCase() : piece.toLowerCase() 1903 | s += ' ' + symbol + ' ' 1904 | } 1905 | 1906 | if ((i + 1) & 0x88) { 1907 | s += '|\n' 1908 | i += 8 1909 | } 1910 | } 1911 | s += ' +------------------------+\n' 1912 | s += ' a b c d e f g h' 1913 | 1914 | return s 1915 | }, 1916 | 1917 | remove: function (square) { 1918 | return remove(square) 1919 | }, 1920 | 1921 | perft: function (depth) { 1922 | return perft(depth) 1923 | }, 1924 | 1925 | square_color: function (square) { 1926 | if (square in SQUARE_MAP) { 1927 | var sq_0x88 = SQUARE_MAP[square] 1928 | return (rank(sq_0x88) + file(sq_0x88)) % 2 === 0 ? 'light' : 'dark' 1929 | } 1930 | 1931 | return null 1932 | }, 1933 | 1934 | history: function (options) { 1935 | var reversed_history = [] 1936 | var move_history = [] 1937 | var verbose = 1938 | typeof options !== 'undefined' && 1939 | 'verbose' in options && 1940 | options.verbose 1941 | 1942 | while (history.length > 0) { 1943 | reversed_history.push(undo_move()) 1944 | } 1945 | 1946 | while (reversed_history.length > 0) { 1947 | var move = reversed_history.pop() 1948 | if (verbose) { 1949 | move_history.push(make_pretty(move)) 1950 | } else { 1951 | move_history.push(move_to_san(move, generate_moves({ legal: true }))) 1952 | } 1953 | make_move(move) 1954 | } 1955 | 1956 | return move_history 1957 | }, 1958 | 1959 | get_comment: function () { 1960 | return comments[generate_fen()] 1961 | }, 1962 | 1963 | set_comment: function (comment) { 1964 | comments[generate_fen()] = comment.replace('{', '[').replace('}', ']') 1965 | }, 1966 | 1967 | delete_comment: function () { 1968 | var comment = comments[generate_fen()] 1969 | delete comments[generate_fen()] 1970 | return comment 1971 | }, 1972 | 1973 | get_comments: function () { 1974 | prune_comments() 1975 | return Object.keys(comments).map(function (fen) { 1976 | return { fen: fen, comment: comments[fen] } 1977 | }) 1978 | }, 1979 | 1980 | delete_comments: function () { 1981 | prune_comments() 1982 | return Object.keys(comments).map(function (fen) { 1983 | var comment = comments[fen] 1984 | delete comments[fen] 1985 | return { fen: fen, comment: comment } 1986 | }) 1987 | }, 1988 | } 1989 | } 1990 | -------------------------------------------------------------------------------- /firefox/icons/anarchy-chess128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phazejeff/auto-en-passant-extension/0fefcaf8ab83869e9135b16c415d08fba3b21822/firefox/icons/anarchy-chess128.png -------------------------------------------------------------------------------- /firefox/icons/anarchy-chess16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phazejeff/auto-en-passant-extension/0fefcaf8ab83869e9135b16c415d08fba3b21822/firefox/icons/anarchy-chess16.png -------------------------------------------------------------------------------- /firefox/icons/anarchy-chess32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phazejeff/auto-en-passant-extension/0fefcaf8ab83869e9135b16c415d08fba3b21822/firefox/icons/anarchy-chess32.png -------------------------------------------------------------------------------- /firefox/icons/anarchy-chess48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phazejeff/auto-en-passant-extension/0fefcaf8ab83869e9135b16c415d08fba3b21822/firefox/icons/anarchy-chess48.png -------------------------------------------------------------------------------- /firefox/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "Auto En Passant", 4 | "version": "0.1", 5 | "description": "anti brick", 6 | "background": { 7 | "scripts": ["chess.js", "util.js", "background.js"] 8 | }, 9 | "permissions": ["storage", "activeTab", "webNavigation", "https://*.lichess.org/*"], 10 | "browser_action": { 11 | "default_popup": "src/popup.html", 12 | "default_icon": { 13 | "16": "/icons/anarchy-chess16.png", 14 | "32": "/icons/anarchy-chess32.png", 15 | "48": "/icons/anarchy-chess48.png", 16 | "128": "/icons/anarchy-chess128.png" 17 | } 18 | }, 19 | "icons": { 20 | "16": "/icons/anarchy-chess16.png", 21 | "32": "/icons/anarchy-chess32.png", 22 | "48": "/icons/anarchy-chess48.png", 23 | "128": "/icons/anarchy-chess128.png" 24 | }, 25 | 26 | "browser_specific_settings": { 27 | "gecko": { 28 | "id": "phazejeff@proton.me" 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /firefox/src/popup.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #262421; 3 | text-align: center; 4 | } 5 | 6 | #piss { 7 | color: #bababa; 8 | font-family: 'Noto Sans', Sans-Serif; 9 | font-size: calc( 20px + 2 * ((100vw - 320px) / 880)); 10 | text-align: center; 11 | } 12 | 13 | .api-key { 14 | color: #3692E7; 15 | font-family: 'Noto Sans', Sans-Serif; 16 | font-size: calc( 12px + 2 * ((100vw - 320px) / 880)); 17 | text-align: center; 18 | text-decoration: none; 19 | } 20 | 21 | .api-key-box { 22 | color: #bababa; 23 | background-color: #404040; 24 | font-family: 'Noto Sans', Sans-Serif; 25 | text-align: center; 26 | border: none; 27 | } 28 | 29 | /* The switch - the box around the slider */ 30 | .switch { 31 | position: relative; 32 | display: inline-block; 33 | width: 60px; 34 | height: 34px; 35 | } 36 | 37 | /* Hide default HTML checkbox */ 38 | .switch input { 39 | opacity: 0; 40 | width: 0; 41 | height: 0; 42 | } 43 | 44 | /* The slider */ 45 | .slider { 46 | position: absolute; 47 | cursor: pointer; 48 | top: 0; 49 | left: 0; 50 | right: 0; 51 | bottom: 0; 52 | background-color: #999; 53 | -webkit-transition: .4s; 54 | transition: .4s; 55 | } 56 | 57 | .slider:before { 58 | position: absolute; 59 | content: ""; 60 | height: 26px; 61 | width: 26px; 62 | left: 4px; 63 | bottom: 4px; 64 | background-color: #404040; 65 | -webkit-transition: .4s; 66 | transition: .4s; 67 | } 68 | 69 | input:checked + .slider { 70 | background-color: #629924; 71 | } 72 | 73 | input:focus + .slider { 74 | box-shadow: 0 0 1px #629924; 75 | } 76 | 77 | input:checked + .slider:before { 78 | -webkit-transform: translateX(26px); 79 | -ms-transform: translateX(26px); 80 | transform: translateX(26px); 81 | } 82 | 83 | /* Rounded sliders */ 84 | .slider.round { 85 | border-radius: 34px; 86 | } 87 | 88 | .slider.round:before { 89 | border-radius: 50%; 90 | } -------------------------------------------------------------------------------- /firefox/src/popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Auto En Passant 5 | 6 | 7 |

Auto En Passant

8 | 12 |

13 |

Get API Key

14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /firefox/src/popup.js: -------------------------------------------------------------------------------- 1 | function checkKey(API_KEY) { 2 | fetch('https://lichess.org/api/account', { 3 | headers: { 4 | Authorization: "Bearer " + API_KEY, 5 | Accept: "application/x-ndjson" 6 | } 7 | }).then(r => { 8 | if (r.status !== 200) { 9 | document.getElementById('checkbox-switch').disabled = true 10 | document.getElementById('span-switch').style.cursor = "not-allowed" 11 | document.getElementById('span-switch').style.title = "Invalid API Key" 12 | } else { 13 | document.getElementById('checkbox-switch').disabled = false 14 | document.getElementById('span-switch').style.cursor = "pointer" 15 | document.getElementById('span-switch').style.title = null 16 | } 17 | }) 18 | } 19 | 20 | // API Key 21 | browser.storage.sync.get(['API_KEY'], (result) => { 22 | if (result.API_KEY == null) { 23 | document.getElementById('api-key').value = "" 24 | } else { 25 | document.getElementById('api-key').value = result.API_KEY 26 | } 27 | 28 | checkKey(result.API_KEY) 29 | }) 30 | 31 | document.getElementById('api-key').addEventListener('change', (key) => { 32 | browser.storage.sync.set({API_KEY: key.target.value}) 33 | checkKey(key.target.value) 34 | }) 35 | 36 | 37 | // Toggles 38 | browser.storage.sync.get(['toggle'], (result) => { 39 | if (result.toggle == true) { 40 | document.getElementById('checkbox-switch').checked = true 41 | } else { 42 | document.getElementById('checkbox-switch').checked = false 43 | } 44 | }) 45 | 46 | document.getElementById('checkbox-switch').addEventListener('change', (e) => { 47 | browser.storage.sync.set({toggle: e.target.checked}) 48 | }) -------------------------------------------------------------------------------- /firefox/src/script.js: -------------------------------------------------------------------------------- 1 | var API_KEY = "" 2 | 3 | // https://gist.github.com/ornicar/a097406810939cf7be1df8ea30e94f3e 4 | const readStream = processLine => response => { 5 | const stream = response.body.getReader(); 6 | const matcher = /\r?\n/; 7 | const decoder = new TextDecoder(); 8 | let buf = ''; 9 | 10 | const loop = () => 11 | stream.read().then(({ done, value }) => { 12 | if (done) { 13 | if (buf.length > 0) processLine(JSON.parse(buf)); 14 | } else { 15 | const chunk = decoder.decode(value, { 16 | stream: true 17 | }); 18 | buf += chunk; 19 | 20 | const parts = buf.split(matcher); 21 | buf = parts.pop(); 22 | for (const i of parts.filter(p => p)) processLine(JSON.parse(i)); 23 | return loop(); 24 | } 25 | }); 26 | 27 | return loop(); 28 | } 29 | 30 | browser.storage.sync.get(['API_KEY'], (result) => { 31 | API_KEY = result.API_KEY 32 | 33 | function main() { 34 | // Actual shit starts here 35 | const gameId = window.location.href.split('/')[3] 36 | const boardStream = fetch('https://lichess.org/api/board/game/stream/' + gameId, { 37 | headers: { 38 | Authorization: "Bearer " + API_KEY, 39 | Accept: "application/x-ndjson" 40 | } 41 | }) 42 | 43 | boardStream.then(readStream(game => { 44 | let moves 45 | if (game.type == "gameFull") { moves = game.state.moves.split(' ') } 46 | else if (game.type == "gameState") { moves = game.moves.split(' ') } 47 | 48 | browser.runtime.sendMessage(moves) // Sends to background process because browser can't import the chess library for whatever reason 49 | })) 50 | } 51 | 52 | browser.storage.onChanged.addListener((changes, areaName) => { 53 | API_KEY = changes.API_KEY.newValue 54 | main() 55 | }) 56 | 57 | main() 58 | }) -------------------------------------------------------------------------------- /firefox/util.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | // Gets current lichess game 4 | function getCurrentGame(moves) { 5 | const chess = new Chess() 6 | 7 | for (let i=0; i < moves.length; i++) { 8 | chess.move({from: moves[i].substring(0,2), to: moves[i].substring(2,4)}) 9 | } 10 | 11 | return chess 12 | } 13 | 14 | // Returns the chess.move for en passant, or null if none avaliable 15 | function hasEnPassant(game) { 16 | const moves = game.moves({ verbose: true }) 17 | for (let i=0; i < moves.length; i++) { 18 | if (moves[i].flags.includes('e')) { return moves[i] } 19 | } 20 | return null 21 | } --------------------------------------------------------------------------------