Skip to content

Instantly share code, notes, and snippets.

@Sephi-Chan
Created March 1, 2012 23:06
Show Gist options
  • Save Sephi-Chan/1953877 to your computer and use it in GitHub Desktop.
Save Sephi-Chan/1953877 to your computer and use it in GitHub Desktop.
class Location
attr_reader :x, :y
def self.find_available_location
begin
location = Location.new(rand(1..10), rand(1..10))
end until location.empty?
location
end
def initialize(x, y)
@x = x
@y = y
end
def empty?
User.where(x: x, y: y).empty?
end
def on_board?
x.in?(1..10) && y.in?(1..10)
end
# Compute the same value for the same coordinates.
def hash
[ x, y ].hash
end
# Allow to use locations as hash keys.
def eql?(other_object)
hash == other_object.hash
end
# Allow locations to match same-coordinates locations in arrays.
def ==(other_object)
hash == other_object.hash
end
class NotOnBoard < StandardError; end
class NotAround < StandardError; end
class AlreadyOccupied < StandardError; end
end
class User < ActiveRecord::Base
has_secure_password
validates_length_of :name, within: 2..15
validates_length_of :password, minimum: 2, on: :create
def self.all_grouped_by_location
User.all.index_by(&:location)
end
def self.generate_persistence_token
begin
persistence_token = SecureRandom.hex(8)
end until User.where(persistence_token: persistence_token).empty?
persistence_token
end
def location
return nil if x.blank? || y.blank?
Location.new(x, y)
end
def location=(location)
self.x = location.x
self.y = location.y
location
end
def around_locations
[
Location.new(x - 1, y - 1),
Location.new( x, y - 1),
Location.new(x + 1, y - 1),
Location.new(x - 1, y),
Location.new(x + 1, y),
Location.new(x - 1, y + 1),
Location.new( x, y + 1),
Location.new(x + 1, y + 1)
]
end
def move(x, y)
target_location = Location.new(x, y)
raise Location::NotOnBoard unless target_location.on_board?
raise Location::NotAround unless target_location.in?(around_locations)
raise Location::AlreadyOccupied unless target_location.empty?
update_attributes(x: x, y: y)
target_location
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment