For now, I am still working on the logic. One of the challenges was to write a generalized method that would allow to move a piece in any direction and return an error if there was a block on the way. At first, I ended up writing 8 if statements - one for each direction - but that looked so, so ugly. However, I realized it was possible to specify vectors instead. In the end, the method looked as follows:
def is_it_blocked?(board, from_x, from_y, to_x, to_y) result = false direction_x = from_x > to_x ? 1 : -1 direction_y = from_y > to_y ? 1 : -1 row = (from_x - to_x).abs col = (from_y - to_y).abs if row > col diff = row else diff = col end (1...diff).each do |i| if row > col cell = board.board[to_x+i*direction_x][to_y] result = true if !cell.nil? elsif col > row cell = board.board[to_x][to_y+i*direction_y] result = true if !cell.nil? else cell = board.board[to_x+i*direction_x][to_y+i*direction_y] result = true if !cell.nil? end end result end
No comments :
Post a Comment