-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.rb
More file actions
94 lines (81 loc) · 2.13 KB
/
game.rb
File metadata and controls
94 lines (81 loc) · 2.13 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
require_relative 'board.rb'
require_relative 'human_player.rb'
require_relative 'display.rb'
require_relative 'computer_player.rb'
require 'yaml'
class Game
def self.load
puts "Enter file name to load"
input = gets.chomp
file = File.read(input)
YAML.load(file).run
end
attr_accessor :board, :current_player
attr_reader :players
def initialize(players_count)
@board = Board.new(true)
if players_count == 1
@players = [HumanPlayer.new("Player 1", board, :white), ComputerPlayer.new("Computer", board, :black)]
elsif players_count == 2
@players = [HumanPlayer.new("Player 1", board, :white), HumanPlayer.new("Player 2", board, :black)]
end
@current_player = players[0]
end
def play
begin
input = current_player.play_turn
save if input == :save
current_piece = board[input[0]]
raise MoveError.new "No piece in that square!" if current_piece.nil?
raise MoveError.new "That is not your piece!" if current_piece.color != current_player.color
board.move(*input)
current_piece.promotion(current_player) if current_piece.class == Pawn
switch_players
rescue MoveError => e
puts e.message
sleep(3)
retry
end
end
def run
until over?
play
end
game_over
end
def over?
board.checkmate?(:black) || board.checkmate?(:white) || board.draw?(current_player.color)
end
def switch_players
self.current_player = (current_player == players[0] ? players[1] : players[0])
end
def game_over
current_player.display.render
if board.checkmate?(:black)
puts "Checkmate! White wins!"
elsif board.checkmate?(:white)
puts "Checkmate! Black wins!"
else
puts "It's a draw!"
end
end
def save
puts "Please enter a file name"
filename = gets.chomp
f = File.new(filename, "w")
f.write(self.to_yaml)
f.close
exit 0
end
end
if __FILE__ == $PROGRAM_NAME
puts "Load game? (y/n)"
input = gets.chomp.downcase
if input == "y"
Game.load
else
puts "How many players? (1 / 2) "
players_count = gets.chomp.to_i
Game.new(players_count).run
end
end