JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
better effects for blipping
[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 # code and css will need adjusting if you change HP_MAX
30 HP_MAX = 10
31
32 ##############################################################
33 ##############    fix javascript some more    ################
34 ##############################################################
35
36 # so annoying that setTimeout has its arguments in the wrong order
37 timeout = (ms, callback) ->
38         setTimeout callback, ms
39
40 # warning: it's shalow (sub-elements are not cloned)
41 Array::clone = ->
42         return this.slice(0)
43
44 Array::sum = ->
45         ret = 0
46         ret += i for i in this
47         return ret
48
49 # ascending. All values must be Numbers
50 Array::num_sort = -> return this.sort((a, b) -> return a - b)
51
52 Array::last = ->
53         return this[this.length - 1]
54
55
56 ##############################################################
57 ##############    cookies (auto-save game)    ################
58 ##############################################################
59
60 set_cookie = (name, value, days) ->
61         date = new Date()
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
66
67 get_cookie = (name) ->
68         key = name + '='
69         for c in document.cookie.split /; */
70                 if c.indexOf key is 0
71                         return c.substr key.length
72         return null
73
74 delete_cookie = (name) ->
75         set_cookie name, '', -1
76 window.dc = delete_cookie
77
78
79 board_cols = board_col_heights.length
80 board_tiles = board_col_heights.sum()
81 board_col_top_px = []
82 score = 0
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
89
90 selected = []
91
92 letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
93 letter_distribution = [
94         14355 # a
95          3968 # b
96          6325 # c
97          7045 # d
98         20258 # e
99          2739 # f
100          5047 # g
101          4372 # h
102         13053 # i
103           516 # j
104          2600 # k
105          9631 # l
106          5115 # m
107         10082 # n
108         11142 # o
109          5292 # p
110           287 # qu
111         12341 # r
112         16571 # s
113         10215 # t
114          6131 # u
115          1728 # v
116          2184 # w
117           619 # x
118          3512 # y
119           831 # z
120
121 ]
122
123 letter_distribution_total = 175973 # letter_distribution.sum()
124
125
126 new_letter_queue = []
127 new_letter = ->
128         if new_letter_queue.length
129                 l = new_letter_queue.shift()
130                 if l is 'Q'
131                         return 'Qu'
132                 else
133                         return l
134         r = Math.floor Math.random() * (letter_distribution_total + 1)
135         for i in [0..25]
136                 r -= letter_distribution[i]
137                 if r <= 0
138                         if letters[i] is 'Q'
139                                 return 'Qu'
140                         return letters[i]
141         return 'Z' # just in case
142
143
144
145 # in memory it's layed out like this:
146 # a c f j m
147 # b d g k n
148 #   e h l
149 #     i
150 # for display, columns are slid vertically like so:
151 #       f
152 #     c   j
153 #   a   g   m
154 #     d   k
155 #   b   h   n
156 #     e   l
157 #       i
158 #
159 # work out which grid spaces are connected
160 init_board_layout = () ->
161         col_offset = 0
162         middle_col = (board_cols - 1) / 2
163
164         # how many tiles before the current tile?
165         for col_num in [0 .. board_cols - 1]
166                 if col_num < middle_col
167                         fw_other = 1
168                 else
169                         fw_other = -1
170
171                 if col_num > middle_col
172                         bw_other = 1
173                 else
174                         bw_other = -1
175
176                 is_first_col = col_num is 0
177                 is_last_col = col_num is board_cols - 1
178
179                 neighbors = []
180                 push = (offset) ->
181                         neighbors.push col_offset + offset
182
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
186
187                 above = []
188                 for i in [0 .. board_col_heights[col_num] - 1]
189                         is_top_tile = i is 0
190                         is_bottom_tile = i is board_col_heights[col_num] - 1
191
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
195
196                         # aboves (array of tile numbers above, starting from top)
197                         board_aboves.push above.clone()
198                         above.push i + col_offset
199
200                         # below (SINGLE tile number of tile below or false)
201                         if is_bottom_tile
202                                 board_below.push false
203                         else
204                                 board_below.push col_offset + i + 1
205
206                         # neighbors (array of tile numbers "next to" this one)
207                         neighbors = []
208                         unless is_top_tile # upward link
209                                 push i - 1
210                         unless is_bottom_tile # downward links
211                                 push i + 1
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
222
223                         board_neighbors.push neighbors.clone()
224
225                 col_offset += board_col_heights[col_num]
226
227
228 init_board = ->
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)
237
238         # work out which grid spaces are connected
239         # (neighbors, above, down)
240         init_board_layout()
241
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')
249         if word.length > 0
250                 if word.length < 3
251                         $big_tip.html word
252                         $little_tip.html "Click more tiles (3 minimum)"
253                 else
254                         if is_word word
255                                 if word.indexOf(word.substr(word.length - 1)) < word.length - 1
256                                         last = 'last '
257                                 else
258                                         last = ''
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')
262                         else
263                                 $big_tip.html word
264                                 $little_tip.html "\"#{word}\" is not in the word list."
265         else
266                 $big_tip.html "← Click a word"
267                 $little_tip.html "(tiles must be touching)"
268
269         # color the selected tiles according to whether they're a word or not
270         if word.length
271                 classes = ['selected_word', 'selected']
272                 if is_word word
273                         c = 0
274                 else
275                         c = 1
276                 for num in selected
277                         tiles[num].dom.addClass classes[c]
278                         tiles[num].dom.removeClass classes[1 - c]
279
280 # unselects the last tile of the selecetion
281 unselect_tile = ->
282         _unselect_tile()
283         update_selection_display()
284
285 _unselect_tile = ->
286         num = selected.pop()
287         html_tile = tiles[num].dom
288         html_tile.removeClass 'selected_word'
289         html_tile.removeClass 'selected'
290
291 unselect_all = ->
292         while selected.length
293                 _unselect_tile()
294         update_selection_display()
295
296 selected_word = ->
297         word = ''
298         word += tiles[i].text for i in selected
299         return word.toLowerCase()
300
301 save_game = ->
302         encoded = ''
303         for t in tiles
304                 encoded += t.text.substr 0, 1
305         encoded += score
306         set_cookie 'hexbog', encoded, 365
307         window.location.hash = encoded
308
309 unsink = (tile) ->
310         tile.new_hp = 10
311         tile.text = new_letter()
312         tile.dom.html tile.text
313
314 # remove the selected tiles from the board, create new tiles, and slide everything into place
315 blip_selection = ->
316         difficulty = 11 - Math.log(400 + score) # higher numbers are easier
317         force = difficulty * score_for selected_word() # how much tile restoration we have left to do
318         word_length = selected_word().length
319         faders = selected.num_sort()
320         selected = []
321         update_selection_display()
322         neighbors = {}
323         nneighbors = {}
324         for i in faders
325                 tiles[i].dom.unbind('click').fadeOut fade_ms
326                 tiles[i].new_hp = tiles[i].hp
327                 for n in board_neighbors[i]
328                         neighbors[n] = tiles[n]
329                         for nn in board_neighbors[n]
330                                 nneighbors[nn] = tiles[nn]
331         for i in faders
332                 delete nneighbors[i]
333                 delete neighbors[i]
334         for k, v of neighbors
335                 delete nneighbors[k]
336         # convert to arrays so we can sort, etc
337         nneighbors = (v for k, v of nneighbors)
338         neighbors = (v for k, v of neighbors)
339         boom = [
340                 {
341                         tiles: neighbors,
342                         up: [],
343                         down: []
344                 },
345                 {
346                         tiles: nneighbors,
347                         up: [],
348                         down: []
349                 }
350         ]
351         for n in boom
352                 for t in n.tiles
353                         if t.hp is 0
354                                 n.down.push t
355                         else
356                                 n.up.push t
357         switch word_length
358                 when 3
359                         boom[0].flips = 1
360                         boom[0].force = 2
361                         boom[1].flips = 0
362                         boom[1].force = 0
363                 when 4
364                         boom[0].flips = 'all'
365                         boom[0].force = 4
366                         boom[1].flips = 0
367                         boom[1].force = 2
368                 when 5
369                         boom[0].flips = 'all'
370                         boom[0].force = 6
371                         boom[1].flips = 2
372                         boom[1].force = 4
373                 when 6
374                         boom[0].flips = 'all'
375                         boom[0].force = 10
376                         boom[1].flips = 5
377                         boom[1].force = 6
378                 when 7
379                         boom[0].flips = 'all'
380                         boom[0].force = 10
381                         boom[1].flips = 'all'
382                         boom[1].force = 10
383                 else
384                         boom[0].flips = 0
385                         boom[0].force = 0
386                         boom[1].flips = 0
387                         boom[1].force = 0
388                         # unsink/heal the whole board
389                         for t in tiles
390                                 if t.hp is 0
391                                         unsink t
392                                 else
393                                         t.new_hp = 10
394         for b in boom
395                 if b.flips is 'all' or b.flips >= b.down.length
396                         for t in b.down
397                                 unsink t
398                 else
399                         while b.flips > 0 and b.down.length > 0
400                                 b.flips -= 1
401                                 flipper = Math.floor(Math.random() * b.down.length)
402                                 unsink b.down[flipper]
403                                 b.down = [b.down[0...flipper]..., b.down[flipper+1...b.down.length]...]
404                 if b.force > 0
405                         for t in b.up
406                                 t.new_hp = t.hp + b.force
407         for i in tiles
408                 i.new_hp ?= i.hp - 1
409                 if i.new_hp < 0
410                         i.new_hp = 0
411                 else if i.new_hp > HP_MAX
412                         i.new_hp = HP_MAX
413                 if i.new_hp isnt i.hp
414                         i.dom.removeClass "hp#{i.hp}"
415                         i.dom.addClass "hp#{i.new_hp}"
416                         i.hp = i.new_hp
417                 delete i.new_hp
418         timeout fade_ms + 1, ->
419                 # which tiles need to be slid down
420                 sliders = (false for i in tiles)
421
422                 prev_col_top = null
423                 next_new_y = null
424                 for deleted in faders
425                         # find the tile number of the top tile in this column
426                         if board_aboves[deleted].length is 0
427                                 col_top = deleted
428                         else
429                                 col_top = board_aboves[deleted][0]
430
431                         # reset location where new tiles appear when we change columns
432                         if prev_col_top isnt col_top
433                                 next_new_y = -10 - tile_width
434                                 prev_col_top = col_top
435
436                         tiles[deleted].dom.remove()
437
438                         # For each each tile above the one we've deleted:
439                         # 1. move it down one slot in the data scructures
440                         # 2. mark it as needing to slide
441                         dest = deleted
442                         aboves = board_aboves[deleted].clone().reverse()
443                         for above in aboves
444                                 tiles[dest] = tiles[above]
445                                 tiles[dest].id = dest
446                                 tiles[dest].dom.data 'tile_number', dest
447                                 sliders[dest] = true
448                                 --dest
449                         sliders[col_top] = true # the new tile needs to be slid down too
450
451                         new_tile col_top, board_left_px[col_top], next_new_y
452                         next_new_y -= tile_width + 50
453
454                 for slide, i in sliders
455                         if slide
456                                 tiles[i].dom.animate {top: "#{tile_top_px[i]}px"}, slide_ms
457                                 sliders[i] = false
458                 save_game()
459
460 score_for = (word) -> Math.round(Math.pow(1.7, word.length))
461
462 activate_selection = ->
463         word = selected_word()
464         if word.length < 3
465                 # FIXME make this a hint
466                 log "Too short: \"#{word}\""
467                 return
468         unless is_word word
469                 # FIXME make this automatically part of the selection display
470                 log "Not on word list: \"#{word}\""
471                 return
472         word_score = score_for word
473         score += word_score
474         $score_display.html score
475         # FIXME make some kind of animation showing score gain
476         log "blipped \"#{word}\" for #{word_score} points"
477         blip_selection()
478         look_up_definition word
479         $('#definition').click()
480
481
482 show_definition = (word, type, definition, language) ->
483         html = "<a href=\"http://en.wiktionary.org/wiki/#{word}\" target=\"_blank\">"
484         html += "#{word.substr(0, 1).toUpperCase() + word.substr(1)}</a>, #{type}"
485         if language isnt 'English'
486                 html += " (#{language})"
487         html += ': '
488         html += definition
489         html += '<div id="definition_credit">Definition &copy;<a href="http://en.wiktionary.org/" target="_blank">wiktionary.org</a> CC-BY-SA</div>'
490         $definition_body.html html
491
492
493 select_tile = (num) ->
494         html_tile = tiles[num].dom
495         # html_tile.css backgroundColor: tile_selected_color
496         selected.push num
497         update_selection_display()
498         return
499
500 new_tile = (num, x, y) ->
501         letter = new_letter()
502
503         hp = 1 + Math.floor(Math.random() * (HP_MAX - 1))
504
505         html_tile = $("<div class=\"tile hp#{hp}\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
506         $board.append(html_tile)
507
508         html_tile.data 'tile_number', num
509         tiles[num] = text: letter, dom: html_tile, hp: hp, id: num
510
511         html_tile.click ->
512                 me = $(this)
513                 num = me.data 'tile_number'
514                 return if tiles[num].hp < 1
515                 if num in selected
516                         if selected_word().length > 2 and num is selected.last()
517                                 activate_selection()
518                         else
519                                 if selected.length > 1
520                                         unselect_all()
521                                         select_tile num
522                                 else
523                                         unselect_all()
524                 else # (not clicking on selected tile)
525                         if selected.length > 0 and not (num in board_neighbors[selected.last()])
526                                 unselect_all()
527                         select_tile num
528
529
530 $board = null
531 init_html_board = ->
532         $('#loading').remove()
533         $big_tip = $('#big_tip')
534         $little_tip = $('#little_tip')
535         $score_display = $('#score')
536         $score_display.html score
537         $definition_body = $('#definition_body')
538         $board = $('#board')
539         # make html for board
540         tile_number = 0
541         for col_num in [0 .. board_cols - 1]
542                 for num in [0 .. board_col_heights[col_num] - 1]
543                         x = col_num * tile_width
544                         y = board_col_top_px[col_num] + num * tile_width
545                         new_tile tile_number, x, y
546                         tile_number++
547
548 word_bins = []; word_bins.push(',') for [0...997]
549 hash_word = (word) ->
550         h = 0
551         for i in [0...word.length]
552                 h ^= word.charCodeAt(i) << ((i*3) % 21)
553         return h % 997
554 is_word = (str) ->
555         word_bins[hash_word str].indexOf(",#{str},") > -1
556
557 # this is called automatically by the compressed wordlist
558 parse_word_list = (compressed) ->
559         prefix = ''
560         cap_a = "A".charCodeAt 0
561         i = 0
562         next_chunk = ->
563                 chunk = compressed[i]
564                 for word in chunk.match(/[a-z]*[A-Z]/g)
565                         # the capital letter (at the end of the match) says how many characters
566                         # from the end of the previous word should be removed to create the prefix
567                         # for the next word. "A" for 0, "B" for 1, "C" for 2, etc
568                         bs = word[word.length - 1].charCodeAt(0) - cap_a
569                         word = prefix + word[0 ... word.length - 1]
570                         word_bins[hash_word word] += word + ','
571                         prefix = word[0 ... word.length - bs]
572                 if ++i is compressed.length
573                         return
574                 else
575                         timeout 1, next_chunk
576         timeout 1, next_chunk
577
578 extract_wiktionary_definiton = (html) ->
579         found = false
580         finds = {}
581         language = false
582         part = false
583
584         # clean HTML
585         ##################
586         # when we instantiate the html so we can use dom traversal, the browser
587         # will start loading images and such. This section attempts to mangle the
588         # html so no resources are loaded when the html is parsed.
589
590         # attributes
591         #                            src: <img>, <audio>, etc
592         #                         onload: only <body>?
593         #   archive,codebase,data,usemap: <object>
594         #                           href: <link>
595         #                 id,class,style: background: url(foo.png), etc
596         html = html.replace /(src|onload|archive|codebase|data|usemap|href|style|id|class)=['"][^"']*['"]/ig, '', html
597
598         elements = $(html)
599
600         valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
601
602         edit_link_regex = new RegExp(' ?\\[edit\\] ?')
603
604         elements.each (i, el) ->
605                 #which tag: el.tagName
606                 if el.tagName is 'H2'
607                         # if we found a definition in the previous language section, run with it
608                         # (we only stop for verbs, in hopes of finding one in english)
609                         if found
610                                 return false # break
611                         part = false # mark us not being in a definition section unless the next section finds a part of speach header
612                         language = $(el).text().replace(edit_link_regex, '')
613                 if language and el.tagName is 'H3' or el.tagName is 'H4' # eg yak def uses one for english and one for dutch
614                         part = false
615                         text = $(el).text().replace(edit_link_regex, '')
616                         for p in valid_parts
617                                 if text is "#{p}"
618                                         part = p.toLowerCase()
619                                         # FIXME break
620                 if part and el.tagName is 'OL'
621                         $(el).children().each (i, el) ->
622                                 new_def = $(el).text()
623                                 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 "
624                                         key = 'lame'
625                                 else
626                                         if part is 'verb'
627                                                 key = 'verb'
628                                         else
629                                                 key = 'nonverb'
630                                 finds[key] ?= [part, new_def, language]
631                                 found = true
632                                 if part is 'verb'
633                                         # verbs are the best! stop scanning when we find one
634                                         return false # break
635                         if found.verb
636                                 return false # break
637
638         part_defs = (finds[i] for i in ['verb', 'nonverb', 'lame'] when finds[i])
639         unless part_defs.length
640                 return false
641
642         return part_defs[0]
643
644
645 look_up_definition = (word) ->
646         $definition_body.html "Looking up definition for \"#{word}\"..."
647         $.ajax({
648                 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
649                 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
650                 dataType: 'jsonp'
651                 cache: true
652                 success: (data, error_msg, xhr) ->
653                         if data?.parse?.text?['*']?
654                                 tdl = extract_wiktionary_definiton data.parse.text['*']
655                                 if tdl
656                                         show_definition word, tdl[0], tdl[1], tdl[2]
657                                 else
658                                         $definition_body.html "Oops, could't find a definition for \"#{word}\"."
659                         else
660                                 $definition_body.html "Sorry, couldn't find a definition for \"#{word}\"."
661         })
662
663 board_as_txt = ->
664         ret = ''
665         index = 0
666         for i in [0 .. board_min_height * 2]
667                 unless i % 2
668                         ret += '   ' + tiles[j].text for j in [board_min_height + index .. board_tiles - 1] by 2 * board_min_height + 1
669                 else
670                         ret += ' ' + tiles[j].text + '  ' for j in [index .. board_tiles - 1] by 2 * board_min_height + 1
671                         index += 1
672
673                 ret += '\n'
674         return ret
675
676 start_over = ->
677         selected = []
678         score = 0
679         $score_display.html score
680         for i in [0...board_tiles]
681                 selected.push i
682         blip_selection()
683
684 init_start_over_link = ->
685         $('#start-over').click (event) ->
686                 event.preventDefault()
687                 if confirm "Are you sure you want to start over? There is no undo."
688                         start_over()
689
690 cur_tab = 'instructions'
691 tabtab_height = 20
692 tab_height = 150
693 init_tab = (t) ->
694         $('#' + t).click ->
695                 return if t is cur_tab
696                 $('#' + cur_tab).removeClass('selected-tab').addClass('tab').animate({height: tabtab_height}, 1000)
697                 $('#' + t).removeClass('tab').addClass('selected-tab').animate({height: tab_height}, 1000)
698                 cur_tab = t
699 init_tabs = ->
700         for t in ['instructions', 'definition', 'donate', 'restart']
701                 init_tab t
702
703 init_keybinding = ->
704         $(window).keydown (e) ->
705                 switch e.keyCode
706                         when 32, 10, 13
707                                 activate_selection()
708                         when 27
709                                 unselect_all()
710
711 log = (msg) ->
712         console.log msg if console?.log?
713
714 init_game = ->
715         if $(window).height() >= 440
716                 $('#centerer').css('margin-top', '25px')
717         init_keybinding()
718         init_tabs()
719         init_board()
720         init_html_board()
721         init_start_over_link()
722         update_selection_display()
723
724 $(init_game)