This repository has been archived by the owner on Apr 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchess.rb
101 lines (85 loc) · 2.28 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
require 'Qt4'
=begin
# Chess rules
http://www.conservativebookstore.com/chess/
Initial board layout:
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
squares (B=black, W=white)
Pieces:
Ro Kn Bi Qu Ki Bi Kn Ro
Pa Pa Pa Pa Pa Pa Pa Pa
- - - - - - - -
- - - - - - - -
- - - - - - - -
- - - - - - - -
Pa Pa Pa Pa Pa Pa Pa Pa
Ro Kn Bi Qu Ki Bi Kn Ro
1. White moves first
2. Pieces may not move through or over other pieces except for the knight
3.
=end
class Chess
# returns an array of valid moves from the row, col coordinates passed
def enumerate_move_destinations(chessBoard, row_in, col_in)
destinations = Array.new
curstate = chessBoard[row_in][col_in].state
return nil unless curstate.hasPiece?
for row in 0.upto(BOARD_HEIGHT-1)
for col in 0.upto(BOARD_WIDTH-1)
destinations.push([row, col]) if curstate.can_move_to?(chessBoard, row, col)
end
end
destinations
end
def enumerate_all_moves(chessBoard, color)
moves = Hash.new
for row in 0.upto(BOARD_HEIGHT-1)
for col in 0.upto(BOARD_WIDTH-1)
#puts "Chess::enumerate_all_moves: checking [#{row}, #{col}]..." if DEBUG
next unless chessBoard[row][col].state.color == color
m = enumerate_move_destinations(chessBoard, row, col)
moves[[row, col]] = m unless m.nil? or m.length < 1
end
end
moves
end
def get_king_state(chessBoard, color)
for row in 0.upto(BOARD_HEIGHT-1)
for col in 0.upto(BOARD_WIDTH-1)
state = chessBoard[row][col].state
return state if state.hasPiece? and state.color == color and state.class == KingState
end
end
end
def in_check?(chessBoard, color)
puts "Checking if #{color} is in check..."
if color == WHITE
enemy_moves = enumerate_all_moves(chessBoard, BLACK)
else
enemy_moves = enumerate_all_moves(chessBoard, WHITE)
end
puts "enemy moves: #{enemy_moves.inspect}"
king = get_king_state(chessBoard, color)
puts "king: #{king.inspect}"
enemy_moves.each_value do |x|
return true if x.include?([king.row, king.col])
end
return false
end
def ai_generate_move(chessBoard, color)
moves = enumerate_all_moves(chessBoard, color)
keys = moves.keys
move_key = keys[rand(keys.length)]
from = move_key
spots = moves[move_key]
to = spots[rand(spots.length)]
return [from, to]
end
end