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