Craft an armadillo in ruby
I cant tilt Ruby encoding and am trying to make a linker game. Now I have some difficulties (found many implementations on Github but can't figure them out).
I have a 10 * 10 board and now I am trying to implement an algorithm for walking across the field. For example: I am at position x on the field, how can I check the availability of cell A1? So here's an option ... but how do you make a generic method? (when I select a position I need to check 8 cells for free space for the next cell).
def test(postition)
letter = position[0]
# 1 2 3
# A O . .
# B x . .
# C . . .
keys = board.keys
index = keys.find_index(letter)
prev_key = keys[index - 1] #up-down
unless prev_key.nil?
is_ship_placed = board[prev_key][postition[1]] #left-right
end
# 1 2 3
# A O . .
# B . . .
# C . . .
end
All my code so far is at ideone.com
I would really appreciate if someone can help me!
PS Sorry my english, pls.
source to share
I've expanded on @JustinWood's excellent advice in this answer. It will be easier for you to represent your board as an array rather than a hash.
So change
board = { a: [false, false, false, false, false, false, false, false, false, false], \
b: [false, false, false, false, false, false, false, false, false, false], etc.
to something like a two dimensional array. (List of lists.)
board = [[false, false, false, false, false, false, false, false, false, false],
[false, false, false, false, false, false, false, false, false, false],
.......... ]]
Naturally, you can fill it in automatically, rather than copying 10 source texts into 10 lines. It works:
blank_row = Array.new(10,false)
board = Array.new(10) { blank_row.clone }
You can then navigate the board using arithmetic to check the 8 surrounding squares. You would do something like this:
def test (position)
x, y = position
return true if board[y][x]
return true if board[y-1][x-1]
return true if board[y-1][x]
....
false
end
Add suitable edge protectors and automate them instead of printing all 9 cases.
As you noticed, when you changed the Hash to an array, it means that you need to change other parts of your game that use the board. For example, you already know how to iterate through your hash (for example, to change it)
board.each do |key, row|
row.each do |v|
# do something with cell v and build a new row
end
# insert the new row at board[key]
end
You can iterate over 2D array like in this example
board.each.with_index do |row, y|
row.each.with_index do |v, x|
# change a true cell to 'S' and false to '.'
if v
board[y][x] = 'S'
else
board[y][x] = '.'
end
end
end
source to share