2 # Copyright (C) 2012 Jason Woofenden
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.
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.
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/>.
17 ##############################################
18 ############## settings ################
19 ##############################################
22 tile_width = tile_radius * 2
28 { height: 5, spaces: [], fader_count: 0 }
29 { height: 6, spaces: [], fader_count: 0 }
30 { height: 7, spaces: [], fader_count: 0 }
31 { height: 8, spaces: [], fader_count: 0 }
32 { height: 7, spaces: [], fader_count: 0 }
33 { height: 6, spaces: [], fader_count: 0 }
34 { height: 5, spaces: [], fader_count: 0 }
37 # code and css will need adjusting if you change HP_MAX
40 ##############################################################
41 ############## fix javascript some more ################
42 ##############################################################
44 # so annoying that setTimeout has its arguments in the wrong order
45 timeout = (ms, callback) ->
46 setTimeout callback, ms
48 # warning: it's shalow (sub-elements are not cloned)
54 ret += i for i in this
58 return this[this.length - 1]
61 ##############################################################
62 ############## cookies (auto-save game) ################
63 ##############################################################
65 set_cookie = (name, value, days) ->
67 date.setTime date.getTime()+(days*24*60*60*1000)
68 cookie = "#{name}=#{value}; expires=#{date.toGMTString()}; path=/"
69 document.cookie = cookie
70 window.sc = set_cookie
72 get_cookie = (name) ->
74 for c in document.cookie.split /; */
76 return c.substr key.length
79 delete_cookie = (name) ->
80 set_cookie name, '', -1
81 window.dc = delete_cookie
85 num_spaces += column.height for column in columns
87 spaces = new Array(num_spaces)
91 letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
92 letter_distribution = [
122 letter_distribution_total = 175973 # letter_distribution.sum()
125 new_letter_queue = []
127 if new_letter_queue.length
128 l = new_letter_queue.shift()
129 l.letter = l.letter.toUpperCase()
133 hp = 1 + Math.floor(Math.random() * (HP_MAX - 1))
134 r = Math.floor Math.random() * (letter_distribution_total + 1)
136 r -= letter_distribution[i]
139 return letter: 'Qu', hp: hp
140 return letter: letters[i], hp: hp
141 return letter: 'Z', hp: hp # just in case
145 # in memory it's layed out like this:
150 # for display, columns are slid vertically like so:
159 # work out which grid spaces are connected
160 init_board_layout = () ->
162 middle_col_num = (columns.length - 1) / 2
166 for column, col_num in columns
167 if col_num < middle_col_num
172 if col_num > middle_col_num
177 is_first_col = col_num is 0
178 is_last_col = col_num is columns.length - 1
181 # neighbors are integers for now, but get dereferenced later, after we've created all the spaces
183 neighbors.push col_offset + offset
185 col_top_px = Math.abs col_num - middle_col_num
186 col_top_px *= tile_radius
189 for i in [0 ... column.height]
190 space = { id: space_num }
191 spaces[space_num] = space
193 column.spaces.push space
194 space.column = column
197 is_bottom_tile = i is column.height - 1
199 # link tile number to pixel "top" and "left" of containing column
200 space.top_px = col_top_px + i * tile_width
201 space.left_px = col_num * tile_width
203 # aboves: array of spaces, top to bottom
204 space.aboves = above.clone()
207 # below: SINGLE tile below
209 spaces[space.id - 1].below = space
211 # neighbors (array of tile numbers "next to" this one)
213 unless is_top_tile # upward link
215 unless is_bottom_tile # downward links
217 unless is_first_col # leftward links
218 unless is_bottom_tile and bw_other is -1
219 push i - columns[col_num - 1].height
220 unless is_top_tile and bw_other is -1
221 push i - columns[col_num - 1].height + bw_other
222 unless is_last_col # rightward links
223 unless is_bottom_tile and fw_other is -1
224 push i + columns[col_num].height
225 unless is_top_tile and fw_other is -1
226 push i + columns[col_num].height + fw_other
227 # will be dereferenced later
228 space.neighbors = neighbors.clone() # FIXME ?remove ``.clone()``
229 col_offset += column.height
230 # convert all space.neighbors arrays from containing space ids to referencing the space
232 for id, key in s.neighbors
233 s.neighbors[key] = spaces[id]
235 # support obsolete save data format
236 load_game_0 = (encoded) ->
237 letters = (encoded.substr 0, num_spaces).split ''
239 new_letter_queue.push {
241 hp: 1 + Math.floor(Math.random() * (HP_MAX - 1))
243 score = parseInt(encoded.substr(num_spaces), 10)
245 load_game_1 = (encoded) ->
247 encoded = encoded.substr 1
248 score = parseInt(encoded.substr(num_spaces * 3 / 2), 10)
249 for t in [0...(spaces.length * 3 / 2)] by 3
253 char = encoded[t + 2 - d]
254 int += save_charset.indexOf(char)
256 int = Math.floor(int / 11)
257 t2letter = String.fromCharCode(char_a + (int % 26))
258 int = Math.floor(int / 26)
260 int = Math.floor(int / 11)
261 t1letter = String.fromCharCode(char_a + (int % 26))
262 new_letter_queue.push {
266 new_letter_queue.push {
271 load_game = (encoded) ->
272 switch encoded.substr 0, 1
279 encoded = window.location.hash
280 if encoded? and encoded.charAt 0 is '#'
281 encoded = encoded.substr 1
282 unless encoded? and encoded.length > num_spaces
283 encoded = get_cookie 'hexbog'
284 if encoded? and encoded.length > num_spaces
287 # work out which grid spaces are connected
288 # (neighbors, above, down)
291 $big_tip = null # initialized by init_html_board
292 $little_tip = null # initialized by init_html_board
293 $score_display = null # initialized by init_html_board
294 $definition_body = null # initialized by init_html_board
295 update_selection_display = ->
296 word = selected_word()
297 $big_tip.removeClass('good')
301 $little_tip.html "Click more tiles (3 minimum)"
304 if word.indexOf(word.substr(word.length - 1)) < word.length - 1
308 $little_tip.html "Click the #{last}\"#{word.substr(word.length - 1)}\" for #{score_for word} points"
309 $big_tip.html "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\" title=\"click for definition\">#{word}</a>"
310 $big_tip.addClass('good')
313 $little_tip.html "\"#{word}\" is not in the word list."
315 $big_tip.html "← Click a word"
316 $little_tip.html "(tiles must be touching)"
318 # color the selected tiles according to whether they're a word or not
320 classes = ['selected_word', 'selected']
326 tile.dom.addClass classes[c]
327 tile.dom.removeClass classes[1 - c]
329 # unselects the last tile of the selecetion
332 update_selection_display()
335 html_tile = selected.pop().dom
336 html_tile.removeClass 'selected_word'
337 html_tile.removeClass 'selected'
340 while selected.length
342 update_selection_display()
346 word += tile.text for tile in selected
347 return word.toLowerCase()
349 save_charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR'
350 char_a = "a".charCodeAt(0)
352 encoded = '1' # save format
353 for i in [0...spaces.length] by 2
354 int = spaces[i].tile.text.toLowerCase().charCodeAt(0) - char_a
356 int += spaces[i].tile.hp
358 int += spaces[i+1].tile.text.toLowerCase().charCodeAt(0) - char_a
360 int += spaces[i+1].tile.hp
362 encoded += save_charset.substr(int % 44, 1)
363 int = Math.floor(int / 44)
365 set_cookie 'hexbog', encoded, 365
366 window.location.hash = encoded
370 tile.text = new_letter().letter
371 tile.dom.html tile.text
374 # top-level key is word length
375 # arrays are [difficulty] level, easiest to hardest
380 force: [2,2,1,1,1,1,0]
382 neighbor_neighbors: {
393 flips: ['all', 4,4,4,4,4,3,3,2,2,1]
394 force: [4,3,3,3,3,3,2]
396 neighbor_neighbors: {
398 force: [2,2,2,1,1,1,0]
407 flips: ['all','all','all','all',5,5,5,4,4,4,3,3,3,2]
408 force: [6,6,6,6,5,5,5,4,4,4,3]
410 neighbor_neighbors: {
411 flips: [2,2,2,2,2,2,1,1,1,1,0]
412 force: [4,3,3,3,3,2,2,2,1]
421 flips: ['all','all','all','all','all',9,9,9,9,8,8,8,7,7,7,6,6,6,5,5,5,4]
422 force: [9,9,9,9,9,8,8,8,7]
424 neighbor_neighbors: {
425 flips: [5,5,5,5,5,5,5,4,4,4,3,3,3,2,2,2,1]
426 force: [6,6,5,5,4,4,3,3,2]
438 neighbor_neighbors: {
439 flips: ['all','all','all','all',9,8,7,6,5,4,3,2]
452 neighbor_neighbors: {
464 adjust_difficulty_level = ->
465 while score > next_level_at
466 difficulty_level += 1
470 # remove the selected tiles from the board, create new tiles, and slide everything into place
472 adjust_difficulty_level()
473 word_length = selected_word().length
476 update_selection_display()
480 tile.dom.unbind('click').fadeOut fade_ms
481 tile.new_hp = tile.hp
482 for n in tile.space.neighbors
483 neighbors[n.id] = n.tile
484 for nn in n.neighbors
485 nneighbors[nn.id] = nn.tile
486 # fix overlaps of faders, neighors, nneighbors
488 delete nneighbors[tile.space.id]
489 delete neighbors[tile.space.id]
490 for k, v of neighbors
492 # convert to arrays so we can sort, etc
493 nneighbors = (v for k, v of nneighbors)
494 neighbors = (v for k, v of neighbors)
501 neighbor_neighbors: {
507 tiles: (space.tile for space in spaces)
519 boom = booms[word_length]
522 for area_name, effects of boom
523 area = areas[area_name]
524 if difficulty_level < effects.flips.length
525 flips = effects.flips[difficulty_level]
527 flips = effects.flips.last()
528 if flips is 'all' or flips >= area.down.length
532 down_count = area.down.length
534 while flips_left > 0 and down_count > 0
536 flipper = Math.floor(Math.random() * down_count)
537 unsink area.down[flipper]
539 # move the last tile back into range
540 area.down[flipper] = area.down[down_count]
541 if difficulty_level < effects.force.length
542 force = effects.force[difficulty_level]
544 force = effects.force.last()
547 tile.new_hp = tile.hp + force
549 s.tile.new_hp ?= s.tile.hp - 1
552 else if s.tile.new_hp > HP_MAX
553 s.tile.new_hp = HP_MAX
554 if s.tile.new_hp isnt s.tile.hp
555 s.tile.dom.removeClass "hp#{s.tile.hp}"
556 s.tile.dom.addClass "hp#{s.tile.new_hp}"
557 s.tile.hp = s.tile.new_hp
559 timeout fade_ms + 1, ->
560 # delete old tiles, mark where tiles are moving
562 fader.space.column.fader_count += 1
565 for above in fader.space.aboves
569 above.tile.dest = above.id + 1
571 # move tiles down (graphically and in data structure)
577 if tile.dest? and not (tile.removed?)
578 dest_space = spaces[tile.dest]
580 tile.dom.animate {top: "#{dest_space.top_px}px"}, slide_ms
581 tile.space = dest_space
582 dest_space.tile = tile
585 for column in columns
587 while column.fader_count > 0
588 column.fader_count -= 1
589 slide_from = -10 - tile_width
590 slide_from -= (50 + tile_width) * column.fader_count
591 space = column.spaces[dest++]
592 tile = new_tile space, slide_from
593 tile.dom.animate {top: "#{space.top_px}px"}, slide_ms
597 score_for = (word) -> Math.round(Math.pow(1.7, word.length))
599 activate_selection = ->
600 word = selected_word()
602 # FIXME make this a hint
603 log "Too short: \"#{word}\""
606 # FIXME make this automatically part of the selection display
607 log "Not on word list: \"#{word}\""
609 word_score = score_for word
611 $score_display.html score
612 # FIXME make some kind of animation showing score gain
614 look_up_definition word
615 $('#definition').click()
618 show_definition = (word, type, definition, language) ->
619 html = "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\">"
620 html += "#{word.substr(0, 1).toUpperCase() + word.substr(1)}</a>, #{type}"
621 if language isnt 'English'
622 html += " (#{language})"
625 html += '<div id="definition_credit">Definition ©<a href="http://en.wiktionary.org/" target="_blank">wiktionary.org</a> CC-BY-SA</div>'
626 $definition_body.html html
629 select_tile = (tile) ->
631 update_selection_display()
633 new_tile = (space, y) ->
639 html_tile = $("<div class=\"tile hp#{hp}\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
640 $board.append(html_tile)
652 return unselect_all() if tile.hp < 1
653 word = selected_word()
655 if selected_word().length > 2 and is_word(word) and tile is selected.last()
658 if selected.length is 1
663 else # clicked a non-selected tile
664 if selected.length > 0 and not (tile.space in selected.last().space.neighbors)
671 $('#loading').remove()
672 $big_tip = $('#big_tip')
673 $little_tip = $('#little_tip')
674 $score_display = $('#score')
675 $score_display.html score
676 $definition_body = $('#definition_body')
678 # make html for board
682 word_bins = []; word_bins.push(',') for [0...997]
683 hash_word = (word) ->
685 for i in [0...word.length]
686 h ^= word.charCodeAt(i) << ((i*3) % 21)
689 word_bins[hash_word str].indexOf(",#{str},") > -1
691 # this is called automatically by the compressed wordlist
692 parse_word_list = (compressed) ->
694 cap_a = "A".charCodeAt 0
697 chunk = compressed[i]
698 for word in chunk.match(/[a-z]*[A-Z]/g)
699 # the capital letter (at the end of the match) says how many characters
700 # from the end of the previous word should be removed to create the prefix
701 # for the next word. "A" for 0, "B" for 1, "C" for 2, etc
702 bs = word[word.length - 1].charCodeAt(0) - cap_a
703 word = prefix + word[0 ... word.length - 1]
704 word_bins[hash_word word] += word + ','
705 prefix = word[0 ... word.length - bs]
706 if ++i is compressed.length
709 timeout 1, next_chunk
710 timeout 1, next_chunk
712 extract_wiktionary_definiton = (html) ->
720 # when we instantiate the html so we can use dom traversal, the browser
721 # will start loading images and such. This section attempts to mangle the
722 # html so no resources are loaded when the html is parsed.
725 # src: <img>, <audio>, etc
726 # onload: only <body>?
727 # archive,codebase,data,usemap: <object>
729 # id,class,style: background: url(foo.png), etc
730 html = html.replace /[ ]?[a-z]+=['"][^"']*['"]/ig, '', html
731 html = html.replace /<\/?(audio|source|a|span|table|tr|td|table)>/ig, '', html
732 html = html.replace /\[edit\]/ig, '', html
736 valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
738 elements.each (i, el) ->
739 #which tag: el.tagName
740 if el.tagName is 'H2'
741 # if we found a definition in the previous language section, run with it
742 # (we only stop for verbs, in hopes of finding one in english)
745 part = false # mark us not being in a definition section unless the next section finds a part of speach header
746 language = $(el).text()
747 if language and el.tagName is 'H3' or el.tagName is 'H4' # eg yak def uses one for english and one for dutch
752 part = p.toLowerCase()
754 if part and el.tagName is 'OL'
755 $(el).children().each (i, el) ->
756 new_def = $(el).text()
757 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 "
764 finds[key] ?= [part, new_def, language]
767 # verbs are the best! stop scanning when we find one
772 part_defs = (finds[i] for i in ['verb', 'nonverb', 'lame'] when finds[i])
773 unless part_defs.length
779 look_up_definition = (word) ->
780 $definition_body.html "Looking up definition for \"#{word}\"..."
782 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
783 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
786 success: (data, error_msg, xhr) ->
787 if data?.parse?.text?['*']?
788 tdl = extract_wiktionary_definiton data.parse.text['*']
790 show_definition word, tdl[0], tdl[1], tdl[2]
792 $definition_body.html "Oops, could't find a definition for \"#{word}\"."
794 $definition_body.html "Sorry, couldn't find a definition for \"#{word}\"."
802 $score_display.html score
807 init_start_over_link = ->
808 $('#start-over').click (event) ->
809 event.preventDefault()
810 if confirm "Are you sure you want to start over? There is no undo."
813 cur_tab = 'instructions'
818 return if t is cur_tab
819 $('#' + cur_tab).removeClass('selected-tab').addClass('tab').animate({height: tabtab_height}, 1000)
820 $('#' + t).removeClass('tab').addClass('selected-tab').animate({height: tab_height}, 1000)
823 for t in ['instructions', 'definition', 'donate', 'restart']
827 $(window).keydown (e) ->
835 console.log args... if console?.log?
838 if $(window).height() >= 440
839 $('#centerer').css('margin-top', '25px')
844 init_start_over_link()
845 update_selection_display()