JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
95e130671bbeecd4bf3b664f996f05638e8572b1
[peach-cgt.git] / client.coffee
1 # globals
2 $table = null
3 table_width = 0
4 table_height = 0
5 card_width = 0
6 card_height = 0
7 state = null
8 server_url = null
9 top_card_z = 0 # css z-index of front-most card
10 piles = null
11
12 window.log = []
13 show_message = (txt) ->
14         window.log.push txt
15         if window.log.length > 20
16                 window.log.shift()
17         return
18
19 # timeout function with args in convenient order
20 timeout = (ms, func) -> setTimeout func, ms
21
22 unless Array::shuffle?
23         Array::shuffle = ->
24                 return if @length is 0
25                 top = @length
26
27                 while --top
28                         current = Math.floor(Math.random() * (top + 1))
29                         tmp = @[current]
30                         @[current] = @[top]
31                         @[top] = tmp
32                 return
33
34 new_button = (text) -> $ $ "<div class=\"button\">#{text}</div>"
35
36 # transform coordinates from client-side coords to server-side coords (or back)
37 # this makes it so p2 view everything upside down (mirrored), but still sends coords rightside up
38 flip_x = (x) -> table_width - card_width - x
39 flip_y = (y) -> table_height - card_height - y
40 transform_x = (x) ->
41         return x unless state.agent is 'p2'
42         return flip_x x
43 transform_y = (y) ->
44         return y unless state.agent is 'p2'
45         return flip_y y
46
47 next_card_z = -> return top_card_z += 1
48
49 bring_card_to_front = (card) ->
50         card.view.css "z-index": next_card_z()
51
52 new_blank_card = (x, y, css_class) ->
53         view = $ $ "<div class=\"blank_card #{css_class}\" style=\"left: #{transform_x x}px; top: #{transform_y y}px; z-index: 0\"></div>"
54         $table.append view
55         return view
56
57 find_pile = (x, y) ->
58         fudge = 40
59         for pile in piles
60                 if -fudge < pile.x - x < fudge and -fudge < pile.y - y < fudge
61                         return pile
62         return null
63
64 uninstantiate_card = (card) ->
65         show_message "uninstantiate card #{card.number}"
66         card.view.remove()
67         delete card.view
68
69 instantiate_card = (card) ->
70         show_message "instantiate card #{card.number}"
71         if card.view
72                 die.a.horrible.death()
73
74         text = card.text
75         if card.owner is state.agent
76                 card_class = 'my_card'
77         else
78                 card_class = 'your_card'
79
80         if card.z > top_card_z
81                 top_card_z = card.z
82
83         view = $ $ "<div class=\"card #{card_class}\" style=\"left: #{transform_x(card.x)}px; top: #{transform_y(card.y)}px; z-index: #{card.z}\"><span class=\"cardtext\">#{text}</span></div>"
84         card.view = view
85         button_box = $ $ '<div/>'
86         flip_button = new_button "flip over"
87         mark_button = new_button "mark"
88         flip_button.bind 'click', ->
89                 state.flip state.agent, card.number, ! view.hasClass 'flipped'
90         mark_button.bind 'click', ->
91                 state.mark state.agent, card.number, ! view.hasClass 'marked'
92         button_box.append flip_button
93         button_box.append mark_button
94         view.append button_box
95         if card.marked
96                 view.addClass 'marked'
97         if card.flipped
98                 view.addClass 'flipped'
99         $table.append view
100         view.draggable containment: '#table', grid: [20, 20]
101         view.bind 'dragstart', (event, ui) ->
102                 view.css 'z-index': card.z = next_card_z()
103                 if card.pile?
104                         delete card.pile
105                 update_pile_views()
106         view.bind 'dragstop', (event, ui) ->
107                 p = view.position()
108                 x = transform_x(p.left)
109                 y = transform_y(p.top)
110                 pile = find_pile x, y
111                 if pile?
112                         x = pile.x
113                         y = pile.y
114                         pile = pile.key
115                         view.css {left: transform_x(x), top: transform_y(y)}
116                 state.move state.agent, card.number, x, y, card.z, pile
117
118 error_lag = 3
119
120 outgoing_messages = []
121 # message should be [agent, method, args...]
122 # don't forget the agent (state.agent)
123 tell_server = (message) ->
124         outgoing_messages.push message
125         send_updates()
126
127 send_updates = ->
128         return if outgoing_messages.length is 0
129
130         messages = outgoing_messages
131         outgoing_messages = []
132
133         $.ajax "#{server_url}/set", {
134                 cache: false
135                 data: {
136                         agent: state.agent
137                         game: 'test' # FIXME, and in the /get call too
138                         messages: JSON.stringify(messages)
139                 }
140                 type: 'POST'
141                 dataType: 'json'
142                 error: (xhr, status, error) ->
143                         show_message "Network error while sending, you might want to refresh. Trying again in #{error_lag} seconds. (Status: #{status}, Error: #{error})"
144                         for message in messages
145                                 outgoing_messages.unshift message
146                         timeout error_lag * 1000, send_updates
147                         error_lag *= 2
148                 success: (data, status, xhr) ->
149                         show_message "update sent"
150                         error_lag = 3
151         }
152
153 error_lag = 3
154 poll_for_updates = ->
155         $.ajax "#{server_url}/get?agent=#{state.agent}&game=test", {
156                 cache: false
157                 type: 'GET'
158                 dataType: 'json'
159                 error: (xhr, status, error) ->
160                         show_message "Network error, you might want to refresh. Trying again in #{error_lag} seconds. (Status: #{status}, Error: #{error})"
161                         timeout error_lag * 1000, poll_for_updates
162                         error_lag *= 2
163                 success: (data, status, xhr) ->
164                         state.process_messages data
165                         timeout 100, poll_for_updates
166                         error_lag = 3
167         }
168
169 n_cards = (count) ->
170         return "#{count} cards" unless count is 1
171         return "1 card"
172
173 initialize_cards = () ->
174         show_message 'initialize_cards'
175         $('.card').remove()
176         top_card_z = 0
177         # instantiate cards in play
178         for card in state.cards
179                 delete card.view
180                 instantiate_card card unless card.pile?
181
182         unless piles?
183                 piles = [ # global
184                         {key: 'p2_draw', x: 140, y: 20, name: "Draw Pile"}
185                         {key: 'p2_discard', x: 20, y: 20, name: "Discard Pile"}
186                         {key: 'p1_draw', x: flip_x(140), y: flip_y(20), name: "Draw Pile"}
187                         {key: 'p1_discard', x: flip_x(20), y: flip_y(20), name: "Discard Pile"}
188                 ]
189                 for pile in piles
190                         if pile.key.substr(0, 2) is state.agent
191                                 css_class = 'my_card'
192                         else
193                                 css_class = 'your_card'
194                         pile.$blank = new_blank_card pile.x, pile.y, css_class
195                         pile.$caption = $ $ "<div class=\"pile_caption\"><div>#{pile.name}:</div><div class=\"n_cards\">#{n_cards 0}</div></div>"
196
197         update_pile_views()
198
199 update_pile_views = ->
200         ps = {}
201         for card in state.cards
202                 if card.pile?
203                         if ps[card.pile]?
204                                 ps[card.pile].total += 1
205                                 if card.z > ps[card.pile].top_z
206                                         if ps[card.pile].top_card.view?
207                                                 uninstantiate_card ps[card.pile].top_card
208                                         ps[card.pile].top_card = card
209                                         ps[card.pile].top_z = card.z
210                                 else if card.view
211                                         uninstantiate_card card
212                         else
213                                 ps[card.pile] = { total: 1, top_card: card, top_z: card.z }
214
215         for pile in piles
216                 # where should the caption be?
217                 if ps[pile.key]?
218                         unless ps[pile.key].top_card.view?
219                                 ps[pile.key].top_card.x = pile.x
220                                 ps[pile.key].top_card.y = pile.y
221                                 instantiate_card ps[pile.key].top_card
222                         caption_dest = ps[pile.key].top_card.view
223                 else
224                         caption_dest = pile.$blank
225                 if caption_dest isnt pile.caption_loc
226                         pile.$caption.detach()
227                         caption_dest.append pile.$caption
228                         pile.caption_loc = caption_dest
229
230                 # update caption to show correct number of cards in the pile
231                 card_count = 0
232                 card_count = ps[pile.key].total if ps[pile.key]?
233                 pile.$caption.children('.n_cards').html n_cards card_count
234
235
236 init = ->
237         if window.location.hash? and window.location.hash.length > 0
238                 me = window.location.hash.substr 1
239                 winloc = "#{window.location}"
240                 server_url = winloc.substr 0, winloc.length - window.location.hash.length
241         else
242                 me = 'p1'
243                 server_url = window.location
244
245         state = window.game_model.new me
246         state.on 'move', (agent, card, x, y, z, pile) ->
247                 update_pile_views()
248                 if agent is me
249                         tell_server ['move', agent, card, x, y, z, pile]
250                 else
251                         # FIXME use the z from the server
252                         bring_card_to_front state.cards[card]
253                         state.cards[card].view.animate { left: "#{transform_x x}px", top: "#{transform_y y}px"}, 800
254         state.on 'mark', (agent, card, state) ->
255                 @cards[card].view.toggleClass 'marked', state
256                 if agent is me
257                         tell_server ['mark', agent, card, state]
258         state.on 'flip', (agent, card, state) ->
259                 @cards[card].view.toggleClass 'flipped', state
260                 if agent is me
261                         tell_server ['flip', agent, card, state]
262         state.on 'set_cards', (agent, cards) ->
263                 initialize_cards()
264                 if agent is me
265                         tell_server ['set_cards', agent, cards]
266
267         # timeout so browser will stop showing that we're loading
268         timeout 1, poll_for_updates
269         timeout 2, ->
270                 # ask for initial state
271                 tell_server ['send_state', state.agent]
272
273 $ ->
274         $table = $ '#table'
275         table_width = $table.width()
276         table_height = $table.height()
277         card_width = $('#loading-card').outerWidth()
278         card_height = $('#loading-card').outerHeight()
279
280         init()