finish move generator, add jump generator, add dup and all associated

functions
This commit is contained in:
Dan Ballard 2011-08-28 16:39:17 -07:00
parent 6f69940642
commit f61b9ee0a7
1 changed files with 127 additions and 2 deletions

View File

@ -1,5 +1,8 @@
#!/usr/bin/ruby
EMPTY = 0
TEAM_1 = 1
TEAM_2 = 2
TEAM_1_MAN = ' w '
TEAM_1_KING = ' W '
TEAM_2_MAN = ' b '
@ -10,6 +13,9 @@ BOARD_SIZE = 8
class Board
def initialize()
@board = Array.new(BOARD_SIZE) {|i| Array.new(BOARD_SIZE, BOARD_EMPTY)}
end
def setup()
0.step(BOARD_SIZE) {|i|
peice = (i < 3 ? TEAM_1_MAN : TEAM_2_MAN)
if [0,2,5,7].include? i
@ -19,15 +25,23 @@ class Board
else
next
end
start.step(BOARD_SIZE,2) {|j|
start.step(BOARD_SIZE-1,2) {|j|
@board[i][j] = peice
}
}
end
def set(x, y, thing)
@board[y][x] = thing
end
def get(x, y)
@board[y][x]
end
def to_s()
str = ' '
0.step(BOARD_SIZE) {|i|
0.step(BOARD_SIZE-1) {|i|
str += ' ' + i.to_s + ' '
}
str += "\n"
@ -43,7 +57,118 @@ class Board
return str
end
def piece_team(piece)
if piece == TEAM_1_MAN or piece == TEAM_1_KING
return TEAM_1
elsif piece == TEAM_2_MAN or piece == TEAM_2_KING
return TEAM_2
else
return EMPTY
end
end
def empty?(x, y)
return @board[y][x] == BOARD_EMPTY
end
def valid_coords(x, y)
return (x >= 0 and x < BOARD_SIZE and y >= 0 and y <= BOARD_SIZE)
end
def gen_moves(x, y, x_mod, y_mod)
moves = []
for xm in x_mod
new_x = x + xm
for ym in y_mod
new_y = y + ym
if valid_coords(new_x, new_y) and empty?(new_x, new_y)
moves += [[new_x, new_y]]
end
end
end
return moves
end
# function to chart path of jumps
# merging them together
# only returns full paths
#
# base case: no jumps avail, return path
# jumps avail: do all and merge and return
def gen_jumps(path, x, y, team, x_mod, y_mod)
jumps = []
for xm in x_mod
new_x = x + xm
for y in ymod
new_y = y + ym
if valid_coords(new_x, new_y) and piece?(new_x, new_y) and team != team(new_x, new_y)
final_x = new_x + xm
final_y = new_y + ym
if (valid_coords(final_x, final_y) and empty?(final_x, final_y))
jumps += gen_jumps(path + [[final_x, final_y]], final_x, final_y, x_mod, y_mod)
end
end
end
end
if jumps == []
return [path]
else
return jumps
end
end
def piece?(x, y)
return !emtpy(x, y)
end
def team(x, y)
if piece?(x, y)
if @board[y][x] == TEAM_1_MAN or @board[y][x] == TEAM_1_KING
return TEAM_1
else
return TEAM_2
end
end
return EMPTY
end
def man?(x, y)
return (@board[y][x] == TEAM_1_MAN or @board[y][x] == TEAM_2_MAN)
end
def king?(x, y)
return (@board[y][x] == TEAM_1_KING or @board[y][x] == TEAM_2_KING)
end
def valid_moves(x, y, team)
moves = []
if piece_team(@board[y][x]) == team
direction = [1]
if king?(x, y)
direction = [-1, 1]
elsif team == TEAM_2
direction = [-1]
end
moves = gen_moves(x, y, [-1,1], direction)
moves += gen_jumps([], x, y, team, [-1, 1], direction)
end
return moves
end
def dup()
b = Board.new
for x in 0..(BOARD_SIZE-1)
for y in 0..(BOARD_SIZE-1)
b.set(x, y, get(x, y))
end
end
return b
end
end
b = Board.new()
b.setup()
puts b.to_s