JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
5c1fab773239f5b92e98cc9309253fd627e01a02
[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_word = null # initialized by init_html_board
247 $definition_link = null # initialized by init_html_board
248 $definition_type = null # initialized by init_html_board
249 $definition_language = null # initialized by init_html_board
250 $definition_text = null # initialized by init_html_board
251 $definition_credit = null # initialized by init_html_board
252 update_selection_display = ->
253         word = selected_word()
254         $selection_display.html word
255
256         # color the selected tiles according to whether they're a word or not
257         if word.length
258                 classes = ['selected_word', 'selected']
259                 if is_word word
260                         c = 0
261                 else
262                         c = 1
263                 for num in selected
264                         html_tiles[num].addClass classes[c]
265                         html_tiles[num].removeClass classes[1 - c]
266
267 # unselects the last tile of the selecetion
268 unselect_tile = ->
269         _unselect_tile()
270         update_selection_display()
271
272 _unselect_tile = ->
273         num = selected.pop()
274         html_tile = html_tiles[num]
275         html_tile.removeClass 'selected_word'
276         html_tile.removeClass 'selected'
277
278 unselect_all = ->
279         while selected.length
280                 _unselect_tile()
281         update_selection_display()
282
283 shrink_selection = (leave_count) ->
284         while selected.length > leave_count
285                 _unselect_tile()
286         update_selection_display()
287
288 selected_word = ->
289         word = ''
290         word += board[i] for i in selected
291         return word.toLowerCase()
292
293 html_slide = (num, dist) ->
294         if dist
295                 cur = html_tiles[num].css 'top'
296                 cur = Number(cur.substr(0, cur.length - 2))
297                 dest = cur + (dist * tile_width)
298                 html_tiles[num].animate {top: "#{dest}px"}, slide_ms
299
300 save_game = ->
301         encoded = ''
302         for t in board
303                 encoded += t.substr 0, 1
304         encoded += score
305         set_cookie 'hexbog', encoded, 365
306         window.location.hash = encoded
307
308 blip_selection = ->
309         faders = selected.clone().num_sort()
310         selected = []
311         for num in faders
312                 html_tiles[num].unbind('click').fadeOut fade_ms
313         timeout fade_ms, ->
314                 top_tile = -1
315                 new_px = 0
316                 new_slide = 0
317                 for fader in faders
318                         cur_top = board_aboves[fader][0]
319                         if cur_top is undefined
320                                 cur_top = fader
321                         if top_tile isnt cur_top
322                                 new_px = board_top_px[fader] - tile_width
323                                 new_slide = 1
324                                 top_tile = cur_top
325                         html_tiles[fader].remove()
326                         dest = fader
327                         aboves = board_aboves[fader].clone().reverse()
328                         for above in aboves
329                                 html_tiles[dest] = html_tiles[above]
330                                 html_tiles[dest].data 'tile_number', dest
331                                 board[dest] = board[above]
332                                 slides[dest] = slides[above] + 1
333                                 --dest
334                         new_tile top_tile, board_left_px[top_tile], new_px
335                         slides[top_tile] = new_slide
336                         new_px -= tile_width
337                         new_slide += 1
338                 for i in [0 .. board.length - 1]
339                         html_slide i, slides[i]
340                         slides[i] = 0
341                 save_game()
342         update_selection_display()
343
344 activate_selection = ->
345         word = selected_word()
346         if word.length < 3
347                 log "Too short: \"#{word}\""
348                 return
349         unless is_word word
350                 log "Not on word list: \"#{word}\""
351                 return
352         score += Math.round(Math.pow(1.7, word.length))
353         $score_display.html score
354         log "blipped: #{word}"
355         blip_selection()
356         look_up_definition word
357
358
359 definition_credited = false
360 show_definition = (word, type, definition, language) ->
361         if language is 'English'
362                 $definition_language.html ''
363         else
364                 $definition_language.html " (#{language})"
365         $definition_type.html type
366         $definition_link.attr 'href', "http://en.wiktionary.org/wiki/#{word}"
367         $definition_word.html word.substr(0, 1).toUpperCase() + word.substr(1)
368         $definition_text.html definition
369         unless definition_credited
370                 definition_credited = true
371                 $definition_credit.html "Definitions &copy; <a href=\"http://en.wiktionary.org/\" target=\"_blank\">wiktionary.org</a> CC-BY-SA"
372
373
374 select_tile = (num) ->
375         html_tile = html_tiles[num]
376         # html_tile.css backgroundColor: tile_selected_color
377         selected.push num
378         update_selection_display()
379         return
380
381 new_tile = (num, x, y) ->
382         letter = new_letter()
383
384         html_tile = $("<div class=\"tile\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
385         $board.append(html_tile)
386
387         html_tile.data 'tile_number', num
388         board[num] = letter
389         html_tiles[num] = html_tile
390
391         html_tile.click ->
392                 me = $(this)
393                 num = me.data 'tile_number'
394                 if num in selected
395                         nth_of_word = selected.indexOf(num)
396                         first = nth_of_word is 0
397                         last = nth_of_word is selected.length - 1
398
399                         if first and last
400                                 unselect_all() # Clicking only selected letter unselects it
401                         else if first and !last
402                                 shrink_selection 1 # Clicking start of word goes back to just that letter
403                                 # should this unselect all?
404                         else if last
405                                 activate_selection()
406                         else
407                                 shrink_selection nth_of_word + 1
408                 else # (not clicking on selected tile)
409                         if selected.length is 0
410                                 select_tile num
411                         else
412                                 unless num in board_neighbors[selected.last()]
413                                         unselect_all()
414                                 select_tile num
415
416
417 $board = null
418 html_tiles = []
419 init_html_board = ->
420         $('#loading').remove()
421         $selection_display = $('#selection')
422         $score_display = $('#score')
423         $score_display.html score
424         $definition_word = $('#definition_word')
425         $definition_type = $('#definition_type')
426         $definition_language = $('#definition_language')
427         $definition_link = $('#definition_link')
428         $definition_text = $('#definition_text')
429         $definition_credit = $('#definition_credit')
430         $board = $('#board')
431         # make html for board
432         tile_number = 0
433         for col_num in [0 .. board_cols - 1]
434                 for num in [0 .. board_col_heights[col_num] - 1]
435                         x = col_num * tile_width
436                         y = board_col_top_px[col_num] + num * tile_width
437                         new_tile tile_number, x, y
438                         tile_number++
439
440 word_bins = []; word_bins.push(',') for [0...997]
441 hash_word = (word) ->
442         h = 0
443         for i in [0...word.length]
444                 h ^= word.charCodeAt(i) << ((i*3) % 21)
445         return h % 997
446 is_word = (str) ->
447         word_bins[hash_word str].indexOf(",#{str},") > -1
448
449 # this is called automatically by the compressed wordlist
450 parse_word_list = (compressed) ->
451         prefix = ''
452         cap_a = "A".charCodeAt 0
453         i = 0
454         next_chunk = ->
455                 chunk = compressed[i]
456                 for word in chunk.match(/[a-z]*[A-Z]/g)
457                         # the capital letter (at the end of the match) says how many characters
458                         # from the end of the previous word should be removed to create the prefix
459                         # for the next word. "A" for 0, "B" for 1, "C" for 2, etc
460                         bs = word[word.length - 1].charCodeAt(0) - cap_a
461                         word = prefix + word[0 ... word.length - 1]
462                         word_bins[hash_word word] += word + ','
463                         prefix = word[0 ... word.length - bs]
464                 if ++i is compressed.length
465                         return
466                 else
467                         timeout 1, next_chunk
468         timeout 1, next_chunk
469
470 extract_wiktionary_definiton = (html) ->
471         found = false
472         finds = {}
473         language = false
474         part = false
475
476         # clean HTML
477         ##################
478         # when we instantiate the html so we can use dom traversal, the browser
479         # will start loading images and such. This section attempts to mangle the
480         # html so no resources are loaded when the html is parsed.
481
482         # attributes
483         #                            src: <img>, <audio>, etc
484         #                         onload: only <body>?
485         #   archive,codebase,data,usemap: <object>
486         #                           href: <link>
487         #                 id,class,style: background: url(foo.png), etc
488         html = html.replace /(src|onload|archive|codebase|data|usemap|href|style|id|class)=['"][^"']*['"]/ig, '', html
489
490         elements = $(html)
491
492         valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
493
494         elements.each (i, el) ->
495                 #which tag: el.tagName
496                 if el.tagName is 'H2'
497                         # if we found a definition in the previous language section, run with it
498                         # (we only stop for verbs, in hopes of finding one in english)
499                         if found
500                                 return false # break
501                         part = false # mark us not being in a definition section unless the next section finds a part of speach header
502                         language = $(el).text().substr 7
503                 if language and el.tagName is 'H3' or el.tagName is 'H4' # eg yak def uses one for english and one for dutch
504                         part = false
505                         text = $(el).text()
506                         for p in valid_parts
507                                 if text is "[edit] #{p}"
508                                         part = p.toLowerCase()
509                                         # FIXME break
510                 if part and el.tagName is 'OL'
511                         $(el).children().each (i, el) ->
512                                 new_def = $(el).text()
513                                 if new_def.substr(0, 9) is '(obsolete' or new_def.substr(0, 8) is "(archaic"
514                                         key = 'obsolete'
515                                 else
516                                         if part is 'verb'
517                                                 key = 'verb'
518                                         else
519                                                 key = 'nonverb'
520                                 finds[key] ?= [part, new_def, language]
521                                 found = true
522                                 if part is 'verb'
523                                         # verbs are the best! stop scanning when we find one
524                                         return false # break
525                         if found.verb
526                                 return false # break
527
528         part_defs = (finds[i] for i in ['verb', 'nonverb', 'obsolete'] when finds[i])
529         unless part_defs.length
530                 return false
531
532         return part_defs[0]
533
534
535 look_up_definition = (word) ->
536         $.ajax({
537                 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
538                 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
539                 dataType: 'jsonp'
540                 cache: true
541                 success: (data, error_msg, xhr) ->
542                         if data?.parse?.text?['*']?
543                                 tdl = extract_wiktionary_definiton data.parse.text['*']
544                                 if tdl
545                                         show_definition word, tdl[0], tdl[1], tdl[2]
546                         else
547                                 log "Sorry, couldn't find a definition for \"#{word}\""
548                 error: ->
549                         log "wiktionary failed to load: \"#{error_msg}\""
550         })
551
552 board_as_txt = ->
553         ret = ''
554         index = 0
555         for i in [0 .. board_min_height * 2]
556                 unless i % 2
557                         ret += '   ' + board[j] for j in [board_min_height + index .. board_tiles - 1] by 2 * board_min_height + 1
558                 else
559                         ret += ' ' + board[j] + '  ' for j in [index .. board_tiles - 1] by 2 * board_min_height + 1
560                         index += 1
561
562                 ret += '\n'
563         return ret
564
565 start_over = ->
566         selected = []
567         score = 0
568         $score_display.html score
569         for i in [0...board_tiles]
570                 selected.push i
571         blip_selection()
572
573 init_start_over_link = ->
574         $('#start-over').click (event) ->
575                 event.preventDefault()
576                 if confirm "Are you sure you want to start over? There is no undo."
577                         start_over()
578
579 $log = undefined
580 init_log = ->
581         $log = $('#log')
582 log = (msg) ->
583         $log.children().last().remove()
584         $log.prepend $('<div></div>').html msg
585
586 init_game = ->
587         init_log()
588         init_board()
589         init_html_board()
590         init_start_over_link()
591
592 $(init_game)