Wednesday, October 29, 2014

Chess game

Last time I played chess I was in the 6th grade or so. Okay, I didn't actually _play_ it, I was sort of moving the figures according to the rules. Since I don't know how to play chess, I decided to implement my own game of chess in Ruby. I hope to find time to turn it into a web game later on. Currently, the game is played in the terminal and it is a bit hard on the eyes.

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