ChessWidget.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "ChessWidget.h"
  27. #include "PromotionDialog.h"
  28. #include <AK/String.h>
  29. #include <LibCore/DateTime.h>
  30. #include <LibCore/File.h>
  31. #include <LibGUI/MessageBox.h>
  32. #include <LibGUI/Painter.h>
  33. #include <LibGfx/Font.h>
  34. #include <LibGfx/FontDatabase.h>
  35. #include <LibGfx/Path.h>
  36. #include <unistd.h>
  37. ChessWidget::ChessWidget(const StringView& set)
  38. {
  39. set_piece_set(set);
  40. }
  41. ChessWidget::ChessWidget()
  42. : ChessWidget("stelar7")
  43. {
  44. }
  45. ChessWidget::~ChessWidget()
  46. {
  47. }
  48. void ChessWidget::paint_event(GUI::PaintEvent& event)
  49. {
  50. GUI::Widget::paint_event(event);
  51. GUI::Painter painter(*this);
  52. painter.add_clip_rect(event.rect());
  53. size_t tile_width = width() / 8;
  54. size_t tile_height = height() / 8;
  55. unsigned coord_rank_file = (side() == Chess::Color::White) ? 0 : 7;
  56. Chess::Board& active_board = (m_playback ? board_playback() : board());
  57. Chess::Square::for_each([&](Chess::Square sq) {
  58. Gfx::IntRect tile_rect;
  59. if (side() == Chess::Color::White) {
  60. tile_rect = { sq.file * tile_width, (7 - sq.rank) * tile_height, tile_width, tile_height };
  61. } else {
  62. tile_rect = { (7 - sq.file) * tile_width, sq.rank * tile_height, tile_width, tile_height };
  63. }
  64. painter.fill_rect(tile_rect, (sq.is_light()) ? board_theme().light_square_color : board_theme().dark_square_color);
  65. if (active_board.last_move().has_value() && (active_board.last_move().value().to == sq || active_board.last_move().value().from == sq)) {
  66. painter.fill_rect(tile_rect, m_move_highlight_color);
  67. }
  68. if (m_coordinates) {
  69. auto coord = sq.to_algebraic();
  70. auto text_color = (sq.is_light()) ? board_theme().dark_square_color : board_theme().light_square_color;
  71. auto shrunken_rect = tile_rect;
  72. shrunken_rect.shrink(4, 4);
  73. if (sq.rank == coord_rank_file)
  74. painter.draw_text(shrunken_rect, coord.substring_view(0, 1), Gfx::FontDatabase::default_bold_font(), Gfx::TextAlignment::BottomRight, text_color);
  75. if (sq.file == coord_rank_file)
  76. painter.draw_text(shrunken_rect, coord.substring_view(1, 1), Gfx::FontDatabase::default_bold_font(), Gfx::TextAlignment::TopLeft, text_color);
  77. }
  78. for (auto& m : m_board_markings) {
  79. if (m.type() == BoardMarking::Type::Square && m.from == sq) {
  80. Gfx::Color color = m.secondary_color ? m_marking_secondary_color : (m.alternate_color ? m_marking_alternate_color : m_marking_primary_color);
  81. painter.fill_rect(tile_rect, color);
  82. }
  83. }
  84. if (!(m_dragging_piece && sq == m_moving_square)) {
  85. auto bmp = m_pieces.get(active_board.get_piece(sq));
  86. if (bmp.has_value()) {
  87. painter.draw_scaled_bitmap(tile_rect, *bmp.value(), bmp.value()->rect());
  88. }
  89. }
  90. return IterationDecision::Continue;
  91. });
  92. auto draw_arrow = [&painter](Gfx::FloatPoint A, Gfx::FloatPoint B, float w1, float w2, float h, Gfx::Color color) {
  93. float dx = B.x() - A.x();
  94. float dy = A.y() - B.y();
  95. float phi = atan2f(dy, dx);
  96. float hdx = h * cosf(phi);
  97. float hdy = h * sinf(phi);
  98. const auto cos_pi_2_phi = cosf(float { M_PI_2 } - phi);
  99. const auto sin_pi_2_phi = sinf(float { M_PI_2 } - phi);
  100. Gfx::FloatPoint A1(A.x() - (w1 / 2) * cos_pi_2_phi, A.y() - (w1 / 2) * sin_pi_2_phi);
  101. Gfx::FloatPoint B3(A.x() + (w1 / 2) * cos_pi_2_phi, A.y() + (w1 / 2) * sin_pi_2_phi);
  102. Gfx::FloatPoint A2(A1.x() + (dx - hdx), A1.y() - (dy - hdy));
  103. Gfx::FloatPoint B2(B3.x() + (dx - hdx), B3.y() - (dy - hdy));
  104. Gfx::FloatPoint A3(A2.x() - w2 * cos_pi_2_phi, A2.y() - w2 * sin_pi_2_phi);
  105. Gfx::FloatPoint B1(B2.x() + w2 * cos_pi_2_phi, B2.y() + w2 * sin_pi_2_phi);
  106. auto path = Gfx::Path();
  107. path.move_to(A);
  108. path.line_to(A1);
  109. path.line_to(A2);
  110. path.line_to(A3);
  111. path.line_to(B);
  112. path.line_to(B1);
  113. path.line_to(B2);
  114. path.line_to(B3);
  115. path.line_to(A);
  116. path.close();
  117. painter.fill_path(path, color, Gfx::Painter::WindingRule::EvenOdd);
  118. };
  119. for (auto& m : m_board_markings) {
  120. if (m.type() == BoardMarking::Type::Arrow) {
  121. Gfx::FloatPoint arrow_start;
  122. Gfx::FloatPoint arrow_end;
  123. if (side() == Chess::Color::White) {
  124. arrow_start = { m.from.file * tile_width + tile_width / 2.0f, (7 - m.from.rank) * tile_height + tile_height / 2.0f };
  125. arrow_end = { m.to.file * tile_width + tile_width / 2.0f, (7 - m.to.rank) * tile_height + tile_height / 2.0f };
  126. } else {
  127. arrow_start = { (7 - m.from.file) * tile_width + tile_width / 2.0f, m.from.rank * tile_height + tile_height / 2.0f };
  128. arrow_end = { (7 - m.to.file) * tile_width + tile_width / 2.0f, m.to.rank * tile_height + tile_height / 2.0f };
  129. }
  130. Gfx::Color color = m.secondary_color ? m_marking_secondary_color : (m.alternate_color ? m_marking_primary_color : m_marking_alternate_color);
  131. draw_arrow(arrow_start, arrow_end, tile_width / 8.0f, tile_width / 10.0f, tile_height / 2.5f, color);
  132. }
  133. }
  134. if (m_dragging_piece) {
  135. if (m_show_available_moves) {
  136. Gfx::IntPoint move_point;
  137. Gfx::IntPoint point_offset = { tile_width / 3, tile_height / 3 };
  138. Gfx::IntSize rect_size = { tile_width / 3, tile_height / 3 };
  139. for (const auto& square : m_available_moves) {
  140. if (side() == Chess::Color::White) {
  141. move_point = { square.file * tile_width, (7 - square.rank) * tile_height };
  142. } else {
  143. move_point = { (7 - square.file) * tile_width, square.rank * tile_height };
  144. }
  145. painter.fill_ellipse({ move_point + point_offset, rect_size }, Gfx::Color::LightGray);
  146. }
  147. }
  148. auto bmp = m_pieces.get(active_board.get_piece(m_moving_square));
  149. if (bmp.has_value()) {
  150. auto center = m_drag_point - Gfx::IntPoint(tile_width / 2, tile_height / 2);
  151. painter.draw_scaled_bitmap({ center, { tile_width, tile_height } }, *bmp.value(), bmp.value()->rect());
  152. }
  153. }
  154. }
  155. void ChessWidget::mousedown_event(GUI::MouseEvent& event)
  156. {
  157. GUI::Widget::mousedown_event(event);
  158. if (event.button() == GUI::MouseButton::Right) {
  159. if (m_dragging_piece) {
  160. m_dragging_piece = false;
  161. m_available_moves.clear();
  162. } else {
  163. m_current_marking.from = mouse_to_square(event);
  164. }
  165. return;
  166. }
  167. m_board_markings.clear();
  168. auto square = mouse_to_square(event);
  169. auto piece = board().get_piece(square);
  170. if (drag_enabled() && piece.color == board().turn() && !m_playback) {
  171. m_dragging_piece = true;
  172. m_drag_point = event.position();
  173. m_moving_square = square;
  174. m_board.generate_moves([&](Chess::Move move) {
  175. if (move.from == m_moving_square) {
  176. m_available_moves.append(move.to);
  177. }
  178. return IterationDecision::Continue;
  179. });
  180. }
  181. update();
  182. }
  183. void ChessWidget::mouseup_event(GUI::MouseEvent& event)
  184. {
  185. GUI::Widget::mouseup_event(event);
  186. if (event.button() == GUI::MouseButton::Right) {
  187. m_current_marking.secondary_color = event.shift();
  188. m_current_marking.alternate_color = event.ctrl();
  189. m_current_marking.to = mouse_to_square(event);
  190. auto match_index = m_board_markings.find_first_index(m_current_marking);
  191. if (match_index.has_value()) {
  192. m_board_markings.remove(match_index.value());
  193. update();
  194. return;
  195. }
  196. m_board_markings.append(m_current_marking);
  197. update();
  198. return;
  199. }
  200. if (!m_dragging_piece)
  201. return;
  202. m_dragging_piece = false;
  203. m_available_moves.clear();
  204. auto target_square = mouse_to_square(event);
  205. Chess::Move move = { m_moving_square, target_square };
  206. if (board().is_promotion_move(move)) {
  207. auto promotion_dialog = PromotionDialog::construct(*this);
  208. if (promotion_dialog->exec() == PromotionDialog::ExecOK)
  209. move.promote_to = promotion_dialog->selected_piece();
  210. }
  211. if (board().apply_move(move)) {
  212. m_playback_move_number = board().moves().size();
  213. m_playback = false;
  214. m_board_playback = m_board;
  215. if (board().game_result() != Chess::Board::Result::NotFinished) {
  216. bool over = true;
  217. String msg;
  218. switch (board().game_result()) {
  219. case Chess::Board::Result::CheckMate:
  220. if (board().turn() == Chess::Color::White) {
  221. msg = "Black wins by Checkmate.";
  222. } else {
  223. msg = "White wins by Checkmate.";
  224. }
  225. break;
  226. case Chess::Board::Result::StaleMate:
  227. msg = "Draw by Stalemate.";
  228. break;
  229. case Chess::Board::Result::FiftyMoveRule:
  230. update();
  231. if (GUI::MessageBox::show(window(), "50 moves have elapsed without a capture. Claim Draw?", "Claim Draw?",
  232. GUI::MessageBox::Type::Information, GUI::MessageBox::InputType::YesNo)
  233. == GUI::Dialog::ExecYes) {
  234. msg = "Draw by 50 move rule.";
  235. } else {
  236. over = false;
  237. }
  238. break;
  239. case Chess::Board::Result::SeventyFiveMoveRule:
  240. msg = "Draw by 75 move rule.";
  241. break;
  242. case Chess::Board::Result::ThreeFoldRepetition:
  243. update();
  244. if (GUI::MessageBox::show(window(), "The same board state has repeated three times. Claim Draw?", "Claim Draw?",
  245. GUI::MessageBox::Type::Information, GUI::MessageBox::InputType::YesNo)
  246. == GUI::Dialog::ExecYes) {
  247. msg = "Draw by threefold repetition.";
  248. } else {
  249. over = false;
  250. }
  251. break;
  252. case Chess::Board::Result::FiveFoldRepetition:
  253. msg = "Draw by fivefold repetition.";
  254. break;
  255. case Chess::Board::Result::InsufficientMaterial:
  256. msg = "Draw by insufficient material.";
  257. break;
  258. default:
  259. VERIFY_NOT_REACHED();
  260. }
  261. if (over) {
  262. set_drag_enabled(false);
  263. update();
  264. GUI::MessageBox::show(window(), msg, "Game Over", GUI::MessageBox::Type::Information);
  265. }
  266. } else {
  267. input_engine_move();
  268. }
  269. }
  270. update();
  271. }
  272. void ChessWidget::mousemove_event(GUI::MouseEvent& event)
  273. {
  274. GUI::Widget::mousemove_event(event);
  275. if (!m_dragging_piece)
  276. return;
  277. m_drag_point = event.position();
  278. update();
  279. }
  280. void ChessWidget::keydown_event(GUI::KeyEvent& event)
  281. {
  282. switch (event.key()) {
  283. case KeyCode::Key_Left:
  284. playback_move(PlaybackDirection::Backward);
  285. break;
  286. case KeyCode::Key_Right:
  287. playback_move(PlaybackDirection::Forward);
  288. break;
  289. case KeyCode::Key_Up:
  290. playback_move(PlaybackDirection::Last);
  291. break;
  292. case KeyCode::Key_Down:
  293. playback_move(PlaybackDirection::First);
  294. break;
  295. case KeyCode::Key_Home:
  296. playback_move(PlaybackDirection::First);
  297. break;
  298. case KeyCode::Key_End:
  299. playback_move(PlaybackDirection::Last);
  300. break;
  301. default:
  302. return;
  303. }
  304. update();
  305. }
  306. static String set_path = String("/res/icons/chess/sets/");
  307. static RefPtr<Gfx::Bitmap> get_piece(const StringView& set, const StringView& image)
  308. {
  309. StringBuilder builder;
  310. builder.append(set_path);
  311. builder.append(set);
  312. builder.append('/');
  313. builder.append(image);
  314. return Gfx::Bitmap::load_from_file(builder.build());
  315. }
  316. void ChessWidget::set_piece_set(const StringView& set)
  317. {
  318. m_piece_set = set;
  319. m_pieces.set({ Chess::Color::White, Chess::Type::Pawn }, get_piece(set, "white-pawn.png"));
  320. m_pieces.set({ Chess::Color::Black, Chess::Type::Pawn }, get_piece(set, "black-pawn.png"));
  321. m_pieces.set({ Chess::Color::White, Chess::Type::Knight }, get_piece(set, "white-knight.png"));
  322. m_pieces.set({ Chess::Color::Black, Chess::Type::Knight }, get_piece(set, "black-knight.png"));
  323. m_pieces.set({ Chess::Color::White, Chess::Type::Bishop }, get_piece(set, "white-bishop.png"));
  324. m_pieces.set({ Chess::Color::Black, Chess::Type::Bishop }, get_piece(set, "black-bishop.png"));
  325. m_pieces.set({ Chess::Color::White, Chess::Type::Rook }, get_piece(set, "white-rook.png"));
  326. m_pieces.set({ Chess::Color::Black, Chess::Type::Rook }, get_piece(set, "black-rook.png"));
  327. m_pieces.set({ Chess::Color::White, Chess::Type::Queen }, get_piece(set, "white-queen.png"));
  328. m_pieces.set({ Chess::Color::Black, Chess::Type::Queen }, get_piece(set, "black-queen.png"));
  329. m_pieces.set({ Chess::Color::White, Chess::Type::King }, get_piece(set, "white-king.png"));
  330. m_pieces.set({ Chess::Color::Black, Chess::Type::King }, get_piece(set, "black-king.png"));
  331. }
  332. Chess::Square ChessWidget::mouse_to_square(GUI::MouseEvent& event) const
  333. {
  334. size_t tile_width = width() / 8;
  335. size_t tile_height = height() / 8;
  336. if (side() == Chess::Color::White) {
  337. return { 7 - (event.y() / tile_height), event.x() / tile_width };
  338. } else {
  339. return { event.y() / tile_height, 7 - (event.x() / tile_width) };
  340. }
  341. }
  342. RefPtr<Gfx::Bitmap> ChessWidget::get_piece_graphic(const Chess::Piece& piece) const
  343. {
  344. return m_pieces.get(piece).value();
  345. }
  346. void ChessWidget::reset()
  347. {
  348. m_board_markings.clear();
  349. m_playback = false;
  350. m_playback_move_number = 0;
  351. m_board_playback = Chess::Board();
  352. m_board = Chess::Board();
  353. m_side = (arc4random() % 2) ? Chess::Color::White : Chess::Color::Black;
  354. m_drag_enabled = true;
  355. input_engine_move();
  356. update();
  357. }
  358. void ChessWidget::set_board_theme(const StringView& name)
  359. {
  360. // FIXME: Add some kind of themes.json
  361. // The following Colors have been taken from lichess.org, but i'm pretty sure they took them from chess.com.
  362. if (name == "Beige") {
  363. m_board_theme = { "Beige", Color::from_rgb(0xb58863), Color::from_rgb(0xf0d9b5) };
  364. } else if (name == "Green") {
  365. m_board_theme = { "Green", Color::from_rgb(0x86a666), Color::from_rgb(0xffffdd) };
  366. } else if (name == "Blue") {
  367. m_board_theme = { "Blue", Color::from_rgb(0x8ca2ad), Color::from_rgb(0xdee3e6) };
  368. } else {
  369. set_board_theme("Beige");
  370. }
  371. }
  372. bool ChessWidget::want_engine_move()
  373. {
  374. if (!m_engine)
  375. return false;
  376. if (board().turn() == side())
  377. return false;
  378. return true;
  379. }
  380. void ChessWidget::input_engine_move()
  381. {
  382. if (!want_engine_move())
  383. return;
  384. bool drag_was_enabled = drag_enabled();
  385. if (drag_was_enabled)
  386. set_drag_enabled(false);
  387. set_override_cursor(Gfx::StandardCursor::Wait);
  388. m_engine->get_best_move(board(), 4000, [this, drag_was_enabled](Chess::Move move) {
  389. set_override_cursor(Gfx::StandardCursor::None);
  390. if (!want_engine_move())
  391. return;
  392. set_drag_enabled(drag_was_enabled);
  393. VERIFY(board().apply_move(move));
  394. m_playback_move_number = m_board.moves().size();
  395. m_playback = false;
  396. m_board_markings.clear();
  397. update();
  398. });
  399. }
  400. void ChessWidget::playback_move(PlaybackDirection direction)
  401. {
  402. if (m_board.moves().is_empty())
  403. return;
  404. m_playback = true;
  405. m_board_markings.clear();
  406. switch (direction) {
  407. case PlaybackDirection::Backward:
  408. if (m_playback_move_number == 0)
  409. return;
  410. m_board_playback = Chess::Board();
  411. for (size_t i = 0; i < m_playback_move_number - 1; i++)
  412. m_board_playback.apply_move(m_board.moves().at(i));
  413. m_playback_move_number--;
  414. break;
  415. case PlaybackDirection::Forward:
  416. if (m_playback_move_number + 1 > m_board.moves().size()) {
  417. m_playback = false;
  418. return;
  419. }
  420. m_board_playback.apply_move(m_board.moves().at(m_playback_move_number++));
  421. if (m_playback_move_number == m_board.moves().size())
  422. m_playback = false;
  423. break;
  424. case PlaybackDirection::First:
  425. m_board_playback = Chess::Board();
  426. m_playback_move_number = 0;
  427. break;
  428. case PlaybackDirection::Last:
  429. while (m_playback) {
  430. playback_move(PlaybackDirection::Forward);
  431. }
  432. break;
  433. default:
  434. VERIFY_NOT_REACHED();
  435. }
  436. update();
  437. }
  438. String ChessWidget::get_fen() const
  439. {
  440. return m_playback ? m_board_playback.to_fen() : m_board.to_fen();
  441. }
  442. bool ChessWidget::import_pgn(const StringView& import_path)
  443. {
  444. auto file_or_error = Core::File::open(import_path, Core::File::OpenMode::ReadOnly);
  445. if (file_or_error.is_error()) {
  446. warnln("Couldn't open '{}': {}", import_path, file_or_error.error());
  447. return false;
  448. }
  449. auto& file = *file_or_error.value();
  450. m_board = Chess::Board();
  451. ByteBuffer bytes = file.read_all();
  452. StringView content = bytes;
  453. auto lines = content.lines();
  454. StringView line;
  455. size_t i = 0;
  456. // Tag Pair Section
  457. // FIXME: Parse these tags when they become relevant
  458. do {
  459. line = lines.at(i++);
  460. } while (!line.is_empty() || i >= lines.size());
  461. // Movetext Section
  462. bool skip = false;
  463. bool recursive_annotation = false;
  464. bool future_expansion = false;
  465. Chess::Color turn = Chess::Color::White;
  466. String movetext;
  467. for (size_t j = i; j < lines.size(); j++)
  468. movetext = String::formatted("{}{}", movetext, lines.at(i).to_string());
  469. for (auto token : movetext.split(' ')) {
  470. token = token.trim_whitespace();
  471. // FIXME: Parse all of these tokens when we start caring about them
  472. if (token.ends_with("}")) {
  473. skip = false;
  474. continue;
  475. }
  476. if (skip)
  477. continue;
  478. if (token.starts_with("{")) {
  479. if (token.ends_with("}"))
  480. continue;
  481. skip = true;
  482. continue;
  483. }
  484. if (token.ends_with(")")) {
  485. recursive_annotation = false;
  486. continue;
  487. }
  488. if (recursive_annotation)
  489. continue;
  490. if (token.starts_with("(")) {
  491. if (token.ends_with(")"))
  492. continue;
  493. recursive_annotation = true;
  494. continue;
  495. }
  496. if (token.ends_with(">")) {
  497. future_expansion = false;
  498. continue;
  499. }
  500. if (future_expansion)
  501. continue;
  502. if (token.starts_with("<")) {
  503. if (token.ends_with(">"))
  504. continue;
  505. future_expansion = true;
  506. continue;
  507. }
  508. if (token.starts_with("$"))
  509. continue;
  510. if (token.contains("*"))
  511. break;
  512. // FIXME: When we become able to set more of the game state, fix these end results
  513. if (token.contains("1-0")) {
  514. m_board.set_resigned(Chess::Color::Black);
  515. break;
  516. }
  517. if (token.contains("0-1")) {
  518. m_board.set_resigned(Chess::Color::White);
  519. break;
  520. }
  521. if (token.contains("1/2-1/2")) {
  522. break;
  523. }
  524. if (!token.ends_with(".")) {
  525. m_board.apply_move(Chess::Move::from_algebraic(token, turn, m_board));
  526. turn = Chess::opposing_color(turn);
  527. }
  528. }
  529. m_board_markings.clear();
  530. m_board_playback = m_board;
  531. m_playback_move_number = m_board_playback.moves().size();
  532. m_playback = true;
  533. update();
  534. file.close();
  535. return true;
  536. }
  537. bool ChessWidget::export_pgn(const StringView& export_path) const
  538. {
  539. auto file_or_error = Core::File::open(export_path, Core::File::WriteOnly);
  540. if (file_or_error.is_error()) {
  541. warnln("Couldn't open '{}': {}", export_path, file_or_error.error());
  542. return false;
  543. }
  544. auto& file = *file_or_error.value();
  545. // Tag Pair Section
  546. file.write("[Event \"Casual Game\"]\n");
  547. file.write("[Site \"SerenityOS Chess\"]\n");
  548. file.write(String::formatted("[Date \"{}\"]\n", Core::DateTime::now().to_string("%Y.%m.%d")));
  549. file.write("[Round \"1\"]\n");
  550. String username(getlogin());
  551. const String player1 = (!username.is_empty() ? username : "?");
  552. const String player2 = (!m_engine.is_null() ? "SerenityOS ChessEngine" : "?");
  553. file.write(String::formatted("[White \"{}\"]\n", m_side == Chess::Color::White ? player1 : player2));
  554. file.write(String::formatted("[Black \"{}\"]\n", m_side == Chess::Color::Black ? player1 : player2));
  555. file.write(String::formatted("[Result \"{}\"]\n", Chess::Board::result_to_points(m_board.game_result(), m_board.turn())));
  556. file.write("[WhiteElo \"?\"]\n");
  557. file.write("[BlackElo \"?\"]\n");
  558. file.write("[Variant \"Standard\"]\n");
  559. file.write("[TimeControl \"-\"]\n");
  560. file.write("[Annotator \"SerenityOS Chess\"]\n");
  561. file.write("\n");
  562. // Movetext Section
  563. for (size_t i = 0, move_no = 1; i < m_board.moves().size(); i += 2, move_no++) {
  564. const String white = m_board.moves().at(i).to_algebraic();
  565. if (i + 1 < m_board.moves().size()) {
  566. const String black = m_board.moves().at(i + 1).to_algebraic();
  567. file.write(String::formatted("{}. {} {} ", move_no, white, black));
  568. } else {
  569. file.write(String::formatted("{}. {} ", move_no, white));
  570. }
  571. }
  572. file.write("{ ");
  573. file.write(Chess::Board::result_to_string(m_board.game_result(), m_board.turn()));
  574. file.write(" } ");
  575. file.write(Chess::Board::result_to_points(m_board.game_result(), m_board.turn()));
  576. file.write("\n");
  577. file.close();
  578. return true;
  579. }
  580. void ChessWidget::flip_board()
  581. {
  582. if (want_engine_move()) {
  583. GUI::MessageBox::show(window(), "You can only flip the board on your turn.", "Flip Board", GUI::MessageBox::Type::Information);
  584. return;
  585. }
  586. m_side = Chess::opposing_color(m_side);
  587. input_engine_move();
  588. update();
  589. }
  590. int ChessWidget::resign()
  591. {
  592. if (want_engine_move()) {
  593. GUI::MessageBox::show(window(), "You can only resign on your turn.", "Resign", GUI::MessageBox::Type::Information);
  594. return -1;
  595. }
  596. auto result = GUI::MessageBox::show(window(), "Are you sure you wish to resign?", "Resign", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNo);
  597. if (result != GUI::MessageBox::ExecYes)
  598. return -1;
  599. board().set_resigned(m_board.turn());
  600. set_drag_enabled(false);
  601. update();
  602. const String msg = Chess::Board::result_to_string(m_board.game_result(), m_board.turn());
  603. GUI::MessageBox::show(window(), msg, "Game Over", GUI::MessageBox::Type::Information);
  604. return 0;
  605. }