JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
show definition failure in definition tab
[hexbog.git] / main.coffee
1 #   HexBog, a word game
2 #   Copyright (C) 2012 Jason Woofenden
3
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.
8
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.
13
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/>.
16
17 ##############################################
18 ##############    settings    ################
19 ##############################################
20
21 tile_radius = 26
22 tile_width = tile_radius * 2
23
24 fade_ms = 400
25 slide_ms = 2000
26
27 board_col_heights = [5, 6, 7, 8, 7, 6, 5]
28
29
30 ##############################################################
31 ##############    fix javascript some more    ################
32 ##############################################################
33
34 # so annoying that setTimeout has its arguments in the wrong order
35 timeout = (ms, callback) ->
36         setTimeout callback, ms
37
38 # warning: it's shalow (sub-elements are not cloned)
39 Array::clone = ->
40         return this.slice(0)
41
42 Array::sum = ->
43         ret = 0
44         ret += i for i in this
45         return ret
46
47 # ascending. All values must be Numbers
48 Array::num_sort = -> return this.sort((a, b) -> return a - b)
49
50 Array::last = ->
51         return this[this.length - 1]
52
53
54 ##############################################################
55 ##############    cookies (auto-save game)    ################
56 ##############################################################
57
58 set_cookie = (name, value, days) ->
59         date = new Date()
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
64
65 get_cookie = (name) ->
66         key = name + '='
67         for c in document.cookie.split /; */
68                 if c.indexOf key is 0
69                         return c.substr key.length
70         return null
71
72 delete_cookie = (name) ->
73         set_cookie name, '', -1
74 window.dc = delete_cookie
75
76
77 board_cols = board_col_heights.length
78 board_tiles = board_col_heights.sum()
79 board_col_top_px = []
80 score = 0
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
87
88 slides = []
89 selected = []
90
91 letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
92 letter_distribution = [
93         14355 # a
94          3968 # b
95          6325 # c
96          7045 # d
97         20258 # e
98          2739 # f
99          5047 # g
100          4372 # h
101         13053 # i
102           516 # j
103          2600 # k
104          9631 # l
105          5115 # m
106         10082 # n
107         11142 # o
108          5292 # p
109           287 # qu
110         12341 # r
111         16571 # s
112         10215 # t
113          6131 # u
114          1728 # v
115          2184 # w
116           619 # x
117          3512 # y
118           831 # z
119
120 ]
121
122 letter_distribution_total = 175973 # letter_distribution.sum()
123
124
125 new_letter_queue = []
126 new_letter = ->
127         if new_letter_queue.length
128                 l = new_letter_queue.shift()
129                 if l is 'Q'
130                         return 'Qu'
131                 else
132                         return l
133         r = Math.floor Math.random() * (letter_distribution_total + 1)
134         for i in [0..25]
135                 r -= letter_distribution[i]
136                 if r <= 0
137                         if letters[i] is 'Q'
138                                 return 'Qu'
139                         return letters[i]
140         return 'Z' # just in case
141
142
143
144 # in memory it's layed out like this:
145 # a c f j m
146 # b d g k n
147 #   e h l
148 #     i
149 # for display, columns are slid vertically like so:
150 #       f
151 #     c   j
152 #   a   g   m
153 #     d   k
154 #   b   h   n
155 #     e   l
156 #       i
157 #
158 # work out which grid spaces are connected
159 init_board_layout = () ->
160         col_offset = 0
161         middle_col = (board_cols - 1) / 2
162
163         # how many tiles before the current tile?
164         for col_num in [0 .. board_cols - 1]
165                 if col_num < middle_col
166                         fw_other = 1
167                 else
168                         fw_other = -1
169
170                 if col_num > middle_col
171                         bw_other = 1
172                 else
173                         bw_other = -1
174
175                 is_first_col = col_num is 0
176                 is_last_col = col_num is board_cols - 1
177
178                 neighbors = []
179                 push = (offset) ->
180                         neighbors.push col_offset + offset
181
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
185
186                 above = []
187                 for i in [0 .. board_col_heights[col_num] - 1]
188                         is_top_tile = i is 0
189                         is_bottom_tile = i is board_col_heights[col_num] - 1
190
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
194
195                         # aboves (array of tile numbers above, starting from top)
196                         board_aboves.push above.clone()
197                         above.push i + col_offset
198
199                         # below (SINGLE tile number of tile below or false)
200                         if is_bottom_tile
201                                 board_below.push false
202                         else
203                                 board_below.push col_offset + i + 1
204
205                         # neighbors (array of tile numbers "next to" this one)
206                         neighbors = []
207                         unless is_top_tile # upward link
208                                 push i - 1
209                         unless is_bottom_tile # downward links
210                                 push i + 1
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
221
222                         board_neighbors.push neighbors.clone()
223
224                 col_offset += board_col_heights[col_num]
225
226
227 init_board = ->
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)
236
237         # how far each tile needs to be slid down
238         slides = (0 for i in board)
239
240         # work out which grid spaces are connected
241         # (neighbors, above, down)
242         init_board_layout()
243
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
250
251         # color the selected tiles according to whether they're a word or not
252         if word.length
253                 classes = ['selected_word', 'selected']
254                 if is_word word
255                         c = 0
256                 else
257                         c = 1
258                 for num in selected
259                         html_tiles[num].addClass classes[c]
260                         html_tiles[num].removeClass classes[1 - c]
261
262 # unselects the last tile of the selecetion
263 unselect_tile = ->
264         _unselect_tile()
265         update_selection_display()
266
267 _unselect_tile = ->
268         num = selected.pop()
269         html_tile = html_tiles[num]
270         html_tile.removeClass 'selected_word'
271         html_tile.removeClass 'selected'
272
273 unselect_all = ->
274         while selected.length
275                 _unselect_tile()
276         update_selection_display()
277
278 shrink_selection = (leave_count) ->
279         while selected.length > leave_count
280                 _unselect_tile()
281         update_selection_display()
282
283 selected_word = ->
284         word = ''
285         word += board[i] for i in selected
286         return word.toLowerCase()
287
288 html_slide = (num, dist) ->
289         if 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
294
295 save_game = ->
296         encoded = ''
297         for t in board
298                 encoded += t.substr 0, 1
299         encoded += score
300         set_cookie 'hexbog', encoded, 365
301         window.location.hash = encoded
302
303 blip_selection = ->
304         faders = selected.clone().num_sort()
305         selected = []
306         for num in faders
307                 html_tiles[num].unbind('click').fadeOut fade_ms
308         timeout fade_ms, ->
309                 top_tile = -1
310                 new_px = 0
311                 new_slide = 0
312                 for fader in faders
313                         cur_top = board_aboves[fader][0]
314                         if cur_top is undefined
315                                 cur_top = fader
316                         if top_tile isnt cur_top
317                                 new_px = board_top_px[fader] - tile_width
318                                 new_slide = 1
319                                 top_tile = cur_top
320                         html_tiles[fader].remove()
321                         dest = fader
322                         aboves = board_aboves[fader].clone().reverse()
323                         for above in aboves
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
328                                 --dest
329                         new_tile top_tile, board_left_px[top_tile], new_px
330                         slides[top_tile] = new_slide
331                         new_px -= tile_width
332                         new_slide += 1
333                 for i in [0 .. board.length - 1]
334                         html_slide i, slides[i]
335                         slides[i] = 0
336                 save_game()
337         update_selection_display()
338
339 activate_selection = ->
340         word = selected_word()
341         if word.length < 3
342                 # FIXME make this a hint
343                 log "Too short: \"#{word}\""
344                 return
345         unless is_word word
346                 # FIXME make this automatically part of the selection display
347                 log "Not on word list: \"#{word}\""
348                 return
349         word_score = Math.round(Math.pow(1.7, word.length))
350         score += word_score
351         $score_display.html score
352         # FIXME make some kind of animation showing score gain
353         log "blipped \"#{word}\" for #{word_score} points"
354         blip_selection()
355         look_up_definition word
356         $('#definition').click()
357
358
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})"
364         html += ': '
365         html += definition
366         html += '<div id="definition_credit">Definition &copy;<a href="http://en.wiktionary.org/" target="_blank">wiktionary.org</a> CC-BY-SA</div>'
367         $definition_body.html html
368
369
370 select_tile = (num) ->
371         html_tile = html_tiles[num]
372         # html_tile.css backgroundColor: tile_selected_color
373         selected.push num
374         update_selection_display()
375         return
376
377 new_tile = (num, x, y) ->
378         letter = new_letter()
379
380         html_tile = $("<div class=\"tile\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
381         $board.append(html_tile)
382
383         html_tile.data 'tile_number', num
384         board[num] = letter
385         html_tiles[num] = html_tile
386
387         html_tile.click ->
388                 me = $(this)
389                 num = me.data 'tile_number'
390                 if num in selected
391                         nth_of_word = selected.indexOf(num)
392                         first = nth_of_word is 0
393                         last = nth_of_word is selected.length - 1
394
395                         if first and last
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?
400                         else if last
401                                 activate_selection()
402                         else
403                                 shrink_selection nth_of_word + 1
404                 else # (not clicking on selected tile)
405                         if selected.length is 0
406                                 select_tile num
407                         else
408                                 unless num in board_neighbors[selected.last()]
409                                         unselect_all()
410                                 select_tile num
411
412
413 $board = null
414 html_tiles = []
415 init_html_board = ->
416         $('#loading').remove()
417         $selection_display = $('#selection')
418         $score_display = $('#score')
419         $score_display.html score
420         $definition_body = $('#definition_body')
421         $board = $('#board')
422         # make html for board
423         tile_number = 0
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
429                         tile_number++
430
431 word_bins = []; word_bins.push(',') for [0...997]
432 hash_word = (word) ->
433         h = 0
434         for i in [0...word.length]
435                 h ^= word.charCodeAt(i) << ((i*3) % 21)
436         return h % 997
437 is_word = (str) ->
438         word_bins[hash_word str].indexOf(",#{str},") > -1
439
440 # this is called automatically by the compressed wordlist
441 parse_word_list = (compressed) ->
442         prefix = ''
443         cap_a = "A".charCodeAt 0
444         i = 0
445         next_chunk = ->
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
456                         return
457                 else
458                         timeout 1, next_chunk
459         timeout 1, next_chunk
460
461 extract_wiktionary_definiton = (html) ->
462         found = false
463         finds = {}
464         language = false
465         part = false
466
467         # clean HTML
468         ##################
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.
472
473         # attributes
474         #                            src: <img>, <audio>, etc
475         #                         onload: only <body>?
476         #   archive,codebase,data,usemap: <object>
477         #                           href: <link>
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
480
481         elements = $(html)
482
483         valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
484
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)
490                         if found
491                                 return false # break
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
495                         part = false
496                         text = $(el).text()
497                         for p in valid_parts
498                                 if text is "[edit] #{p}"
499                                         part = p.toLowerCase()
500                                         # FIXME break
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"
505                                         key = 'obsolete'
506                                 else
507                                         if part is 'verb'
508                                                 key = 'verb'
509                                         else
510                                                 key = 'nonverb'
511                                 finds[key] ?= [part, new_def, language]
512                                 found = true
513                                 if part is 'verb'
514                                         # verbs are the best! stop scanning when we find one
515                                         return false # break
516                         if found.verb
517                                 return false # break
518
519         part_defs = (finds[i] for i in ['verb', 'nonverb', 'obsolete'] when finds[i])
520         unless part_defs.length
521                 return false
522
523         return part_defs[0]
524
525
526 look_up_definition = (word) ->
527         $.ajax({
528                 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
529                 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
530                 dataType: 'jsonp'
531                 cache: true
532                 success: (data, error_msg, xhr) ->
533                         if data?.parse?.text?['*']?
534                                 tdl = extract_wiktionary_definiton data.parse.text['*']
535                                 if tdl
536                                         show_definition word, tdl[0], tdl[1], tdl[2]
537                         else
538                                 $definition_body.html "Sorry, couldn't find a definition for \"#{word}\"."
539         })
540
541 board_as_txt = ->
542         ret = ''
543         index = 0
544         for i in [0 .. board_min_height * 2]
545                 unless i % 2
546                         ret += '   ' + board[j] for j in [board_min_height + index .. board_tiles - 1] by 2 * board_min_height + 1
547                 else
548                         ret += ' ' + board[j] + '  ' for j in [index .. board_tiles - 1] by 2 * board_min_height + 1
549                         index += 1
550
551                 ret += '\n'
552         return ret
553
554 start_over = ->
555         selected = []
556         score = 0
557         $score_display.html score
558         for i in [0...board_tiles]
559                 selected.push i
560         blip_selection()
561
562 init_start_over_link = ->
563         $('#start-over').click (event) ->
564                 event.preventDefault()
565                 if confirm "Are you sure you want to start over? There is no undo."
566                         start_over()
567
568 cur_tab = 'instructions'
569 tabtab_height = 20
570 tab_height = 150
571 init_tab = (t) ->
572         $('#' + t).click ->
573                 return if t is cur_tab
574                 $('#' + cur_tab).removeClass('selected-tab').addClass('tab').animate({height: tabtab_height}, 1000)
575                 $('#' + t).removeClass('tab').addClass('selected-tab').animate({height: tab_height}, 1000)
576                 cur_tab = t
577 init_tabs = ->
578         for t in ['instructions', 'definition', 'donate', 'restart']
579                 init_tab t
580
581 init_keybinding = ->
582         $(window).keydown (e) ->
583                 switch e.keyCode
584                         when 32, 10, 13
585                                 activate_selection()
586                         when 27
587                                 unselect_all()
588
589 $log = undefined
590 init_log = ->
591         $log = $('#log')
592 log = (msg) ->
593         console.log msg if console.log?
594
595 init_game = ->
596         init_log()
597         if $(window).height() >= 440
598                 $('#centerer').css('margin-top', '25px')
599         init_keybinding()
600         init_tabs()
601         init_board()
602         init_html_board()
603         init_start_over_link()
604
605 $(init_game)