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()
134 r = Math.floor Math.random() * (letter_distribution_total + 1)
136 r -= letter_distribution[i]
141 return 'Z' # 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 = (board_cols - 1) / 2
164 # how many tiles before the current tile?
165 for col_num in [0 .. board_cols - 1]
166 if col_num < middle_col
171 if col_num > middle_col
176 is_first_col = col_num is 0
177 is_last_col = col_num is board_cols - 1
181 neighbors.push col_offset + offset
183 col_top_px = Math.abs col_num - middle_col
184 col_top_px *= tile_radius
185 board_col_top_px.push col_top_px
188 for i in [0 .. board_col_heights[col_num] - 1]
190 is_bottom_tile = i is board_col_heights[col_num] - 1
192 # link tile number to pixel "top" and "left" of containing column
193 tile_top_px.push col_top_px + i * tile_width
194 board_left_px.push col_num * tile_width
196 # aboves (array of tile numbers above, starting from top)
197 board_aboves.push above.clone()
198 above.push i + col_offset
200 # below (SINGLE tile number of tile below or false)
202 board_below.push false
204 board_below.push col_offset + i + 1
206 # neighbors (array of tile numbers "next to" this one)
208 unless is_top_tile # upward link
210 unless is_bottom_tile # downward links
212 unless is_first_col # leftward links
213 unless is_bottom_tile and bw_other is -1
214 push i - board_col_heights[col_num - 1]
215 unless is_top_tile and bw_other is -1
216 push i - board_col_heights[col_num - 1] + bw_other
217 unless is_last_col # rightward links
218 unless is_bottom_tile and fw_other is -1
219 push i + board_col_heights[col_num]
220 unless is_top_tile and fw_other is -1
221 push i + board_col_heights[col_num] + fw_other
223 board_neighbors.push neighbors.clone()
225 col_offset += board_col_heights[col_num]
229 encoded = window.location.hash
230 if encoded? and encoded.charAt 0 is '#'
231 encoded = encoded.substr 1
232 unless encoded? and encoded.length > board_tiles
233 encoded = get_cookie 'hexbog'
234 if encoded? and encoded.length > board_tiles
235 new_letter_queue = (encoded.substr 0, board_tiles).split ''
236 score = parseInt(encoded.substr(board_tiles), HP_MAX)
238 # work out which grid spaces are connected
239 # (neighbors, above, down)
242 $big_tip = null # initialized by init_html_board
243 $little_tip = null # initialized by init_html_board
244 $score_display = null # initialized by init_html_board
245 $definition_body = null # initialized by init_html_board
246 update_selection_display = ->
247 word = selected_word()
248 $big_tip.removeClass('good')
252 $little_tip.html "Click more tiles (3 minimum)"
255 if word.indexOf(word.substr(word.length - 1)) < word.length - 1
259 $little_tip.html "Click the #{last}\"#{word.substr(word.length - 1)}\" for #{score_for word} points"
260 $big_tip.html "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\" title=\"click for definition\">#{word}</a>"
261 $big_tip.addClass('good')
264 $little_tip.html "\"#{word}\" is not in the word list."
266 $big_tip.html "← Click a word"
267 $little_tip.html "(tiles must be touching)"
269 # color the selected tiles according to whether they're a word or not
271 classes = ['selected_word', 'selected']
277 tiles[num].dom.addClass classes[c]
278 tiles[num].dom.removeClass classes[1 - c]
280 # unselects the last tile of the selecetion
283 update_selection_display()
287 html_tile = tiles[num].dom
288 html_tile.removeClass 'selected_word'
289 html_tile.removeClass 'selected'
292 while selected.length
294 update_selection_display()
296 shrink_selection = (leave_count) ->
297 while selected.length > leave_count
299 update_selection_display()
303 word += tiles[i].text for i in selected
304 return word.toLowerCase()
309 encoded += t.text.substr 0, 1
311 set_cookie 'hexbog', encoded, 365
312 window.location.hash = encoded
314 # remove the selected tiles from the board, create new tiles, and slide everything into place
316 difficulty = 11 - Math.log(100 + score) # higher numbers are easier
317 unsink = difficulty * score_for selected_word() # how much tile restoration we have left to do
318 faders = selected.num_sort()
320 update_selection_display()
324 tiles[i].dom.unbind('click').fadeOut fade_ms
325 tiles[i].new_hp = tiles[i].hp
326 for n in board_neighbors[i]
327 neighbors[n] = tiles[n]
328 for nn in board_neighbors[n]
329 nneighbors[nn] = tiles[nn]
333 for k, v of neighbors
335 # convert to arrays so we can sort, etc
336 nneighbors = (v for k, v of nneighbors)
337 neighbors = (v for k, v of neighbors)
338 # TODO randsort neighbors and nneighbors
339 for nei in [neighbors, nneighbors]
342 if i.hp is 0 and unsink >= 15
345 i.text = new_letter()
349 if i.hp > 0 and unsink > 0
356 else if i.new_hp > HP_MAX
358 if i.new_hp isnt i.hp
359 i.dom.removeClass "hp#{i.hp}"
360 i.dom.addClass "hp#{i.new_hp}"
363 timeout fade_ms + 1, ->
364 # which tiles need to be slid down
365 sliders = (false for i in tiles)
369 for deleted in faders
370 # find the tile number of the top tile in this column
371 if board_aboves[deleted].length is 0
374 col_top = board_aboves[deleted][0]
376 # reset location where new tiles appear when we change columns
377 if prev_col_top isnt col_top
378 next_new_y = -10 - tile_width
379 prev_col_top = col_top
381 tiles[deleted].dom.remove()
383 # For each each tile above the one we've deleted:
384 # 1. move it down one slot in the data scructures
385 # 2. mark it as needing to slide
387 aboves = board_aboves[deleted].clone().reverse()
389 tiles[dest] = tiles[above]
390 tiles[dest].id = dest
391 tiles[dest].dom.data 'tile_number', dest
394 sliders[col_top] = true # the new tile needs to be slid down too
396 new_tile col_top, board_left_px[col_top], next_new_y
397 next_new_y -= tile_width + 50
399 for slide, i in sliders
401 tiles[i].dom.animate {top: "#{tile_top_px[i]}px"}, slide_ms
405 score_for = (word) -> Math.round(Math.pow(1.7, word.length))
407 activate_selection = ->
408 word = selected_word()
410 # FIXME make this a hint
411 log "Too short: \"#{word}\""
414 # FIXME make this automatically part of the selection display
415 log "Not on word list: \"#{word}\""
417 word_score = score_for word
419 $score_display.html score
420 # FIXME make some kind of animation showing score gain
421 log "blipped \"#{word}\" for #{word_score} points"
423 look_up_definition word
424 $('#definition').click()
427 show_definition = (word, type, definition, language) ->
428 html = "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\">"
429 html += "#{word.substr(0, 1).toUpperCase() + word.substr(1)}</a>, #{type}"
430 if language isnt 'English'
431 html += " (#{language})"
434 html += '<div id="definition_credit">Definition ©<a href="http://en.wiktionary.org/" target="_blank">wiktionary.org</a> CC-BY-SA</div>'
435 $definition_body.html html
438 select_tile = (num) ->
439 html_tile = tiles[num].dom
440 # html_tile.css backgroundColor: tile_selected_color
442 update_selection_display()
445 new_tile = (num, x, y) ->
446 letter = new_letter()
448 hp = Math.floor(Math.random() * HP_MAX)
450 html_tile = $("<div class=\"tile hp#{hp}\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
451 $board.append(html_tile)
453 html_tile.data 'tile_number', num
454 tiles[num] = text: letter, dom: html_tile, hp: hp, id: num
458 num = me.data 'tile_number'
460 nth_of_word = selected.indexOf(num)
461 first = nth_of_word is 0
462 last = nth_of_word is selected.length - 1
465 unselect_all() # Clicking only selected letter unselects it
466 else if first and !last
467 shrink_selection 1 # Clicking start of word goes back to just that letter
468 # should this unselect all?
472 shrink_selection nth_of_word + 1
473 else # (not clicking on selected tile)
474 if selected.length is 0
477 unless num in board_neighbors[selected.last()]
484 $('#loading').remove()
485 $big_tip = $('#big_tip')
486 $little_tip = $('#little_tip')
487 $score_display = $('#score')
488 $score_display.html score
489 $definition_body = $('#definition_body')
491 # make html for board
493 for col_num in [0 .. board_cols - 1]
494 for num in [0 .. board_col_heights[col_num] - 1]
495 x = col_num * tile_width
496 y = board_col_top_px[col_num] + num * tile_width
497 new_tile tile_number, x, y
500 word_bins = []; word_bins.push(',') for [0...997]
501 hash_word = (word) ->
503 for i in [0...word.length]
504 h ^= word.charCodeAt(i) << ((i*3) % 21)
507 word_bins[hash_word str].indexOf(",#{str},") > -1
509 # this is called automatically by the compressed wordlist
510 parse_word_list = (compressed) ->
512 cap_a = "A".charCodeAt 0
515 chunk = compressed[i]
516 for word in chunk.match(/[a-z]*[A-Z]/g)
517 # the capital letter (at the end of the match) says how many characters
518 # from the end of the previous word should be removed to create the prefix
519 # for the next word. "A" for 0, "B" for 1, "C" for 2, etc
520 bs = word[word.length - 1].charCodeAt(0) - cap_a
521 word = prefix + word[0 ... word.length - 1]
522 word_bins[hash_word word] += word + ','
523 prefix = word[0 ... word.length - bs]
524 if ++i is compressed.length
527 timeout 1, next_chunk
528 timeout 1, next_chunk
530 extract_wiktionary_definiton = (html) ->
538 # when we instantiate the html so we can use dom traversal, the browser
539 # will start loading images and such. This section attempts to mangle the
540 # html so no resources are loaded when the html is parsed.
543 # src: <img>, <audio>, etc
544 # onload: only <body>?
545 # archive,codebase,data,usemap: <object>
547 # id,class,style: background: url(foo.png), etc
548 html = html.replace /(src|onload|archive|codebase|data|usemap|href|style|id|class)=['"][^"']*['"]/ig, '', html
552 valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
554 edit_link_regex = new RegExp(' ?\\[edit\\] ?')
556 elements.each (i, el) ->
557 #which tag: el.tagName
558 if el.tagName is 'H2'
559 # if we found a definition in the previous language section, run with it
560 # (we only stop for verbs, in hopes of finding one in english)
563 part = false # mark us not being in a definition section unless the next section finds a part of speach header
564 language = $(el).text().replace(edit_link_regex, '')
565 if language and el.tagName is 'H3' or el.tagName is 'H4' # eg yak def uses one for english and one for dutch
567 text = $(el).text().replace(edit_link_regex, '')
570 part = p.toLowerCase()
572 if part and el.tagName is 'OL'
573 $(el).children().each (i, el) ->
574 new_def = $(el).text()
575 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 "
582 finds[key] ?= [part, new_def, language]
585 # verbs are the best! stop scanning when we find one
590 part_defs = (finds[i] for i in ['verb', 'nonverb', 'lame'] when finds[i])
591 unless part_defs.length
597 look_up_definition = (word) ->
598 $definition_body.html "Looking up definition for \"#{word}\"..."
600 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
601 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
604 success: (data, error_msg, xhr) ->
605 if data?.parse?.text?['*']?
606 tdl = extract_wiktionary_definiton data.parse.text['*']
608 show_definition word, tdl[0], tdl[1], tdl[2]
610 $definition_body.html "Oops, could't find a definition for \"#{word}\"."
612 $definition_body.html "Sorry, couldn't find a definition for \"#{word}\"."
618 for i in [0 .. board_min_height * 2]
620 ret += ' ' + tiles[j].text for j in [board_min_height + index .. board_tiles - 1] by 2 * board_min_height + 1
622 ret += ' ' + tiles[j].text + ' ' for j in [index .. board_tiles - 1] by 2 * board_min_height + 1
631 $score_display.html score
632 for i in [0...board_tiles]
636 init_start_over_link = ->
637 $('#start-over').click (event) ->
638 event.preventDefault()
639 if confirm "Are you sure you want to start over? There is no undo."
642 cur_tab = 'instructions'
647 return if t is cur_tab
648 $('#' + cur_tab).removeClass('selected-tab').addClass('tab').animate({height: tabtab_height}, 1000)
649 $('#' + t).removeClass('tab').addClass('selected-tab').animate({height: tab_height}, 1000)
652 for t in ['instructions', 'definition', 'donate', 'restart']
656 $(window).keydown (e) ->
664 console.log msg if console?.log?
667 if $(window).height() >= 440
668 $('#centerer').css('margin-top', '25px')
673 init_start_over_link()
674 update_selection_display()