72 lines
1.9 KiB
Ruby
72 lines
1.9 KiB
Ruby
# Nathan Hinton
|
|
# Holds a grid of each otem in the game
|
|
|
|
class GameGrid
|
|
def initialize(game_width, game_height)
|
|
|
|
@game_grid = []
|
|
game_width.times do |xx|
|
|
@game_grid.append(Array.new(game_height))
|
|
end
|
|
end
|
|
|
|
|
|
## Add an item to the grid
|
|
# @param x [Integer] The x position (top left corner of item)
|
|
# @param y [Integer] The y position (top left corner of item)
|
|
# @param item [Object] The item to add. Should be an actual reference to the item
|
|
# @retval [Boolean] True if the item was placed, false otherwise (space conflict)
|
|
def add_item(x, y, item)
|
|
size_x = item.size_x
|
|
size_y = item.size_y
|
|
|
|
puts "#{item.to_s}"
|
|
puts "top left: (#{x}, #{y}), size: (#{size_x}, #{size_y})"
|
|
|
|
# Check that the grid is empty in those spots:
|
|
size_x.times do |xx|
|
|
size_y.times do |yy|
|
|
unless @game_grid[x + xx][y + yy].nil?
|
|
puts "Failed to add item: #{item.to_s}:"
|
|
puts " - top left: (#{x}, #{y}), size: (#{size_x}, #{size_y}), collision: (#{xx}, #{yy})"
|
|
return false
|
|
end
|
|
end
|
|
end
|
|
|
|
# place item in grid
|
|
size_x.times do |xx|
|
|
size_y.times do |yy|
|
|
@game_grid[x + xx][y + yy] = item
|
|
end
|
|
end
|
|
return true
|
|
end
|
|
|
|
## Add an item to the grid
|
|
# @param x [Integer] The x position (top left corner of item)
|
|
# @param y [Integer] The y position (top left corner of item)
|
|
# @param item [Object] The item to remove. Used to ensure we are removing the right thing.
|
|
def remove_item(x, y, item)
|
|
size_x = item.size_x
|
|
size_y = item.size_y
|
|
|
|
# Check that the grid is empty in those spots:
|
|
size_x.times do |xx|
|
|
size_y.times do |yy|
|
|
if @game_grid[x + xx][y + yy] != item
|
|
raise RuntimeError.new('Item mismatch in internal game grid! Game state corrupted1')
|
|
end
|
|
end
|
|
end
|
|
|
|
# place item in grid
|
|
size_x.times do |xx|
|
|
size_y.times do |yy|
|
|
@game_grid[x + xx][y + yy] = nil
|
|
end
|
|
end
|
|
end
|
|
|
|
end
|