ChessWidget.cpp 25 KB

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