-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchess.rb
executable file
·530 lines (426 loc) · 12.4 KB
/
chess.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
#!/usr/bin/env ruby
require 'colorize'
require 'yaml'
class Game
LETTER_HASH = {}
("a".."h").each {|letter| LETTER_HASH[letter] = letter.ord - 97}
attr_accessor :player1, :player2, :board, :current_player
def self.load
YAML.load_file(ARGV.shift)
end
def initialize
@board = Board.new
@white_king = King.new('white',[7, 4])
@black_king = King.new('black',[0, 4])
@board.put_piece(@white_king)
@board.put_piece(@black_king)
@turn = 0
end
def play
@player1 = HumanPlayer.new
@player2 = HumanPlayer.new
puts "Name of Player 1 (white)?"
name1 = gets.chomp
@player1.name = name1
@player1.color = "white"
puts "Name of Player 2 (black)?"
name2 = gets.chomp
@player2.name = name2
@player2.color = "black"
@board.display_board
while true
@current_player = @turn % 2 == 0? @player1: @player2
p "#{current_player.name}'s turn..."
begin
if checked? && checkmate?
p "Checkmate! #{current_player.name} loses!"
break
end
p "You are in check" if checked?
move
rescue RuntimeError => e
puts "Here is your chance to fix your boneheaded move."
puts "Error was: #{e.message}"
end
end
end
def convert_coordinates(coord)
start_pos, end_pos = coord.split(',')
start_col = LETTER_HASH[start_pos[0]]
start_row = 8 - start_pos[1].to_i
end_col = LETTER_HASH[end_pos[0]]
end_row = 8 - end_pos[1].to_i
[[start_row, start_col], [end_row, end_col]]
end
def get_input
puts "#{@player1.name} input coordinates (e.g. \"f2,f8\") or s to save"
coord = gets.chomp.downcase
if coord == "s"
save_game
get_input
else
convert_coordinates(coord)
end
end
def save_game
puts "Enter filename to save at:"
filename = gets.chomp
File.open(filename, "w") do |f|
YAML.dump(self, f)
end
end
def check_for_errors(piece, end_pos)
if piece.class == String
raise RuntimeError.new "No piece at starting position."
end
unless check_possible_moves?(piece, end_pos)
raise RuntimeError.new "This is not a possible move."
end
if @board.occupied_and_own?(piece, end_pos)
raise RuntimeError.new "Your piece is there."
end
if piece.blocked?(@board, end_pos)
raise RuntimeError.new "Either pieces are in the way or there are no
pieces to capture for your pawn"
end
end
def move
start_pos, end_pos = get_input
piece = @board.chessboard[start_pos[0]][start_pos[1]]
end_piece = @board.chessboard[end_pos[0]][end_pos[1]]
check_for_errors(piece, end_pos)
piece.position = end_pos
piece.first_move = false if piece.class == Pawn
@board.update_board(start_pos, end_pos)
if checked?
unmove(piece, end_piece, start_pos, end_pos)
raise RuntimeError.new "Either still in check or moving into check."
end
@board.display_board
@turn += 1
end
def unmove(piece, end_piece, start_pos, end_pos)
@board.chessboard[start_pos[0]][start_pos[1]] = piece
@board.chessboard[end_pos[0]][end_pos[1]] = end_piece
piece.position = start_pos
end
def checked?
end_pos = @white_king.position if @current_player.color == "white"
end_pos = @black_king.position if @current_player.color == "black"
@board.chessboard.each_with_index do |row, idx1|
row.each_with_index do |col, idx2|
piece = @board.chessboard[idx1][idx2]
next if piece.class == String || piece.color == @current_player.color
if check_possible_moves?(piece, end_pos) &&
!piece.blocked?(@board, end_pos)
return true
end
end
end
false
end
def valid_moves(piece)
legal_moves = piece.possible_moves
legal_moves = legal_moves.select do |move|
[email protected]_and_own?(piece, move) &&
!piece.blocked?(@board, move)
end
legal_moves
end
def checkmate?
bool_array = []
@board.chessboard.each_with_index do |row, idx1|
row.each_with_index do |col, idx2|
piece = @board.chessboard[idx1][idx2]
next if piece.class == String || piece.color != @current_player.color
legal_moves = valid_moves(piece)
legal_moves.each do |move|
start_pos = piece.position
end_piece = @board.chessboard[move[0]][move[1]]
piece.position = move
@board.update_board(start_pos, move)
bool_array << checked?
unmove(piece, end_piece, start_pos, move)
end
end
end
bool_array.all?
end
def check_possible_moves?(piece, end_pos)
piece.possible_moves.include?(end_pos)
end
end
class Board
attr_accessor :chessboard, :piece_at
def initialize
class_array = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook]
pawn_array = [Pawn] * 8
@chessboard = Array.new(8) {Array.new(8) {' '}}
class_array.each_with_index do |cl, i|
next if i == 4
new_piece = cl.new('white',[7, i])
put_piece(new_piece)
new_piece = cl.new('black',[0, i])
put_piece(new_piece)
end
pawn_array.each_with_index do |cl, i|
new_piece = cl.new('white',[6, i])
put_piece(new_piece)
new_piece = cl.new('black',[1, i])
put_piece(new_piece)
end
end
def put_piece(piece)
y = piece.position.first
x = piece.position.last
@chessboard[y][x] = piece
end
def display_board
@chessboard.each_with_index do |row, idx1|
print "#{8-idx1} "
row.each_with_index do |col, idx2|
tile = @chessboard[idx1][idx2]
if (idx1 + idx2) % 2 == 0
if tile.class == String
print (tile + " ").colorize(:background => :red)
else
print (tile.symbol + " ").colorize(:background => :red)
end
else
if tile.class == String
print (tile + " ").colorize(:background => :blue)
else
print (tile.symbol + " ").colorize(:background => :blue)
end
end
end
puts ""
end
puts " a b c d e f g h"
end
def update_board(start_pos, end_pos)
piece = @chessboard[start_pos[0]][start_pos[1]]
@chessboard[end_pos[0]][end_pos[1]] = piece
@chessboard[start_pos[0]][start_pos[1]] = " "
end
def occupied_and_own?(piece, pos)
end_piece = @chessboard[pos[0]][pos[1]]
(end_piece.class.superclass == Piece) && end_piece.color == piece.color
end
def diag_opp_occupied?(piece, diag_pos)
end_piece = @chessboard[diag_pos[0]][diag_pos[1]]
(end_piece.class.superclass == Piece) && end_piece.color != piece.color
end
def occupied?(pos)
piece = @chessboard[pos[0]][pos[1]]
piece.class.superclass == Piece
end
end
class HumanPlayer
attr_accessor :name, :color
end
class Piece
attr_accessor :color, :position
def initialize(color, position)
@color = color
@position = position
end
def diagonal_moves
delta = [[-1, -1], [-1, 1], [1, -1], [1, 1]]
diag_moves = []
delta.each do |dy, dx|
7.times do |i|
diag_moves << [(position[0] + (dy * (i + 1))),
(position[1] + (dx * (i + 1)))]
end
end
diag_moves = diag_moves.select do |y,x|
(0..7).include?(y) && (0..7).include?(x)
end
diag_moves
end
def orthogonal_moves
delta = [[-1, 0], [1, 0], [0, -1], [0, 1]]
ortho_moves = []
delta.each do |dy, dx|
7.times do |i|
ortho_moves << [(position[0] + (dy * (i + 1))),
(position[1] + (dx * (i + 1)))]
end
end
ortho_moves = ortho_moves.select do |y,x|
(0..7).include?(y) && (0..7).include?(x)
end
ortho_moves
end
def blocked?(board, end_pos) #comes after narrowing down possible_moves
case self
when Bishop
spaces_to_check = diag_blocked_spaces(end_pos)
when Rook
spaces_to_check = ortho_blocked_spaces(end_pos)
when Queen
spaces_to_check = diag_blocked_spaces(end_pos) +
ortho_blocked_spaces(end_pos)
when Knight
return false
when Pawn
if end_pos[1] == position[1] #going straight
spaces_to_check = ((color == 'white') ?
[[-1 + position[0], position[1]]] : [[1 + position[0], position[1]]])
if first_move
spaces_to_check << ((color == 'white') ?
[-2 + position[0], position[1]] : [2 + position[0], position[1]])
end
else #going diagonally
return !board.diag_opp_occupied?(self, end_pos)
end
when King
return false
end
spaces_to_check.any? {|space| board.occupied?(space)}
end
def ortho_blocked_spaces(end_pos)
dy = end_pos[0] - position[0]
dx = end_pos[1] - position[1]
spaces_to_check = []
if dy == 0
if dx < 0
dx.abs.times do |i|
next if i == 0
spaces_to_check << [dy, (dx.abs - i) * -1]
end
elsif dx > 0
dx.abs.times do |i|
next if i == 0
spaces_to_check << [dy, (dx.abs - i) * 1]
end
end
elsif dx == 0
if dy < 0
dy.abs.times do |i|
next if i == 0
spaces_to_check << [(dy.abs - i) * -1, dx]
end
elsif dy > 0
dy.abs.times do |i|
next if i == 0
spaces_to_check << [(dy.abs - i) * 1, dx]
end
end
end
spaces_to_check.map! {|dy, dx| [dy + position[0], dx + position[1]]}
end
def diag_blocked_spaces(end_pos) #helper method for blocked?
# generate array of spaces in the correct direction
dy = end_pos[0] - position[0]
dx = end_pos[1] - position[1]
spaces_to_check = []
dy.abs.times do |i|
next if i == 0
if dy < 0 && dx < 0
spaces_to_check << [(dy.abs - i) * -1, (dx.abs - i) * -1]
elsif dy < 0 && dx > 0
spaces_to_check << [(dy.abs - i) * -1, (dx.abs - i) * 1]
elsif dy > 0 && dx < 0
spaces_to_check << [(dy.abs - i) * 1, (dx.abs - i) * -1]
elsif dy > 0 && dx > 0
spaces_to_check << [(dy.abs - i) * 1, (dx.abs - i) * 1]
end
end
spaces_to_check.map! {|dy, dx| [dy + position[0], dx + position[1]]}
end
end
class Pawn < Piece
attr_accessor :symbol, :first_move
def initialize(color, position)
super(color, position)
@symbol = color == 'white' ? "\u2659" : "\u265F"
@first_move = true
end
def possible_moves
pos_moves =
[[-1, -1], [-1, 0], [-1, 1]]
pos_moves.map! do |dy, dx|
y = color == "white" ? dy + position[0] : -dy + position[0]
x = dx + position[1]
[y, x] if (0..7).include?(y) && (0..7).include?(x)
end
if @first_move
two_spaces_forward = (color == "white") ?
[-2 + position[0], position[1]] : [2 + position[0], position[1]]
pos_moves << two_spaces_forward
end
pos_moves = pos_moves.select { |el| !el.nil?}
end
end
class Knight < Piece
attr_accessor :symbol
def initialize(color, position)
super(color, position)
@symbol = color == 'white' ? "\u2658" : "\u265E"
end
def possible_moves
pos_moves =
[[-2,-1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]
pos_moves.map! do |dy, dx|
y = dy + position[0]
x = dx + position[1]
[y, x] if (0..7).include?(y) && (0..7).include?(x)
end
pos_moves = pos_moves.select { |el| !el.nil?}
end
end
class Rook < Piece
attr_accessor :symbol
def initialize(color,position)
super(color, position)
@symbol = color == 'white' ? "\u2656" : "\u265C"
end
def possible_moves
orthogonal_moves
end
end
class Queen < Piece
attr_accessor :symbol
def initialize(color,position)
super(color, position)
@symbol = color == 'white' ? "\u2655" : "\u265B"
end
def possible_moves
orthogonal_moves + diagonal_moves
end
end
class King < Piece
attr_accessor :symbol
def initialize(color,position)
super(color, position)
@symbol = color == 'white' ? "\u2654" : "\u265A"
end
def possible_moves
delta =
[[-1, -1], [-1, 1], [1, -1], [1, 1], [-1, 0], [1, 0], [0, -1], [0, 1]]
pos_moves = []
delta.each do |dy, dx|
pos_moves << [dy + position[0], dx + position[1]]
end
pos_moves = pos_moves.select do |y,x|
(0..7).include?(y) && (0..7).include?(x)
end
pos_moves
end
end
class Bishop < Piece
attr_accessor :symbol
def initialize(color,position)
super(color, position)
@symbol = color == 'white' ? "\u2657" : "\u265D"
end
def possible_moves
diagonal_moves
end
end
if __FILE__ == $PROGRAM_NAME
newgame = Game.new
newgame.play
end