JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
basic gameplay working
[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          9 # A
94          2 # B
95          2 # C
96          4 # D
97         14 # E
98          2 # F
99          3 # G
100          2 # H
101          7 # I
102          1 # J
103          1 # K
104          4 # L
105          2 # M
106          6 # N
107          8 # O
108          2 # P
109          1 # Q
110          6 # R
111          7 # S
112          6 # T
113          2 # U
114          2 # V
115          2 # W
116          1 # X
117          2 # Y
118          1 # Z
119 ]
120
121 letter_distribution_total = letter_distribution.sum()
122
123
124 new_letter_queue = []
125 new_letter = ->
126         if new_letter_queue.length
127                 l = new_letter_queue.shift()
128                 if l is 'Q'
129                         return 'Qu'
130                 else
131                         return l
132         r = Math.floor Math.random() * (letter_distribution_total + 1)
133         for i in [0..25]
134                 r -= letter_distribution[i]
135                 if r <= 0
136                         if letters[i] is 'Q'
137                                 return 'Qu'
138                         return letters[i]
139         return 'Z' # just in case
140
141
142
143 # in memory it's layed out like this:
144 # a c f j m
145 # b d g k n
146 #   e h l
147 #     i
148 # for display, columns are slid vertically like so:
149 #       f
150 #     c   j
151 #   a   g   m
152 #     d   k
153 #   b   h   n
154 #     e   l
155 #       i
156 #
157 # work out which grid spaces are connected
158 init_board_layout = () ->
159         col_offset = 0
160         middle_col = (board_cols - 1) / 2
161
162         # how many tiles before the current tile?
163         for col_num in [0 .. board_cols - 1]
164                 if col_num < middle_col
165                         fw_other = 1
166                 else
167                         fw_other = -1
168
169                 if col_num > middle_col
170                         bw_other = 1
171                 else
172                         bw_other = -1
173
174                 is_first_col = col_num is 0
175                 is_last_col = col_num is board_cols - 1
176
177                 neighbors = []
178                 push = (offset) ->
179                         neighbors.push col_offset + offset
180
181                 col_top_px = Math.abs col_num - middle_col
182                 col_top_px *= tile_radius
183                 board_col_top_px.push col_top_px
184
185                 above = []
186                 for i in [0 .. board_col_heights[col_num] - 1]
187                         is_top_tile = i is 0
188                         is_bottom_tile = i is board_col_heights[col_num] - 1
189
190                         # link tile number to pixel "top" and "left" of containing column
191                         board_top_px.push col_top_px
192                         board_left_px.push col_num * tile_width
193
194                         # aboves (array of tile numbers above, starting from top)
195                         board_aboves.push above.clone()
196                         above.push i + col_offset
197
198                         # below (SINGLE tile number of tile below or false)
199                         if is_bottom_tile
200                                 board_below.push false
201                         else
202                                 board_below.push col_offset + i + 1
203
204                         # neighbors (array of tile numbers "next to" this one)
205                         neighbors = []
206                         unless is_top_tile # upward link
207                                 push i - 1
208                         unless is_bottom_tile # downward links
209                                 push i + 1
210                         unless is_first_col # leftward links
211                                 unless is_bottom_tile and bw_other is -1
212                                         push i - board_col_heights[col_num - 1]
213                                 unless is_top_tile and bw_other is -1
214                                         push i - board_col_heights[col_num - 1] + bw_other
215                         unless is_last_col # rightward links
216                                 unless is_bottom_tile and fw_other is -1
217                                         push i + board_col_heights[col_num]
218                                 unless is_top_tile and fw_other is -1
219                                         push i + board_col_heights[col_num] + fw_other
220
221                         board_neighbors.push neighbors.clone()
222
223                 col_offset += board_col_heights[col_num]
224
225
226 init_board = ->
227         encoded = window.location.hash
228         if encoded? and encoded.charAt 0 is '#'
229                 encoded = encoded.substr 1
230         unless encoded? and encoded.length > board_tiles
231                 encoded = get_cookie 'hexbog'
232         if encoded? and encoded.length > board_tiles
233                 new_letter_queue = (encoded.substr 0, board_tiles).split ''
234                 score = parseInt(encoded.substr(board_tiles), 10)
235
236         # how far each tile needs to be slid down
237         slides = (0 for i in board)
238
239         # work out which grid spaces are connected
240         # (neighbors, above, down)
241         init_board_layout()
242
243 $selection_display = null # initialized by init_html_board
244 $score_display = null # initialized by init_html_board
245 $definition_word = null # initialized by init_html_board
246 $definition_link = null # initialized by init_html_board
247 $definition_type = null # initialized by init_html_board
248 $definition_language = null # initialized by init_html_board
249 $definition_text = null # initialized by init_html_board
250 $definition_credit = null # initialized by init_html_board
251 update_selection_display = ->
252         word = selected_word()
253         $selection_display.html word
254
255         # color the selected tiles according to whether they're a word or not
256         if word.length
257                 classes = ['selected_word', 'selected']
258                 if is_word word
259                         c = 0
260                 else
261                         c = 1
262                 for num in selected
263                         html_tiles[num].addClass classes[c]
264                         html_tiles[num].removeClass classes[1 - c]
265
266 # unselects the last tile of the selecetion
267 unselect_tile = ->
268         _unselect_tile()
269         update_selection_display()
270
271 _unselect_tile = ->
272         num = selected.pop()
273         html_tile = html_tiles[num]
274         html_tile.removeClass 'selected_word'
275         html_tile.removeClass 'selected'
276
277 unselect_all = ->
278         while selected.length
279                 _unselect_tile()
280         update_selection_display()
281
282 shrink_selection = (leave_count) ->
283         while selected.length > leave_count
284                 _unselect_tile()
285         update_selection_display()
286
287 selected_word = ->
288         word = ''
289         word += board[i] for i in selected
290         return word.toLowerCase()
291
292 html_slide = (num, dist) ->
293         if dist
294                 cur = html_tiles[num].css 'top'
295                 cur = Number(cur.substr(0, cur.length - 2))
296                 dest = cur + (dist * tile_width)
297                 html_tiles[num].animate {top: "#{dest}px"}, slide_ms
298
299 save_game = ->
300         encoded = ''
301         for t in board
302                 encoded += t.substr 0, 1
303         encoded += score
304         set_cookie 'hexbog', encoded, 365
305         window.location.hash = encoded
306
307 blip_selection = ->
308         faders = selected.clone().num_sort()
309         selected = []
310         for num in faders
311                 html_tiles[num].unbind('click').fadeOut fade_ms
312         timeout fade_ms, ->
313                 top_tile = -1
314                 new_px = 0
315                 new_slide = 0
316                 for fader in faders
317                         cur_top = board_aboves[fader][0]
318                         if cur_top is undefined
319                                 cur_top = fader
320                         if top_tile isnt cur_top
321                                 new_px = board_top_px[fader] - tile_width
322                                 new_slide = 1
323                                 top_tile = cur_top
324                         html_tiles[fader].remove()
325                         dest = fader
326                         aboves = board_aboves[fader].clone().reverse()
327                         for above in aboves
328                                 html_tiles[dest] = html_tiles[above]
329                                 html_tiles[dest].data 'tile_number', dest
330                                 board[dest] = board[above]
331                                 slides[dest] = slides[above] + 1
332                                 --dest
333                         new_tile top_tile, board_left_px[top_tile], new_px
334                         slides[top_tile] = new_slide
335                         new_px -= tile_width
336                         new_slide += 1
337                 for i in [0 .. board.length - 1]
338                         html_slide i, slides[i]
339                         slides[i] = 0
340                 save_game()
341         update_selection_display()
342
343 activate_selection = ->
344         word = selected_word()
345         if word.length < 3
346                 log "Too short: \"#{word}\""
347                 return
348         unless is_word word
349                 log "Not on word list: \"#{word}\""
350                 return
351         score += Math.round(Math.pow(1.7, word.length))
352         $score_display.html score
353         log "blipped: #{word}"
354         blip_selection()
355         look_up_definition word
356
357
358 definition_credited = false
359 show_definition = (word, type, definition, language) ->
360         if language is 'English'
361                 $definition_language.html ''
362         else
363                 $definition_language.html " (#{language})"
364         $definition_type.html type
365         $definition_link.attr 'href', "http://en.wiktionary.org/wiki/#{word}"
366         $definition_word.html word.substr(0, 1).toUpperCase() + word.substr(1)
367         $definition_text.html definition
368         unless definition_credited
369                 definition_credited = true
370                 $definition_credit.html "Definitions &copy; <a href=\"http://en.wiktionary.org/\" target=\"_blank\">wiktionary.org</a> CC-BY-SA"
371
372
373 select_tile = (num) ->
374         html_tile = html_tiles[num]
375         # html_tile.css backgroundColor: tile_selected_color
376         selected.push num
377         update_selection_display()
378         return
379
380 new_tile = (num, x, y) ->
381         letter = new_letter()
382
383         html_tile = $("<div class=\"tile\" style=\"left: #{x}px; top: #{y}px\" unselectable=\"on\">#{letter}</div>")
384         $board.append(html_tile)
385
386         html_tile.data 'tile_number', num
387         board[num] = letter
388         html_tiles[num] = html_tile
389
390         html_tile.click ->
391                 me = $(this)
392                 num = me.data 'tile_number'
393                 if num in selected
394                         nth_of_word = selected.indexOf(num)
395                         first = nth_of_word is 0
396                         last = nth_of_word is selected.length - 1
397
398                         if first and last
399                                 unselect_all() # Clicking only selected letter unselects it
400                         else if first and !last
401                                 shrink_selection 1 # Clicking start of word goes back to just that letter
402                                 # should this unselect all?
403                         else if last
404                                 activate_selection()
405                         else
406                                 shrink_selection nth_of_word + 1
407                 else # (not clicking on selected tile)
408                         if selected.length is 0
409                                 select_tile num
410                         else
411                                 unless num in board_neighbors[selected.last()]
412                                         unselect_all()
413                                 select_tile num
414
415
416 $board = null
417 html_tiles = []
418 init_html_board = ->
419         $('#loading').remove()
420         $selection_display = $('#selection')
421         $score_display = $('#score')
422         $score_display.html score
423         $definition_word = $('#definition_word')
424         $definition_type = $('#definition_type')
425         $definition_language = $('#definition_language')
426         $definition_link = $('#definition_link')
427         $definition_text = $('#definition_text')
428         $definition_credit = $('#definition_credit')
429         $board = $('#board')
430         # make html for board
431         tile_number = 0
432         for col_num in [0 .. board_cols - 1]
433                 for num in [0 .. board_col_heights[col_num] - 1]
434                         x = col_num * tile_width
435                         y = board_col_top_px[col_num] + num * tile_width
436                         new_tile tile_number, x, y
437                         tile_number++
438
439 word_bins = []; word_bins.push(',') for [0...997]
440 hash_word = (word) ->
441         h = 0
442         for i in [0...word.length]
443                 h ^= word.charCodeAt(i) << ((i*3) % 21)
444         return h % 997
445 is_word = (str) ->
446         word_bins[hash_word str].indexOf(",#{str},") > -1
447
448 # this is called automatically by the compressed wordlist
449 parse_word_list = (compressed) ->
450         prefix = ''
451         cap_a = "A".charCodeAt 0
452         i = 0
453         next_chunk = ->
454                 chunk = compressed[i]
455                 for word in chunk.match(/[a-z]*[A-Z]/g)
456                         # the capital letter (at the end of the match) says how many characters
457                         # from the end of the previous word should be removed to create the prefix
458                         # for the next word. "A" for 0, "B" for 1, "C" for 2, etc
459                         bs = word[word.length - 1].charCodeAt(0) - cap_a
460                         word = prefix + word[0 ... word.length - 1]
461                         word_bins[hash_word word] += word + ','
462                         prefix = word[0 ... word.length - bs]
463                 if ++i is compressed.length
464                         return
465                 else
466                         timeout 1, next_chunk
467         timeout 1, next_chunk
468
469 extract_wiktionary_definiton = (html) ->
470         found = false
471         finds = {}
472         language = false
473         part = false
474
475         # clean HTML
476         ##################
477         # when we instantiate the html so we can use dom traversal, the browser
478         # will start loading images and such. This section attempts to mangle the
479         # html so no resources are loaded when the html is parsed.
480
481         # attributes
482         #                            src: <img>, <audio>, etc
483         #                         onload: only <body>?
484         #   archive,codebase,data,usemap: <object>
485         #                           href: <link>
486         #                 id,class,style: background: url(foo.png), etc
487         html = html.replace /(src|onload|archive|codebase|data|usemap|href|style|id|class)=['"][^"']*['"]/ig, '', html
488
489         elements = $(html)
490
491         valid_parts = ["Abbreviation", "Adjective", "Adverb", "Article", "Cardinal number", "Conjunction", "Determiner", "Interjection", "Noun", "Numeral", "Particle", "Preposition", "Pronoun", "Verb"]
492
493         elements.each (i, el) ->
494                 #which tag: el.tagName
495                 if el.tagName is 'H2'
496                         # if we found a definition in the previous language section, run with it
497                         # (we only stop for verbs, in hopes of finding one in english)
498                         if found
499                                 return false # break
500                         part = false # mark us not being in a definition section unless the next section finds a part of speach header
501                         language = $(el).text().substr 7
502                 if language and el.tagName is 'H3' or el.tagName is 'H4' # eg yak def uses one for english and one for dutch
503                         part = false
504                         text = $(el).text()
505                         for p in valid_parts
506                                 if text is "[edit] #{p}"
507                                         part = p.toLowerCase()
508                                         # FIXME break
509                 if part and el.tagName is 'OL'
510                         $(el).children().each (i, el) ->
511                                 new_def = $(el).text()
512                                 if new_def.substr(0, 9) is '(obsolete' or new_def.substr(0, 8) is "(archaic"
513                                         key = 'obsolete'
514                                 else
515                                         if part is 'verb'
516                                                 key = 'verb'
517                                         else
518                                                 key = 'nonverb'
519                                 finds[key] ?= [part, new_def, language]
520                                 found = true
521                                 if part is 'verb'
522                                         # verbs are the best! stop scanning when we find one
523                                         return false # break
524                         if found.verb
525                                 return false # break
526
527         part_defs = (finds[i] for i in ['verb', 'nonverb', 'obsolete'] when finds[i])
528         unless part_defs.length
529                 return false
530
531         return part_defs[0]
532
533
534 look_up_definition = (word) ->
535         $.ajax({
536                 url: "http://en.wiktionary.org/w/api.php?action=parse&format=json&page=#{word}"
537                 jsonpCallback: "lud_#{word}" # always use the same callback for the same word so it's cacheable
538                 dataType: 'jsonp'
539                 cache: true
540                 success: (data, error_msg, xhr) ->
541                         if data?.parse?.text?['*']?
542                                 tdl = extract_wiktionary_definiton data.parse.text['*']
543                                 if tdl
544                                         show_definition word, tdl[0], tdl[1], tdl[2]
545                         else
546                                 log "Sorry, couldn't find a definition for \"#{word}\""
547                 error: ->
548                         log "wiktionary failed to load: \"#{error_msg}\""
549         })
550
551 board_as_txt = ->
552         ret = ''
553         index = 0
554         for i in [0 .. board_min_height * 2]
555                 unless i % 2
556                         ret += '   ' + board[j] for j in [board_min_height + index .. board_tiles - 1] by 2 * board_min_height + 1
557                 else
558                         ret += ' ' + board[j] + '  ' for j in [index .. board_tiles - 1] by 2 * board_min_height + 1
559                         index += 1
560
561                 ret += '\n'
562         return ret
563
564 start_over = ->
565         selected = []
566         score = 0
567         $score_display.html score
568         for i in [0...board_tiles]
569                 selected.push i
570         blip_selection()
571
572 init_start_over_link = ->
573         $('#start-over').click (event) ->
574                 event.preventDefault()
575                 if confirm "Are you sure you want to start over? There is no undo."
576                         start_over()
577
578 $log = undefined
579 init_log = ->
580         $log = $('#log')
581 log = (msg) ->
582         $log.children().last().remove()
583         $log.prepend $('<div></div>').html msg
584
585 init_game = ->
586         init_log()
587         init_board()
588         init_html_board()
589         init_start_over_link()
590
591 $(init_game)