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 board = new Array(board_tiles) # letters ("Qu" or single letter)
82 board_neighbors = [] # array of tile numbers "next to" this one
83 board_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
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()
133 r = Math.floor Math.random() * (letter_distribution_total + 1)
135 r -= letter_distribution[i]
140 return 'Z' # just in case
144 # in memory it's layed out like this:
149 # for display, columns are slid vertically like so:
158 # work out which grid spaces are connected
159 init_board_layout = () ->
161 middle_col = (board_cols - 1) / 2
163 # how many tiles before the current tile?
164 for col_num in [0 .. board_cols - 1]
165 if col_num < middle_col
170 if col_num > middle_col
175 is_first_col = col_num is 0
176 is_last_col = col_num is board_cols - 1
180 neighbors.push col_offset + offset
182 col_top_px = Math.abs col_num - middle_col
183 col_top_px *= tile_radius
184 board_col_top_px.push col_top_px
187 for i in [0 .. board_col_heights[col_num] - 1]
189 is_bottom_tile = i is board_col_heights[col_num] - 1
191 # link tile number to pixel "top" and "left" of containing column
192 board_top_px.push col_top_px
193 board_left_px.push col_num * tile_width
195 # aboves (array of tile numbers above, starting from top)
196 board_aboves.push above.clone()
197 above.push i + col_offset
199 # below (SINGLE tile number of tile below or false)
201 board_below.push false
203 board_below.push col_offset + i + 1
205 # neighbors (array of tile numbers "next to" this one)
207 unless is_top_tile # upward link
209 unless is_bottom_tile # downward links
211 unless is_first_col # leftward links
212 unless is_bottom_tile and bw_other is -1
213 push i - board_col_heights[col_num - 1]
214 unless is_top_tile and bw_other is -1
215 push i - board_col_heights[col_num - 1] + bw_other
216 unless is_last_col # rightward links
217 unless is_bottom_tile and fw_other is -1
218 push i + board_col_heights[col_num]
219 unless is_top_tile and fw_other is -1
220 push i + board_col_heights[col_num] + fw_other
222 board_neighbors.push neighbors.clone()
224 col_offset += board_col_heights[col_num]
228 encoded = window.location.hash
229 if encoded? and encoded.charAt 0 is '#'
230 encoded = encoded.substr 1
231 unless encoded? and encoded.length > board_tiles
232 encoded = get_cookie 'hexbog'
233 if encoded? and encoded.length > board_tiles
234 new_letter_queue = (encoded.substr 0, board_tiles).split ''
235 score = parseInt(encoded.substr(board_tiles), 10)
237 # how far each tile needs to be slid down
238 slides = (0 for i in board)
240 # work out which grid spaces are connected
241 # (neighbors, above, down)
244 $selection_display = null # initialized by init_html_board
245 $score_display = null # initialized by init_html_board
246 $definition_body = null # initialized by init_html_board
247 update_selection_display = ->
248 word = selected_word()
249 $selection_display.html word
251 # color the selected tiles according to whether they're a word or not
253 classes = ['selected_word', 'selected']
259 html_tiles[num].addClass classes[c]
260 html_tiles[num].removeClass classes[1 - c]
262 # unselects the last tile of the selecetion
265 update_selection_display()
269 html_tile = html_tiles[num]
270 html_tile.removeClass 'selected_word'
271 html_tile.removeClass 'selected'
274 while selected.length
276 update_selection_display()
278 shrink_selection = (leave_count) ->
279 while selected.length > leave_count
281 update_selection_display()
285 word += board[i] for i in selected
286 return word.toLowerCase()
288 html_slide = (num, dist) ->
290 cur = html_tiles[num].css 'top'
291 cur = Number(cur.substr(0, cur.length - 2))
292 dest = cur + (dist * tile_width)
293 html_tiles[num].animate {top: "#{dest}px"}, slide_ms
298 encoded += t.substr 0, 1
300 set_cookie 'hexbog', encoded, 365
301 window.location.hash = encoded
304 faders = selected.clone().num_sort()
307 html_tiles[num].unbind('click').fadeOut fade_ms
313 cur_top = board_aboves[fader][0]
314 if cur_top is undefined
316 if top_tile isnt cur_top
317 new_px = board_top_px[fader] - tile_width
320 html_tiles[fader].remove()
322 aboves = board_aboves[fader].clone().reverse()
324 html_tiles[dest] = html_tiles[above]
325 html_tiles[dest].data 'tile_number', dest
326 board[dest] = board[above]
327 slides[dest] = slides[above] + 1
329 new_tile top_tile, board_left_px[top_tile], new_px
330 slides[top_tile] = new_slide
333 for i in [0 .. board.length - 1]
334 html_slide i, slides[i]
337 update_selection_display()
339 activate_selection = ->
340 word = selected_word()
342 # FIXME make this a hint
343 log "Too short: \"#{word}\""
346 # FIXME make this automatically part of the selection display
347 log "Not on word list: \"#{word}\""
349 word_score = Math.round(Math.pow(1.7, word.length))
351 $score_display.html score
352 # FIXME make some kind of animation showing score gain
353 log "blipped \"#{word}\" for #{word_score} points"
355 look_up_definition word
356 $('#definition').click()
359 show_definition = (word, type, definition, language) ->
360 html = "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\">"
361 html += "#{word.substr(0, 1).toUpperCase() + word.substr(1)}</a>, #{type}"
362 if language isnt 'English'
363 html += " (#{language})"
366 html += '<div id="definition_credit">Definition ©<a href="http://en.wiktionary.org/" target="_blank">wiktionary.org</a> CC-BY-SA</div>'
367 $definition_body.html html
370 select_tile = (num) ->
371 html_tile = html_tiles[num]
372 # html_tile.css backgroundColor: tile_selected_color
374 update_selection_display()
377 new_tile = (num, x, y) ->
378 letter = new_letter()
380 html_tile = $("<div class=\"tile\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
381 $board.append(html_tile)
383 html_tile.data 'tile_number', num
385 html_tiles[num] = html_tile
389 num = me.data 'tile_number'
391 nth_of_word = selected.indexOf(num)
392 first = nth_of_word is 0
393 last = nth_of_word is selected.length - 1
396 unselect_all() # Clicking only selected letter unselects it
397 else if first and !last
398 shrink_selection 1 # Clicking start of word goes back to just that letter
399 # should this unselect all?
403 shrink_selection nth_of_word + 1
404 else # (not clicking on selected tile)
405 if selected.length is 0
408 unless num in board_neighbors[selected.last()]
416 $('#loading').remove()
417 $selection_display = $('#selection')
418 $score_display = $('#score')
419 $score_display.html score
420 $definition_body = $('#definition_body')
422 # make html for board
424 for col_num in [0 .. board_cols - 1]
425 for num in [0 .. board_col_heights[col_num] - 1]
426 x = col_num * tile_width
427 y = board_col_top_px[col_num] + num * tile_width
428 new_tile tile_number, x, y
431 word_bins = []; word_bins.push(',') for [0...997]
432 hash_word = (word) ->
434 for i in [0...word.length]
435 h ^= word.charCodeAt(i) << ((i*3) % 21)
438 word_bins[hash_word str].indexOf(",#{str},") > -1
440 # this is called automatically by the compressed wordlist
441 parse_word_list = (compressed) ->
443 cap_a = "A".charCodeAt 0
446 chunk = compressed[i]
447 for word in chunk.match(/[a-z]*[A-Z]/g)
448 # the capital letter (at the end of the match) says how many characters
449 # from the end of the previous word should be removed to create the prefix
450 # for the next word. "A" for 0, "B" for 1, "C" for 2, etc
451 bs = word[word.length - 1].charCodeAt(0) - cap_a
452 word = prefix + word[0 ... word.length - 1]
453 word_bins[hash_word word] += word + ','
454 prefix = word[0 ... word.length - bs]
455 if ++i is compressed.length
458 timeout 1, next_chunk
459 timeout 1, next_chunk
461 extract_wiktionary_definiton = (html) ->
469 # when we instantiate the html so we can use dom traversal, the browser
470 # will start loading images and such. This section attempts to mangle the
471 # html so no resources are loaded when the html is parsed.
474 # src: <img>, <audio>, etc
475 # onload: only <body>?
476 # archive,codebase,data,usemap: <object>
478 # id,class,style: background: url(foo.png), etc
479 html = html.replace /(src|onload|archive|codebase|data|usemap|href|style|id|class)=['"][^"']*['"]/ig, '', html
483 valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
485 elements.each (i, el) ->
486 #which tag: el.tagName
487 if el.tagName is 'H2'
488 # if we found a definition in the previous language section, run with it
489 # (we only stop for verbs, in hopes of finding one in english)
492 part = false # mark us not being in a definition section unless the next section finds a part of speach header
493 language = $(el).text().substr 7
494 if language and el.tagName is 'H3' or el.tagName is 'H4' # eg yak def uses one for english and one for dutch
498 if text is "[edit] #{p}"
499 part = p.toLowerCase()
501 if part and el.tagName is 'OL'
502 $(el).children().each (i, el) ->
503 new_def = $(el).text()
504 if new_def.substr(0, 9) is '(obsolete' or new_def.substr(0, 8) is "(archaic"
511 finds[key] ?= [part, new_def, language]
514 # verbs are the best! stop scanning when we find one
519 part_defs = (finds[i] for i in ['verb', 'nonverb', 'obsolete'] when finds[i])
520 unless part_defs.length
526 look_up_definition = (word) ->
527 $definition_body.html "Looking up definition for \"#{word}\"."
529 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
530 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
533 success: (data, error_msg, xhr) ->
534 if data?.parse?.text?['*']?
535 tdl = extract_wiktionary_definiton data.parse.text['*']
537 show_definition word, tdl[0], tdl[1], tdl[2]
539 $definition_body.html "Sorry, couldn't find a definition for \"#{word}\"."
545 for i in [0 .. board_min_height * 2]
547 ret += ' ' + board[j] for j in [board_min_height + index .. board_tiles - 1] by 2 * board_min_height + 1
549 ret += ' ' + board[j] + ' ' for j in [index .. board_tiles - 1] by 2 * board_min_height + 1
558 $score_display.html score
559 for i in [0...board_tiles]
563 init_start_over_link = ->
564 $('#start-over').click (event) ->
565 event.preventDefault()
566 if confirm "Are you sure you want to start over? There is no undo."
569 cur_tab = 'instructions'
574 return if t is cur_tab
575 $('#' + cur_tab).removeClass('selected-tab').addClass('tab').animate({height: tabtab_height}, 1000)
576 $('#' + t).removeClass('tab').addClass('selected-tab').animate({height: tab_height}, 1000)
579 for t in ['instructions', 'definition', 'donate', 'restart']
583 $(window).keydown (e) ->
594 console.log msg if console.log?
598 if $(window).height() >= 440
599 $('#centerer').css('margin-top', '25px')
604 init_start_over_link()