JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Change the new tile animation
[hexbog.git] / main.coffee
1 #   HexBog, a word game
2 #   Copyright (C) 2012 Jason Woofenden
3
4 #   This program is free software: you can redistribute it and/or modify
5 #   it under the terms of the GNU Affero General Public License as published by
6 #   the Free Software Foundation, either version 3 of the License, or
7 #   (at your option) any later version.
8
9 #   This program is distributed in the hope that it will be useful,
10 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #   GNU Affero General Public License for more details.
13
14 #   You should have received a copy of the GNU Affero General Public License
15 #   along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 ##############################################
18 ##############    settings    ################
19 ##############################################
20
21 tile_radius = 26
22 tile_width = tile_radius * 2
23
24 fade_ms = 400
25 slide_ms = 2000
26
27 board_col_heights = [5, 6, 7, 8, 7, 6, 5]
28
29
30 ##############################################################
31 ##############    fix javascript some more    ################
32 ##############################################################
33
34 # so annoying that setTimeout has its arguments in the wrong order
35 timeout = (ms, callback) ->
36         setTimeout callback, ms
37
38 # warning: it's shalow (sub-elements are not cloned)
39 Array::clone = ->
40         return this.slice(0)
41
42 Array::sum = ->
43         ret = 0
44         ret += i for i in this
45         return ret
46
47 # ascending. All values must be Numbers
48 Array::num_sort = -> return this.sort((a, b) -> return a - b)
49
50 Array::last = ->
51         return this[this.length - 1]
52
53
54 ##############################################################
55 ##############    cookies (auto-save game)    ################
56 ##############################################################
57
58 set_cookie = (name, value, days) ->
59         date = new Date()
60         date.setTime date.getTime()+(days*24*60*60*1000)
61         cookie = "#{name}=#{value}; expires=#{date.toGMTString()}; path=/"
62         document.cookie = cookie
63 window.sc = set_cookie
64
65 get_cookie = (name) ->
66         key = name + '='
67         for c in document.cookie.split /; */
68                 if c.indexOf key is 0
69                         return c.substr key.length
70         return null
71
72 delete_cookie = (name) ->
73         set_cookie name, '', -1
74 window.dc = delete_cookie
75
76
77 board_cols = board_col_heights.length
78 board_tiles = board_col_heights.sum()
79 board_col_top_px = []
80 score = 0
81 board = new Array(board_tiles) # letters ("Qu" or single letter)
82 board_neighbors = [] # array of tile numbers "next to" this one
83 tile_top_px = [] # array of pixel coordinates for top of column
84 board_left_px = [] # array of pixel coordinates for left of column
85 board_aboves = [] # array of tile numbers above, starting from top
86 board_below = [] # tile number of next tile below or false
87
88 slides = []
89 selected = []
90
91 letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
92 letter_distribution = [
93         14355 # a
94          3968 # b
95          6325 # c
96          7045 # d
97         20258 # e
98          2739 # f
99          5047 # g
100          4372 # h
101         13053 # i
102           516 # j
103          2600 # k
104          9631 # l
105          5115 # m
106         10082 # n
107         11142 # o
108          5292 # p
109           287 # qu
110         12341 # r
111         16571 # s
112         10215 # t
113          6131 # u
114          1728 # v
115          2184 # w
116           619 # x
117          3512 # y
118           831 # z
119
120 ]
121
122 letter_distribution_total = 175973 # letter_distribution.sum()
123
124
125 new_letter_queue = []
126 new_letter = ->
127         if new_letter_queue.length
128                 l = new_letter_queue.shift()
129                 if l is 'Q'
130                         return 'Qu'
131                 else
132                         return l
133         r = Math.floor Math.random() * (letter_distribution_total + 1)
134         for i in [0..25]
135                 r -= letter_distribution[i]
136                 if r <= 0
137                         if letters[i] is 'Q'
138                                 return 'Qu'
139                         return letters[i]
140         return 'Z' # just in case
141
142
143
144 # in memory it's layed out like this:
145 # a c f j m
146 # b d g k n
147 #   e h l
148 #     i
149 # for display, columns are slid vertically like so:
150 #       f
151 #     c   j
152 #   a   g   m
153 #     d   k
154 #   b   h   n
155 #     e   l
156 #       i
157 #
158 # work out which grid spaces are connected
159 init_board_layout = () ->
160         col_offset = 0
161         middle_col = (board_cols - 1) / 2
162
163         # how many tiles before the current tile?
164         for col_num in [0 .. board_cols - 1]
165                 if col_num < middle_col
166                         fw_other = 1
167                 else
168                         fw_other = -1
169
170                 if col_num > middle_col
171                         bw_other = 1
172                 else
173                         bw_other = -1
174
175                 is_first_col = col_num is 0
176                 is_last_col = col_num is board_cols - 1
177
178                 neighbors = []
179                 push = (offset) ->
180                         neighbors.push col_offset + offset
181
182                 col_top_px = Math.abs col_num - middle_col
183                 col_top_px *= tile_radius
184                 board_col_top_px.push col_top_px
185
186                 above = []
187                 for i in [0 .. board_col_heights[col_num] - 1]
188                         is_top_tile = i is 0
189                         is_bottom_tile = i is board_col_heights[col_num] - 1
190
191                         # link tile number to pixel "top" and "left" of containing column
192                         tile_top_px.push col_top_px + i * tile_width
193                         board_left_px.push col_num * tile_width
194
195                         # aboves (array of tile numbers above, starting from top)
196                         board_aboves.push above.clone()
197                         above.push i + col_offset
198
199                         # below (SINGLE tile number of tile below or false)
200                         if is_bottom_tile
201                                 board_below.push false
202                         else
203                                 board_below.push col_offset + i + 1
204
205                         # neighbors (array of tile numbers "next to" this one)
206                         neighbors = []
207                         unless is_top_tile # upward link
208                                 push i - 1
209                         unless is_bottom_tile # downward links
210                                 push i + 1
211                         unless is_first_col # leftward links
212                                 unless is_bottom_tile and bw_other is -1
213                                         push i - board_col_heights[col_num - 1]
214                                 unless is_top_tile and bw_other is -1
215                                         push i - board_col_heights[col_num - 1] + bw_other
216                         unless is_last_col # rightward links
217                                 unless is_bottom_tile and fw_other is -1
218                                         push i + board_col_heights[col_num]
219                                 unless is_top_tile and fw_other is -1
220                                         push i + board_col_heights[col_num] + fw_other
221
222                         board_neighbors.push neighbors.clone()
223
224                 col_offset += board_col_heights[col_num]
225
226
227 init_board = ->
228         encoded = window.location.hash
229         if encoded? and encoded.charAt 0 is '#'
230                 encoded = encoded.substr 1
231         unless encoded? and encoded.length > board_tiles
232                 encoded = get_cookie 'hexbog'
233         if encoded? and encoded.length > board_tiles
234                 new_letter_queue = (encoded.substr 0, board_tiles).split ''
235                 score = parseInt(encoded.substr(board_tiles), 10)
236
237         # how far each tile needs to be slid down
238         slides = (0 for i in board)
239
240         # work out which grid spaces are connected
241         # (neighbors, above, down)
242         init_board_layout()
243
244 $selection_display = null # initialized by init_html_board
245 $score_display = null # initialized by init_html_board
246 $definition_body = null # initialized by init_html_board
247 update_selection_display = ->
248         word = selected_word()
249         $selection_display.html word
250
251         # color the selected tiles according to whether they're a word or not
252         if word.length
253                 classes = ['selected_word', 'selected']
254                 if is_word word
255                         c = 0
256                 else
257                         c = 1
258                 for num in selected
259                         html_tiles[num].addClass classes[c]
260                         html_tiles[num].removeClass classes[1 - c]
261
262 # unselects the last tile of the selecetion
263 unselect_tile = ->
264         _unselect_tile()
265         update_selection_display()
266
267 _unselect_tile = ->
268         num = selected.pop()
269         html_tile = html_tiles[num]
270         html_tile.removeClass 'selected_word'
271         html_tile.removeClass 'selected'
272
273 unselect_all = ->
274         while selected.length
275                 _unselect_tile()
276         update_selection_display()
277
278 shrink_selection = (leave_count) ->
279         while selected.length > leave_count
280                 _unselect_tile()
281         update_selection_display()
282
283 selected_word = ->
284         word = ''
285         word += board[i] for i in selected
286         return word.toLowerCase()
287
288 html_slide = (num) ->
289         html_tiles[num].animate {top: "#{tile_top_px[num]}px"}, slide_ms
290
291 save_game = ->
292         encoded = ''
293         for t in board
294                 encoded += t.substr 0, 1
295         encoded += score
296         set_cookie 'hexbog', encoded, 365
297         window.location.hash = encoded
298
299 blip_selection = ->
300         faders = selected.clone().num_sort()
301         selected = []
302         for num in faders
303                 html_tiles[num].unbind('click').fadeOut fade_ms
304         timeout fade_ms, ->
305                 top_tile = -1
306                 new_px = 0
307                 new_slide = 0
308                 for fader in faders
309                         cur_top = board_aboves[fader][0]
310                         if cur_top is undefined
311                                 cur_top = fader
312                         if top_tile isnt cur_top
313                                 new_px = -20 - tile_width
314                                 new_slide = 1
315                                 top_tile = cur_top
316                         html_tiles[fader].remove()
317                         dest = fader
318                         aboves = board_aboves[fader].clone().reverse()
319                         for above in aboves
320                                 html_tiles[dest] = html_tiles[above]
321                                 html_tiles[dest].data 'tile_number', dest
322                                 board[dest] = board[above]
323                                 slides[dest] = slides[above] + 1
324                                 --dest
325                         new_tile top_tile, board_left_px[top_tile], new_px
326                         slides[top_tile] = new_slide
327                         new_px -= tile_width
328                         new_px -= 50
329                         new_slide += 1
330                 for i in [0 .. board.length - 1]
331                         if slides[i]
332                                 html_slide i
333                 save_game()
334         update_selection_display()
335
336 activate_selection = ->
337         word = selected_word()
338         if word.length < 3
339                 # FIXME make this a hint
340                 log "Too short: \"#{word}\""
341                 return
342         unless is_word word
343                 # FIXME make this automatically part of the selection display
344                 log "Not on word list: \"#{word}\""
345                 return
346         word_score = Math.round(Math.pow(1.7, word.length))
347         score += word_score
348         $score_display.html score
349         # FIXME make some kind of animation showing score gain
350         log "blipped \"#{word}\" for #{word_score} points"
351         blip_selection()
352         look_up_definition word
353         $('#definition').click()
354
355
356 show_definition = (word, type, definition, language) ->
357         html = "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\">"
358         html += "#{word.substr(0, 1).toUpperCase() + word.substr(1)}</a>, #{type}"
359         if language isnt 'English'
360                 html += " (#{language})"
361         html += ': '
362         html += definition
363         html += '<div id="definition_credit">Definition &copy;<a href="http://en.wiktionary.org/" target="_blank">wiktionary.org</a> CC-BY-SA</div>'
364         $definition_body.html html
365
366
367 select_tile = (num) ->
368         html_tile = html_tiles[num]
369         # html_tile.css backgroundColor: tile_selected_color
370         selected.push num
371         update_selection_display()
372         return
373
374 new_tile = (num, x, y) ->
375         letter = new_letter()
376
377         html_tile = $("<div class=\"tile\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
378         $board.append(html_tile)
379
380         html_tile.data 'tile_number', num
381         board[num] = letter
382         html_tiles[num] = html_tile
383
384         html_tile.click ->
385                 me = $(this)
386                 num = me.data 'tile_number'
387                 if num in selected
388                         nth_of_word = selected.indexOf(num)
389                         first = nth_of_word is 0
390                         last = nth_of_word is selected.length - 1
391
392                         if first and last
393                                 unselect_all() # Clicking only selected letter unselects it
394                         else if first and !last
395                                 shrink_selection 1 # Clicking start of word goes back to just that letter
396                                 # should this unselect all?
397                         else if last
398                                 activate_selection()
399                         else
400                                 shrink_selection nth_of_word + 1
401                 else # (not clicking on selected tile)
402                         if selected.length is 0
403                                 select_tile num
404                         else
405                                 unless num in board_neighbors[selected.last()]
406                                         unselect_all()
407                                 select_tile num
408
409
410 $board = null
411 html_tiles = []
412 init_html_board = ->
413         $('#loading').remove()
414         $selection_display = $('#selection')
415         $score_display = $('#score')
416         $score_display.html score
417         $definition_body = $('#definition_body')
418         $board = $('#board')
419         # make html for board
420         tile_number = 0
421         for col_num in [0 .. board_cols - 1]
422                 for num in [0 .. board_col_heights[col_num] - 1]
423                         x = col_num * tile_width
424                         y = board_col_top_px[col_num] + num * tile_width
425                         new_tile tile_number, x, y
426                         tile_number++
427
428 word_bins = []; word_bins.push(',') for [0...997]
429 hash_word = (word) ->
430         h = 0
431         for i in [0...word.length]
432                 h ^= word.charCodeAt(i) << ((i*3) % 21)
433         return h % 997
434 is_word = (str) ->
435         word_bins[hash_word str].indexOf(",#{str},") > -1
436
437 # this is called automatically by the compressed wordlist
438 parse_word_list = (compressed) ->
439         prefix = ''
440         cap_a = "A".charCodeAt 0
441         i = 0
442         next_chunk = ->
443                 chunk = compressed[i]
444                 for word in chunk.match(/[a-z]*[A-Z]/g)
445                         # the capital letter (at the end of the match) says how many characters
446                         # from the end of the previous word should be removed to create the prefix
447                         # for the next word. "A" for 0, "B" for 1, "C" for 2, etc
448                         bs = word[word.length - 1].charCodeAt(0) - cap_a
449                         word = prefix + word[0 ... word.length - 1]
450                         word_bins[hash_word word] += word + ','
451                         prefix = word[0 ... word.length - bs]
452                 if ++i is compressed.length
453                         return
454                 else
455                         timeout 1, next_chunk
456         timeout 1, next_chunk
457
458 extract_wiktionary_definiton = (html) ->
459         found = false
460         finds = {}
461         language = false
462         part = false
463
464         # clean HTML
465         ##################
466         # when we instantiate the html so we can use dom traversal, the browser
467         # will start loading images and such. This section attempts to mangle the
468         # html so no resources are loaded when the html is parsed.
469
470         # attributes
471         #                            src: <img>, <audio>, etc
472         #                         onload: only <body>?
473         #   archive,codebase,data,usemap: <object>
474         #                           href: <link>
475         #                 id,class,style: background: url(foo.png), etc
476         html = html.replace /(src|onload|archive|codebase|data|usemap|href|style|id|class)=['"][^"']*['"]/ig, '', html
477
478         elements = $(html)
479
480         valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
481
482         elements.each (i, el) ->
483                 #which tag: el.tagName
484                 if el.tagName is 'H2'
485                         # if we found a definition in the previous language section, run with it
486                         # (we only stop for verbs, in hopes of finding one in english)
487                         if found
488                                 return false # break
489                         part = false # mark us not being in a definition section unless the next section finds a part of speach header
490                         language = $(el).text().substr 7
491                 if language and el.tagName is 'H3' or el.tagName is 'H4' # eg yak def uses one for english and one for dutch
492                         part = false
493                         text = $(el).text()
494                         for p in valid_parts
495                                 if text is "[edit] #{p}"
496                                         part = p.toLowerCase()
497                                         # FIXME break
498                 if part and el.tagName is 'OL'
499                         $(el).children().each (i, el) ->
500                                 new_def = $(el).text()
501                                 if new_def.substr(0, 9) is '(obsolete' or new_def.substr(0, 8) is "(archaic"
502                                         key = 'obsolete'
503                                 else
504                                         if part is 'verb'
505                                                 key = 'verb'
506                                         else
507                                                 key = 'nonverb'
508                                 finds[key] ?= [part, new_def, language]
509                                 found = true
510                                 if part is 'verb'
511                                         # verbs are the best! stop scanning when we find one
512                                         return false # break
513                         if found.verb
514                                 return false # break
515
516         part_defs = (finds[i] for i in ['verb', 'nonverb', 'obsolete'] when finds[i])
517         unless part_defs.length
518                 return false
519
520         return part_defs[0]
521
522
523 look_up_definition = (word) ->
524         $definition_body.html "Looking up definition for \"#{word}\"."
525         $.ajax({
526                 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
527                 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
528                 dataType: 'jsonp'
529                 cache: true
530                 success: (data, error_msg, xhr) ->
531                         if data?.parse?.text?['*']?
532                                 tdl = extract_wiktionary_definiton data.parse.text['*']
533                                 if tdl
534                                         show_definition word, tdl[0], tdl[1], tdl[2]
535                         else
536                                 $definition_body.html "Sorry, couldn't find a definition for \"#{word}\"."
537         })
538
539 board_as_txt = ->
540         ret = ''
541         index = 0
542         for i in [0 .. board_min_height * 2]
543                 unless i % 2
544                         ret += '   ' + board[j] for j in [board_min_height + index .. board_tiles - 1] by 2 * board_min_height + 1
545                 else
546                         ret += ' ' + board[j] + '  ' for j in [index .. board_tiles - 1] by 2 * board_min_height + 1
547                         index += 1
548
549                 ret += '\n'
550         return ret
551
552 start_over = ->
553         selected = []
554         score = 0
555         $score_display.html score
556         for i in [0...board_tiles]
557                 selected.push i
558         blip_selection()
559
560 init_start_over_link = ->
561         $('#start-over').click (event) ->
562                 event.preventDefault()
563                 if confirm "Are you sure you want to start over? There is no undo."
564                         start_over()
565
566 cur_tab = 'instructions'
567 tabtab_height = 20
568 tab_height = 150
569 init_tab = (t) ->
570         $('#' + t).click ->
571                 return if t is cur_tab
572                 $('#' + cur_tab).removeClass('selected-tab').addClass('tab').animate({height: tabtab_height}, 1000)
573                 $('#' + t).removeClass('tab').addClass('selected-tab').animate({height: tab_height}, 1000)
574                 cur_tab = t
575 init_tabs = ->
576         for t in ['instructions', 'definition', 'donate', 'restart']
577                 init_tab t
578
579 init_keybinding = ->
580         $(window).keydown (e) ->
581                 switch e.keyCode
582                         when 32, 10, 13
583                                 activate_selection()
584                         when 27
585                                 unselect_all()
586
587 $log = undefined
588 init_log = ->
589         $log = $('#log')
590 log = (msg) ->
591         console.log msg if console.log?
592
593 init_game = ->
594         init_log()
595         if $(window).height() >= 440
596                 $('#centerer').css('margin-top', '25px')
597         init_keybinding()
598         init_tabs()
599         init_board()
600         init_html_board()
601         init_start_over_link()
602
603 $(init_game)