require 'socket' require 'thread' require 'ants'
require 'pp'
module AntGame::Client
include AntGame
class ClientAnt < Ant
attr_accessor :id
attr_accessor :cell, :cell_north, :cell_east, :cell_south, :cell_west
def initialize(client)
super()
@client = client
end
end
class AntClient
attr_reader :ants, :socket, :id
def initialize(host, port)
@ants = {}
@socket = TCPSocket.new(host, port)
@on_new_round
end
def listen
begin
while line = @socket.gets("\n")
if /^#{Protocoll::PLAYER_ID} @id = $1.to_i
elsif /^#{Protocoll::ANT} info = Marshal.load($1.hex_decode)
@ants[info.id] ||= ClientAnt.new(self)
info.update_ant(@ants[info.id])
action = get_action(@ants[info.id])
@socket.print "#{Protocoll::ANT} <#{action}>\n"
end
end
ensure
socket.close
end
end
end
def on_calculate_action(&block)
@on_calculate_action = block
end
private
def get_action(ant)
return Action::WAIT unless @on_calculate_action
@on_calculate_action.call(ant)
end
end
include AntGame::Client
include AntGame::Actions
host, port = ARGV[0] || 'localhost', ARGV[1] || 11112
type = ARGV[2] || 'random' client = AntClient.new(host, port)
load "types/#{type}.rb"
client.on_calculate_action do | ant | calculate_action(client, ant) end
client.listen