├── favicon.ico ├── img ├── bgTile.png ├── sprites.png ├── acceptable.png └── ajax-loader.gif ├── apple-touch-icon.png ├── php ├── waitForStart.php ├── waitForMove.php ├── hostGame.php ├── joinGame.php └── makeMove.php ├── css ├── reset.css └── default.css ├── index.html ├── js ├── game.min.js ├── jquery-ui.min.js └── game.js └── LICENSE /favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwoelfle/PlainChess/HEAD/favicon.ico -------------------------------------------------------------------------------- /img/bgTile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwoelfle/PlainChess/HEAD/img/bgTile.png -------------------------------------------------------------------------------- /img/sprites.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwoelfle/PlainChess/HEAD/img/sprites.png -------------------------------------------------------------------------------- /img/acceptable.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwoelfle/PlainChess/HEAD/img/acceptable.png -------------------------------------------------------------------------------- /apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwoelfle/PlainChess/HEAD/apple-touch-icon.png -------------------------------------------------------------------------------- /img/ajax-loader.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwoelfle/PlainChess/HEAD/img/ajax-loader.gif -------------------------------------------------------------------------------- /php/waitForStart.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /php/waitForMove.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /php/hostGame.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /php/joinGame.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /css/reset.css: -------------------------------------------------------------------------------- 1 | /* http://meyerweb.com/eric/tools/css/reset/ */ 2 | /* v1.0 | 20080212 */ 3 | 4 | html, body, div, span, applet, object, iframe, 5 | h1, h2, h3, h4, h5, h6, p, blockquote, pre, 6 | a, abbr, acronym, address, big, cite, code, 7 | del, dfn, em, font, img, ins, kbd, q, s, samp, 8 | small, strike, strong, sub, sup, tt, var, 9 | b, u, i, center, 10 | dl, dt, dd, ol, ul, li, 11 | fieldset, form, label, legend, 12 | table, caption, tbody, tfoot, thead, tr, th, td { 13 | margin: 0; 14 | padding: 0; 15 | border: 0; 16 | outline: 0; 17 | font-size: 100%; 18 | vertical-align: baseline; 19 | background: transparent; 20 | } 21 | body { 22 | line-height: 1; 23 | } 24 | ol, ul { 25 | list-style: none; 26 | } 27 | 28 | :focus { 29 | outline: 0; 30 | } 31 | 32 | table { 33 | border-collapse: collapse; 34 | border-spacing: 0; 35 | } -------------------------------------------------------------------------------- /php/makeMove.php: -------------------------------------------------------------------------------- 1 | 8) return false; 5 | if ((!$startRow = $_POST["startRow"]) || intval($startRow) < 1 || intval($startRow) > 8) return false; 6 | if ((!$endCol = $_POST["endColumn"]) || intval($endCol) < 1 || intval($endCol) > 8) return false; 7 | if ((!$endRow = $_POST["endRow"]) || intval($endRow) < 1 || intval($endRow) > 8) return false; 8 | if (($promType = $_POST["promotionType"]) && strlen($promType) > 3) return false; 9 | $gameOver = $_POST["gameOver"]; 10 | 11 | if (!$oldMoves = file_get_contents("../games/".$gameName, 0, NULL, 0, 100000)) return false; 12 | $newMove = $startCol . $startRow . " " . $endCol . $endRow; 13 | if ($promType) { 14 | $newMove .= "=" . $promType; 15 | } 16 | $newMove .= " " . date("d.m.Y H:i:s"); 17 | file_put_contents("../games/".$gameName, $newMove . "\n" . $oldMoves); 18 | if ($gameOver) { 19 | copy("../games/".$gameName, "../games/finished/".$gameName); 20 | } 21 | 22 | echo $gameName; 23 | ?> -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | PlainChess 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 |
19 |

20 | PlainChess 21 |

22 | 23 |
24 |
25 |
26 | 27 |
28 |

What is PlainChess?

29 |

PlainChess aims to be a simple yet full–featured and beautiful alternative to the cluttered chess portals currently existing.

30 |

Its primary goal is to allow two persons to play a round of chess, no matter whether they happen to be at the same location or on a different continent. It's designed to be platform independent and to run on every computer or smart phone equipped with a modern web browser and thus enabling people everywhere around the globe to play chess, at home and on the go, online and offline.

31 |

It was originally published in January 2011 and as of March 2013 its code is open source and licensed under the GPL Version 3 license.

32 | 33 | 36 | 37 |

Why yet another chess implementation, what makes PlainChess different?

38 | 39 |

Its minimalistic approach sets it apart from most of the other chess implementations on the internet. They usually use browser plugins like Adobe Flash or even client software to realize the game itself and offer a variety of features around it: news, riddles, communities and dozens of little gadgets.

40 |

Due to this complexity they often take a lot of clicks to get a game started, they tend to react slowly and are often cluttered with ads. Some even require registration fees in order to be able to play a game. PlainChess is free, fast and built on modern web technologies but on the other hand also passes on features beyond basic gameplay.

41 | 42 |

I want a list, what features do you offer?

43 |
    44 |
  • Online and offline games with an appointed partner
  • 45 |
  • Nearly full implementation of all official chess rules
  • 46 |
  • Autosaving the game for interrupted sessions
  • 47 |
  • Minimalistic and clean interface
  • 48 |
  • Platform independent due to the use of modern web technologies
  • 49 |
  • Free and ad–free
  • 50 |
51 | 52 |

Which chess rules exactly are implemented, which aren't?

53 |

Nearly all of them: PlainChess recognizes valid moves as well as check, mate and stalemate situations. It also supports the three specials moves of kings and pawns: castling, pawn promotions and en passant capturing. The only rules currently not supported are the draw rules except for stalemate: threefold repetition, the fifty–move rule, impossibility of checkmate and mutual agreement.

54 | 55 |

I like PlainChess. How can I support you?

56 |

Spread the word, tell your friends and enemies about PlainChess; twitter, blog or write letters about it. Share it on your social networks. Send me an e-mail. Have a look at the code and add new features.

57 | 58 |

What features could be implemented next?

59 |

General

60 |
    61 |
  • Support of time control and chess clocks
  • 62 |
  • Support of FEN codes and saved games
  • 63 |
  • Support of at least some of the draw rules
  • 64 |
  • Optimized layout for smart phones
  • 65 |
66 | 67 |

Online mode

68 |
    69 |
  • Synchronized game time for time control and chess clocks
  • 70 |
  • Server side turn saving for rejoins and spectator mode
  • 71 |
  • Player pings for recognition of disconnection
  • 72 |
73 | 74 |

You keep mentioning modern web technologies: What exactly are you talking about?

75 |

PlainChess is the first chess implementation built completely with HTML5 technologies (at least as far as I know).

76 |

The game engine is written in JavaScript and relies on the frameworks jQuery and jQuery UI, which means that offline games can be played without internet connectivity (this would be interesting for a smart phone optimized version with HTML5 manifest).

77 |

The design uses CSS3 en masse: rounded borders, shadows, opacity, sprite images and transitions & transforms.

78 | 79 |

Who are you and why did you make this?

80 |

I'm Tim Wölfle from Germany and wanted to try out the new possibilities HTML5 technologies offer. At the same time I wanted to play a quick round of chess with a friend on the internet, but didn't find anything that would allow me to start right away and without registration.

81 |
82 |
83 | 84 |
85 |
86 |

87 |

88 |

89 |
90 | 91 |
92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 |
103 |
104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 |
115 | 116 |
    117 |
      118 |
        119 | 120 | 137 | 138 | 151 | 152 | 165 |
        166 |
        167 |
        168 | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /css/default.css: -------------------------------------------------------------------------------- 1 | /* Layout */ 2 | 3 | body { 4 | font-family: "Lucida Grande", "Trebuchet MS", sans-serif; 5 | background-color: #fff; 6 | } 7 | 8 | /* Header */ 9 | 10 | #header { 11 | line-height: 20px; 12 | width: 100%; 13 | padding: 5px 30px; 14 | background-color: #5a4232; 15 | color: #ccc; 16 | box-sizing: border-box; 17 | box-shadow: 0 -10px 10px 10px #000; 18 | } 19 | 20 | #header a { 21 | color: inherit; 22 | text-decoration: none; 23 | } 24 | 25 | #header a:hover, #header a.active { 26 | color: #999; 27 | text-decoration: underline; 28 | } 29 | 30 | /* Headline */ 31 | 32 | h1 { 33 | width: 100%; 34 | position: absolute; 35 | top: -58px; 36 | color: #342217; 37 | font-size: 36pt; 38 | font-weight: bold; 39 | text-align: right; 40 | text-shadow: 0 0 10px RGBa(0,0,0,0.5); 41 | } 42 | 43 | h1 a { 44 | text-decoration: none; 45 | color: inherit; 46 | } 47 | 48 | .light { 49 | color: #793e12; /* 793e12 / 905622 */ 50 | font-weight: lighter; 51 | } 52 | 53 | #main a { 54 | text-decoration: none; 55 | color: inherit; 56 | } 57 | 58 | /* Container & Flipping */ 59 | 60 | #main { 61 | position: relative; 62 | width: 540px; 63 | height: 540px; 64 | margin: 0 auto 0 auto; 65 | top: 86px; 66 | 67 | perspective: 900px; 68 | } 69 | 70 | #flip { 71 | width: inherit; 72 | height: inherit; 73 | transform-style: preserve-3d; 74 | transition: transform 1.5s; 75 | } 76 | 77 | .flipped { 78 | transform: rotateX(180deg); 79 | } 80 | 81 | #faq { 82 | transform: rotateX(180deg); 83 | } 84 | 85 | #chess { 86 | transform: rotateX(0deg); 87 | } 88 | 89 | #faq, #chess { 90 | backface-visibility: hidden; 91 | transition: opacity 1.5s; 92 | } 93 | 94 | #faq, #flip.flipped #chess { 95 | opacity: 0; 96 | z-index: 0; 97 | } 98 | 99 | #flip.flipped #faq, #chess { 100 | opacity: 1; 101 | z-index: 1; 102 | } 103 | 104 | /* FAQ */ 105 | 106 | #wideBorder { 107 | position: absolute; 108 | left: -120px; 109 | height: 540px; 110 | width: 780px; 111 | border: 30px solid #342217; 112 | background: url("../img/bgTile.png") bottom left repeat; 113 | 114 | border-radius: 20px; 115 | box-shadow: 0 0 10px #000; 116 | box-sizing: border-box; 117 | } 118 | 119 | #content { 120 | background-color: RGBa(161, 142, 128, 0.93); 121 | top: 30px; 122 | left: -90px; 123 | padding: 30px; 124 | height: 480px; 125 | width: 720px; 126 | position: absolute; 127 | 128 | border-radius: 5px; 129 | box-sizing: border-box; 130 | 131 | overflow: scroll; 132 | overflow-x: auto; 133 | overflow-y: scroll; 134 | } 135 | 136 | #faq h2:first-child { 137 | margin: 0px 0 10px 0; 138 | font-size: 16pt; 139 | } 140 | 141 | #faq h2 { 142 | margin: 30px 0 10px 0; 143 | font-size: 16pt; 144 | } 145 | 146 | #faq h3 { 147 | margin: 10px 0 10px 0; 148 | } 149 | 150 | #faq p, #faq ul { 151 | line-height: 120%; 152 | margin-bottom: 10px; 153 | } 154 | 155 | #faq ul { 156 | list-style: inside disc; 157 | } 158 | 159 | #faq a { 160 | color: #342217; 161 | text-decoration: underline; 162 | } 163 | 164 | /* Chess */ 165 | 166 | #faq, #chess { 167 | position: absolute; 168 | width: inherit; 169 | height: inherit; 170 | } 171 | 172 | #border { 173 | position: absolute; 174 | width: inherit; 175 | height: inherit; 176 | background-color: #342217; 177 | 178 | border-radius: 20px; 179 | } 180 | 181 | #border table { 182 | display: none; 183 | } 184 | 185 | th { 186 | font-weight: normal; 187 | color: #999; 188 | } 189 | 190 | tr > th:first-child { 191 | height: 60px; 192 | padding-right: 9px; 193 | vertical-align: middle; 194 | } 195 | 196 | tr:last-child > th { 197 | width: 60px; 198 | padding-top: 5px; 199 | text-align: center; 200 | } 201 | 202 | 203 | /* Chess board */ 204 | 205 | #board, #border table { 206 | position: absolute; 207 | top: 30px; 208 | right: 30px; 209 | } 210 | 211 | #board { 212 | border-radius: 10px; 213 | box-shadow: inset 0 0 5px #000; 214 | } 215 | 216 | #board td { 217 | width: 60px; 218 | height: 60px; 219 | text-align: center; 220 | vertical-align: middle; 221 | background-color: #793e12; 222 | border-radius: 5px; 223 | transition: background-color 1s; 224 | } 225 | 226 | #chess:not(.awareness) #board tr:nth-child(odd) > td:nth-child(odd), #chess:not(.awareness) #board tr:nth-child(even) > td:nth-child(even) { 227 | background-color: #d19a53; /* #986534 */ 228 | } 229 | 230 | #chess.awareness #board td { background-color: #ccc; } 231 | /* owned by white */ 232 | #chess.awareness #board td.property1 { background-color: #99bb99; } 233 | #chess.awareness #board td.property2 { background-color: #77dd77; } 234 | #chess.awareness #board td.property3 { background-color: #63d863; } /* #55ff55 */ 235 | #chess.awareness #board td.property4 { background-color: #4ed34e; } 236 | #chess.awareness #board td.property5 { background-color: #3ace3a; } 237 | #chess.awareness #board td.property6 { background-color: #30bf30; } 238 | #chess.awareness #board td.property7 { background-color: #2aab2a; } 239 | #chess.awareness #board td.property8 { background-color: #259625; } 240 | #chess.awareness #board td.property9 { background-color: #208220; } 241 | #chess.awareness #board td.property10 { background-color: #1b6d1b; } 242 | /* neutral */ 243 | #chess.awareness #board td.neutral1 { background-color: #9999bb; } 244 | #chess.awareness #board td.neutral2 { background-color: #7777dd; } 245 | #chess.awareness #board td.neutral3 { background-color: #6363d8; } /* #5555ff */ 246 | #chess.awareness #board td.neutral4 { background-color: #4e4ed3; } 247 | #chess.awareness #board td.neutral5 { background-color: #3a3ace; } 248 | #chess.awareness #board td.neutral6 { background-color: #3030bf; } 249 | #chess.awareness #board td.neutral7 { background-color: #2a2aab; } 250 | #chess.awareness #board td.neutral8 { background-color: #252596; } 251 | #chess.awareness #board td.neutral9 { background-color: #202082; } 252 | #chess.awareness #board td.neutral10 { background-color: #161659; } 253 | /* owned by black */ 254 | #chess.awareness #board td.property-1 { background-color: #bb9999; } 255 | #chess.awareness #board td.property-2 { background-color: #dd7777; } 256 | #chess.awareness #board td.property-3 { background-color: #d86363; } /* #ff5555 */ 257 | #chess.awareness #board td.property-4 { background-color: #d34e4e; } 258 | #chess.awareness #board td.property-5 { background-color: #ce3a3a; } 259 | #chess.awareness #board td.property-6 { background-color: #bf3030; } 260 | #chess.awareness #board td.property-7 { background-color: #ab2a2a; } 261 | #chess.awareness #board td.property-8 { background-color: #962525; } 262 | #chess.awareness #board td.property-9 { background-color: #822020; } 263 | #chess.awareness #board td.property-10 { background-color: #6d1b1b; } 264 | 265 | #board tr:first-child > td:first-child { 266 | border-top-left-radius: 10px; 267 | } 268 | 269 | #board tr:first-child > td:last-child { 270 | border-top-right-radius: 10px; 271 | } 272 | 273 | #board tr:last-child > td:first-child { 274 | border-bottom-left-radius: 10px; 275 | } 276 | 277 | #board tr:last-child > td:last-child { 278 | border-bottom-right-radius: 10px; 279 | } 280 | 281 | .acceptable:empty { 282 | background-image: url("../img/acceptable.png"); 283 | background-position: center center; 284 | background-repeat: no-repeat; 285 | } 286 | 287 | .acceptable > .piece { 288 | opacity: 0.5; 289 | } 290 | 291 | .piece { 292 | width: 60px; 293 | height: 60px; 294 | overflow: hidden; 295 | font: 40pt "MS Gothic", "Arial Unicode", "Apple Symbols"; 296 | color: transparent; 297 | background: url("../img/sprites.png") no-repeat; 298 | background-size: 360px auto; 299 | } 300 | 301 | .white.pawn { 302 | background-position: 0 0; 303 | } 304 | 305 | .white.knight { 306 | background-position: 20% 0; 307 | } 308 | 309 | .white.bishop { 310 | background-position: 40% 0; 311 | } 312 | 313 | .white.rook { 314 | background-position: 60% 0; 315 | } 316 | 317 | .white.queen { 318 | background-position: 80% 0; 319 | } 320 | 321 | .white.king { 322 | background-position: 100% 0; 323 | } 324 | 325 | .black.pawn { 326 | background-position: 0 28.57%; 327 | } 328 | 329 | .black.knight { 330 | background-position: 20% 28.57%; 331 | } 332 | 333 | .black.bishop { 334 | background-position: 40% 28.57%; 335 | } 336 | 337 | .black.rook { 338 | background-position: 60% 28.57%; 339 | } 340 | 341 | .black.queen { 342 | background-position: 80% 28.57%; 343 | } 344 | 345 | .black.king { 346 | background-position: 100% 28.57%; 347 | } 348 | 349 | #whiteCemetery { 350 | position: absolute; 351 | top: 30px; 352 | left: -130px; 353 | width: 120px; 354 | height: 480px; 355 | padding-right: 10px; 356 | } 357 | 358 | #blackCemetery { 359 | position: absolute; 360 | top: 30px; 361 | left: 540px; 362 | width: 120px; 363 | height: 480px; 364 | padding-left: 10px; 365 | } 366 | 367 | #whiteCemtery > li, #blackCemtery > li { 368 | width: 60px; 369 | height: 60px; 370 | text-align: center; 371 | vertical-align: middle; 372 | } 373 | 374 | #whiteCemetery > li { 375 | float: right; 376 | } 377 | 378 | #blackCemetery > li { 379 | float: left; 380 | } 381 | 382 | /* Info drawer */ 383 | 384 | #info { 385 | position: absolute; 386 | width: 540px; 387 | height: 540px; 388 | border-radius: 20px; 389 | color: #ccc; 390 | box-shadow: 0 0 10px #000; 391 | background-color: #5a4232; 392 | } 393 | 394 | #info > p { 395 | width: 480px; 396 | position: absolute; 397 | bottom: 9px; 398 | left: 30px; 399 | right: 30px; 400 | } 401 | 402 | #currentTurn { 403 | float: left; 404 | text-align: left; 405 | } 406 | 407 | #gameTime { 408 | text-align: center; 409 | } 410 | 411 | #lastMove { 412 | float: right; 413 | text-align: right; 414 | } 415 | 416 | #toggleAwareness { 417 | cursor: pointer; 418 | } 419 | 420 | #chess:not(.awareness) #toggleAwareness { 421 | opacity: 0.3; 422 | } 423 | 424 | /* Pawn promotion menu */ 425 | 426 | .promotion { 427 | display: none; 428 | background-color: RGBa(52,34,23,0.9); 429 | width: 240px; 430 | height: 60px; 431 | position: absolute; 432 | left: 140px; 433 | border-radius: 20px; 434 | padding: 10px; 435 | box-shadow: 0 0 10px #000; 436 | } 437 | 438 | #top.promotion { 439 | top: 105px; 440 | } 441 | 442 | #bottom.promotion { 443 | top: 355px; 444 | } 445 | 446 | .promotion > div { 447 | border-color: transparent; 448 | border-style: solid; 449 | border-width: 20px; 450 | height: 1px; 451 | width: 1px; 452 | position: absolute; 453 | left: 110px; 454 | } 455 | 456 | #top.promotion > div { 457 | border-bottom-color: RGBa(52,34,23,0.9); 458 | top: -41px; 459 | } 460 | 461 | #bottom.promotion > div { 462 | border-top-color: RGBa(52,34,23,0.9); 463 | top: 80px; 464 | } 465 | 466 | .promotion > ul { 467 | background-color: #5a4232; 468 | width: 240px; 469 | height: 60px; 470 | border-radius: 15px; 471 | } 472 | 473 | .promotion > ul > li > div { 474 | transition: opacity 0.3s; 475 | } 476 | 477 | .promotion > ul:hover div { 478 | opacity: 0.3; 479 | } 480 | 481 | .promotion > ul > li { 482 | float: left; 483 | } 484 | 485 | .promotion > ul > li:first-child > div { 486 | transform: scaleX(-1); 487 | } 488 | 489 | .promotion > ul > li:hover > div { 490 | opacity: 1; 491 | } 492 | 493 | /* Menu general */ 494 | 495 | .menu { 496 | display: none; 497 | height: 480px; 498 | width: 480px; 499 | overflow: hidden; 500 | position: absolute; 501 | top: 30px; 502 | left: 30px; 503 | } 504 | 505 | .stripe { 506 | width: 100%; 507 | height: 25%; 508 | position: relative; 509 | overflow: hidden; 510 | } 511 | 512 | .menu > .stripe:first-child { 513 | border-radius: 10px 10px 0 0; 514 | } 515 | 516 | .menu > .stripe:last-child { 517 | border-radius: 0 0 10px 10px; 518 | } 519 | 520 | .thin { 521 | height: 12.5%; 522 | } 523 | 524 | .tone30 { 525 | background-color: RGBa(161, 142, 128, 0.93); 526 | } 527 | 528 | .tone40 { 529 | background-color: RGBa(155, 130, 111, 0.94); /* RGBa(180,180,180,0.9) & RGBa(121,62,18,0.40) */ 530 | } 531 | 532 | .tone55 { 533 | background-color: RGBa(146, 112, 87, 0.96); /* RGBa(180,180,180,0.9) & RGBa(121,62,18,0.55) */ 534 | } 535 | 536 | .tone70 { 537 | background-color: RGBa(137, 95, 63, 0.97); /* RGBa(180,180,180,0.9) & RGBa(121,62,18,0.70) */ 538 | } 539 | 540 | .tone85 { 541 | background-color: RGBa(129, 78, 40, 0.99); /* RGBa(180,180,180,0.9) & RGBa(121,62,18,0.85) */ 542 | } 543 | 544 | .tone100 { 545 | background-color: RGBa(121, 62, 18, 1); /* RGBa(180,180,180,0.9) & RGBa(121,62,18,1) */ 546 | } 547 | 548 | .stripe > h2 { 549 | font-size: 28pt; 550 | font-weight: normal; 551 | color: #342217; 552 | position: absolute; 553 | left: 147px; 554 | top: 27px; 555 | } 556 | 557 | .stripe > h2 span:first-child { 558 | font: 128.1px 'MS Gothic', 'Arial Unicode', 'Apple Symbols'; /* HACK font-size is odd for correct placing in firefox */ 559 | position: absolute; 560 | left: -125px; 561 | top: -25px; 562 | width: 120px; 563 | height: 120px; 564 | color: transparent; 565 | background: url("../img/sprites.png") no-repeat; 566 | } 567 | 568 | .menu input { 569 | border: 0; 570 | background-color: #5a4232; 571 | padding: 4px; 572 | border-radius: 5px; 573 | font-size: 14pt; 574 | color: #999; 575 | } 576 | 577 | .menu input[type="text"] { 578 | width: 205px; 579 | position: absolute; 580 | left: 147px; 581 | top: 70px; 582 | height: 21px; 583 | } 584 | 585 | .menu input[type="text"]::placeholder { 586 | color: #999; 587 | opacity: 1; 588 | } 589 | 590 | .menu input[type="text"]:not(.error):focus::placeholder { 591 | opacity: 0; 592 | } 593 | 594 | .menu input[type="button"] { 595 | width: 40px; 596 | position: absolute; 597 | left: 366px; 598 | top: 70px; 599 | height: 29px; 600 | } 601 | 602 | .menu .error { 603 | background-color: rgb(153,30,30); 604 | } 605 | 606 | .inactive { 607 | opacity: 0.3; 608 | } 609 | 610 | /* Specific menu items */ 611 | 612 | #pause h2, #end > .tone100 > h2 { 613 | font-size: 42pt; 614 | } 615 | 616 | #start > .tone55 > h2 span { 617 | background-position: 0 57.14%; 618 | } 619 | 620 | #start > .tone70 > h2 span { 621 | background-position: 20% 57.14%; 622 | } 623 | 624 | #start > .tone85 > h2 span { 625 | background-position: 40% 57.14%; 626 | } 627 | 628 | #pause > .tone55 > h2 span { 629 | background-position: 60% 57.14%; 630 | } 631 | 632 | #pause > .tone70 > h2 span { 633 | background-position: 80% 57.14%; 634 | } 635 | 636 | #pause > .tone85 > h2 span { 637 | background-position: 100% 57.14%; 638 | } 639 | 640 | #end > .tone100 > h2 span:first-child { 641 | background-position: 0px 100%; 642 | width: 180px; 643 | height: 180px; 644 | left: -175px; 645 | top: -57px 646 | } 647 | 648 | #end > .stripe > h2 { 649 | left: 165px; 650 | } 651 | 652 | /* Selection behaviour */ 653 | 654 | #info, #border, #board, #whiteCemetery, #blackCemetery, #promotion, .menu h2 { 655 | user-select: none; 656 | cursor: default; 657 | } 658 | 659 | /* Animations */ 660 | 661 | .horizontal { 662 | transform: scaleX(0); 663 | } 664 | 665 | .vertical { 666 | transform: scaleY(0); 667 | } -------------------------------------------------------------------------------- /js/game.min.js: -------------------------------------------------------------------------------- 1 | /* 2 | * PlainChess v1.22 3 | * http://plainchess.timwoelfle.de 4 | * 5 | * Copyright by Tim Wölfle (http://timwoelfle.de) 6 | * Licensed under the GPL Version 3 license (http://www.gnu.org/licenses/gpl-3.0.txt) 7 | * 8 | */ 9 | var game,sync,menu,controller;function Game(savedGame){var pieceSymbols={"♙":{color:"white",kind:"pawn"},"♘":{color:"white",kind:"knight"},"♗":{color:"white",kind:"bishop"},"♖":{color:"white",kind:"rook"},"♕":{color:"white",kind:"queen"},"♔":{color:"white",kind:"king"},"♟":{color:"black",kind:"pawn"},"♞":{color:"black",kind:"knight"},"♝":{color:"black",kind:"bishop"},"♜":{color:"black",kind:"rook"},"♛":{color:"black",kind:"queen"},"♚":{color:"black",kind:"king"}};var gameTime=0;var moves=[];var gameState;var whitesTurn=1;var castlingAllowed={white:{queenSide:true,kingSide:true},black:{queenSide:true,kingSide:true}};var field={};var timerInterval;var showCaptionInterval;var gameOver;var clickedPieceIsMoving;function generateNotationString(move){var notationString;if(pieceSymbols[move.pieceSymbol].kind==="king"&&Math.abs(move.startColumn-move.endColumn)>1){return move.endColumn===3?"O-O-O":"O-O"}notationString=pieceSymbols[move.pieceSymbol].color==="white"?move.pieceSymbol:''+move.pieceSymbol+"";notationString+=String.fromCharCode(96+move.startColumn);notationString+=move.startRow;notationString+=" ";if(move.capturedPieceSymbol){notationString+=pieceSymbols[move.capturedPieceSymbol].color==="white"?move.capturedPieceSymbol:''+move.capturedPieceSymbol+""}notationString+=String.fromCharCode(96+move.endColumn);notationString+=move.endRow;if(move.promotionType){notationString+="=";notationString+=pieceSymbols[move.pieceSymbol].color==="white"?move.promotionType:''+move.promotionType+""}else if(move.enPassant){notationString+=" e.p."}if(move.check&&!move.mate){notationString+="+"}if(move.mate||move.stalemate){notationString+="#"}return notationString}function updateInfoDrawer(){var lastMove=moves[moves.length-1];var currentTurnString="";var lastMoveString;if(lastMove&&lastMove.stalemate){currentTurnString="Stalemate!"}else{if(lastMove&&lastMove.mate){currentTurnString="Mate! ";if(sync){currentTurnString+=whitesTurn===sync.playerIsWhite?"Opponent wins.":"You win."}else{currentTurnString+=whitesTurn?"Black wins.":"White wins."}}else{if(lastMove&&lastMove.check){currentTurnString="Check! "}if(sync){currentTurnString+=whitesTurn===sync.playerIsWhite?"Your turn.":"Opponent's turn."}else{currentTurnString+=whitesTurn?"White's turn.":"Black's turn."}}}$("#currentTurn > span:first-child").html(currentTurnString);if(moves.length){lastMoveString="Last move: "+generateNotationString(lastMove)}else{lastMoveString="No move yet."}$("#lastMove").html(lastMoveString)}function updateGameTime(){var min;var sec;var string="";gameTime++;min=Math.floor(gameTime/60);sec=gameTime%60;string+=min<10?"0"+min:min;string+=":";string+=sec<10?"0"+sec:sec;$("#gameTime").html(string)}function hidePromotionMenu(){$(".promotion").fadeOut(300,function(){$(".promotion > ul > li").off().remove();$(".promotion")[0].id="";$(".promotion").css("left","")})}function hideInfoDrawer(){if($("#info").height()===570){$("#info").clearQueue().animate({height:"540px"},100,"easeOutQuad")}}function showInfoDrawer(){if($("#info").height()===540){$("#info").clearQueue().animate({height:"570px"},100,"easeInQuad")}}function pieceObject(element,object){if(!object)return $(element).data("pieceObject");else return $(element).data("pieceObject",object)}function fieldObject(element,object){if(!object)return $(element).data("fieldObject");else return $(element).data("fieldObject",object)}function finishMove(){var possibleTurn;whitesTurn=whitesTurn?0:1;if(pieceObject($("td > .piece.king."+(whitesTurn?"white":"black"))).field.reachableBy[whitesTurn?"black":"white"].length){moves[moves.length-1].check=true}$(whitesTurn?"td > .white":"td> .black").each(function(index,piece){if(pieceObject(piece).accessibleFields().length){possibleTurn=true;return false}});if(!possibleTurn){if(moves[moves.length-1].check){moves[moves.length-1].mate=true;$("#end > .tone100 > h2 > span:first-child").css("background-position",whitesTurn?"-180px 100%":"0 100%");$("#end > .tone100 > h2 > span:last-child").html(whitesTurn?"Black wins":"White wins")}else{moves[moves.length-1].stalemate=true;$("#end > .tone100 > h2 > span:first-child").css("background-position","-360px 100%");$("#end > .tone100 > h2 > span:last-child").html("Stalemate")}game.gameOver=true;clearInterval(timerInterval)}if(moves[moves.length-1].check){if(moves[moves.length-1].mate){controller.blink($("td > .piece.king."+(whitesTurn?"white":"black")),3,1e3,function(){if(!menu){menu=new Menu("#end");menu.appear(true)}})}else{controller.blink($("td > .piece.king."+(whitesTurn?"white":"black")),2,1e3)}}else if(moves[moves.length-1].stalemate){controller.blink($("td > .piece.king"),3,1e3,function(){if(!menu){menu=new Menu("#end");menu.appear(true)}})}updateInfoDrawer();if(controller.autoSave){game.updateLocalStorage()}if(sync&&sync.playerIsWhite!==whitesTurn){sync.makeMove(moves[moves.length-1])}}function Piece(pieceElement){var that=this;pieceObject(pieceElement,this);this.element=pieceElement;this.symbol=pieceElement.innerHTML;this.kind=pieceSymbols[this.symbol].kind;this.color=pieceSymbols[this.symbol].color;this.isWhite=this.color==="white"?1:0;this.field=fieldObject(pieceElement.parentNode);this.reachableFields=[];function removeCastlingRights(){if(that.kind==="king"||that.kind==="rook"&&that.field.column===1){castlingAllowed[that.color].queenSide=false}if(that.kind==="king"||that.kind==="rook"&&that.field.column===8){castlingAllowed[that.color].kingSide=false}}this.getReachableFields=function(){function Fields(column,row){this.add=function(columnDiff,rowDiff){if(field[column+columnDiff]&&field[column+columnDiff][row+rowDiff]){return this.push(field[column+columnDiff][row+rowDiff])}return false}}Fields.prototype=[];var fields=new Fields(this.field.column,this.field.row);var forward=that.isWhite?+1:-1;var i;switch(this.kind){case"pawn":fields.add(-1,forward);fields.add(+1,forward);break;case"knight":fields.add(-1,+2);fields.add(+1,+2);fields.add(-1,-2);fields.add(+1,-2);fields.add(-2,+1);fields.add(-2,-1);fields.add(+2,+1);fields.add(+2,-1);break;case"king":fields.add(-1,+1);fields.add(+0,+1);fields.add(+1,+1);fields.add(-1,+0);fields.add(+1,+0);fields.add(-1,-1);fields.add(+0,-1);fields.add(+1,-1);break;case"bishop":case"rook":case"queen":if(this.kind!=="bishop"){$.each([[-1,0],[+1,0],[0,-1],[0,+1]],function(index,coords){for(i=1;fields.add(coords[0]*i,coords[1]*i);i++){if(fields[fields.length-1].piece){break}}})}if(this.kind!=="rook"){$.each([[-1,+1],[-1,-1],[+1,+1],[+1,-1]],function(index,coords){for(i=1;fields.add(coords[0]*i,coords[1]*i);i++){if(fields[fields.length-1].piece){break}}})}break}return fields};this.captureableFields=function(){var otherFields=this.reachableFields;var fields=[];$.each(otherFields,function(index,otherField){if(otherField.piece){if(otherField.piece.isWhite!==that.isWhite){fields.push(otherField)}}else if(that.kind!=="pawn"){fields.push(otherField)}});return fields};this.accessibleFields=function(){var fields=this.captureableFields();var forward=that.isWhite?1:-1;var homeRow=that.isWhite?1:8;var cachedFields;var king=pieceObject($("td > .piece.king."+(that.isWhite?"white":"black")));var opponentColor=that.isWhite?"black":"white";var aggressors=king.field.reachableBy[opponentColor];var i;var lineFld;var behindPiece;switch(this.kind){case"pawn":if(field[this.field.column][this.field.row+forward]&&!field[this.field.column][this.field.row+forward].piece){fields.push(field[this.field.column][this.field.row+forward])}if(this.field.row===homeRow+forward&&!field[this.field.column][this.field.row+forward].piece&&!field[this.field.column][this.field.row+forward*2].piece){fields.push(field[this.field.column][this.field.row+forward*2])}if(this.field.row===homeRow+forward*4&&moves.length&&pieceSymbols[moves[moves.length-1].pieceSymbol].kind==="pawn"&&moves[moves.length-1].endRow===this.field.row&&Math.abs(moves[moves.length-1].startRow-moves[moves.length-1].endRow)===2&&Math.abs(moves[moves.length-1].startColumn-this.field.column)===1){fields.push(field[moves[moves.length-1].startColumn][this.field.row+forward])}break;case"king":if(castlingAllowed[this.color].queenSide&&field[1][homeRow].piece&&field[1][homeRow].piece.kind==="rook"&&!field[2][homeRow].piece&&!field[3][homeRow].piece&&!field[4][homeRow].piece&&!field[3][homeRow].reachableBy[opponentColor].length&&!field[4][homeRow].reachableBy[opponentColor].length&&!field[5][homeRow].reachableBy[opponentColor].length){fields.push(field[3][homeRow])}if(castlingAllowed[this.color].kingSide&&field[8][homeRow].piece&&field[8][homeRow].piece.kind==="rook"&&!field[6][homeRow].piece&&!field[7][homeRow].piece&&!field[7][homeRow].reachableBy[opponentColor].length&&!field[6][homeRow].reachableBy[opponentColor].length&&!field[5][homeRow].reachableBy[opponentColor].length){fields.push(field[7][homeRow])}$.each(fields,function(index,fld){if(fld.reachableBy[opponentColor].length){fields[index]=[]}else{$.each(aggressors,function(aggressorIndex,aggressor){if(["rook","queen"].includes(aggressor.kind)&&that.field.inBetweenCross(aggressor.field,fld))fields[index]=[];if(["bishop","queen"].includes(aggressor.kind)&&that.field.inBetweenDiag(aggressor.field,fld))fields[index]=[]})}});return fields.flat()}if(aggressors.length){cachedFields=fields;fields=[];if(aggressors.length>1){return[]}else{$.each(cachedFields,function(index,fld){if(aggressors[0].kind==="bishop"||aggressors[0].kind==="rook"||aggressors[0].kind==="queen"){if(fld.inBetween(king.field,aggressors[0].field)){fields.push(fld)}}if(fld===aggressors[0].field){fields.push(fld)}})}}$.each([[-1,0],[+1,0],[0,-1],[0,+1],[-1,+1],[-1,-1],[+1,+1],[+1,-1]],function(index,coords){if(!field[that.field.column+coords[0]]||!(lineFld=field[that.field.column+coords[0]][that.field.row+coords[1]])){return true}if(that.field.inBetween(lineFld,king.field)){for(i=1;field[king.field.column+coords[0]*i]&&(lineFld=field[king.field.column+coords[0]*i][king.field.row+coords[1]*i]);i++){if(lineFld.piece){if(lineFld.piece===that){behindPiece=true;continue}else if(behindPiece&&lineFld.piece.isWhite!==that.isWhite&&(lineFld.piece.kind==="queen"||lineFld.piece.kind==="bishop"&&index>3||lineFld.piece.kind==="rook"&&index<4)){cachedFields=fields;fields=[];$.each(cachedFields,function(index,cachedFld){if(cachedFld.inBetween(king.field,lineFld)||cachedFld===lineFld){fields.push(cachedFld)}})}return false}}}});return fields};this.updateReachables=function(){function updatePropertyClass(fld){if(fld.reachableBy.white.length!==fld.reachableBy.black.length)fld.element.className="property"+(fld.reachableBy.white.length-fld.reachableBy.black.length);else fld.element.className="neutral"+fld.reachableBy.white.length}$.each(this.reachableFields,function(index,fld){index=fld.reachableBy[that.color].indexOf(that);if(index!==-1){fld.reachableBy[that.color].splice(index,1);updatePropertyClass(fld)}});if(!this.field){return false}this.reachableFields=this.getReachableFields();$.each(this.reachableFields,function(index,fld){fld.reachableBy[that.color].push(that);updatePropertyClass(fld)})};this.moveToCemetery=function(){var target;if(this.kind==="rook"){removeCastlingRights()}target=$("
      • ").appendTo($("#"+this.color+"Cemetery"));this.moveInDOM(target,true,true);if($(pieceElement).hasClass("ui-draggable")){$(pieceElement).draggable("destroy")}};this.move=function(targetField,promotionType){var capturedPiece,castling;moves.push({startColumn:that.field.column,startRow:that.field.row,endColumn:targetField.column,endRow:targetField.row,pieceSymbol:that.symbol});capturedPiece=field[targetField.column][targetField.row].piece;if(that.kind==="pawn"&&that.field.column!==targetField.column&&!capturedPiece){capturedPiece=field[targetField.column][targetField.row+(that.isWhite?-1:1)].piece;moves[moves.length-1].enPassant=true}if(capturedPiece){moves[moves.length-1].capturedPieceSymbol=capturedPiece.symbol;capturedPiece.moveToCemetery()}if((that.symbol==="♔"&&targetField.row===1||that.symbol==="♚"&&targetField.row===8)&&(targetField.column===3&&castlingAllowed[that.color].queenSide||targetField.column===7&&castlingAllowed[that.color].kingSide)){castling={};castling.row=that.symbol==="♔"?1:8;castling.startColumn=targetField.column===3?1:8;castling.endColumn=targetField.column===3?4:6;castling.tower=field[castling.startColumn][castling.row].piece;castling.tower.moveInDOM(field[castling.endColumn][castling.row].element,true)}if(that.kind==="rook"||that.kind==="king"){removeCastlingRights()}that.moveInDOM(targetField.element);if(that.symbol==="♙"&&targetField.row===8||that.symbol==="♟"&&targetField.row===1){return that.promote(promotionType)}finishMove()};this.animateMove=function(targetField,promotionType){$(pieceElement).css("position","relative").animate({left:$(targetField.element).offset().left-$(this.field.element).offset().left,top:$(targetField.element).offset().top-$(this.field.element).offset().top},1e3,"easeInOutQuad",function(){if(clickedPieceIsMoving){clickedPieceIsMoving=false}that.move(targetField,promotionType)})};this.startDragging=function(){var fields;$("#board td").removeClass("acceptable").off("click");if(whitesTurn!==this.isWhite||clickedPieceIsMoving||moves[moves.length-1]&&(moves[moves.length-1].mate||moves[moves.length-1].stalemate)||$(".promotion").is(":visible")){return false}$("#board td").droppable("option","accept","");fields=this.accessibleFields();$.each(fields,function(index,fld){$(fld.element).droppable("option","accept",".piece")});return true};this.clickPiece=function(){if(whitesTurn!==this.isWhite||clickedPieceIsMoving||moves[moves.length-1]&&(moves[moves.length-1].mate||moves[moves.length-1].stalemate)||$(".promotion").is(":visible")){return true}function unselect(){$("#board td").removeClass("acceptable").off("click")}unselect();$("#board td").on("click",function(){unselect()});$.each(this.accessibleFields(),function(index,fld){$(fld.element).addClass("acceptable");$(fld.element).on("click",function(){clickedPieceIsMoving=true;unselect();that.animateMove(fld)})});return false};this.promote=function(pieceSymbol){if(pieceSymbol){that.symbol=pieceElement.innerHTML=pieceSymbol;that.kind=pieceSymbols[pieceSymbol].kind;moves[moves.length-1].promotionType=pieceSymbol;gameState[moves[moves.length-1].endColumn][moves[moves.length-1].endRow]=pieceSymbol;that.updateReachables();finishMove();hidePromotionMenu();controller.flip(pieceElement,"horizontal",1e3,function(){$(pieceElement).removeClass("pawn");$(pieceElement).addClass(that.kind)})}else{var mirroredBoardOrientation;$.each(this.isWhite?["♘","♗","♖","♕"]:["♞","♝","♜","♛"],function(index,pieceSymbol){$('
      • '+pieceSymbol+"
      • ").appendTo($(".promotion > ul")).on("click",function(){that.promote(pieceSymbol)})});mirroredBoardOrientation=sync?!sync.playerIsWhite:0;$(".promotion")[0].id=this.isWhite||mirroredBoardOrientation?"top":"bottom";$(".promotion").css("left",-130+60*Math.abs(this.field.column-9*mirroredBoardOrientation)+"px");$(".promotion").fadeIn(300)}};this.moveInDOM=function(target,animated,spin){var oldFieldsReachables,oldPosLeft,oldPosTop;oldFieldsReachables=this.field.reachableBy.white.concat(this.field.reachableBy.black);gameState[this.field.column][this.field.row]="";this.field.piece=undefined;this.field=undefined;$.each(oldFieldsReachables,function(index,piece){if(piece.kind==="bishop"||piece.kind==="rook"||piece.kind==="queen"){piece.updateReachables()}});if(animated){oldPosLeft=$(pieceElement).offset().left;oldPosTop=$(pieceElement).offset().top}$(target).append(pieceElement);if(animated){if(spin){controller.spin(pieceElement,1e3)}$(pieceElement).css({position:"relative",left:oldPosLeft-$(pieceElement).offset().left+"px",top:oldPosTop-$(pieceElement).offset().top+"px"}).animate({left:"0",top:"0"},1e3,"easeInOutQuad")}else{$(pieceElement).css({left:"0",top:"0"})}if(fieldObject(target)){gameState[fieldObject(target).column][fieldObject(target).row]=this.symbol;this.field=fieldObject(target);this.field.piece=this;$.each(this.field.reachableBy.white.concat(this.field.reachableBy.black),function(index,piece){if(piece.kind==="bishop"||piece.kind==="rook"||piece.kind==="queen"){piece.updateReachables()}})}this.updateReachables()}}function Field(fieldElement){fieldObject(fieldElement,this);this.element=fieldElement;this.column=parseInt(fieldElement.id.substr(0,1),10);this.row=parseInt(fieldElement.id.substr(1,1),10);this.piece=fieldElement.firstChild?pieceObject(fieldElement.firstChild):undefined;this.reachableBy={white:[],black:[]};this.createPiece=function(pieceSymbol){this.piece=new Piece($('
        '+pieceSymbol+"
        ").appendTo(fieldElement)[0])};this.inBetweenCross=function(startField,endField){if(startField.column===endField.column&&this.column===startField.column){return this.rowendField.row||this.row>startField.row&&this.rowendField.column||this.column>startField.column&&this.column
        '+move.capturedPieceSymbol+"
        ").appendTo($("#"+pieceSymbols[move.capturedPieceSymbol].color+"Cemetery"))}});if(moves.length&&(moves[moves.length-1].mate||moves[moves.length-1].stalemate)){gameOver=true;if(moves[moves.length-1].mate){$("#end > .tone100 > h2 > span:first-child").css("background-position",whitesTurn?"30% 100%":"0 100%");$("#end > .tone100 > h2 > span:last-child").html(whitesTurn?"Black wins":"White wins")}else{$("#end > .tone100 > h2 > span:first-child").css("background-position","60% 100%");$("#end > .tone100 > h2 > span:last-child").html("Stalemate")}}}gameState=gameState||{1:{1:"♖",2:"♙",7:"♟",8:"♜"},2:{1:"♘",2:"♙",7:"♟",8:"♞"},3:{1:"♗",2:"♙",7:"♟",8:"♝"},4:{1:"♕",2:"♙",7:"♟",8:"♛"},5:{1:"♔",2:"♙",7:"♟",8:"♚"},6:{1:"♗",2:"♙",7:"♟",8:"♝"},7:{1:"♘",2:"♙",7:"♟",8:"♞"},8:{1:"♖",2:"♙",7:"♟",8:"♜"}};$.each(field,function(columnIndex,column){$.each(column,function(rowIndex,fld){if(gameState[columnIndex]&&gameState[columnIndex][rowIndex]){field[columnIndex][rowIndex].createPiece(gameState[columnIndex][rowIndex])}})});$("td > .piece").each(function(index,piece){pieceObject(piece).updateReachables()});$("td > .white.knight:first, td > .black.knight:first").css("transform","scaleX(-1)");$("td > .piece").each(function(index,element){if(!sync||sync.playerIsWhite===pieceObject(element).isWhite){$(element).draggable({containment:$("#board"),revert:"invalid",start:function(event,ui){return pieceObject(ui.helper[0]).startDragging()}});$(element).on("click",function(){return pieceObject(this).clickPiece()})}});$("#board td").droppable({addClasses:false,accept:"",activeClass:"acceptable",drop:function(event,ui){return pieceObject(ui.draggable[0]).move(fieldObject(this))}});$("#border").hover(function(){if(!menu){showCaptionInterval=setTimeout(function(){$("#border table").fadeIn(300)},500)}},function(){$("#border table").fadeOut(300);clearInterval(showCaptionInterval)});updateInfoDrawer();updateGameTime();showInfoDrawer();if(!gameOver){timerInterval=setInterval(function(){updateGameTime()},1e3)}})();return{gameOver:gameOver,deinit:function(){localStorage.clear();if(!controller.autoSave){localStorage.noAutoSave=true}hidePromotionMenu();$(".piece").fadeOut(300,function(){$(this).parent("li").remove();$(this).remove()});$(".ui-draggable").draggable("destroy");$("#board td").droppable("destroy");$("#board td").removeClass();clearInterval(timerInterval);hideInfoDrawer();$("#border").off()},fieldIsTaken:function(column,row){if(field[column]&&field[column][row]&&field[column][row].piece){return true}return false},receiveCoordinates:function(startColumn,startRow,endColumn,endRow,promotionType,preanimation){var startField;var targetField;var piece;var validMove=false;startField=document.getElementById(startColumn+""+startRow);targetField=document.getElementById(endColumn+""+endRow);piece=startField.firstChild;if(!startField||!targetField||!piece){return false}$.each(pieceObject(piece).accessibleFields(),function(index,fld){if(fieldObject(targetField)===fld){validMove=true}});if(preanimation){controller.blink(piece,2,1e3,function(){pieceObject(piece).animateMove(fieldObject(targetField),promotionType)})}else{pieceObject(piece).animateMove(fieldObject(targetField),promotionType)}return validMove},updateLocalStorage:function(){localStorage.whitesTurn=whitesTurn;localStorage.gameState=JSON.stringify(gameState);localStorage.castlingAllowed=JSON.stringify(castlingAllowed);localStorage.gameTime=gameTime;localStorage.moves=JSON.stringify(moves)}}}function Sync(){var gameName;var syncInterval;var windowHasFocus=1;function toggleTitleNotification(){document.title=document.title==="PlainChess"&&!windowHasFocus?"Your turn!":"PlainChess";if(!windowHasFocus){setTimeout(function(){toggleTitleNotification()},1e3)}}(function init(){$(window).on("focus",function(){windowHasFocus=1});$(window).on("blur",function(){windowHasFocus=0})})();return{playerIsWhite:1,deinit:function(){clearInterval(syncInterval);$(window).off()},hostGame:function(name){$.post("php/hostGame.php",{id:name},function(data){if(!data){menu.error(document.getElementById("hostGameName"),"Name already taken…")}else{gameName=data;$("#hostGame > input[type='button']")[0].value="";$("#hostGame > input[type='button']").css("background","#5a4232 url(img/ajax-loader.gif) center no-repeat");$("input[type='text']").attr("readonly",true);$("input[type='button']").attr("disabled",true);menu.deinit();syncInterval=setInterval(function(){sync.waitForStart()},5e3);localStorage.gameName=gameName;localStorage.playerIsWhite=sync.playerIsWhite}})},joinGame:function(name){$.post("php/joinGame.php",{id:name},function(data){if(!data){menu.error(document.getElementById("joinGameName"),"Game not hosted…")}else{sync.playerIsWhite=0;gameName=data;game=new Game;menu.disappear(true);syncInterval=setInterval(function(){sync.waitForMove()},5e3);localStorage.gameName=gameName;localStorage.playerIsWhite=sync.playerIsWhite}})},resumeGame:function(){if(!localStorage.gameName||!localStorage.playerIsWhite){return false}gameName=localStorage.gameName;sync.playerIsWhite=parseInt(localStorage.playerIsWhite,10);if(localStorage.whitesTurn!=sync.playerIsWhite){syncInterval=setInterval(function(){sync.waitForMove()},5e3)}},waitForStart:function(){$.post("php/waitForStart.php",{id:gameName},function(data){if(data==="joined"){toggleTitleNotification();menu.disappear(true);game=new Game;clearInterval(syncInterval)}})},waitForMove:function(){var startColumn,startRow,endColumn,endRow,promotionType;function passMove(preanimation){if(!game.receiveCoordinates(startColumn,startRow,endColumn,endRow,promotionType,preanimation)){alert("Invalid move received, maybe due to cheating. Games might be out of sync, restart is recommended.")}}$.post("php/waitForMove.php",{id:gameName},function(data){if(data!=="joined"){startColumn=parseInt(data.substr(0,1),10);startRow=parseInt(data.substr(1,1),10);endColumn=parseInt(data.substr(3,1),10);endRow=parseInt(data.substr(4,1),10);if(data.substr(6,1)){promotionType=data.substr(6,1)}if(game.fieldIsTaken(startColumn,startRow)){clearInterval(syncInterval);if(windowHasFocus){passMove(0)}else{toggleTitleNotification();$(window).on("focus",function(){windowHasFocus=1;passMove(1);$(window).off("focus");$(window).on("focus",function(){windowHasFocus=1})})}}}})},makeMove:function(move){$.post("php/makeMove.php",{id:gameName,startColumn:move.startColumn,startRow:move.startRow,endColumn:move.endColumn,endRow:move.endRow,promotionType:move.promotionType,gameOver:game.gameOver},function(data){if(!data){alert("Error occured during sync! Game might have ended!")}else{syncInterval=setInterval(function(){sync.waitForMove()},5e3)}})}}}function Menu(name){var menuBox,stripes,textFields,buttons,quickOptions,locked;menuBox=$(name);stripes=menuBox.children();textFields=stripes.children("input[type='text']");buttons=stripes.children("input[type='button']");quickOptions=stripes.children("h2").children("a");locked=0;function highlightStripe(number){if(locked){return false}stripes.each(function(index,element){$(element).children().clearQueue();if(number===index+1||!number){$(element).children().fadeTo(300,1)}else{$(element).children().fadeTo(300,.3)}})}function init(){var code;menuBox.on("mouseleave",function(handler){highlightStripe(0)});stripes.each(function(index,element){if(element.id){$(element).on("mouseenter",function(){highlightStripe(index+1)});$(element).on("click",function(){$(element).children("input[type='text']").focus();highlightStripe(index+1)})}else{$(element).on("mouseenter",function(){highlightStripe(0)})}$(element).children().each(function(childIndex,childElement){$(childElement).on("focus",function(){highlightStripe(index+1);locked=1});$(childElement).on("blur",function(){locked=0;highlightStripe(0)})})});textFields.each(function(index,element){$(element).on("focus",function(){if(element.value===element.getAttribute("value")){element.value=""}});$(element).on("blur",function(){if(element.value===""||$(element).hasClass("error")){element.value=element.getAttribute("value");$(element).removeClass("error")}});$(element).on("keypress",function(key){code=key.keyCode?key.keyCode:key.which;if(code!==13){if($(element).hasClass("error")){element.value="";$(element).removeClass("error");return true}return true}menu.menuOption(element.parentNode.id)})});buttons.each(function(index,element){$(element).on("click",function(){menu.menuOption(element.parentNode.id)})});quickOptions.each(function(index,element){$(element).on("click",function(){menu.menuOption(element.parentNode.parentNode.id);return false})});menu.initialized=true}return{name:name,initialized:false,deinit:function(){menuBox.off();$(stripes).off();$(stripes).children().off();$(quickOptions).off()},appear:function(animated){menuBox.show();if(animated){stripes.each(function(index,element){$(element).css("left","-480px").animate({left:"0"},500+index*100,"easeOutQuad",function(){if(index===stripes.length-1){init()}})})}else{init()}},disappear:function(animated){menu.deinit();function deinitAfterAnimation(){menuBox.hide();if(menu){menu=undefined}$("input[type='text']")[0].value=$("input[type='text']")[0].getAttribute("value");$("#hostGame > input[type='button']")[0].value="Go";$("#hostGame > input[type='button']").css("background","");$("input[type='text']").attr("readonly",false);$("input[type='button']").attr("disabled",false)}if(animated){stripes.each(function(index,element){$(element).animate({left:"480px"},400+100*(stripes.length-index),"easeInQuad",function(){if(!index){deinitAfterAnimation()}})})}else{deinitAfterAnimation()}if(menu){menu.initialized=false}},error:function(input,msg){input.value="";input.placeholder=msg;$(input).addClass("error").focus()},menuOption:function(optionId){var name;switch(optionId){case"hostGame":name=document.getElementById("hostGameName").value.trim();if(!name){return menu.error(document.getElementById("hostGameName"),"Enter game name…")}sync=new Sync;sync.hostGame(name);break;case"joinGame":name=document.getElementById("joinGameName").value.trim();if(!name){return menu.error(document.getElementById("joinGameName"),"Enter game name…")}sync=new Sync;sync.joinGame(name);break;case"playOffline":game=new Game;menu.disappear(true);break;case"toggleAutoSave":if(sync){break}controller.autoSave=!controller.autoSave;if(controller.autoSave){localStorage.noAutoSave=undefined;game.updateLocalStorage()}else{localStorage.noAutoSave=true}$("#toggleAutoSave > h2 > a > span:last-child").html(controller.autoSave?"on":"off");controller.flip($("#pause > .tone55 > h2 span:first-child"),"horizontal",250,function(){$("#pause > .tone55 > h2 span:first-child").css("background-position",controller.autoSave?"60% 57.14%":"100% 85.71%")});break;case"playOn":menu.disappear(true);break;case"quitGame":game=game.deinit();if(sync){sync=sync.deinit()}menu=menu.disappear();menu=new Menu("#start");menu.appear(true);break}}}}controller=function(){function toggleMenu(animated){if($("#toggleFaq").hasClass("active")){$("#toggleFaq").click();return false}if(menu){if(menu.name!=="#start"&&menu.initialized){menu.disappear(animated)}}else{menu=new Menu(game.gameOver?"#end":"#pause");menu.appear(animated)}}(function init(){var savedGame;if(localStorage.gameState||localStorage.gameName){if(localStorage.gameState){savedGame={};savedGame.whitesTurn=parseInt(localStorage.whitesTurn,10);savedGame.gameTime=parseInt(localStorage.gameTime,10);try{savedGame.gameState=JSON.parse(localStorage.gameState);savedGame.castlingAllowed=JSON.parse(localStorage.castlingAllowed);savedGame.moves=JSON.parse(localStorage.moves)}catch(error){localStorage.clear();savedGame=undefined}}if(localStorage.gameName){sync=new Sync;sync.resumeGame()}game=new Game(savedGame);toggleMenu(false)}else{menu=new Menu("#start");menu.appear()}$("h1 a").on("click",function(){toggleMenu(true);return false});$(document).on("keydown",function(key){if(key.keyCode===27||key.which===27){toggleMenu(true);return false}});$("#toggleAwareness").on("click",function(){if($("#chess").hasClass("awareness")){$("#chess").removeClass("awareness")}else{$("#chess").addClass("awareness")}});$("#toggleFaq").on("click",function(){$("#toggleFaq").toggleClass("active");$("#flip").toggleClass("flipped");return false});$("#contact").on("click",function(){$("#contact").off();controller.flip($("#contact"),"vertical",250,function(){$("#contact").html("plainchess@timwoelfle.de");$("#contact").attr("href","mailto:plainchess@timwoelfle.de?subject=PlainChess")});return false});if(localStorage.noAutoSave&&!sync){$("#toggleAutoSave > h2 > a > span:last-child").html("off");$("#pause > .tone55 > h2 span:first-child").css("background-position","100% 85.71%")}})();return{autoSave:!(localStorage.noAutoSave&&!sync),blink:function(element,count,durationEach,callback){$(element).animate({opacity:"0"},durationEach/2,"easeOutQuad",function(){$(element).animate({opacity:"1"},durationEach/2,"easeInQuad",function(){if(count>1){controller.blink(element,count-1,durationEach,callback)}else{if(typeof callback==="function"){callback()}}})})},spin:function(element,duration){$(element).css("transition-property","transform").css("transition-duration",duration+"ms").css("transition-timing-function","ease-out");setTimeout(function(){$(element).css("transform","rotate(360deg)")})},flip:function(element,className,duration,callback){$(element).on("transitionend",function(){$(element).off("transitionend");$(element).css("transition-timing-function","ease-out").removeClass(className);if(typeof callback==="function"){callback()}}).css("transition-property","transform").css("transition-duration",duration/2+"ms").css("transition-timing-function","ease-in");setTimeout(function(){$(element).addClass(className)})}}}(); -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /js/jquery-ui.min.js: -------------------------------------------------------------------------------- 1 | /*! jQuery UI - v1.13.1 - 2022-04-24 2 | * http://jqueryui.com 3 | * Includes: widget.js, data.js, scroll-parent.js, widgets/draggable.js, widgets/droppable.js, widgets/mouse.js, effect.js, effects/effect-fade.js 4 | * Copyright jQuery Foundation and other contributors; Licensed MIT */ 5 | 6 | !function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(b){"use strict";b.ui=b.ui||{};b.ui.version="1.13.1";var o,i=0,r=Array.prototype.hasOwnProperty,a=Array.prototype.slice;b.cleanData=(o=b.cleanData,function(t){for(var e,i,s=0;null!=(i=t[s]);s++)(e=b._data(i,"events"))&&e.remove&&b(i).triggerHandler("remove");o(t)}),b.widget=function(t,i,e){var s,o,n,r={},a=t.split(".")[0],l=a+"-"+(t=t.split(".")[1]);return e||(e=i,i=b.Widget),Array.isArray(e)&&(e=b.extend.apply(null,[{}].concat(e))),b.expr.pseudos[l.toLowerCase()]=function(t){return!!b.data(t,l)},b[a]=b[a]||{},s=b[a][t],o=b[a][t]=function(t,e){if(!this||!this._createWidget)return new o(t,e);arguments.length&&this._createWidget(t,e)},b.extend(o,s,{version:e.version,_proto:b.extend({},e),_childConstructors:[]}),(n=new i).options=b.widget.extend({},n.options),b.each(e,function(e,s){function o(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}r[e]="function"==typeof s?function(){var t,e=this._super,i=this._superApply;return this._super=o,this._superApply=n,t=s.apply(this,arguments),this._super=e,this._superApply=i,t}:s}),o.prototype=b.widget.extend(n,{widgetEventPrefix:s&&n.widgetEventPrefix||t},r,{constructor:o,namespace:a,widgetName:t,widgetFullName:l}),s?(b.each(s._childConstructors,function(t,e){var i=e.prototype;b.widget(i.namespace+"."+i.widgetName,o,e._proto)}),delete s._childConstructors):i._childConstructors.push(o),b.widget.bridge(t,o),o},b.widget.extend=function(t){for(var e,i,s=a.call(arguments,1),o=0,n=s.length;o",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=b(e||this.defaultElement||this)[0],this.element=b(e),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=b(),this.hoverable=b(),this.focusable=b(),this.classesElementLookup={},e!==this&&(b.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=b(e.style?e.ownerDocument:e.document||e),this.window=b(this.document[0].defaultView||this.document[0].parentWindow)),this.options=b.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:b.noop,_create:b.noop,_init:b.noop,destroy:function(){var i=this;this._destroy(),b.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:b.noop,widget:function(){return this.element},option:function(t,e){var i,s,o,n=t;if(0===arguments.length)return b.widget.extend({},this.options);if("string"==typeof t)if(n={},t=(i=t.split(".")).shift(),i.length){for(s=n[t]=b.widget.extend({},this.options[t]),o=0;o=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),b.ui.plugin={add:function(t,e,i){var s,o=b.ui[t].prototype;for(s in i)o.plugins[s]=o.plugins[s]||[],o.plugins[s].push([e,i[s]])},call:function(t,e,i,s){var o,n=t.plugins[e];if(n&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(o=0;o").css("position","absolute").appendTo(t.parent()).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(t){var e=b.ui.safeActiveElement(this.document[0]);b(t.target).closest(e).length||b.ui.safeBlur(e)},_mouseStart:function(t){var e=this.options;return this.helper=this._createHelper(t),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),b.ui.ddmanager&&(b.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=0i[2]&&(n=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(r=i[3]+this.offset.click.top)),s.grid&&(t=s.grid[1]?this.originalPageY+Math.round((r-this.originalPageY)/s.grid[1])*s.grid[1]:this.originalPageY,r=!i||t-this.offset.click.top>=i[1]||t-this.offset.click.top>i[3]?t:t-this.offset.click.top>=i[1]?t-s.grid[1]:t+s.grid[1],t=s.grid[0]?this.originalPageX+Math.round((n-this.originalPageX)/s.grid[0])*s.grid[0]:this.originalPageX,n=!i||t-this.offset.click.left>=i[0]||t-this.offset.click.left>i[2]?t:t-this.offset.click.left>=i[0]?t-s.grid[0]:t+s.grid[0]),"y"===s.axis&&(n=this.originalPageX),"x"===s.axis&&(r=this.originalPageY)),{top:r-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:o?0:this.offset.scroll.top),left:n-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:o?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(t,e,i){return i=i||this._uiHash(),b.ui.plugin.call(this,t,[e,i,this],!0),/^(drag|start|stop)/.test(t)&&(this.positionAbs=this._convertPositionTo("absolute"),i.offset=this.positionAbs),b.Widget.prototype._trigger.call(this,t,e,i)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),b.ui.plugin.add("draggable","connectToSortable",{start:function(e,t,i){var s=b.extend({},t,{item:i.element});i.sortables=[],b(i.options.connectToSortable).each(function(){var t=b(this).sortable("instance");t&&!t.options.disabled&&(i.sortables.push(t),t.refreshPositions(),t._trigger("activate",e,s))})},stop:function(e,t,i){var s=b.extend({},t,{item:i.element});i.cancelHelperRemoval=!1,b.each(i.sortables,function(){var t=this;t.isOver?(t.isOver=0,i.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,s))})},drag:function(i,s,o){b.each(o.sortables,function(){var t=!1,e=this;e.positionAbs=o.positionAbs,e.helperProportions=o.helperProportions,e.offset.click=o.offset.click,e._intersectsWith(e.containerCache)&&(t=!0,b.each(o.sortables,function(){return this.positionAbs=o.positionAbs,this.helperProportions=o.helperProportions,this.offset.click=o.offset.click,t=this!==e&&this._intersectsWith(this.containerCache)&&b.contains(e.element[0],this.element[0])?!1:t})),t?(e.isOver||(e.isOver=1,o._parent=s.helper.parent(),e.currentItem=s.helper.appendTo(e.element).data("ui-sortable-item",!0),e.options._helper=e.options.helper,e.options.helper=function(){return s.helper[0]},i.target=e.currentItem[0],e._mouseCapture(i,!0),e._mouseStart(i,!0,!0),e.offset.click.top=o.offset.click.top,e.offset.click.left=o.offset.click.left,e.offset.parent.left-=o.offset.parent.left-e.offset.parent.left,e.offset.parent.top-=o.offset.parent.top-e.offset.parent.top,o._trigger("toSortable",i),o.dropped=e.element,b.each(o.sortables,function(){this.refreshPositions()}),o.currentItem=o.element,e.fromOutside=o),e.currentItem&&(e._mouseDrag(i),s.position=e.position)):e.isOver&&(e.isOver=0,e.cancelHelperRemoval=!0,e.options._revert=e.options.revert,e.options.revert=!1,e._trigger("out",i,e._uiHash(e)),e._mouseStop(i,!0),e.options.revert=e.options._revert,e.options.helper=e.options._helper,e.placeholder&&e.placeholder.remove(),s.helper.appendTo(o._parent),o._refreshOffsets(i),s.position=o._generatePosition(i,!0),o._trigger("fromSortable",i),o.dropped=!1,b.each(o.sortables,function(){this.refreshPositions()}))})}}),b.ui.plugin.add("draggable","cursor",{start:function(t,e,i){var s=b("body"),i=i.options;s.css("cursor")&&(i._cursor=s.css("cursor")),s.css("cursor",i.cursor)},stop:function(t,e,i){i=i.options;i._cursor&&b("body").css("cursor",i._cursor)}}),b.ui.plugin.add("draggable","opacity",{start:function(t,e,i){e=b(e.helper),i=i.options;e.css("opacity")&&(i._opacity=e.css("opacity")),e.css("opacity",i.opacity)},stop:function(t,e,i){i=i.options;i._opacity&&b(e.helper).css("opacity",i._opacity)}}),b.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(t,e,i){var s=i.options,o=!1,n=i.scrollParentNotHidden[0],r=i.document[0];n!==r&&"HTML"!==n.tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+n.offsetHeight-t.pageY")[0],m=l.each;function v(t){return null==t?t+"":"object"==typeof t?s[e.call(t)]||"object":typeof t}function _(t,e,i){var s=f[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:Math.min(s.max,Math.max(0,t)))}function y(s){var o=h(),n=o._rgba=[];return s=s.toLowerCase(),m(t,function(t,e){var i=e.re.exec(s),i=i&&e.parse(i),e=e.space||"rgba";if(i)return i=o[e](i),o[p[e].cache]=i[p[e].cache],n=o._rgba=i._rgba,!1}),n.length?("0,0,0,0"===n.join()&&l.extend(n,N.transparent),o):N[s]}function w(t,e,i){return 6*(i=(i+1)%1)<1?t+(e-t)*i*6:2*i<1?e:3*i<2?t+(e-t)*(2/3-i)*6:t}g.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=-1n.mod/2?s+=n.mod:s-o>n.mod/2&&(s-=n.mod)),l[i]=_((o-s)*r+s,e)))}),this[e](l)},blend:function(t){if(1===this._rgba[3])return this;var e=this._rgba.slice(),i=e.pop(),s=h(t)._rgba;return h(l.map(e,function(t,e){return(1-i)*s[e]+i*t}))},toRgbaString:function(){var t="rgba(",e=l.map(this._rgba,function(t,e){return null!=t?t:2").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),e={width:i.width(),height:i.height()},o=document.activeElement;try{o.id}catch(t){o=document.body}return i.wrap(t),i[0]!==o&&!b.contains(i[0],o)||b(o).trigger("focus"),t=i.parent(),"static"===i.css("position")?(t.css({position:"relative"}),i.css({position:"relative"})):(b.extend(s,{position:i.css("position"),zIndex:i.css("z-index")}),b.each(["top","left","bottom","right"],function(t,e){s[e]=i.css(e),isNaN(parseInt(s[e],10))&&(s[e]="auto")}),i.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),i.css(e),t.css(s).show()},removeWrapper:function(t){var e=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),t[0]!==e&&!b.contains(t[0],e)||b(e).trigger("focus")),t}}),b.extend(b.effects,{version:"1.13.1",define:function(t,e,i){return i||(i=e,e="effect"),b.effects.effect[t]=i,b.effects.effect[t].mode=e,i},scaledDimensions:function(t,e,i){if(0===e)return{height:0,width:0,outerHeight:0,outerWidth:0};var s="horizontal"!==i?(e||100)/100:1,e="vertical"!==i?(e||100)/100:1;return{height:t.height()*e,width:t.width()*s,outerHeight:t.outerHeight()*e,outerWidth:t.outerWidth()*s}},clipToBox:function(t){return{width:t.clip.right-t.clip.left,height:t.clip.bottom-t.clip.top,left:t.clip.left,top:t.clip.top}},unshift:function(t,e,i){var s=t.queue();1").insertAfter(t).css({display:/^(inline|ruby)/.test(t.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:t.css("marginTop"),marginBottom:t.css("marginBottom"),marginLeft:t.css("marginLeft"),marginRight:t.css("marginRight"),float:t.css("float")}).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).addClass("ui-effects-placeholder"),t.data(D+"placeholder",e)),t.css({position:i,left:s.left,top:s.top}),e},removePlaceholder:function(t){var e=D+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(t){b.effects.restoreStyle(t),b.effects.removePlaceholder(t)},setTransition:function(s,t,o,n){return n=n||{},b.each(t,function(t,e){var i=s.cssUnit(e);0");l.appendTo("body").addClass(t.className).css({top:s.top-r,left:s.left-a,height:i.innerHeight(),width:i.innerWidth(),position:o?"fixed":"absolute"}).animate(n,t.duration,t.easing,function(){l.remove(),"function"==typeof e&&e()})}}),b.fx.step.clip=function(t){t.clipInit||(t.start=b(t.elem).cssClip(),"string"==typeof t.end&&(t.end=B(t.end,t.elem)),t.clipInit=!0),b(t.elem).cssClip({top:t.pos*(t.end.top-t.start.top)+t.start.top,right:t.pos*(t.end.right-t.start.right)+t.start.right,bottom:t.pos*(t.end.bottom-t.start.bottom)+t.start.bottom,left:t.pos*(t.end.left-t.start.left)+t.start.left})},M={},b.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,t){M[t]=function(t){return Math.pow(t,e+2)}}),b.extend(M,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;t<((e=Math.pow(2,--i))-1)/11;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),b.each(M,function(t,e){b.easing["easeIn"+t]=e,b.easing["easeOut"+t]=function(t){return 1-e(1-t)},b.easing["easeInOut"+t]=function(t){return t<.5?e(2*t)/2:1-e(-2*t+2)/2}});b.effects,b.effects.define("fade","toggle",function(t,e){var i="show"===t.mode;b(this).css("opacity",i?0:1).animate({opacity:i?1:0},{queue:!1,duration:t.duration,easing:t.easing,complete:e})})}); -------------------------------------------------------------------------------- /js/game.js: -------------------------------------------------------------------------------- 1 | /* 2 | * PlainChess v1.22 3 | * http://plainchess.timwoelfle.de 4 | * 5 | * Copyright by Tim Wölfle (http://timwoelfle.de) 6 | * Licensed under the GPL Version 3 license (http://www.gnu.org/licenses/gpl-3.0.txt) 7 | * 8 | */ 9 | 10 | /* global $, localStorage, alert */ 11 | 12 | // =========== 13 | // = Globals = 14 | // =========== 15 | 16 | var game, sync, menu, controller 17 | 18 | // ======== 19 | // = Game = 20 | // ======== 21 | 22 | function Game (savedGame) { 23 | /* -- Private attributes & methods -- */ 24 | 25 | // Game constants 26 | var pieceSymbols = { 27 | '♙': { color: 'white', kind: 'pawn' }, 28 | '♘': { color: 'white', kind: 'knight' }, 29 | '♗': { color: 'white', kind: 'bishop' }, 30 | '♖': { color: 'white', kind: 'rook' }, 31 | '♕': { color: 'white', kind: 'queen' }, 32 | '♔': { color: 'white', kind: 'king' }, 33 | '♟': { color: 'black', kind: 'pawn' }, 34 | '♞': { color: 'black', kind: 'knight' }, 35 | '♝': { color: 'black', kind: 'bishop' }, 36 | '♜': { color: 'black', kind: 'rook' }, 37 | '♛': { color: 'black', kind: 'queen' }, 38 | '♚': { color: 'black', kind: 'king' } 39 | } 40 | 41 | // Game variables to be saved 42 | var gameTime = 0; var moves = []; var gameState; var whitesTurn = 1; var castlingAllowed = { white: { queenSide: true, kingSide: true }, black: { queenSide: true, kingSide: true } } 43 | 44 | // Environment variables that can be recalculated in runtime 45 | var field = {}; var timerInterval; var showCaptionInterval; var gameOver; var clickedPieceIsMoving 46 | 47 | function generateNotationString (move) { 48 | var notationString 49 | 50 | // Check for castling 51 | if ((pieceSymbols[move.pieceSymbol].kind === 'king') && Math.abs(move.startColumn - move.endColumn) > 1) { 52 | return (move.endColumn === 3) ? 'O-O-O' : 'O-O' 53 | } 54 | 55 | // Normal start & target field string 56 | notationString = (pieceSymbols[move.pieceSymbol].color === 'white') ? move.pieceSymbol : '' + move.pieceSymbol + '' 57 | notationString += String.fromCharCode(96 + move.startColumn) 58 | notationString += move.startRow 59 | notationString += ' ' 60 | 61 | if (move.capturedPieceSymbol) { 62 | notationString += (pieceSymbols[move.capturedPieceSymbol].color === 'white') ? move.capturedPieceSymbol : '' + move.capturedPieceSymbol + '' 63 | } 64 | 65 | notationString += String.fromCharCode(96 + move.endColumn) 66 | notationString += move.endRow 67 | 68 | // Add suffix for promotion or en passant capturing 69 | if (move.promotionType) { 70 | notationString += '=' 71 | notationString += (pieceSymbols[move.pieceSymbol].color === 'white') ? move.promotionType : '' + move.promotionType + '' 72 | } else if (move.enPassant) { 73 | notationString += ' e.p.' 74 | } 75 | 76 | // Add suffix for check or mate 77 | if (move.check && !move.mate) { 78 | notationString += '+' 79 | } 80 | if (move.mate || move.stalemate) { 81 | notationString += '#' 82 | } 83 | 84 | return notationString 85 | } 86 | 87 | function updateInfoDrawer () { 88 | var lastMove = moves[moves.length - 1]; var currentTurnString = ''; var lastMoveString 89 | 90 | // Current Turn 91 | if (lastMove && lastMove.stalemate) { 92 | currentTurnString = 'Stalemate!' 93 | } else { 94 | if (lastMove && lastMove.mate) { 95 | currentTurnString = 'Mate! ' 96 | if (sync) { 97 | currentTurnString += (whitesTurn === sync.playerIsWhite) ? 'Opponent wins.' : 'You win.' 98 | } else { 99 | currentTurnString += (whitesTurn) ? 'Black wins.' : 'White wins.' 100 | } 101 | } else { 102 | if (lastMove && lastMove.check) { 103 | currentTurnString = 'Check! ' 104 | } 105 | if (sync) { 106 | currentTurnString += (whitesTurn === sync.playerIsWhite) ? 'Your turn.' : "Opponent's turn." 107 | } else { 108 | currentTurnString += (whitesTurn) ? "White's turn." : "Black's turn." 109 | } 110 | } 111 | } 112 | $('#currentTurn > span:first-child').html(currentTurnString) 113 | 114 | // Last Move 115 | if (moves.length) { 116 | lastMoveString = 'Last move: ' + generateNotationString(lastMove) 117 | } else { 118 | lastMoveString = 'No move yet.' 119 | } 120 | $('#lastMove').html(lastMoveString) 121 | } 122 | 123 | function updateGameTime () { 124 | var min; var sec; var string = '' 125 | 126 | gameTime++ 127 | min = Math.floor(gameTime / 60) 128 | sec = gameTime % 60 129 | string += (min < 10) ? '0' + min : min 130 | string += ':' 131 | string += (sec < 10) ? '0' + sec : sec 132 | 133 | $('#gameTime').html(string) 134 | } 135 | 136 | function hidePromotionMenu () { 137 | // Fade promotion menu out and reset after animation 138 | $('.promotion').fadeOut(300, function () { 139 | $('.promotion > ul > li').off().remove() 140 | $('.promotion')[0].id = '' 141 | $('.promotion').css('left', '') 142 | }) 143 | } 144 | 145 | function hideInfoDrawer () { 146 | if ($('#info').height() === 570) { 147 | $('#info').clearQueue().animate({ height: '540px' }, 100, 'easeOutQuad') 148 | } 149 | } 150 | 151 | function showInfoDrawer () { 152 | if ($('#info').height() === 540) { 153 | $('#info').clearQueue().animate({ height: '570px' }, 100, 'easeInQuad') 154 | } 155 | } 156 | 157 | function pieceObject (element, object) { 158 | if (!object) return $(element).data('pieceObject') 159 | else return $(element).data('pieceObject', object) 160 | } 161 | 162 | function fieldObject (element, object) { 163 | if (!object) return $(element).data('fieldObject') 164 | else return $(element).data('fieldObject', object) 165 | } 166 | 167 | function finishMove () { 168 | var possibleTurn 169 | 170 | // Update turns 171 | whitesTurn = (whitesTurn) ? 0 : 1 172 | 173 | // Check for check, mate and stalemate 174 | if (pieceObject($('td > .piece.king.' + ((whitesTurn) ? 'white' : 'black'))).field.reachableBy[((whitesTurn) ? 'black' : 'white')].length) { 175 | moves[moves.length - 1].check = true 176 | } 177 | $((whitesTurn) ? 'td > .white' : 'td> .black').each(function (index, piece) { 178 | if (pieceObject(piece).accessibleFields().length) { 179 | possibleTurn = true 180 | 181 | // This is for performance reasons and makes sure, that the .each loop ends after the first possible turn found 182 | return false 183 | } 184 | }) 185 | if (!possibleTurn) { 186 | if (moves[moves.length - 1].check) { 187 | // Mate 188 | moves[moves.length - 1].mate = true 189 | 190 | // Update end menu 191 | $('#end > .tone100 > h2 > span:first-child').css('background-position', (whitesTurn) ? '-180px 100%' : '0 100%') 192 | $('#end > .tone100 > h2 > span:last-child').html((whitesTurn) ? 'Black wins' : 'White wins') 193 | } else { 194 | // Stalemate 195 | moves[moves.length - 1].stalemate = true 196 | 197 | // Update end menu 198 | $('#end > .tone100 > h2 > span:first-child').css('background-position', '-360px 100%') 199 | $('#end > .tone100 > h2 > span:last-child').html('Stalemate') 200 | } 201 | game.gameOver = true 202 | clearInterval(timerInterval) 203 | } 204 | 205 | // Make king(s) blink if checked or the game ended 206 | if (moves[moves.length - 1].check) { 207 | if (moves[moves.length - 1].mate) { 208 | controller.blink($('td > .piece.king.' + ((whitesTurn) ? 'white' : 'black')), 3, 1000, function () { 209 | if (!menu) { 210 | menu = new Menu('#end') 211 | menu.appear(true) 212 | } 213 | }) 214 | } else { 215 | controller.blink($('td > .piece.king.' + ((whitesTurn) ? 'white' : 'black')), 2, 1000) 216 | } 217 | } else if (moves[moves.length - 1].stalemate) { 218 | controller.blink($('td > .piece.king'), 3, 1000, function () { 219 | if (!menu) { 220 | menu = new Menu('#end') 221 | menu.appear(true) 222 | } 223 | }) 224 | } 225 | 226 | // Update info drawer 227 | updateInfoDrawer() 228 | 229 | // Update local storage if autosave option is turned on 230 | if (controller.autoSave) { 231 | game.updateLocalStorage() 232 | } 233 | 234 | // Only send move to server if it's an online game and this turn wasn't received itself 235 | if (sync && sync.playerIsWhite !== whitesTurn) { 236 | sync.makeMove(moves[moves.length - 1]) 237 | } 238 | } 239 | 240 | function Piece (pieceElement) { 241 | // that has to be used instead of this in private functions, in timeout/interval functions and in for/each functions 242 | var that = this 243 | 244 | pieceObject(pieceElement, this) 245 | 246 | this.element = pieceElement 247 | 248 | this.symbol = pieceElement.innerHTML 249 | 250 | this.kind = pieceSymbols[this.symbol].kind 251 | 252 | this.color = pieceSymbols[this.symbol].color 253 | 254 | this.isWhite = (this.color === 'white') ? 1 : 0 255 | 256 | this.field = fieldObject(pieceElement.parentNode) 257 | 258 | this.reachableFields = [] 259 | 260 | function removeCastlingRights () { 261 | if (that.kind === 'king' || (that.kind === 'rook' && that.field.column === 1)) { 262 | castlingAllowed[that.color].queenSide = false 263 | } 264 | if (that.kind === 'king' || (that.kind === 'rook' && that.field.column === 8)) { 265 | castlingAllowed[that.color].kingSide = false 266 | } 267 | } 268 | 269 | // TODO Maybe getReachableFields and updateReachables should be combined for reasons of clarity & structure 270 | this.getReachableFields = function () { 271 | // Datatype for field collections with the Array functionality as prototype 272 | function Fields (column, row) { 273 | this.add = function (columnDiff, rowDiff) { 274 | if (field[column + columnDiff] && field[column + columnDiff][row + rowDiff]) { 275 | return this.push(field[column + columnDiff][row + rowDiff]) 276 | } 277 | return false 278 | } 279 | } 280 | Fields.prototype = [] 281 | 282 | var fields = new Fields(this.field.column, this.field.row); var forward = (that.isWhite) ? +1 : -1; var i 283 | 284 | switch (this.kind) { 285 | case 'pawn': 286 | fields.add(-1, forward) 287 | fields.add(+1, forward) 288 | break 289 | case 'knight': 290 | fields.add(-1, +2) 291 | fields.add(+1, +2) 292 | fields.add(-1, -2) 293 | fields.add(+1, -2) 294 | fields.add(-2, +1) 295 | fields.add(-2, -1) 296 | fields.add(+2, +1) 297 | fields.add(+2, -1) 298 | break 299 | case 'king': 300 | fields.add(-1, +1) 301 | fields.add(+0, +1) 302 | fields.add(+1, +1) 303 | fields.add(-1, +0) 304 | fields.add(+1, +0) 305 | fields.add(-1, -1) 306 | fields.add(+0, -1) 307 | fields.add(+1, -1) 308 | break 309 | case 'bishop': case 'rook': case 'queen': 310 | // Rook and queen 311 | if (this.kind !== 'bishop') { 312 | $.each([[-1, 0], [+1, 0], [0, -1], [0, +1]], function (index, coords) { 313 | for (i = 1; fields.add(coords[0] * i, coords[1] * i); i++) { 314 | if (fields[fields.length - 1].piece) { 315 | break 316 | } 317 | } 318 | }) 319 | } 320 | // Bishop and queen 321 | if (this.kind !== 'rook') { 322 | $.each([[-1, +1], [-1, -1], [+1, +1], [+1, -1]], function (index, coords) { 323 | for (i = 1; fields.add(coords[0] * i, coords[1] * i); i++) { 324 | if (fields[fields.length - 1].piece) { 325 | break 326 | } 327 | } 328 | }) 329 | } 330 | break 331 | } 332 | 333 | return fields 334 | } 335 | this.captureableFields = function () { 336 | var otherFields = this.reachableFields; var fields = [] 337 | 338 | $.each(otherFields, function (index, otherField) { 339 | // If the target field is taken: only make it captureable when taken by the other color 340 | if (otherField.piece) { 341 | if (otherField.piece.isWhite !== that.isWhite) { 342 | fields.push(otherField) 343 | } 344 | // If it's not taken, always make it accessible, except for pawns 345 | } else if (that.kind !== 'pawn') { 346 | fields.push(otherField) 347 | } 348 | }) 349 | 350 | return fields 351 | } 352 | this.accessibleFields = function () { 353 | var fields = this.captureableFields(); var forward = (that.isWhite) ? 1 : -1; var homeRow = (that.isWhite) ? 1 : 8; var cachedFields; var king = pieceObject($('td > .piece.king.' + ((that.isWhite) ? 'white' : 'black'))); var opponentColor = (that.isWhite) ? 'black' : 'white'; var aggressors = king.field.reachableBy[opponentColor]; var i; var lineFld; var behindPiece 354 | 355 | switch (this.kind) { 356 | case 'pawn': 357 | // One forward 358 | if (field[this.field.column][this.field.row + forward] && !field[this.field.column][this.field.row + forward].piece) { 359 | fields.push(field[this.field.column][this.field.row + forward]) 360 | } 361 | 362 | // Two forward in home line 363 | if (this.field.row === homeRow + forward && !field[this.field.column][this.field.row + forward].piece && !field[this.field.column][this.field.row + forward * 2].piece) { 364 | fields.push(field[this.field.column][this.field.row + forward * 2]) 365 | } 366 | 367 | // One diagonally in case of en passant 368 | if (this.field.row === homeRow + forward * 4 && moves.length && pieceSymbols[moves[moves.length - 1].pieceSymbol].kind === 'pawn' && moves[moves.length - 1].endRow === this.field.row && Math.abs(moves[moves.length - 1].startRow - moves[moves.length - 1].endRow) === 2 && Math.abs(moves[moves.length - 1].startColumn - this.field.column) === 1) { 369 | fields.push(field[moves[moves.length - 1].startColumn][this.field.row + forward]) 370 | } 371 | break 372 | case 'king': 373 | // Check for castling 374 | if (castlingAllowed[this.color].queenSide && field[1][homeRow].piece && field[1][homeRow].piece.kind === 'rook' && !field[2][homeRow].piece && !field[3][homeRow].piece && !field[4][homeRow].piece && !field[3][homeRow].reachableBy[opponentColor].length && !field[4][homeRow].reachableBy[opponentColor].length && !field[5][homeRow].reachableBy[opponentColor].length) { 375 | fields.push(field[3][homeRow]) 376 | } 377 | if (castlingAllowed[this.color].kingSide && field[8][homeRow].piece && field[8][homeRow].piece.kind === 'rook' && !field[6][homeRow].piece && !field[7][homeRow].piece && !field[7][homeRow].reachableBy[opponentColor].length && !field[6][homeRow].reachableBy[opponentColor].length && !field[5][homeRow].reachableBy[opponentColor].length) { 378 | fields.push(field[7][homeRow]) 379 | } 380 | 381 | // Don't move on a dangerous field 382 | $.each(fields, function (index, fld) { 383 | // Fields that are directly reachable by opponent 384 | if (fld.reachableBy[opponentColor].length) { 385 | fields[index] = [] 386 | // You can't run away from bishops, rooks and queens in their direct lines 387 | } else { 388 | $.each(aggressors, function (aggressorIndex, aggressor) { 389 | if (['rook', 'queen'].includes(aggressor.kind) && that.field.inBetweenCross(aggressor.field, fld)) fields[index] = [] 390 | if (['bishop', 'queen'].includes(aggressor.kind) && that.field.inBetweenDiag(aggressor.field, fld)) fields[index] = [] 391 | }) 392 | } 393 | }) 394 | return fields.flat() 395 | } 396 | 397 | // If king is checked only certain moves are valid 398 | if (aggressors.length) { 399 | cachedFields = fields 400 | fields = [] 401 | 402 | // Other pieces can't assist if king is threatened by two aggressors 403 | if (aggressors.length > 1) { 404 | return [] 405 | // If it's only one aggressor, check whether this piece can capture it or slip in between 406 | } else { 407 | $.each(cachedFields, function (index, fld) { 408 | if (aggressors[0].kind === 'bishop' || aggressors[0].kind === 'rook' || aggressors[0].kind === 'queen') { 409 | if (fld.inBetween(king.field, aggressors[0].field)) { 410 | fields.push(fld) 411 | } 412 | } 413 | if (fld === aggressors[0].field) { 414 | fields.push(fld) 415 | } 416 | }) 417 | } 418 | } 419 | 420 | // Make sure king won't be checked after this move 421 | $.each([[-1, 0], [+1, 0], [0, -1], [0, +1], [-1, +1], [-1, -1], [+1, +1], [+1, -1]], function (index, coords) { 422 | // If piece is in one of the four outermost board fields, not all lines have to be checked 423 | if (!field[that.field.column + coords[0]] || !(lineFld = field[that.field.column + coords[0]][that.field.row + coords[1]])) { 424 | // return true; works in $.each as continue does in for 425 | return true 426 | } 427 | 428 | // Is piece in between the currently described field and the king? 429 | if (that.field.inBetween(lineFld, king.field)) { 430 | // Check the whole line from king on 431 | for (i = 1; field[king.field.column + coords[0] * i] && (lineFld = field[king.field.column + coords[0] * i][king.field.row + coords[1] * i]); i++) { 432 | if (lineFld.piece) { 433 | // First for this piece 434 | if (lineFld.piece === that) { 435 | behindPiece = true 436 | 437 | continue 438 | // Secondly for possible aggressors 439 | } else if (behindPiece && lineFld.piece.isWhite !== that.isWhite && (lineFld.piece.kind === 'queen' || (lineFld.piece.kind === 'bishop' && index > 3) || (lineFld.piece.kind === 'rook' && index < 4))) { 440 | // If this piece is protecting the king, make sure it stays in the line 441 | cachedFields = fields 442 | fields = [] 443 | $.each(cachedFields, function (index, cachedFld) { 444 | if (cachedFld.inBetween(king.field, lineFld) || cachedFld === lineFld) { 445 | fields.push(cachedFld) 446 | } 447 | }) 448 | } 449 | 450 | return false 451 | } 452 | } 453 | } 454 | }) 455 | 456 | return fields 457 | } 458 | 459 | this.updateReachables = function () { 460 | // Set field classes used for awareness mode 461 | function updatePropertyClass (fld) { 462 | if (fld.reachableBy.white.length !== fld.reachableBy.black.length) fld.element.className = 'property' + (fld.reachableBy.white.length - fld.reachableBy.black.length) 463 | else fld.element.className = 'neutral' + fld.reachableBy.white.length 464 | } 465 | 466 | // Let old reachableFields forget about this piece 467 | $.each(this.reachableFields, function (index, fld) { 468 | index = fld.reachableBy[that.color].indexOf(that) 469 | if (index !== -1) { 470 | fld.reachableBy[that.color].splice(index, 1) 471 | updatePropertyClass(fld) 472 | } 473 | }) 474 | 475 | // If already dead: stop here 476 | if (!this.field) { 477 | return false 478 | } 479 | 480 | // Calculate new reachableFields 481 | this.reachableFields = this.getReachableFields() 482 | 483 | // Make new reachableFields know about this piece 484 | $.each(this.reachableFields, function (index, fld) { 485 | fld.reachableBy[that.color].push(that) 486 | updatePropertyClass(fld) 487 | }) 488 | } 489 | 490 | this.moveToCemetery = function () { 491 | var target 492 | 493 | // Remove castling rights if a tower was captured that didn't move yet 494 | if (this.kind === 'rook') { 495 | removeCastlingRights() 496 | } 497 | 498 | // Move in DOM and animate 499 | target = $('
      • ').appendTo($('#' + this.color + 'Cemetery')) 500 | this.moveInDOM(target, true, true) 501 | 502 | // Remove draggability 503 | if ($(pieceElement).hasClass('ui-draggable')) { 504 | $(pieceElement).draggable('destroy') 505 | } 506 | } 507 | 508 | this.move = function (targetField, promotionType) { 509 | var capturedPiece, castling 510 | 511 | // Update moves array 512 | moves.push({ startColumn: that.field.column, startRow: that.field.row, endColumn: targetField.column, endRow: targetField.row, pieceSymbol: that.symbol }) 513 | 514 | // Check for captured piece on end field 515 | capturedPiece = field[targetField.column][targetField.row].piece 516 | 517 | // Check for captured piece en passant 518 | if (that.kind === 'pawn' && that.field.column !== targetField.column && !capturedPiece) { 519 | capturedPiece = field[targetField.column][targetField.row + ((that.isWhite) ? -1 : 1)].piece 520 | moves[moves.length - 1].enPassant = true 521 | } 522 | 523 | // If there's a captured piece: move it to cemetery 524 | if (capturedPiece) { 525 | moves[moves.length - 1].capturedPieceSymbol = capturedPiece.symbol 526 | capturedPiece.moveToCemetery() 527 | } 528 | 529 | // Check for castling 530 | // Don't check whether king's start position is correct, that is being taken care of by castlingAllowed 531 | // Make sure it's a king that was moved in its home row and that it's a castling move that's allowed 532 | if (((that.symbol === '♔' && targetField.row === 1) || (that.symbol === '♚' && targetField.row === 8)) && ((targetField.column === 3 && castlingAllowed[that.color].queenSide) || (targetField.column === 7 && castlingAllowed[that.color].kingSide))) { 533 | castling = {} 534 | castling.row = (that.symbol === '♔') ? 1 : 8 535 | castling.startColumn = (targetField.column === 3) ? 1 : 8 536 | castling.endColumn = (targetField.column === 3) ? 4 : 6 537 | 538 | castling.tower = field[castling.startColumn][castling.row].piece 539 | 540 | // Move in DOM and animate 541 | castling.tower.moveInDOM(field[castling.endColumn][castling.row].element, true) 542 | } 543 | 544 | // Make sure to update castlingAllowed when towers or kings are moved 545 | if (that.kind === 'rook' || that.kind === 'king') { 546 | removeCastlingRights() 547 | } 548 | 549 | // Move in DOM 550 | that.moveInDOM(targetField.element) 551 | 552 | // Check for pawn promotion: if one was received in an online game, don't show the menu 553 | if ((that.symbol === '♙' && targetField.row === 8) || (that.symbol === '♟' && targetField.row === 1)) { 554 | return that.promote(promotionType) 555 | } 556 | 557 | // Update gameState and save it in localStorage 558 | finishMove() 559 | } 560 | 561 | this.animateMove = function (targetField, promotionType) { 562 | $(pieceElement).css('position', 'relative').animate({ 563 | left: $(targetField.element).offset().left - $(this.field.element).offset().left, 564 | top: $(targetField.element).offset().top - $(this.field.element).offset().top 565 | }, 1000, 'easeInOutQuad', function () { 566 | if (clickedPieceIsMoving) { 567 | clickedPieceIsMoving = false 568 | } 569 | that.move(targetField, promotionType) 570 | }) 571 | } 572 | 573 | this.startDragging = function () { 574 | var fields 575 | 576 | // Unselect piece if one was clicked on 577 | $('#board td').removeClass('acceptable').off('click') 578 | 579 | // If it's not the player's turn or the game is over or a promotion is happening, dragging is not allowed 580 | if (whitesTurn !== this.isWhite || clickedPieceIsMoving || (moves[moves.length - 1] && (moves[moves.length - 1].mate || moves[moves.length - 1].stalemate)) || $('.promotion').is(':visible')) { 581 | return false 582 | } 583 | 584 | // Reset droppable options to remove last turn's accessible flags 585 | $('#board td').droppable('option', 'accept', '') 586 | 587 | // Mark fields that are accessible 588 | fields = this.accessibleFields() 589 | $.each(fields, function (index, fld) { 590 | $(fld.element).droppable('option', 'accept', '.piece') 591 | }) 592 | 593 | return true 594 | } 595 | 596 | this.clickPiece = function () { 597 | // If it's not the player's turn or the game is over or a promotion is happening, clicking is not allowed 598 | if (whitesTurn !== this.isWhite || clickedPieceIsMoving || (moves[moves.length - 1] && (moves[moves.length - 1].mate || moves[moves.length - 1].stalemate)) || $('.promotion').is(':visible')) { 599 | return true 600 | } 601 | 602 | function unselect () { 603 | $('#board td').removeClass('acceptable').off('click') 604 | } 605 | 606 | // Reset 607 | unselect() 608 | 609 | $('#board td').on('click', function () { 610 | unselect() 611 | }) 612 | 613 | // Show fields that are accessible 614 | $.each(this.accessibleFields(), function (index, fld) { 615 | $(fld.element).addClass('acceptable') 616 | 617 | $(fld.element).on('click', function () { 618 | clickedPieceIsMoving = true 619 | unselect() 620 | that.animateMove(fld) 621 | }) 622 | }) 623 | 624 | // Makes sure only one click event is called, and not one for piece and one for field 625 | return false 626 | } 627 | 628 | this.promote = function (pieceSymbol) { 629 | // If a pieceSymbol is passed: promote & finish move! 630 | if (pieceSymbol) { 631 | // Promote pawn, update everything, finish move and hide menu 632 | that.symbol = pieceElement.innerHTML = pieceSymbol 633 | that.kind = pieceSymbols[pieceSymbol].kind 634 | moves[moves.length - 1].promotionType = pieceSymbol 635 | gameState[moves[moves.length - 1].endColumn][moves[moves.length - 1].endRow] = pieceSymbol 636 | that.updateReachables() 637 | finishMove() 638 | hidePromotionMenu() 639 | 640 | // Animate promotion 641 | controller.flip(pieceElement, 'horizontal', 1000, function () { 642 | $(pieceElement).removeClass('pawn') 643 | $(pieceElement).addClass(that.kind) 644 | }) 645 | // Otherwise: show promotion menu 646 | } else { 647 | var mirroredBoardOrientation 648 | 649 | // Add menu items for possible pieces 650 | $.each(this.isWhite ? ['♘', '♗', '♖', '♕'] : ['♞', '♝', '♜', '♛'], function (index, pieceSymbol) { 651 | // Convert piece when menu item is clicked 652 | $('
      • ' + pieceSymbol + '
      • ').appendTo($('.promotion > ul')).on('click', function () { 653 | that.promote(pieceSymbol) 654 | }) 655 | }) 656 | 657 | // Position and show menu 658 | mirroredBoardOrientation = (sync) ? !sync.playerIsWhite : 0 659 | $('.promotion')[0].id = (this.isWhite || mirroredBoardOrientation) ? 'top' : 'bottom' 660 | $('.promotion').css('left', -130 + 60 * Math.abs(this.field.column - 9 * mirroredBoardOrientation) + 'px') 661 | $('.promotion').fadeIn(300) 662 | } 663 | } 664 | 665 | this.moveInDOM = function (target, animated, spin) { 666 | var oldFieldsReachables, oldPosLeft, oldPosTop 667 | 668 | // Cache old field's reachables 669 | oldFieldsReachables = this.field.reachableBy.white.concat(this.field.reachableBy.black) 670 | 671 | // Update start field 672 | gameState[this.field.column][this.field.row] = '' 673 | this.field.piece = undefined 674 | this.field = undefined 675 | 676 | // Update reachables for old field's neighbours 677 | // This not only happens for moved pieces but also for dead ones, which might seem unnecessary: they are already updated via newField.reachableBy, aren't they? In most cases yes, but not in en passant capturing 678 | $.each(oldFieldsReachables, function (index, piece) { 679 | if (piece.kind === 'bishop' || piece.kind === 'rook' || piece.kind === 'queen') { 680 | piece.updateReachables() 681 | } 682 | }) 683 | 684 | // Save old position for animation 685 | if (animated) { 686 | oldPosLeft = $(pieceElement).offset().left 687 | oldPosTop = $(pieceElement).offset().top 688 | } 689 | 690 | // Move in DOM tree 691 | $(target).append(pieceElement) 692 | 693 | // Animate move 694 | if (animated) { 695 | if (spin) { 696 | controller.spin(pieceElement, 1000) 697 | } 698 | 699 | $(pieceElement).css({ 700 | position: 'relative', 701 | left: oldPosLeft - $(pieceElement).offset().left + 'px', 702 | top: oldPosTop - $(pieceElement).offset().top + 'px' 703 | }).animate({ left: '0', top: '0' }, 1000, 'easeInOutQuad') 704 | } else { 705 | $(pieceElement).css({ left: '0', top: '0' }) 706 | } 707 | 708 | // Update target field if not moved to cemetery 709 | if (fieldObject(target)) { 710 | gameState[fieldObject(target).column][fieldObject(target).row] = this.symbol 711 | this.field = fieldObject(target) 712 | this.field.piece = this 713 | 714 | // TODO PERFORMANCE Investigate whether there is a simple method to not update several pieces twice 715 | // Update reachables 716 | $.each(this.field.reachableBy.white.concat(this.field.reachableBy.black), function (index, piece) { 717 | if (piece.kind === 'bishop' || piece.kind === 'rook' || piece.kind === 'queen') { 718 | piece.updateReachables() 719 | } 720 | }) 721 | } 722 | this.updateReachables() 723 | } 724 | } 725 | 726 | function Field (fieldElement) { 727 | fieldObject(fieldElement, this) 728 | 729 | this.element = fieldElement 730 | 731 | this.column = parseInt(fieldElement.id.substr(0, 1), 10) 732 | this.row = parseInt(fieldElement.id.substr(1, 1), 10) 733 | 734 | this.piece = (fieldElement.firstChild) ? pieceObject(fieldElement.firstChild) : undefined 735 | 736 | this.reachableBy = { white: [], black: [] } 737 | 738 | this.createPiece = function (pieceSymbol) { 739 | this.piece = new Piece($('
        ' + pieceSymbol + '
        ').appendTo(fieldElement)[0]) 740 | } 741 | 742 | this.inBetweenCross = function (startField, endField) { 743 | // Vertically 744 | if (startField.column === endField.column && this.column === startField.column) { 745 | return (this.row < startField.row && this.row > endField.row) || (this.row > startField.row && this.row < endField.row) 746 | // Horizontally 747 | } else if (startField.row === endField.row && this.row === startField.row) { 748 | return (this.column < startField.column && this.column > endField.column) || (this.column > startField.column && this.column < endField.column) 749 | } 750 | return false 751 | } 752 | 753 | this.inBetweenDiag = function (startField, endField) { 754 | // Diagonally 755 | if (Math.abs(startField.column - endField.column) === Math.abs(startField.row - endField.row)) { 756 | return Math.abs(startField.column - this.column) === Math.abs(startField.row - this.row) && Math.abs(startField.column - this.column) < Math.abs(startField.column - endField.column) && Math.abs(endField.column - this.column) < Math.abs(startField.column - endField.column) && Math.abs(startField.row - this.row) < Math.abs(startField.row - endField.row) && Math.abs(endField.row - this.row) < Math.abs(startField.row - endField.row) 757 | } 758 | return false 759 | } 760 | 761 | this.inBetween = function (startField, endField) { 762 | return this.inBetweenCross(startField, endField) || this.inBetweenDiag(startField, endField) 763 | } 764 | } 765 | 766 | (function init () { 767 | var boardOrientation, row, column 768 | 769 | /* Introduce field object and create caption */ 770 | boardOrientation = (sync) ? sync.playerIsWhite : 1 771 | $('#board td').each(function (index, element) { 772 | row = Math.abs(Math.floor(index / 8) - 7 * boardOrientation) + 1 773 | column = Math.abs(index % 8 - 7 * Math.abs(boardOrientation - 1)) + 1 774 | 775 | element.setAttribute('id', column + '' + row) 776 | field[column] = field[column] || {} 777 | field[column][row] = new Field(element) 778 | }) 779 | $('th').each(function (index, element) { 780 | // The first 8 th tags get the vertical captions and the last 8 the horizontal ones 781 | element.innerHTML = (index < 8) ? Math.abs(index - 7 * boardOrientation) + 1 : String.fromCharCode(96 + Math.abs(index - 8 - 7 * Math.abs(boardOrientation - 1)) + 1) 782 | }) 783 | 784 | // If saved game found, load that! 785 | if (savedGame) { 786 | whitesTurn = savedGame.whitesTurn 787 | gameState = savedGame.gameState 788 | castlingAllowed = savedGame.castlingAllowed 789 | gameTime = savedGame.gameTime 790 | moves = savedGame.moves 791 | 792 | // Find capturedPieceSymbols in moves 793 | $.each(moves, function (index, move) { 794 | if (move.capturedPieceSymbol) { 795 | $('
      • ' + move.capturedPieceSymbol + '
      • ').appendTo($('#' + pieceSymbols[move.capturedPieceSymbol].color + 'Cemetery')) 796 | } 797 | }) 798 | 799 | // TODO REDUNDANCY Update end menu code is used twice (see game.finishMove) 800 | // If a finished game is loaded, notice that and update end menu 801 | if (moves.length && (moves[moves.length - 1].mate || moves[moves.length - 1].stalemate)) { 802 | gameOver = true 803 | if (moves[moves.length - 1].mate) { 804 | $('#end > .tone100 > h2 > span:first-child').css('background-position', (whitesTurn) ? '30% 100%' : '0 100%') 805 | $('#end > .tone100 > h2 > span:last-child').html((whitesTurn) ? 'Black wins' : 'White wins') 806 | } else { 807 | $('#end > .tone100 > h2 > span:first-child').css('background-position', '60% 100%') 808 | $('#end > .tone100 > h2 > span:last-child').html('Stalemate') 809 | } 810 | } 811 | } 812 | 813 | // Place pieces 814 | gameState = gameState || { 1: { 1: '♖', 2: '♙', 7: '♟', 8: '♜' }, 2: { 1: '♘', 2: '♙', 7: '♟', 8: '♞' }, 3: { 1: '♗', 2: '♙', 7: '♟', 8: '♝' }, 4: { 1: '♕', 2: '♙', 7: '♟', 8: '♛' }, 5: { 1: '♔', 2: '♙', 7: '♟', 8: '♚' }, 6: { 1: '♗', 2: '♙', 7: '♟', 8: '♝' }, 7: { 1: '♘', 2: '♙', 7: '♟', 8: '♞' }, 8: { 1: '♖', 2: '♙', 7: '♟', 8: '♜' } } 815 | $.each(field, function (columnIndex, column) { 816 | $.each(column, function (rowIndex, fld) { 817 | if (gameState[columnIndex] && gameState[columnIndex][rowIndex]) { 818 | field[columnIndex][rowIndex].createPiece(gameState[columnIndex][rowIndex]) 819 | } 820 | }) 821 | }) 822 | 823 | // Calculate first set of reachableFields 824 | $('td > .piece').each(function (index, piece) { 825 | pieceObject(piece).updateReachables() 826 | }) 827 | 828 | // Mirror the first knight of each color 829 | $('td > .white.knight:first, td > .black.knight:first').css('transform', 'scaleX(-1)') 830 | 831 | /* Piece draggability */ 832 | $('td > .piece').each(function (index, element) { 833 | // Only make piece draggable if it's an offline game or the piece color matches the online player's color 834 | if (!sync || sync.playerIsWhite === pieceObject(element).isWhite) { 835 | // Pieces: stay in the table and go back to origin when not dropped on a valid field 836 | $(element).draggable({ 837 | containment: $('#board'), 838 | revert: 'invalid', 839 | // Call a function before actually dragged 840 | start: function (event, ui) { 841 | return pieceObject(ui.helper[0]).startDragging() 842 | } 843 | }) 844 | 845 | $(element).on('click', function () { 846 | return pieceObject(this).clickPiece() 847 | }) 848 | } 849 | }) 850 | 851 | /* Field droppability */ 852 | $('#board td').droppable({ 853 | addClasses: false, 854 | accept: '', 855 | activeClass: 'acceptable', 856 | // Fields: call a function when a piece is dropped on 857 | drop: function (event, ui) { 858 | return pieceObject(ui.draggable[0]).move(fieldObject(this)) 859 | } 860 | }) 861 | 862 | /* Info drawer & field captions */ 863 | $('#border').hover( 864 | function () { 865 | if (!menu) { 866 | showCaptionInterval = setTimeout(function () { $('#border table').fadeIn(300) }, 500) 867 | } 868 | }, 869 | function () { 870 | $('#border table').fadeOut(300) 871 | clearInterval(showCaptionInterval) 872 | } 873 | ) 874 | updateInfoDrawer() 875 | updateGameTime() 876 | showInfoDrawer() 877 | if (!gameOver) { 878 | timerInterval = setInterval(function () { updateGameTime() }, 1000) 879 | } 880 | }()) 881 | 882 | /* -- Public attributes & privileged methods -- */ 883 | 884 | return { 885 | gameOver: gameOver, 886 | 887 | deinit: function () { 888 | // Remove locally saved game (and sync information) 889 | localStorage.clear() 890 | 891 | // Resave autoSave option 892 | if (!controller.autoSave) { 893 | localStorage.noAutoSave = true 894 | } 895 | 896 | // Quit promotion if one is happening right now 897 | hidePromotionMenu() 898 | 899 | // Remove all pieces and draggability / droppability functionality 900 | $('.piece').fadeOut(300, function () { 901 | // In case of dead pieces: remove their parent containers too 902 | $(this).parent('li').remove() 903 | $(this).remove() 904 | }) 905 | $('.ui-draggable').draggable('destroy') 906 | $('#board td').droppable('destroy') 907 | 908 | // Remove classes indicating field "ownership" 909 | $('#board td').removeClass() 910 | 911 | // Remove game timer and hide info drawer 912 | clearInterval(timerInterval) 913 | hideInfoDrawer() 914 | $('#border').off() 915 | }, 916 | 917 | fieldIsTaken: function (column, row) { // TODO This function is only for sync.waitForMove() and it'll become obsolete with better server side turn recognition 918 | if (field[column] && field[column][row] && field[column][row].piece) { 919 | return true 920 | } 921 | return false 922 | }, 923 | 924 | receiveCoordinates: function (startColumn, startRow, endColumn, endRow, promotionType, preanimation) { 925 | var startField; var targetField; var piece; var validMove = false 926 | 927 | startField = document.getElementById(startColumn + '' + startRow) 928 | targetField = document.getElementById(endColumn + '' + endRow) 929 | piece = startField.firstChild 930 | 931 | /* Make sure the received move is valid because of possible desync (most likely due to cheating) */ 932 | 933 | if (!startField || !targetField || !piece) { 934 | return false 935 | } 936 | 937 | // Walk through all accessible coordinates for the moved piece 938 | $.each(pieceObject(piece).accessibleFields(), function (index, fld) { 939 | if (fieldObject(targetField) === fld) { 940 | validMove = true 941 | } 942 | }) 943 | 944 | /* Move piece and report success / deync */ 945 | 946 | // If window was inactive since last move, make piece blink twice for the player to gain orientation again 947 | if (preanimation) { 948 | controller.blink(piece, 2, 1000, function () { 949 | pieceObject(piece).animateMove(fieldObject(targetField), promotionType) 950 | }) 951 | } else { 952 | pieceObject(piece).animateMove(fieldObject(targetField), promotionType) 953 | } 954 | 955 | return validMove 956 | }, 957 | 958 | updateLocalStorage: function () { 959 | localStorage.whitesTurn = whitesTurn 960 | localStorage.gameState = JSON.stringify(gameState) 961 | localStorage.castlingAllowed = JSON.stringify(castlingAllowed) 962 | localStorage.gameTime = gameTime 963 | localStorage.moves = JSON.stringify(moves) 964 | } 965 | } 966 | } 967 | 968 | // ======== 969 | // = Sync = 970 | // ======== 971 | 972 | function Sync () { 973 | /* -- Private attributes & methods -- */ 974 | 975 | var gameName; var syncInterval; var windowHasFocus = 1 976 | 977 | function toggleTitleNotification () { 978 | document.title = (document.title === 'PlainChess' && !windowHasFocus) ? 'Your turn!' : 'PlainChess' 979 | if (!windowHasFocus) { 980 | setTimeout(function () { toggleTitleNotification() }, 1000) 981 | } 982 | } 983 | 984 | (function init () { 985 | // Notice when window is focused or blurred 986 | $(window).on('focus', function () { 987 | windowHasFocus = 1 988 | }) 989 | $(window).on('blur', function () { 990 | windowHasFocus = 0 991 | }) 992 | }()) 993 | 994 | /* -- Public attributes & privileged methods -- */ 995 | 996 | return { 997 | playerIsWhite: 1, 998 | 999 | deinit: function () { 1000 | clearInterval(syncInterval) 1001 | $(window).off() 1002 | }, 1003 | 1004 | hostGame: function (name) { 1005 | $.post('php/hostGame.php', { id: name }, function (data) { 1006 | if (!data) { 1007 | menu.error(document.getElementById('hostGameName'), 'Name already taken…') 1008 | } else { 1009 | gameName = data 1010 | $("#hostGame > input[type='button']")[0].value = '' 1011 | $("#hostGame > input[type='button']").css('background', '#5a4232 url(img/ajax-loader.gif) center no-repeat') 1012 | $("input[type='text']").attr('readonly', true) 1013 | $("input[type='button']").attr('disabled', true) 1014 | menu.deinit() 1015 | syncInterval = setInterval(function () { sync.waitForStart() }, 5000) 1016 | 1017 | localStorage.gameName = gameName 1018 | localStorage.playerIsWhite = sync.playerIsWhite 1019 | } 1020 | }) 1021 | }, 1022 | 1023 | joinGame: function (name) { 1024 | $.post('php/joinGame.php', { id: name }, function (data) { 1025 | if (!data) { 1026 | menu.error(document.getElementById('joinGameName'), 'Game not hosted…') 1027 | } else { 1028 | sync.playerIsWhite = 0 1029 | gameName = data 1030 | game = new Game() 1031 | menu.disappear(true) 1032 | syncInterval = setInterval(function () { sync.waitForMove() }, 5000) 1033 | 1034 | localStorage.gameName = gameName 1035 | localStorage.playerIsWhite = sync.playerIsWhite 1036 | } 1037 | }) 1038 | }, 1039 | 1040 | resumeGame: function () { 1041 | if (!localStorage.gameName || !localStorage.playerIsWhite) { 1042 | return false 1043 | } 1044 | gameName = localStorage.gameName 1045 | sync.playerIsWhite = parseInt(localStorage.playerIsWhite, 10) 1046 | if (localStorage.whitesTurn != sync.playerIsWhite) { 1047 | syncInterval = setInterval(function () { sync.waitForMove() }, 5000) 1048 | } 1049 | }, 1050 | 1051 | waitForStart: function () { 1052 | $.post('php/waitForStart.php', { id: gameName }, function (data) { 1053 | if (data === 'joined') { 1054 | toggleTitleNotification() 1055 | menu.disappear(true) 1056 | game = new Game() 1057 | clearInterval(syncInterval) 1058 | } 1059 | }) 1060 | }, 1061 | 1062 | waitForMove: function () { 1063 | var startColumn, startRow, endColumn, endRow, promotionType 1064 | 1065 | function passMove (preanimation) { 1066 | if (!game.receiveCoordinates(startColumn, startRow, endColumn, endRow, promotionType, preanimation)) { 1067 | alert('Invalid move received, maybe due to cheating. Games might be out of sync, restart is recommended.') 1068 | } 1069 | } 1070 | 1071 | $.post('php/waitForMove.php', { id: gameName }, function (data) { 1072 | if (data !== 'joined') { 1073 | startColumn = parseInt(data.substr(0, 1), 10) 1074 | startRow = parseInt(data.substr(1, 1), 10) 1075 | endColumn = parseInt(data.substr(3, 1), 10) 1076 | endRow = parseInt(data.substr(4, 1), 10) 1077 | if (data.substr(6, 1)) { 1078 | promotionType = data.substr(6, 1) 1079 | } 1080 | 1081 | if (game.fieldIsTaken(startColumn, startRow)) { 1082 | clearInterval(syncInterval) 1083 | 1084 | // TODO Shown menus, esp. Resume menus after reload should count as inactive. Right now if you open the site/app and there is a new move it is done behind the menu and doesn't get noticed. 1085 | // Move piece right away if window is active 1086 | if (windowHasFocus) { 1087 | passMove(0) 1088 | } else { 1089 | // Otherwise use blinking title notification to make user aware of the move 1090 | toggleTitleNotification() 1091 | 1092 | // Do not animate the move until the window is active again 1093 | $(window).on('focus', function () { 1094 | windowHasFocus = 1 1095 | 1096 | passMove(1) 1097 | 1098 | // Make sure the move won't be repeated every time the window is focused, reset focus event 1099 | $(window).off('focus') 1100 | $(window).on('focus', function () { 1101 | windowHasFocus = 1 1102 | }) 1103 | }) 1104 | } 1105 | } 1106 | } 1107 | }) 1108 | }, 1109 | 1110 | makeMove: function (move) { 1111 | $.post('php/makeMove.php', { id: gameName, startColumn: move.startColumn, startRow: move.startRow, endColumn: move.endColumn, endRow: move.endRow, promotionType: move.promotionType, gameOver: game.gameOver }, function (data) { 1112 | if (!data) { 1113 | alert('Error occured during sync! Game might have ended!') 1114 | } else { 1115 | syncInterval = setInterval(function () { sync.waitForMove() }, 5000) 1116 | } 1117 | }) 1118 | } 1119 | } 1120 | } 1121 | 1122 | // ======== 1123 | // = Menu = 1124 | // ======== 1125 | 1126 | function Menu (name) { 1127 | /* -- Private attributes & methods -- */ 1128 | 1129 | var menuBox, stripes, textFields, buttons, quickOptions, locked 1130 | 1131 | menuBox = $(name) 1132 | stripes = menuBox.children() 1133 | textFields = stripes.children("input[type='text']") 1134 | buttons = stripes.children("input[type='button']") 1135 | quickOptions = stripes.children('h2').children('a') 1136 | locked = 0 1137 | 1138 | function highlightStripe (number) { 1139 | if (locked) { 1140 | return false 1141 | } 1142 | stripes.each(function (index, element) { 1143 | $(element).children().clearQueue() 1144 | if (number === index + 1 || !number) { 1145 | $(element).children().fadeTo(300, 1) 1146 | } else { 1147 | $(element).children().fadeTo(300, 0.3) 1148 | } 1149 | }) 1150 | } 1151 | 1152 | function init () { 1153 | var code 1154 | 1155 | // Behaviour for menu options 1156 | // Remove option highlight when cursor exits menu 1157 | menuBox.on('mouseleave', function (handler) { 1158 | highlightStripe(0) 1159 | }) 1160 | stripes.each(function (index, element) { 1161 | // Highlight options on mouseenter (jQuery alternative to mouseover that doesn't refire on entering child elements) and also focus input fields when clicked 1162 | if (element.id) { 1163 | $(element).on('mouseenter', function () { 1164 | highlightStripe(index + 1) 1165 | }) 1166 | $(element).on('click', function () { 1167 | $(element).children("input[type='text']").focus() 1168 | // Necessary when clicking on a quickLink stripe while an other's child is focused 1169 | highlightStripe(index + 1) 1170 | }) 1171 | // Remove option highlight when an empty stripe is hovered or clicked 1172 | } else { 1173 | $(element).on('mouseenter', function () { 1174 | highlightStripe(0) 1175 | }) 1176 | } 1177 | 1178 | // Higlight option when a child object is focused and remove highlight when focus blurs 1179 | $(element).children().each(function (childIndex, childElement) { 1180 | $(childElement).on('focus', function () { 1181 | highlightStripe(index + 1) 1182 | locked = 1 1183 | }) 1184 | 1185 | $(childElement).on('blur', function () { 1186 | locked = 0 1187 | highlightStripe(0) 1188 | }) 1189 | }) 1190 | }) 1191 | 1192 | // Behaviour for text fields 1193 | textFields.each(function (index, element) { 1194 | // Focus 1195 | $(element).on('focus', function () { 1196 | if (element.value === element.getAttribute('value')) { 1197 | element.value = '' 1198 | } 1199 | }) 1200 | // Blur 1201 | $(element).on('blur', function () { 1202 | if (element.value === '' || $(element).hasClass('error')) { 1203 | element.value = element.getAttribute('value') 1204 | $(element).removeClass('error') 1205 | } 1206 | }) 1207 | 1208 | // Keypress: when Enter is hit, call the option's function 1209 | $(element).on('keypress', function (key) { 1210 | code = (key.keyCode) ? key.keyCode : key.which 1211 | if (code !== 13) { 1212 | // When an error message is shown and another key than Enter is hit, remove error message 1213 | if ($(element).hasClass('error')) { 1214 | element.value = '' 1215 | $(element).removeClass('error') 1216 | return true 1217 | } 1218 | return true 1219 | } 1220 | menu.menuOption(element.parentNode.id) 1221 | }) 1222 | }) 1223 | 1224 | // Behaviour for buttons: when clicked, call the option's function 1225 | buttons.each(function (index, element) { 1226 | $(element).on('click', function () { menu.menuOption(element.parentNode.id) }) 1227 | }) 1228 | 1229 | // Behaviour for links: when clicked, call the option's function 1230 | quickOptions.each(function (index, element) { 1231 | $(element).on('click', function () { 1232 | menu.menuOption(element.parentNode.parentNode.id) 1233 | return false 1234 | }) 1235 | }) 1236 | 1237 | // Tag initialization 1238 | menu.initialized = true 1239 | } 1240 | 1241 | /* -- Public attributes & privileged methods -- */ 1242 | 1243 | return { 1244 | name: name, 1245 | 1246 | initialized: false, 1247 | 1248 | deinit: function () { 1249 | // Remove all mouse and key events set in init() 1250 | menuBox.off() 1251 | $(stripes).off() 1252 | $(stripes).children().off() 1253 | $(quickOptions).off() 1254 | }, 1255 | 1256 | appear: function (animated) { 1257 | menuBox.show() 1258 | if (animated) { 1259 | stripes.each(function (index, element) { 1260 | $(element).css('left', '-480px').animate({ left: '0' }, 500 + index * 100, 'easeOutQuad', function () { 1261 | // When last stripe stops moving (the last one takes the longest), init menu 1262 | if (index === stripes.length - 1) { 1263 | init() 1264 | } 1265 | }) 1266 | }) 1267 | } else { 1268 | init() 1269 | } 1270 | }, 1271 | 1272 | disappear: function (animated) { 1273 | menu.deinit() 1274 | 1275 | function deinitAfterAnimation () { 1276 | menuBox.hide() 1277 | 1278 | // Reset global variable 1279 | if (menu) { 1280 | menu = undefined 1281 | } 1282 | 1283 | // Reset DOM 1284 | $("input[type='text']")[0].value = $("input[type='text']")[0].getAttribute('value') 1285 | 1286 | // Reset host game option 1287 | $("#hostGame > input[type='button']")[0].value = 'Go' 1288 | $("#hostGame > input[type='button']").css('background', '') 1289 | $("input[type='text']").attr('readonly', false) 1290 | $("input[type='button']").attr('disabled', false) 1291 | } 1292 | 1293 | if (animated) { 1294 | stripes.each(function (index, element) { 1295 | $(element).animate({ left: '480px' }, 400 + 100 * (stripes.length - index), 'easeInQuad', function () { 1296 | // When last stripe (the first one takes the longest) is gone, hide menu 1297 | if (!index) { 1298 | deinitAfterAnimation() 1299 | } 1300 | }) 1301 | }) 1302 | } else { 1303 | deinitAfterAnimation() 1304 | } 1305 | 1306 | // Tag deinitialization 1307 | if (menu) { 1308 | menu.initialized = false 1309 | } 1310 | }, 1311 | 1312 | error: function (input, msg) { 1313 | input.value = '' 1314 | input.placeholder = msg 1315 | $(input).addClass('error').focus() 1316 | }, 1317 | 1318 | /* -- Menu options -- */ 1319 | 1320 | menuOption: function (optionId) { 1321 | var name 1322 | 1323 | switch (optionId) { 1324 | case 'hostGame': 1325 | name = document.getElementById('hostGameName').value.trim() 1326 | if (!name) { 1327 | return menu.error(document.getElementById('hostGameName'), 'Enter game name…') 1328 | } 1329 | sync = new Sync() 1330 | sync.hostGame(name) 1331 | break 1332 | 1333 | case 'joinGame': 1334 | name = document.getElementById('joinGameName').value.trim() 1335 | if (!name) { 1336 | return menu.error(document.getElementById('joinGameName'), 'Enter game name…') 1337 | } 1338 | sync = new Sync() 1339 | sync.joinGame(name) 1340 | break 1341 | 1342 | case 'playOffline': 1343 | game = new Game() 1344 | menu.disappear(true) 1345 | break 1346 | 1347 | case 'toggleAutoSave': 1348 | // Only in offline games 1349 | if (sync) { 1350 | break 1351 | } 1352 | 1353 | // Set option 1354 | controller.autoSave = !(controller.autoSave) 1355 | 1356 | // Save option 1357 | if (controller.autoSave) { 1358 | localStorage.noAutoSave = undefined 1359 | game.updateLocalStorage() 1360 | } else { 1361 | localStorage.noAutoSave = true 1362 | } 1363 | 1364 | // Adjust menu 1365 | $('#toggleAutoSave > h2 > a > span:last-child').html((controller.autoSave) ? 'on' : 'off') 1366 | controller.flip($('#pause > .tone55 > h2 span:first-child'), 'horizontal', 250, function () { 1367 | $('#pause > .tone55 > h2 span:first-child').css('background-position', (controller.autoSave) ? '60% 57.14%' : '100% 85.71%') 1368 | }) 1369 | break 1370 | 1371 | case 'playOn': 1372 | menu.disappear(true) 1373 | break 1374 | 1375 | case 'quitGame': 1376 | game = game.deinit() 1377 | if (sync) { 1378 | sync = sync.deinit() 1379 | } 1380 | menu = menu.disappear() 1381 | menu = new Menu('#start') 1382 | menu.appear(true) 1383 | break 1384 | } 1385 | } 1386 | } 1387 | } 1388 | 1389 | // ============== 1390 | // = Controller = 1391 | // ============== 1392 | 1393 | controller = (function () { 1394 | /* -- Private attributes & methods -- */ 1395 | 1396 | function toggleMenu (animated) { 1397 | if ($('#toggleFaq').hasClass('active')) { 1398 | $('#toggleFaq').click() 1399 | return false 1400 | } 1401 | 1402 | if (menu) { 1403 | if (menu.name !== '#start' && menu.initialized) { 1404 | menu.disappear(animated) 1405 | } 1406 | } else { 1407 | menu = new Menu((game.gameOver) ? '#end' : '#pause') 1408 | menu.appear(animated) 1409 | } 1410 | } 1411 | 1412 | (function init () { 1413 | var savedGame 1414 | 1415 | // If a saved gameState or gameName or both is found, resume 1416 | if (localStorage.gameState || localStorage.gameName) { 1417 | if (localStorage.gameState) { 1418 | savedGame = {} 1419 | savedGame.whitesTurn = parseInt(localStorage.whitesTurn, 10) 1420 | savedGame.gameTime = parseInt(localStorage.gameTime, 10) 1421 | 1422 | // In the case that localStorage contains old or modified data that can't be parsed simply clear localStorage 1423 | try { 1424 | savedGame.gameState = JSON.parse(localStorage.gameState) 1425 | savedGame.castlingAllowed = JSON.parse(localStorage.castlingAllowed) 1426 | savedGame.moves = JSON.parse(localStorage.moves) 1427 | } catch (error) { 1428 | localStorage.clear() 1429 | savedGame = undefined 1430 | } 1431 | } 1432 | 1433 | if (localStorage.gameName) { 1434 | sync = new Sync() 1435 | sync.resumeGame() 1436 | } 1437 | 1438 | game = new Game(savedGame) 1439 | 1440 | toggleMenu(false) 1441 | 1442 | // If nothing saved is found, show start menu 1443 | } else { 1444 | menu = new Menu('#start') 1445 | menu.appear() 1446 | } 1447 | 1448 | // Initialize showing/hiding of pause menu when clicking on the logo or pressing Esc 1449 | $('h1 a').on('click', function () { 1450 | toggleMenu(true) 1451 | return false 1452 | }) 1453 | $(document).on('keydown', function (key) { 1454 | if (key.keyCode === 27 || key.which === 27) { 1455 | toggleMenu(true) 1456 | return false 1457 | } 1458 | }) 1459 | 1460 | // Initialize "toggle awareness mode" button 1461 | $('#toggleAwareness').on('click', function () { 1462 | if ($('#chess').hasClass('awareness')) { 1463 | $('#chess').removeClass('awareness') 1464 | } else { 1465 | $('#chess').addClass('awareness') 1466 | } 1467 | }) 1468 | 1469 | // Initialize header menu 1470 | $('#toggleFaq').on('click', function () { 1471 | $('#toggleFaq').toggleClass('active') 1472 | $('#flip').toggleClass('flipped') 1473 | return false 1474 | }) 1475 | 1476 | $('#contact').on('click', function () { 1477 | $('#contact').off() 1478 | controller.flip($('#contact'), 'vertical', 250, function () { 1479 | $('#contact').html('plainchess@timwoelfle.de') 1480 | $('#contact').attr('href', 'mailto:plainchess@timwoelfle.de?subject=PlainChess') 1481 | }) 1482 | return false 1483 | }) 1484 | 1485 | // If autoSave option is turned off, adjust pause menu 1486 | if (localStorage.noAutoSave && !sync) { 1487 | // TODO REDUNDANCY Adjust menu code is used twice (see menu.menuOption.toggleAutoSave) 1488 | // Adjust menu 1489 | $('#toggleAutoSave > h2 > a > span:last-child').html('off') 1490 | $('#pause > .tone55 > h2 span:first-child').css('background-position', '100% 85.71%') 1491 | } 1492 | }()) 1493 | 1494 | /* -- Public attributes & privileged methods -- */ 1495 | 1496 | return { 1497 | autoSave: !((localStorage.noAutoSave && !sync)), 1498 | 1499 | blink: function (element, count, durationEach, callback) { 1500 | $(element).animate({ opacity: '0' }, durationEach / 2, 'easeOutQuad', function () { 1501 | $(element).animate({ opacity: '1' }, durationEach / 2, 'easeInQuad', function () { 1502 | if (count > 1) { 1503 | controller.blink(element, count - 1, durationEach, callback) 1504 | } else { 1505 | if (typeof callback === 'function') { 1506 | callback() 1507 | } 1508 | } 1509 | }) 1510 | }) 1511 | }, 1512 | 1513 | spin: function (element, duration) { 1514 | $(element).css('transition-property', 'transform').css('transition-duration', duration + 'ms').css('transition-timing-function', 'ease-out') 1515 | 1516 | setTimeout(function () { 1517 | $(element).css('transform', 'rotate(360deg)') 1518 | }) 1519 | }, 1520 | 1521 | flip: function (element, className, duration, callback) { 1522 | // Flip and call the callback in the middle of the animation 1523 | $(element).on('transitionend', function () { 1524 | $(element).off('transitionend') 1525 | 1526 | $(element).css('transition-timing-function', 'ease-out').removeClass(className) 1527 | 1528 | if (typeof callback === 'function') { 1529 | callback() 1530 | } 1531 | }).css('transition-property', 'transform').css('transition-duration', duration / 2 + 'ms').css('transition-timing-function', 'ease-in') 1532 | 1533 | setTimeout(function () { 1534 | $(element).addClass(className) 1535 | }) 1536 | } 1537 | } 1538 | }()) 1539 | --------------------------------------------------------------------------------