-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.rb
More file actions
82 lines (71 loc) · 1.79 KB
/
game.rb
File metadata and controls
82 lines (71 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
require_relative 'board.rb'
require_relative 'player.rb'
class Game
attr_reader :board
def initialize(player1, player2)
@board = Board.new
@player1 = player1
@player2 = player2
@player1.color = :white
@player2.color = :black
@current_player = @player1
end
def play
until checkmate?
display_board
user_in_check_message if user_in_check?
begin
move = @current_player.play_turn
if @board[move.first] && @board[move.first].color != @current_player.color
raise NotPlayersPiece
end
@board.move(move.first, move.last)
rescue NoPieceAtPosition => e
puts "No piece at that starting position."
retry
rescue OccupiedSpace => e
puts "That ending position is currently occupied."
retry
rescue MoveIntoCheck => e
puts "That move puts you into check."
retry
rescue InvalidMove => e
puts "That is an invalid move."
retry
rescue NotPlayersPiece => e
puts "That is not your piece."
retry
end
toggle_player unless checkmate?
end
display_board
victory
end
private
def user_in_check?
@board.in_check?(@current_player.color)
end
def display_board
system "clear"
@board.display
end
def user_in_check_message
puts "You are in check."
end
def toggle_player
@current_player = @current_player == @player1 ? @player2 : @player1
end
def checkmate?
@board.checkmate?(:black) || @board.checkmate?(:white)
end
def victory
puts "#{@current_player.name}, you win!"
end
end
if __FILE__ == $PROGRAM_NAME
player_one = Player.new(ARGV[0] || "Player 1")
player_two = Player.new(ARGV[1] || "Player 2")
ARGV.clear
game = Game.new player_one, player_two
game.play
end