-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.rb
71 lines (60 loc) · 1.57 KB
/
game.rb
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
require_relative 'board'
require_relative 'pieces'
require_relative 'computer_player'
require_relative 'human_player'
require 'byebug'
class Game
attr_accessor :board, :current_player
attr_reader :player1, :player2
def initialize(board = Board.new,
player1 = HumanPlayer.new(:white, board),
player2 = ComputerPlayer.new(:black, board))
ARGV.clear
@board = board
@player1 = player1
@player2 = player2
@current_player = player1
end
def play
board.populate_board
until board.over?
board.render
puts "Current player is: #{current_player.color}"
begin
player_move = current_player.get_move
check_move(player_move)
board.move(*player_move)
rescue ChessError, InputError => e
puts "#{e.message}"
retry
end
switch_player
sleep(0.15)
end
end
def check_move(move)
start_pos = move[0]
raise ChessError.new("Not your piece") if board[start_pos].color != current_player.color
end
def switch_player
self.current_player = (current_player == player2 ? player1 : player2)
end
end
class InputError < StandardError
end
if __FILE__ == $PROGRAM_NAME
board = Board.new
case ARGV[0]
when '0'
player1 = ComputerPlayer.new(:white, board)
player2 = ComputerPlayer.new(:black, board)
when '1'
player1 = HumanPlayer.new(:white, board)
player2 = ComputerPlayer.new(:black, board)
when '2'
player1 = HumanPlayer.new(:white, board)
player2 = HumanPlayer.new(:black, board)
end
game = Game.new(board, player1, player2)
game.play
end