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]
30 ##############################################################
31 ############## fix javascript some more ################
32 ##############################################################
34 # so annoying that setTimeout has its arguments in the wrong order
35 timeout = (ms, callback) ->
36 setTimeout callback, ms
38 # warning: it's shalow (sub-elements are not cloned)
44 ret += i for i in this
47 # ascending. All values must be Numbers
48 Array::num_sort = -> return this.sort((a, b) -> return a - b)
51 return this[this.length - 1]
54 ##############################################################
55 ############## cookies (auto-save game) ################
56 ##############################################################
58 set_cookie = (name, value, days) ->
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
65 get_cookie = (name) ->
67 for c in document.cookie.split /; */
69 return c.substr key.length
72 delete_cookie = (name) ->
73 set_cookie name, '', -1
74 window.dc = delete_cookie
77 board_cols = board_col_heights.length
78 board_tiles = board_col_heights.sum()
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
90 letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
91 letter_distribution = [
121 letter_distribution_total = 175973 # letter_distribution.sum()
124 new_letter_queue = []
126 if new_letter_queue.length
127 l = new_letter_queue.shift()
132 r = Math.floor Math.random() * (letter_distribution_total + 1)
134 r -= letter_distribution[i]
139 return 'Z' # just in case
143 # in memory it's layed out like this:
148 # for display, columns are slid vertically like so:
157 # work out which grid spaces are connected
158 init_board_layout = () ->
160 middle_col = (board_cols - 1) / 2
162 # how many tiles before the current tile?
163 for col_num in [0 .. board_cols - 1]
164 if col_num < middle_col
169 if col_num > middle_col
174 is_first_col = col_num is 0
175 is_last_col = col_num is board_cols - 1
179 neighbors.push col_offset + offset
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
186 for i in [0 .. board_col_heights[col_num] - 1]
188 is_bottom_tile = i is board_col_heights[col_num] - 1
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
194 # aboves (array of tile numbers above, starting from top)
195 board_aboves.push above.clone()
196 above.push i + col_offset
198 # below (SINGLE tile number of tile below or false)
200 board_below.push false
202 board_below.push col_offset + i + 1
204 # neighbors (array of tile numbers "next to" this one)
206 unless is_top_tile # upward link
208 unless is_bottom_tile # downward links
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
221 board_neighbors.push neighbors.clone()
223 col_offset += board_col_heights[col_num]
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)
236 # work out which grid spaces are connected
237 # (neighbors, above, down)
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')
250 $little_tip.html "Click more tiles (3 minimum)"
253 if word.indexOf(word.substr(word.length - 1)) < word.length - 1
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')
262 $little_tip.html "\"#{word}\" is not in the word list."
264 $big_tip.html "← Click a word"
265 $little_tip.html "(tiles must be touching)"
267 # color the selected tiles according to whether they're a word or not
269 classes = ['selected_word', 'selected']
275 tiles[num].dom.addClass classes[c]
276 tiles[num].dom.removeClass classes[1 - c]
278 # unselects the last tile of the selecetion
281 update_selection_display()
285 html_tile = tiles[num].dom
286 html_tile.removeClass 'selected_word'
287 html_tile.removeClass 'selected'
290 while selected.length
292 update_selection_display()
294 shrink_selection = (leave_count) ->
295 while selected.length > leave_count
297 update_selection_display()
301 word += tiles[i].text for i in selected
302 return word.toLowerCase()
307 encoded += t.text.substr 0, 1
309 set_cookie 'hexbog', encoded, 365
310 window.location.hash = encoded
312 # remove the selected tiles from the board, create new tiles, and slide everything into place
314 faders = selected.num_sort()
316 update_selection_display()
318 tiles[i].dom.unbind('click').fadeOut fade_ms
322 i.dom.removeClass "hp#{i.hp}"
324 i.dom.addClass "hp#{i.hp}"
325 timeout fade_ms + 1, ->
326 # which tiles need to be slid down
327 sliders = (false for i in tiles)
331 for deleted in faders
332 # find the tile number of the top tile in this column
333 if board_aboves[deleted].length is 0
336 col_top = board_aboves[deleted][0]
338 # reset location where new tiles appear when we change columns
339 if prev_col_top isnt col_top
340 next_new_y = -10 - tile_width
341 prev_col_top = col_top
343 tiles[deleted].dom.remove()
345 # For each each tile above the one we've deleted:
346 # 1. move it down one slot in the data scructures
347 # 2. mark it as needing to slide
349 aboves = board_aboves[deleted].clone().reverse()
351 tiles[dest] = tiles[above]
352 tiles[dest].id = dest
353 tiles[dest].dom.data 'tile_number', dest
356 sliders[col_top] = true # the new tile needs to be slid down too
358 new_tile col_top, board_left_px[col_top], next_new_y
359 next_new_y -= tile_width + 50
361 for slide, i in sliders
363 tiles[i].dom.animate {top: "#{tile_top_px[i]}px"}, slide_ms
367 score_for = (word) -> Math.round(Math.pow(1.7, word.length))
369 activate_selection = ->
370 word = selected_word()
372 # FIXME make this a hint
373 log "Too short: \"#{word}\""
376 # FIXME make this automatically part of the selection display
377 log "Not on word list: \"#{word}\""
379 word_score = score_for word
381 $score_display.html score
382 # FIXME make some kind of animation showing score gain
383 log "blipped \"#{word}\" for #{word_score} points"
385 look_up_definition word
386 $('#definition').click()
389 show_definition = (word, type, definition, language) ->
390 html = "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\">"
391 html += "#{word.substr(0, 1).toUpperCase() + word.substr(1)}</a>, #{type}"
392 if language isnt 'English'
393 html += " (#{language})"
396 html += '<div id="definition_credit">Definition ©<a href="http://en.wiktionary.org/" target="_blank">wiktionary.org</a> CC-BY-SA</div>'
397 $definition_body.html html
400 select_tile = (num) ->
401 html_tile = tiles[num].dom
402 # html_tile.css backgroundColor: tile_selected_color
404 update_selection_display()
407 new_tile = (num, x, y) ->
408 letter = new_letter()
410 html_tile = $("<div class=\"tile hp10\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
411 $board.append(html_tile)
413 html_tile.data 'tile_number', num
414 tiles[num] = text: letter, dom: html_tile, hp: 10, id: num
418 num = me.data 'tile_number'
420 nth_of_word = selected.indexOf(num)
421 first = nth_of_word is 0
422 last = nth_of_word is selected.length - 1
425 unselect_all() # Clicking only selected letter unselects it
426 else if first and !last
427 shrink_selection 1 # Clicking start of word goes back to just that letter
428 # should this unselect all?
432 shrink_selection nth_of_word + 1
433 else # (not clicking on selected tile)
434 if selected.length is 0
437 unless num in board_neighbors[selected.last()]
444 $('#loading').remove()
445 $big_tip = $('#big_tip')
446 $little_tip = $('#little_tip')
447 $score_display = $('#score')
448 $score_display.html score
449 $definition_body = $('#definition_body')
451 # make html for board
453 for col_num in [0 .. board_cols - 1]
454 for num in [0 .. board_col_heights[col_num] - 1]
455 x = col_num * tile_width
456 y = board_col_top_px[col_num] + num * tile_width
457 new_tile tile_number, x, y
460 word_bins = []; word_bins.push(',') for [0...997]
461 hash_word = (word) ->
463 for i in [0...word.length]
464 h ^= word.charCodeAt(i) << ((i*3) % 21)
467 word_bins[hash_word str].indexOf(",#{str},") > -1
469 # this is called automatically by the compressed wordlist
470 parse_word_list = (compressed) ->
472 cap_a = "A".charCodeAt 0
475 chunk = compressed[i]
476 for word in chunk.match(/[a-z]*[A-Z]/g)
477 # the capital letter (at the end of the match) says how many characters
478 # from the end of the previous word should be removed to create the prefix
479 # for the next word. "A" for 0, "B" for 1, "C" for 2, etc
480 bs = word[word.length - 1].charCodeAt(0) - cap_a
481 word = prefix + word[0 ... word.length - 1]
482 word_bins[hash_word word] += word + ','
483 prefix = word[0 ... word.length - bs]
484 if ++i is compressed.length
487 timeout 1, next_chunk
488 timeout 1, next_chunk
490 extract_wiktionary_definiton = (html) ->
498 # when we instantiate the html so we can use dom traversal, the browser
499 # will start loading images and such. This section attempts to mangle the
500 # html so no resources are loaded when the html is parsed.
503 # src: <img>, <audio>, etc
504 # onload: only <body>?
505 # archive,codebase,data,usemap: <object>
507 # id,class,style: background: url(foo.png), etc
508 html = html.replace /(src|onload|archive|codebase|data|usemap|href|style|id|class)=['"][^"']*['"]/ig, '', html
512 valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
514 edit_link_regex = new RegExp(' ?\\[edit\\] ?')
516 elements.each (i, el) ->
517 #which tag: el.tagName
518 if el.tagName is 'H2'
519 # if we found a definition in the previous language section, run with it
520 # (we only stop for verbs, in hopes of finding one in english)
523 part = false # mark us not being in a definition section unless the next section finds a part of speach header
524 language = $(el).text().replace(edit_link_regex, '')
525 if language and el.tagName is 'H3' or el.tagName is 'H4' # eg yak def uses one for english and one for dutch
527 text = $(el).text().replace(edit_link_regex, '')
530 part = p.toLowerCase()
532 if part and el.tagName is 'OL'
533 $(el).children().each (i, el) ->
534 new_def = $(el).text()
535 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 "
542 finds[key] ?= [part, new_def, language]
545 # verbs are the best! stop scanning when we find one
550 part_defs = (finds[i] for i in ['verb', 'nonverb', 'lame'] when finds[i])
551 unless part_defs.length
557 look_up_definition = (word) ->
558 $definition_body.html "Looking up definition for \"#{word}\"..."
560 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
561 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
564 success: (data, error_msg, xhr) ->
565 if data?.parse?.text?['*']?
566 tdl = extract_wiktionary_definiton data.parse.text['*']
568 show_definition word, tdl[0], tdl[1], tdl[2]
570 $definition_body.html "Oops, could't find a definition for \"#{word}\"."
572 $definition_body.html "Sorry, couldn't find a definition for \"#{word}\"."
578 for i in [0 .. board_min_height * 2]
580 ret += ' ' + tiles[j].text for j in [board_min_height + index .. board_tiles - 1] by 2 * board_min_height + 1
582 ret += ' ' + tiles[j].text + ' ' for j in [index .. board_tiles - 1] by 2 * board_min_height + 1
591 $score_display.html score
592 for i in [0...board_tiles]
596 init_start_over_link = ->
597 $('#start-over').click (event) ->
598 event.preventDefault()
599 if confirm "Are you sure you want to start over? There is no undo."
602 cur_tab = 'instructions'
607 return if t is cur_tab
608 $('#' + cur_tab).removeClass('selected-tab').addClass('tab').animate({height: tabtab_height}, 1000)
609 $('#' + t).removeClass('tab').addClass('selected-tab').animate({height: tab_height}, 1000)
612 for t in ['instructions', 'definition', 'donate', 'restart']
616 $(window).keydown (e) ->
627 console.log msg if console.log?
631 if $(window).height() >= 440
632 $('#centerer').css('margin-top', '25px')
637 init_start_over_link()
638 update_selection_display()