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
27 board_col_heights = [5, 6, 7, 8, 7, 6, 5]
29 # code and css will need adjusting if you change HP_MAX
32 ##############################################################
33 ############## fix javascript some more ################
34 ##############################################################
36 # so annoying that setTimeout has its arguments in the wrong order
37 timeout = (ms, callback) ->
38 setTimeout callback, ms
40 # warning: it's shalow (sub-elements are not cloned)
46 ret += i for i in this
49 # ascending. All values must be Numbers
50 Array::num_sort = -> return this.sort((a, b) -> return a - b)
53 return this[this.length - 1]
56 ##############################################################
57 ############## cookies (auto-save game) ################
58 ##############################################################
60 set_cookie = (name, value, days) ->
62 date.setTime date.getTime()+(days*24*60*60*1000)
63 cookie = "#{name}=#{value}; expires=#{date.toGMTString()}; path=/"
64 document.cookie = cookie
65 window.sc = set_cookie
67 get_cookie = (name) ->
69 for c in document.cookie.split /; */
71 return c.substr key.length
74 delete_cookie = (name) ->
75 set_cookie name, '', -1
76 window.dc = delete_cookie
79 board_cols = board_col_heights.length
80 board_tiles = board_col_heights.sum()
83 tiles = new Array(board_tiles)
84 board_neighbors = [] # array of tile numbers "next to" this one
85 tile_top_px = [] # array of pixel coordinates for top of column
86 board_left_px = [] # array of pixel coordinates for left of column
87 board_aboves = [] # array of tile numbers above, starting from top
88 board_below = [] # tile number of next tile below or false
92 letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
93 letter_distribution = [
123 letter_distribution_total = 175973 # letter_distribution.sum()
126 new_letter_queue = []
128 if new_letter_queue.length
129 l = new_letter_queue.shift()
130 l.letter = l.letter.toUpperCase()
134 hp = 1 + Math.floor(Math.random() * (HP_MAX - 1))
135 r = Math.floor Math.random() * (letter_distribution_total + 1)
137 r -= letter_distribution[i]
140 return letter: 'Qu', hp: hp
141 return letter: letters[i], hp: hp
142 return letter: 'Z', hp: hp # just in case
146 # in memory it's layed out like this:
151 # for display, columns are slid vertically like so:
160 # work out which grid spaces are connected
161 init_board_layout = () ->
163 middle_col = (board_cols - 1) / 2
165 # how many tiles before the current tile?
166 for col_num in [0 .. board_cols - 1]
167 if col_num < middle_col
172 if col_num > middle_col
177 is_first_col = col_num is 0
178 is_last_col = col_num is board_cols - 1
182 neighbors.push col_offset + offset
184 col_top_px = Math.abs col_num - middle_col
185 col_top_px *= tile_radius
186 board_col_top_px.push col_top_px
189 for i in [0 .. board_col_heights[col_num] - 1]
191 is_bottom_tile = i is board_col_heights[col_num] - 1
193 # link tile number to pixel "top" and "left" of containing column
194 tile_top_px.push col_top_px + i * tile_width
195 board_left_px.push col_num * tile_width
197 # aboves (array of tile numbers above, starting from top)
198 board_aboves.push above.clone()
199 above.push i + col_offset
201 # below (SINGLE tile number of tile below or false)
203 board_below.push false
205 board_below.push col_offset + i + 1
207 # neighbors (array of tile numbers "next to" this one)
209 unless is_top_tile # upward link
211 unless is_bottom_tile # downward links
213 unless is_first_col # leftward links
214 unless is_bottom_tile and bw_other is -1
215 push i - board_col_heights[col_num - 1]
216 unless is_top_tile and bw_other is -1
217 push i - board_col_heights[col_num - 1] + bw_other
218 unless is_last_col # rightward links
219 unless is_bottom_tile and fw_other is -1
220 push i + board_col_heights[col_num]
221 unless is_top_tile and fw_other is -1
222 push i + board_col_heights[col_num] + fw_other
224 board_neighbors.push neighbors.clone()
226 col_offset += board_col_heights[col_num]
228 # support obsolete save data format
229 load_game_0 = (encoded) ->
230 letters = (encoded.substr 0, board_tiles).split ''
232 new_letter_queue.push {
234 hp: 1 + Math.floor(Math.random() * (HP_MAX - 1))
236 score = parseInt(encoded.substr(board_tiles), 10)
238 load_game_1 = (encoded) ->
240 encoded = encoded.substr 1
241 score = parseInt(encoded.substr(board_tiles * 3 / 2), 10)
242 for t in [0...(tiles.length * 3 / 2)] by 3
246 char = encoded[t + 2 - d]
247 int += save_charset.indexOf(char)
249 int = Math.floor(int / 11)
250 t2letter = String.fromCharCode(char_a + (int % 26))
251 int = Math.floor(int / 26)
253 int = Math.floor(int / 11)
254 t1letter = String.fromCharCode(char_a + (int % 26))
255 new_letter_queue.push {
259 new_letter_queue.push {
264 load_game = (encoded) ->
265 switch encoded.substr 0, 1
272 encoded = window.location.hash
273 if encoded? and encoded.charAt 0 is '#'
274 encoded = encoded.substr 1
275 unless encoded? and encoded.length > board_tiles
276 encoded = get_cookie 'hexbog'
277 if encoded? and encoded.length > board_tiles
280 # work out which grid spaces are connected
281 # (neighbors, above, down)
284 $big_tip = null # initialized by init_html_board
285 $little_tip = null # initialized by init_html_board
286 $score_display = null # initialized by init_html_board
287 $definition_body = null # initialized by init_html_board
288 update_selection_display = ->
289 word = selected_word()
290 $big_tip.removeClass('good')
294 $little_tip.html "Click more tiles (3 minimum)"
297 if word.indexOf(word.substr(word.length - 1)) < word.length - 1
301 $little_tip.html "Click the #{last}\"#{word.substr(word.length - 1)}\" for #{score_for word} points"
302 $big_tip.html "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\" title=\"click for definition\">#{word}</a>"
303 $big_tip.addClass('good')
306 $little_tip.html "\"#{word}\" is not in the word list."
308 $big_tip.html "← Click a word"
309 $little_tip.html "(tiles must be touching)"
311 # color the selected tiles according to whether they're a word or not
313 classes = ['selected_word', 'selected']
319 tiles[num].dom.addClass classes[c]
320 tiles[num].dom.removeClass classes[1 - c]
322 # unselects the last tile of the selecetion
325 update_selection_display()
329 html_tile = tiles[num].dom
330 html_tile.removeClass 'selected_word'
331 html_tile.removeClass 'selected'
334 while selected.length
336 update_selection_display()
340 word += tiles[i].text for i in selected
341 return word.toLowerCase()
343 save_charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR'
344 char_a = "a".charCodeAt(0)
346 encoded = '1' # save format
347 for i in [0...tiles.length] by 2
348 int = tiles[i].text.toLowerCase().charCodeAt(0) - char_a
352 int += tiles[i+1].text.toLowerCase().charCodeAt(0) - char_a
356 encoded += save_charset.substr(int % 44, 1)
357 int = Math.floor(int / 44)
359 set_cookie 'hexbog', encoded, 365
360 window.location.hash = encoded
364 tile.text = new_letter().letter
365 tile.dom.html tile.text
367 # remove the selected tiles from the board, create new tiles, and slide everything into place
369 difficulty = 11 - Math.log(400 + score) # higher numbers are easier
370 force = difficulty * score_for selected_word() # how much tile restoration we have left to do
371 word_length = selected_word().length
372 faders = selected.num_sort()
374 update_selection_display()
378 tiles[i].dom.unbind('click').fadeOut fade_ms
379 tiles[i].new_hp = tiles[i].hp
380 for n in board_neighbors[i]
381 neighbors[n] = tiles[n]
382 for nn in board_neighbors[n]
383 nneighbors[nn] = tiles[nn]
387 for k, v of neighbors
389 # convert to arrays so we can sort, etc
390 nneighbors = (v for k, v of nneighbors)
391 neighbors = (v for k, v of neighbors)
417 boom[0].flips = 'all'
422 boom[0].flips = 'all'
427 boom[0].flips = 'all'
432 boom[0].flips = 'all'
434 boom[1].flips = 'all'
441 # unsink/heal the whole board
448 if b.flips is 'all' or b.flips >= b.down.length
452 while b.flips > 0 and b.down.length > 0
454 flipper = Math.floor(Math.random() * b.down.length)
455 unsink b.down[flipper]
456 b.down = [b.down[0...flipper]..., b.down[flipper+1...b.down.length]...]
459 t.new_hp = t.hp + b.force
464 else if i.new_hp > HP_MAX
466 if i.new_hp isnt i.hp
467 i.dom.removeClass "hp#{i.hp}"
468 i.dom.addClass "hp#{i.new_hp}"
471 timeout fade_ms + 1, ->
472 # which tiles need to be slid down
473 sliders = (false for i in tiles)
477 for deleted in faders
478 # find the tile number of the top tile in this column
479 if board_aboves[deleted].length is 0
482 col_top = board_aboves[deleted][0]
484 # reset location where new tiles appear when we change columns
485 if prev_col_top isnt col_top
486 next_new_y = -10 - tile_width
487 prev_col_top = col_top
489 tiles[deleted].dom.remove()
491 # For each each tile above the one we've deleted:
492 # 1. move it down one slot in the data scructures
493 # 2. mark it as needing to slide
495 aboves = board_aboves[deleted].clone().reverse()
497 tiles[dest] = tiles[above]
498 tiles[dest].id = dest
499 tiles[dest].dom.data 'tile_number', dest
502 sliders[col_top] = true # the new tile needs to be slid down too
504 new_tile col_top, board_left_px[col_top], next_new_y
505 next_new_y -= tile_width + 50
507 for slide, i in sliders
509 tiles[i].dom.animate {top: "#{tile_top_px[i]}px"}, slide_ms
513 score_for = (word) -> Math.round(Math.pow(1.7, word.length))
515 activate_selection = ->
516 word = selected_word()
518 # FIXME make this a hint
519 log "Too short: \"#{word}\""
522 # FIXME make this automatically part of the selection display
523 log "Not on word list: \"#{word}\""
525 word_score = score_for word
527 $score_display.html score
528 # FIXME make some kind of animation showing score gain
529 log "blipped \"#{word}\" for #{word_score} points"
531 look_up_definition word
532 $('#definition').click()
535 show_definition = (word, type, definition, language) ->
536 html = "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\">"
537 html += "#{word.substr(0, 1).toUpperCase() + word.substr(1)}</a>, #{type}"
538 if language isnt 'English'
539 html += " (#{language})"
542 html += '<div id="definition_credit">Definition ©<a href="http://en.wiktionary.org/" target="_blank">wiktionary.org</a> CC-BY-SA</div>'
543 $definition_body.html html
546 select_tile = (num) ->
547 html_tile = tiles[num].dom
548 # html_tile.css backgroundColor: tile_selected_color
550 update_selection_display()
553 new_tile = (num, x, y) ->
558 html_tile = $("<div class=\"tile hp#{hp}\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
559 $board.append(html_tile)
561 html_tile.data 'tile_number', num
562 tiles[num] = text: letter, dom: html_tile, hp: hp, id: num
566 num = me.data 'tile_number'
567 return if tiles[num].hp < 1
569 if selected_word().length > 2 and num is selected.last()
572 if selected.length > 1
577 else # (not clicking on selected tile)
578 if selected.length > 0 and not (num in board_neighbors[selected.last()])
585 $('#loading').remove()
586 $big_tip = $('#big_tip')
587 $little_tip = $('#little_tip')
588 $score_display = $('#score')
589 $score_display.html score
590 $definition_body = $('#definition_body')
592 # make html for board
594 for col_num in [0 .. board_cols - 1]
595 for num in [0 .. board_col_heights[col_num] - 1]
596 x = col_num * tile_width
597 y = board_col_top_px[col_num] + num * tile_width
598 new_tile tile_number, x, y
601 word_bins = []; word_bins.push(',') for [0...997]
602 hash_word = (word) ->
604 for i in [0...word.length]
605 h ^= word.charCodeAt(i) << ((i*3) % 21)
608 word_bins[hash_word str].indexOf(",#{str},") > -1
610 # this is called automatically by the compressed wordlist
611 parse_word_list = (compressed) ->
613 cap_a = "A".charCodeAt 0
616 chunk = compressed[i]
617 for word in chunk.match(/[a-z]*[A-Z]/g)
618 # the capital letter (at the end of the match) says how many characters
619 # from the end of the previous word should be removed to create the prefix
620 # for the next word. "A" for 0, "B" for 1, "C" for 2, etc
621 bs = word[word.length - 1].charCodeAt(0) - cap_a
622 word = prefix + word[0 ... word.length - 1]
623 word_bins[hash_word word] += word + ','
624 prefix = word[0 ... word.length - bs]
625 if ++i is compressed.length
628 timeout 1, next_chunk
629 timeout 1, next_chunk
631 extract_wiktionary_definiton = (html) ->
639 # when we instantiate the html so we can use dom traversal, the browser
640 # will start loading images and such. This section attempts to mangle the
641 # html so no resources are loaded when the html is parsed.
644 # src: <img>, <audio>, etc
645 # onload: only <body>?
646 # archive,codebase,data,usemap: <object>
648 # id,class,style: background: url(foo.png), etc
649 html = html.replace /(src|onload|archive|codebase|data|usemap|href|style|id|class)=['"][^"']*['"]/ig, '', html
653 valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
655 edit_link_regex = new RegExp(' ?\\[edit\\] ?')
657 elements.each (i, el) ->
658 #which tag: el.tagName
659 if el.tagName is 'H2'
660 # if we found a definition in the previous language section, run with it
661 # (we only stop for verbs, in hopes of finding one in english)
664 part = false # mark us not being in a definition section unless the next section finds a part of speach header
665 language = $(el).text().replace(edit_link_regex, '')
666 if language and el.tagName is 'H3' or el.tagName is 'H4' # eg yak def uses one for english and one for dutch
668 text = $(el).text().replace(edit_link_regex, '')
671 part = p.toLowerCase()
673 if part and el.tagName is 'OL'
674 $(el).children().each (i, el) ->
675 new_def = $(el).text()
676 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 "
683 finds[key] ?= [part, new_def, language]
686 # verbs are the best! stop scanning when we find one
691 part_defs = (finds[i] for i in ['verb', 'nonverb', 'lame'] when finds[i])
692 unless part_defs.length
698 look_up_definition = (word) ->
699 $definition_body.html "Looking up definition for \"#{word}\"..."
701 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
702 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
705 success: (data, error_msg, xhr) ->
706 if data?.parse?.text?['*']?
707 tdl = extract_wiktionary_definiton data.parse.text['*']
709 show_definition word, tdl[0], tdl[1], tdl[2]
711 $definition_body.html "Oops, could't find a definition for \"#{word}\"."
713 $definition_body.html "Sorry, couldn't find a definition for \"#{word}\"."
719 for i in [0 .. board_min_height * 2]
721 ret += ' ' + tiles[j].text for j in [board_min_height + index .. board_tiles - 1] by 2 * board_min_height + 1
723 ret += ' ' + tiles[j].text + ' ' for j in [index .. board_tiles - 1] by 2 * board_min_height + 1
732 $score_display.html score
733 for i in [0...board_tiles]
737 init_start_over_link = ->
738 $('#start-over').click (event) ->
739 event.preventDefault()
740 if confirm "Are you sure you want to start over? There is no undo."
743 cur_tab = 'instructions'
748 return if t is cur_tab
749 $('#' + cur_tab).removeClass('selected-tab').addClass('tab').animate({height: tabtab_height}, 1000)
750 $('#' + t).removeClass('tab').addClass('selected-tab').animate({height: tab_height}, 1000)
753 for t in ['instructions', 'definition', 'donate', 'restart']
757 $(window).keydown (e) ->
765 console.log msg if console?.log?
768 if $(window).height() >= 440
769 $('#centerer').css('margin-top', '25px')
774 init_start_over_link()
775 update_selection_display()