ChessWidget.cpp 23 KB

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