-
Notifications
You must be signed in to change notification settings - Fork 1
/
application.rb
101 lines (86 loc) · 2.28 KB
/
application.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class Application
attr_reader :controllers
def initialize
@controllers = {}
@clients = []
@players = PlayersCollection.get_instance
puts 'Aplicacao WarApp iniciada...'
end
#adiciona um controller a aplicacao
def add_c(obj)
@controllers[obj.name] = obj if obj.respond_to?(:name) and obj.name.is_a?(Symbol)
end
#vincula um cliente a algum objeto
def bind_client(conn,obj)
@clients.push({:conn => conn, :obj => obj})
end
def unbind_client(o)
to_delete = []
@clients.each do |c|
to_delete << c if c[:obj] == o
end
@clients -= to_delete
end
def get_conn(o)
cr = nil
@clients.each do |c|
cr = c[:conn] if c[:obj] == o
end
return cr
end
def get_client(conn)
cr = nil
@clients.each do |c|
cr = c[:obj] if c[:conn] == conn
end
return cr
end
def broadcast(msg,ignore=[])
@clients.each do |c|
c[:conn].send_msg(msg) unless ignore.include?(c[:obj])
end
end
def send(o,msg)
array = o.is_a?(Array)
@clients.each do |c|
if array
c[:conn].send_msg(msg) if o.include?(c[:obj])
else
c[:conn].send_msg(msg) if c[:obj] == o
end
end
end
#events
def new_conn(conn)
#Percorre por todos os controllers chamando aqueles que implementam o método new_conn
@controllers.each do |k,v|
v.new_conn(conn) if v.respond_to?(:new_conn)
end
#########
end
def closed_conn(conn)
#Percorre por todos os controllers chamando aqueles que implementam o método closed_conn
@controllers.each do |k,v|
v.closed_conn(conn) if v.respond_to?(:closed_conn)
end
#########
p = get_client(conn)
unless p.nil?
@players.rem(p)
unbind_client(p)
end
list = @players.list.clone
list = list.delete_if { |p| p.is_a?(Ai) }
broadcast(Message.new('playerList','update',{'list' => list})); #atualiza lista de jogadores
end
#actions
def message(msg,conn)
#Exemplo de mensagem { controller: chat, action: send, params: { msg: 'exemplo' } }
c = msg['controller'].to_sym
a = msg['action'].to_sym
p = msg['params']
#puts "#{c}##{a}(#{p})"
#o = get_client(conn)
@controllers[c].__send__ a, conn, p if @controllers[c].respond_to?(a)
end
end