-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.rb
More file actions
105 lines (76 loc) · 2.43 KB
/
game.rb
File metadata and controls
105 lines (76 loc) · 2.43 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
require_relative 'board'
require_relative 'player'
require 'yaml'
class Game
def initialize(player1, player2)
@player1, @player2 = player1, player2
@game_board = Board.new
play
end
private
def play
player = @player1
until won?(player)
begin
puts "\n#{player.name.capitalize}'s turn. #{player.color.capitalize} pieces."
@game_board.display
moves_array = get_input(player)
@game_board.perform_moves(moves_array)
rescue IOError => e
puts e.message
retry
end
player == @player1 ? player = @player2 : player = @player1
end
end
def won?(player)
return true if @game_board.pieces(opponent(player.color)).empty?
if @game_board.pieces(opponent(player.color)).all? { |piece| piece.all_moves.empty? }
return true
end
false
end
def opponent(color)
color == :white ? :black : :white
end
def get_input(player)
puts "#{player.name.capitalize}, where would you like to move from?"
start_pos = gets.chomp.split("")
unless Integer(start_pos.first) && Integer(start_pos.last)
raise IOError.new "Please enter two numbers with a space between each number."
end
start_pos.map! { |n| n.to_i }
unless @game_board[start_pos].nil? || @game_board[start_pos].color == player.color
raise IOError.new "That is not your piece. You are the #{player.color} pieces."
end
puts "Where would you like to move to?"
puts "If jumping, put in each position you will jump to in order."
end_pos = gets.chomp.split("")
unless Integer(end_pos.first) && Integer(end_pos.last)
raise IOError.new "Please enter two numbers with a space between each number."
end
end_pos.map! { |n| n.to_i }
moves_array = [start_pos]
until end_pos.empty?
move = [end_pos.shift, end_pos.shift]
end_pos.shift
moves_array << move
end
moves_array
end
end
if __FILE__ == $PROGRAM_NAME
unless ARGV.empty?
YAML.load_file(ARGV.shift).play
else
puts "Who is playing as white?"
name = gets.chomp
player1 = Player.new(name, :black)
puts "Who is playing as black?"
name = gets.chomp
player2 = Player.new(name, :white)
Game.new(player1, player2)
end
end
# g = Game.new(Player.new("Tom", :black), Player.new("Chelsea", :white))
# g = Game.new(tom, chelsea)