JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Let drags go off the edge
[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 = ->
48         top_card_z += 1
49         # p1 gets even numbers, p2 gets odd numbers
50         if state.agent is 'p1'
51                 top_card_z += top_card_z % 2
52         else
53                 top_card_z += 1 - (top_card_z % 2)
54
55         show_message "new z: #{top_card_z}"
56
57         return top_card_z
58
59
60 new_blank_card = (x, y, css_class) ->
61         view = $ $ "<div class=\"blank_card #{css_class}\" style=\"left: #{transform_x x}px; top: #{transform_y y}px; z-index: 0\"></div>"
62         $table.append view
63         return view
64
65 find_pile = (x, y) ->
66         fudge = 40
67         for pile in piles
68                 if -fudge < pile.x - x < fudge and -fudge < pile.y - y < fudge
69                         return pile
70         return null
71
72 in_your_hand = (card) ->
73         return (not (card.pile?)) and ((transform_y card.y) < (card_height * 0.8))
74
75 uninstantiate_card = (card) ->
76         show_message "uninstantiate card #{card.number}"
77         card.view.remove()
78         delete card.view
79
80 instantiate_card = (card) ->
81         show_message "instantiate card #{card.number}"
82         if card.view
83                 die.a.horrible.death()
84
85         text = card.text
86         if card.owner is state.agent
87                 card_class = 'my_card'
88         else
89                 card_class = 'your_card'
90
91         if in_your_hand card
92                 card_class = "#{card_class} your_hand"
93
94         if card.z > top_card_z
95                 top_card_z = card.z
96
97         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>"
98         card.view = view
99         button_box = $ $ '<div/>'
100         flip_button = new_button "flip over"
101         mark_button = new_button "mark"
102         flip_button.bind 'click', ->
103                 state.flip state.agent, card.number, ! view.hasClass 'flipped'
104         mark_button.bind 'click', ->
105                 state.mark state.agent, card.number, ! view.hasClass 'marked'
106         button_box.append flip_button
107         button_box.append mark_button
108         view.append button_box
109         if card.marked
110                 view.addClass 'marked'
111         if card.flipped
112                 view.addClass 'flipped'
113         $table.append view
114         view.draggable grid: [20, 20]
115         view.bind 'dragstart', (event, ui) ->
116                 view.css 'z-index': card.z = next_card_z()
117                 if card.pile?
118                         delete card.pile
119                 update_pile_views()
120         view.bind 'dragstop', (event, ui) ->
121                 p = view.position()
122                 x = transform_x(p.left)
123                 y = transform_y(p.top)
124                 pile = find_pile x, y
125                 if pile?
126                         x = pile.x
127                         y = pile.y
128                         pile = pile.key
129                         view.css {left: transform_x(x), top: transform_y(y)}
130                 state.move state.agent, card.number, x, y, card.z, pile
131
132 error_lag = 3
133
134 outgoing_messages = []
135 # message should be [agent, method, args...]
136 # don't forget the agent (state.agent)
137 tell_server = (message) ->
138         outgoing_messages.push message
139         send_updates()
140
141 send_updates = ->
142         return if outgoing_messages.length is 0
143
144         messages = outgoing_messages
145         outgoing_messages = []
146
147         $.ajax "#{server_url}/set", {
148                 cache: false
149                 data: {
150                         agent: state.agent
151                         game: 'test' # FIXME, and in the /get call too
152                         messages: JSON.stringify(messages)
153                 }
154                 type: 'POST'
155                 dataType: 'json'
156                 error: (xhr, status, error) ->
157                         show_message "Network error while sending, you might want to refresh. Trying again in #{error_lag} seconds. (Status: #{status}, Error: #{error})"
158                         for message in messages
159                                 outgoing_messages.unshift message
160                         timeout error_lag * 1000, send_updates
161                         error_lag *= 2
162                 success: (data, status, xhr) ->
163                         show_message "update sent"
164                         error_lag = 3
165         }
166
167 error_lag = 3
168 poll_for_updates = ->
169         $.ajax "#{server_url}/get?agent=#{state.agent}&game=test", {
170                 cache: false
171                 type: 'GET'
172                 dataType: 'json'
173                 error: (xhr, status, error) ->
174                         show_message "Network error, you might want to refresh. Trying again in #{error_lag} seconds. (Status: #{status}, Error: #{error})"
175                         timeout error_lag * 1000, poll_for_updates
176                         error_lag *= 2
177                 success: (data, status, xhr) ->
178                         state.process_messages data
179                         timeout 100, poll_for_updates
180                         error_lag = 3
181         }
182
183 n_cards = (count) ->
184         return "#{count} cards" unless count is 1
185         return "1 card"
186
187 initialize_cards = () ->
188         show_message 'initialize_cards'
189         $('.card').remove()
190         top_card_z = 0
191         # instantiate cards in play
192         hide_deck_designer = false
193         for card in state.cards
194                 if card.owner is state.agent
195                         hide_deck_designer = true
196                 delete card.view
197
198         if hide_deck_designer
199                 $('#deck_designer').remove()
200
201         unless piles?
202                 piles = [ # global
203                         {key: 'p2_draw', x: 140, y: 20, name: "Draw Pile"}
204                         {key: 'p2_discard', x: 20, y: 20, name: "Discard Pile"}
205                         {key: 'p1_draw', x: flip_x(140), y: flip_y(20), name: "Draw Pile"}
206                         {key: 'p1_discard', x: flip_x(20), y: flip_y(20), name: "Discard Pile"}
207                 ]
208                 for pile in piles
209                         if pile.key.substr(0, 2) is state.agent
210                                 css_class = 'my_card'
211                         else
212                                 css_class = 'your_card'
213                         pile.$blank = new_blank_card pile.x, pile.y, css_class
214                         pile.$caption = $ $ "<div class=\"pile_caption\"><div>#{pile.name}:</div><div class=\"n_cards\">#{n_cards 0}</div></div>"
215
216         update_pile_views()
217
218 # also makes sure all non-piled cards are instantiated
219 update_pile_views = ->
220         ps = {}
221         for card in state.cards
222                 if card.pile?
223                         if ps[card.pile]?
224                                 ps[card.pile].total += 1
225                                 if card.z > ps[card.pile].top_z
226                                         if ps[card.pile].top_card.view?
227                                                 uninstantiate_card ps[card.pile].top_card
228                                         ps[card.pile].top_card = card
229                                         ps[card.pile].top_z = card.z
230                                 else if card.view
231                                         uninstantiate_card card
232                         else
233                                 ps[card.pile] = { total: 1, top_card: card, top_z: card.z }
234                 else
235                         # not in a pile
236                         instantiate_card card unless card.view?
237
238         for pile in piles
239                 # where should the caption be?
240                 if ps[pile.key]?
241                         unless ps[pile.key].top_card.view?
242                                 ps[pile.key].top_card.x = pile.x
243                                 ps[pile.key].top_card.y = pile.y
244                                 instantiate_card ps[pile.key].top_card
245                         caption_dest = ps[pile.key].top_card.view
246                 else
247                         caption_dest = pile.$blank
248                 if caption_dest isnt pile.caption_loc
249                         pile.$caption.detach()
250                         caption_dest.append pile.$caption
251                         pile.caption_loc = caption_dest
252
253                 # update caption to show correct number of cards in the pile
254                 card_count = 0
255                 card_count = ps[pile.key].total if ps[pile.key]?
256                 pile.$caption.children('.n_cards').html n_cards card_count
257
258 possible_cards = {}
259
260 valumenous = (val) -> return true unless val is '' or val is ' '
261
262 init_possible_cards = ->
263         for card in window.cs_cards
264                 text = "#{card.cardname} (#{card.faction})"
265                 if valumenous card.attack or valumenous card.defense
266                         text += "  #{card.attack}/#{card.defense}"
267                 text += "<br>#{card.type}"
268                 if valumenous card.subtype
269                         text += " &bull; #{card.subtype}"
270                 text += "<br>cost: #{card.cost} thresh: #{card.threshold}<br>"
271                 text += card.rules
272
273                 summary = text.replace(/<br>/g, "\n")
274
275                 possible_cards[card.id] = {id: card.id, text: text, summary: summary}
276
277
278 init_card_designer = ->
279         show_message 'init_card_designer'
280         cards_in_deck = {}
281         container = $ '#deck_designer'
282         init_possible_cards()
283         ul = $ $ '<ul/>'
284         for key, card of possible_cards
285                 view = $ $ "<li>#{card.summary}</li>"
286                 view.data 'id', card.id
287                 view.bind 'click', ->
288                         $el = $ this
289                         id = $el.data 'id'
290                         if cards_in_deck[id]?
291                                 delete cards_in_deck[id]
292                                 value = false
293                         else
294                                 value = true
295                                 cards_in_deck[id] = true
296                         $el.toggleClass 'in_deck', value
297                 ul.append view
298
299         container.append ul
300
301         submit = $ $ "<div style=\"border: 1px solid black; margin: 0 auto 10px 10px; width: 40px; text-align: center\">Done</div>"
302         submit.bind 'click', ->
303                 $('#deck_designer').remove()
304                 show_message cards_in_deck
305                 cards = []
306                 for key, value of cards_in_deck
307                         card = {
308                                 text: possible_cards[key].text
309                                 owner: state.agent
310                                 pile: "#{state.agent}_draw"
311                                 x: 0
312                                 y: 0
313                                 flipped: true
314                         }
315                         cards.push card
316                         cards.push $.extend {}, card # clone
317                         cards.push $.extend {}, card # clone
318                         cards.push $.extend {}, card # clone
319
320                 # asign z-index in random order
321                 cards.shuffle()
322                 for card in cards
323                         card.z = next_card_z()
324                 show_message cards
325
326                 # let server assign card numbers
327                 tell_server ['new_cards', state.agent, cards]
328
329
330         container.append submit
331
332 init = ->
333         if window.location.hash? and window.location.hash.length > 0
334                 me = window.location.hash.substr 1
335                 winloc = "#{window.location}"
336                 server_url = winloc.substr 0, winloc.length - window.location.hash.length
337         else
338                 me = 'p1'
339                 server_url = window.location
340
341         state = window.game_model.new me
342         state.on 'move', (agent, card, x, y, z, pile) ->
343                 if z > top_card_z
344                         top_card_z = z
345                 update_pile_views() # ensures instantiation of all visible cards
346                 if @cards[card].view? # the card is visible
347                         # show it face down if it's in the other player's hand
348                         @cards[card].view.toggleClass 'your_hand', in_your_hand @cards[card]
349
350                 if agent is me
351                         tell_server ['move', agent, card, x, y, z, pile]
352                 else
353                         if @cards[card].view?
354                                 @cards[card].view.css "z-index": z
355                                 @cards[card].view.animate { left: "#{transform_x x}px", top: "#{transform_y y}px"}, 800
356         state.on 'mark', (agent, card, state) ->
357                 if @cards[card].view?
358                         @cards[card].view.toggleClass 'marked', state
359                 if agent is me
360                         tell_server ['mark', agent, card, state]
361         state.on 'flip', (agent, card, state) ->
362                 if @cards[card].view?
363                         @cards[card].view.toggleClass 'flipped', state
364                 if agent is me
365                         tell_server ['flip', agent, card, state]
366         state.on 'set_cards', (agent, cards) ->
367                 if agent is me
368                         tell_server ['set_cards', agent, cards]
369                 initialize_cards()
370         state.on 'new_cards', (agent, cards) ->
371                 initialize_cards()
372
373         # timeout so browser will stop showing that we're loading
374         timeout 1, init_card_designer
375         timeout 1, poll_for_updates
376         timeout 2, ->
377                 # ask for initial state
378                 tell_server ['send_state', state.agent]
379
380 $ ->
381         $table = $ '#table'
382         table_width = $table.width()
383         table_height = $table.height()
384         card_width = $('#loading_card').outerWidth()
385         card_height = $('#loading_card').outerHeight()
386
387         init()