Permalink
Browse files

Begin of work on "code", to create AI for any ship.

  • Loading branch information...
mauricioszabo committed Nov 25, 2011
1 parent 2f1e93a commit 71efaab9a57193c1636f9ad9be7b365f099441c7
Showing with 110 additions and 0 deletions.
  1. +36 −0 lib/code.rb
  2. +74 −0 spec/code_spec.rb
View
@@ -0,0 +1,36 @@
+Object.send :remove_const, :ObjectSpace
+class Code
+ attr_accessor :block
+
+ class << self
+ block = nil
+ define_method(:each_frame) { |&b| block = b }
+
+ define_method :register_to do |player|
+ code = new
+ define_methods(player)
+ define_method(:run) { instance_exec &block }
+ eigen = class << code.class; self; end
+ eigen.send :undef_method, :register_to
+ return code
+ end
+
+ def define_methods(player)
+ define_method(:turn_to) do |d|
+ dir = case d
+ when :upper, :up then Player::UPPER
+ when :upper_right then Player::UPPER_RIGHT
+ when :right then Player::RIGHT
+ when :lower_right then Player::LOWER_RIGHT
+ when :lower, :down then Player::LOWER
+ when :lower_left then Player::LOWER_LEFT
+ when :left then Player::LEFT
+ when :upper_left then Player::UPPER_LEFT
+ else raise ArgumentError, "must be :upper, :right, :lower or :left or any of their combinations"
+ end
+ player.turn_to(dir)
+ end
+ end
+ private :define_methods
+ end
+end
View
@@ -0,0 +1,74 @@
+require_relative 'helper'
+
+describe Code do
+ let(:player) { mock(Player) }
+
+ context "turning the ship" do
+ it 'should ask for ship to turn' do
+ converts = {
+ :upper => Player::UPPER,
+ :upper_right => Player::UPPER_RIGHT,
+ :right => Player::RIGHT,
+ :lower_right => Player::LOWER_RIGHT,
+ :lower => Player::LOWER,
+ :lower_left => Player::LOWER_LEFT,
+ :left => Player::LEFT,
+ :upper_left => Player::UPPER_LEFT
+ }
+
+ converts.each_pair do |key, value|
+ player.should_receive(:turn_to).with(value)
+ run do
+ turn_to key
+ end
+ end
+ end
+
+ it 'should raise an error if given with invalid argument' do
+ expect {
+ run { turn_to :sky }
+ }.to raise_error(ArgumentError)
+ end
+ end
+
+ context "on security" do
+ it 'should not register a new player' do
+ new_player = mock Player
+ expect {
+ run do
+ self.class.register_to new_player
+ end
+ }.to raise_error(NoMethodError)
+ end
+
+ it 'should not have any instance variable to change' do
+ code = this_code {}
+ code.instance_variables.should be_empty
+ code.class.instance_variables.should be_empty
+ eigen = class << code.class; self; end
+ eigen.instance_variables.should be_empty
+ end
+
+ it 'should be able to run the block if "block" is redefined' do
+ run { block = nil }
+ end
+
+ it 'should not be able to traversal between objects' do
+ expect {
+ run { ObjectSpace.each_object { |x| x } }
+ }.to raise_error
+ end
+ end
+
+ def run(&block)
+ this_code(&block).run
+ end
+
+ def this_code &block
+ code = Class.new(Code) do
+ each_frame &block
+ end
+ #FIXME: Cannot stay on Code interface
+ code.register_to player
+ end
+end

0 comments on commit 71efaab

Please sign in to comment.