67 lines
1.6 KiB
Ruby
67 lines
1.6 KiB
Ruby
class RpgGrid
|
|
@mc = nil
|
|
@gridSize = nil
|
|
|
|
# need the @mc to query occupied locations.
|
|
def initialize(mc, grid_size=25)
|
|
@mc = mc
|
|
@gridSize = grid_size
|
|
end
|
|
|
|
# Finds a place to put either a player or a monster that isn't currently occupied
|
|
# Players need to spawn in a non-player cell, monsters can replace an existing monster
|
|
def find_location()
|
|
loop do
|
|
x = rand(@gridSize)
|
|
y = rand(@gridSize)
|
|
|
|
loc = [x, y]
|
|
|
|
n = @mc.collection().find({'location' => [x, y]})
|
|
if n.count == 0 then
|
|
return loc
|
|
elsif n.first["type"] == :monster then
|
|
@mc.collection().delete_one({"_id" => n.first["_id"]})
|
|
return loc
|
|
end
|
|
end
|
|
end
|
|
|
|
# Move the +/- 1 on the x/y with them "bumping" off the walls to find a new position.
|
|
# Gotta keep em in the grid.
|
|
def get_move_location(cur_loc=nil)
|
|
if cur_loc == nil then
|
|
cur_loc = [0, 0]
|
|
end
|
|
|
|
# get the x/y differences
|
|
dx = get_move_diff(cur_loc[0])
|
|
dy = get_move_diff(cur_loc[1])
|
|
|
|
# Build a new [x,y] to save to location
|
|
new_loc = [cur_loc[0] + dx, cur_loc[1] + dy]
|
|
|
|
return new_loc
|
|
end
|
|
|
|
# Should keep all chars inside the @gridSize playfield though without getting locked on an edge
|
|
def get_move_diff(cur_loc)
|
|
# i should be a num between 0 and 2. If 0 == 0, 1 == 1, 2 == -1. Intuitive right?
|
|
i = rand(3)
|
|
d = 0
|
|
|
|
if i == 2 then
|
|
d = -1
|
|
else
|
|
d = i
|
|
end
|
|
|
|
if cur_loc == 0 and d == -1 then
|
|
d = rand(2)
|
|
elsif cur_loc == @gridSize - 1 and d == 1 then
|
|
d = rand(2) - 1
|
|
end
|
|
|
|
return d
|
|
end
|
|
end
|