Module: Chess::WinAndDraw
- Included in:
- Game
- Defined in:
- lib/chess/game/win_and_draw.rb
Overview
WinAndDraw
Instance Method Summary collapse
-
#any_legal_move?(board) ⇒ Boolean
check if any legal move available.
-
#checkmate?(board) ⇒ Boolean
check if player is in checkmate.
-
#detect_win_or_draws(board) ⇒ nil, Integer
detects wins or draws and exits the game.
-
#fifty_move_draw?(board) ⇒ Boolean
check if there’s a fifty_move draw (100 half moves).
-
#game_exit ⇒ Integer
exits the game.
-
#save_and_exit(board) ⇒ Integer
save and exit the game.
-
#save_game(board) ⇒ Object
save the game.
-
#stalemate?(board) ⇒ Boolean
check if player is in stalemate.
Instance Method Details
#any_legal_move?(board) ⇒ Boolean
check if any legal move available
63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/chess/game/win_and_draw.rb', line 63 def any_legal_move?(board) pieces = if board.current_player == 'w' board.white_pieces else board.black_pieces end total_moves = [] pieces.each do |piece| total_moves += valid_moves(piece, board) end total_moves != [] end |
#checkmate?(board) ⇒ Boolean
check if player is in checkmate
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/chess/game/win_and_draw.rb', line 31 def checkmate?(board) in_check = if board.current_player == 'w' board.white_king.in_check else board.black_king.in_check end return false unless in_check return false if any_legal_move?(board) true end |
#detect_win_or_draws(board) ⇒ nil, Integer
detects wins or draws and exits the game
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/chess/game/win_and_draw.rb', line 11 def detect_win_or_draws(board) # rubocop:disable Metrics/MethodLength if checkmate?(board) puts 'Checkmate!' return game_exit end if stalemate?(board) puts 'Stalemate!' return game_exit end return unless fifty_move_draw?(board) puts 'draw' game_exit end |
#fifty_move_draw?(board) ⇒ Boolean
check if there’s a fifty_move draw (100 half moves)
79 80 81 |
# File 'lib/chess/game/win_and_draw.rb', line 79 def fifty_move_draw?(board) board.half_move >= 100 end |
#game_exit ⇒ Integer
exits the game
94 95 96 97 |
# File 'lib/chess/game/win_and_draw.rb', line 94 def game_exit pp 'exiting...' 0 end |
#save_and_exit(board) ⇒ Integer
save and exit the game
101 102 103 104 |
# File 'lib/chess/game/win_and_draw.rb', line 101 def save_and_exit(board) save_game(board) game_exit end |
#save_game(board) ⇒ Object
save the game
86 87 88 89 90 |
# File 'lib/chess/game/win_and_draw.rb', line 86 def save_game(board) save_name = prompt_save_name fen = generate_fen_code(board) save(save_name, fen) end |
#stalemate?(board) ⇒ Boolean
check if player is in stalemate
47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/chess/game/win_and_draw.rb', line 47 def stalemate?(board) in_check = if board.current_player == 'w' board.white_king.in_check else board.black_king.in_check end return false if in_check return false if any_legal_move?(board) true end |