-
Notifications
You must be signed in to change notification settings - Fork 4
/
hex.html
568 lines (542 loc) · 15.1 KB
/
hex.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
<!DOCTYPE html>
<html>
<head>
<title>Hex</title>
<style>
object {
position: absolute;
left: -9000px;
top: -9000px;
}
html {
font-family: Helvetica, arial, sans-serif;
}
h3 { font-family: monospace; }
h3:first-child { margin-top: 0 }
#board { margin: 2em; margin-bottom: 0.5em; }
#game {
position: absolute;
left: 400px;
width: 560px;
}
#rules {
margin-top: 0.5em;
}
#ot {
position: absolute;
width: 360px;
padding: 20px;
font-family: monospace;
word-wrap: break-word;
}
.op {
margin-bottom: 0.5em;
}
#chat {
position: absolute;
left: 960px;
padding: 20px;
font-family: monospace;
width: 300px;
}
#chat input {
font-size: inherit;
font-family: inherit;
width: 100%;
margin-top: 5px;
}
.message {
margin-top: 5px;
}
.message .user {
display: inline;
margin-right: 0.8em;
font-weight: bold;
}
.message .text {
display: inline;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="/channel/bcsocket.js"></script>
<script src="/share/share.uncompressed.js"></script>
<script src="/share/json.js"></script>
</head>
<body>
<div id='ot'>
<h3>Document</h3>
<div id="doc">
</div>
<h3>Operations</h3>
<div id="ops">
</div>
</div>
<div id='game'>
<canvas id='board' width='600' height='420'></canvas>
<button id='reset' onclick='reset()'>Reset board</button>
<div id='rules'>
<h3>How to play</h3>
<ul>
<li>Pieces can't be placed next to pieces of a different color.</li>
<li>A hex is your territory if one of your pieces is next to it. If
there are two pieces of different colors next to a hex, it belongs to
neither player.</li>
<li>Try to win more territory than your opponent!</li>
</div>
</div>
<div id='chat'>
<h3>Chat</h3>
<div id='messages'></div>
<input id='message'>
</div>
<script>
var randomDocName = function(length) {
var chars, x;
if (length == null) {
length = 10;
}
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=";
var name = [];
for (x = 0; x < length; x++) {
name.push(chars[Math.floor(Math.random() * chars.length)]);
}
return name.join('');
};
// from http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var username;
if (!(username = readCookie('username'))) {
username = randomDocName(4);
createCookie('username', username, 5);
}
$('#message').keydown(function (e) {
if ((e.keyCode || e.which) == 13) {
if (!e.srcElement.value) return;
// enter was pressed
$state.submitOp({
p: ['chat',0],
li: {
from: username,
message: e.srcElement.value
}
});
e.srcElement.value = '';
}
})
var defaultSide = 20, spacing = 5,
selectedX = null,
selectedY = null,
grid = {width: 10, height: 10,
},
gridAt = function (g,x,y) {
return g.values[y*g.width+x];
},
playerTurn = 1,
playerColors = [[200,0,0], [0,0,200]],
colorStyle = function (color) {
return 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';
},
fillHex = function (ctx, x, y, color, side) {
ctx.fillStyle = color;
x += 0.5;
y += 0.5;
pathHex(ctx, x, y, color, side);
ctx.fill();
},
strokeHex = function (ctx, x, y, color, side) {
ctx.strokeStyle = color;
x += 0.5;
y += 0.5;
pathHex(ctx, x, y, color, side);
ctx.stroke();
},
pathHex = function (ctx, x, y, color, side) {
if (!side) side = defaultSide;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x+side, y);
ctx.lineTo(x+side+side*Math.cos(Math.PI/3),
y+side*Math.sin(Math.PI/3));
ctx.lineTo(x+side, y+2*side*Math.sin(Math.PI/3));
ctx.lineTo(x, y+2*side*Math.sin(Math.PI/3));
ctx.lineTo(x-side*Math.cos(Math.PI/3), y+side*Math.sin(Math.PI/3));
ctx.lineTo(x, y);
},
hexEdgeWidth = function (side) {
// _
// / \
// \_/
// v ~~~~ this width
if (!side) side = defaultSide;
return side*Math.cos(Math.PI/3);
},
hexHeight = function (side) {
// height of one hex of side length +side+
if (!side) side = defaultSide;
return 2*side*Math.sin(Math.PI/3);
},
adjacencies = function (x, y) {
// odd and even columns have different adjacencies
var odd = (x % 2 == 0) ? -1 : 1;
return [[x-1,y], [x+1,y], [x, y-1], [x, y+1],
[x-1, y+odd], [x+1,y+odd]];
},
all = function (f, xs) {
for (var i = 0; i < xs.length; i++) {
if (!f(xs[i])) {
return false;
}
}
return true;
},
any = function (f, xs) {
for (var i = 0; i < xs.length; i++) {
if (f(xs[i])) {
return true;
}
}
return false;
},
okToPlace = function (gr, player, x, y) {
if (x < 0 || x >= gr.width || y < 0 || y >= gr.height) return false;
if (gridAt(gr, x,y) != 0) return false;
// a move adjacent to (x,y) would be OK
var adjMoveOK = function (xy) {
var x = xy[0], y = xy[1];
if (x < 0 || x >= gr.width || y < 0 || y >= gr.width) {
return true;
}
var val = gridAt(gr, x,y);
return val == 0 || val == player;
}
return (all(adjMoveOK, adjacencies(x,y)));
},
drawGrid = function (ctx, gr) {
for (var y = 0; y < gr.height; y++) {
for (var x = 0; x < gr.width; x++) {
var hexX = hexEdgeWidth() + (defaultSide+hexEdgeWidth() +
spacing*Math.cos(Math.PI/6))*x;
var hexY = (hexHeight() + spacing)*y +
(x % 2 == 0 ? 0 :
spacing*Math.sin(Math.PI/6) +
hexHeight()/2);
var value = gridAt(gr,x,y);
if (value != 0) {
var fillColor = colorStyle(playerColors[value-1]);
fillHex(ctx, hexX, hexY, fillColor);
}
var strokeColor = 'rgb(0,0,0)';
var ok1 = okToPlace(gr, 1, x, y),
ok2 = okToPlace(gr, 2, x, y);
if (ok1 && !ok2) {
strokeColor = 'rgb(250,140,140)';
} else if (!ok1 && ok2) {
strokeColor = 'rgb(140,140,250)';
} else if (!ok1 && !ok2) {
strokeColor = 'rgb(255,255,255)';
}
if (x == selectedX && y == selectedY) {
strokeColor = 'rgb(0,200,0)';
}
strokeHex(ctx, hexX, hexY, strokeColor);
}
}
},
yForX = function (m, b, x) {
// y = mx + b
return m*x + b;
},
hexForPixel = function (x,y) {
// take the pixel (x,y) and return the coordinates of the hex under
// that pixel
var xspacing = Math.cos(Math.PI/6)*spacing;
x += xspacing;
var cellwidth = defaultSide + hexEdgeWidth() + xspacing;
var cellheight = hexHeight() + spacing;
var xcell = Math.floor(x / cellwidth);
// determine if we're in an odd column
var odd = xcell % 2 != 0;
if (odd) {
y -= cellheight/2;
}
var ycell = Math.floor(y / cellheight);
var xoff = x - xcell*cellwidth;
var yoff = y - ycell*cellheight;
var s3 = Math.sqrt(3);
// top line
var t_m = -s3, t_b = s3*(xspacing + hexEdgeWidth());
// bottom line
var b_m = s3, b_b = hexHeight()/2 - s3*xspacing;
if ((xoff >= hexEdgeWidth() + xspacing && yoff <= hexHeight()) ||
(xoff >= xspacing && xoff < hexEdgeWidth() + xspacing &&
yoff >= yForX(t_m, t_b, xoff) &&
yoff <= yForX(b_m, b_b, xoff))
) {
return {x:xcell, y:ycell};
}
if (yoff <= hexHeight()/2 && yoff <= yForX(t_m, hexHeight()/2, xoff)) {
return {x:xcell-1, y:ycell + (odd ? 0 : -1)};
}
if (yoff >= hexHeight()/2 + spacing &&
yoff >= yForX(b_m, spacing + hexHeight() / 2, xoff)) {
return {x:xcell-1, y:ycell + (odd ? 1 : 0)};
}
},
isComplete = function (gr) {
for (var y = 0; y < gr.height; y++) {
for (var x = 0; x < gr.width; x++) {
var ok1 = okToPlace(gr, 1, x, y),
ok2 = okToPlace(gr, 2, x, y);
if (ok1 && ok2) {
// either player can place; board not complete.
return false;
} else if (ok1 && !ok2) {
// player 1 can place. if player 2 can place at any point
// adjacent to this one, the board is not complete.
if (any(function (xy) { return okToPlace(gr, 2, xy[0], xy[1]); },
adjacencies(x,y))) {
return false;
}
} else if (!ok1 && ok2) {
// player 2 can place. if player 1 can place at any point
// adjacent to this one, the board is not complete.
if (any(function (xy) { return okToPlace(gr, 1, xy[0], xy[1]); },
adjacencies(x,y))) {
return false;
}
} else if (!ok1 && !ok2) {
// no-man's land
}
}
}
return true;
},
controller = function (gr, x, y) {
var ok1 = okToPlace(gr, 1, x, y) || gridAt(gr, x,y) == 1,
ok2 = okToPlace(gr, 2, x, y) || gridAt(gr, x,y) == 2;
if (ok1 && !ok2) return 1;
if (ok2 && !ok1) return 2;
return 0;
},
territory = function (gr, player) {
var num = 0;
for (var y = 0; y < gr.height; y++) {
for (var x = 0; x < gr.width; x++) {
if (controller(gr, x, y) == player) {
num++;
}
}
}
return num;
},
mousePos = function (ev) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
} else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
return {x:posx,y:posy}
},
boardMouseMoved = function (e) {
var board = $('#board').offset();
var pos = mousePos(e);
var x = pos.x - board.left, y = pos.y - board.top;
var hex = hexForPixel(x,y);
if (hex) {
selectedX = hex.x;
selectedY = hex.y;
} else {
selectedX = null;
selectedY = null;
}
redraw();
},
boardMouseClicked = function (e) {
var board = $('#board').offset();
var pos = mousePos(e);
var x = pos.x - board.left, y = pos.y - board.top;
var hex = hexForPixel(x,y);
if (hex && hex.x >= 0 && hex.x < grid.width &&
hex.y >= 0 && hex.y < grid.height &&
okToPlace(grid, playerTurn, hex.x, hex.y)) {
//grid.values[hex.y*grid.width+hex.x] = playerTurn;
$state.submitOp([{
p:['grid','values',hex.y*grid.width+hex.x],
ld:0,li:playerTurn
},{
p:['playerTurn'],
od:playerTurn,
oi:playerTurn == 1 ? 2 : 1
}]);
}
},
redraw = function () {
var board = document.getElementById('board');
var ctx = board.getContext('2d');
ctx.clearRect(0,0,board.width, board.height);
drawGrid(ctx, grid);
ctx.font = '30px sans-serif';
ctx.textBaseline = 'top';
ctx.fillStyle = colorStyle(playerColors[playerTurn-1]);
ctx.fillText('Player ' + playerTurn, 400,100);
ctx.font = '20px sans-serif';
ctx.fillStyle = colorStyle(playerColors[0]);
ctx.fillText('P1: ' + territory(grid, 1), 400,140);
ctx.fillStyle = colorStyle(playerColors[1]);
ctx.fillText('P2: ' + territory(grid, 2), 400,165);
if (isComplete(grid)) {
ctx.fillStyle = '#000';
ctx.fillText('Board complete!', 400,200);
}
},
clear = function () {
grid.values = [];
for (var y = 0; y < grid.height; y++) {
for (var x = 0; x < grid.width; x++) {
grid.values[y*grid.width+x] = 0;
}
}
},
reset = function () {
clear();
playerTurn = 1;
$state.submitOp([
{p:['grid','values'],od:$state.snapshot.grid.values,oi:grid.values},
{p:['playerTurn'],od:$state.snapshot.playerTurn,oi:playerTurn}
]);
},
begin = function () {
var board = document.getElementById('board');
board.onmousemove = boardMouseMoved;
board.onclick = boardMouseClicked;
redraw();
};
function hslToRgb(h, s, l){
var r, g, b;
if(s == 0){
r = g = b = l; // achromatic
} else {
function hue2rgb(p, q, t) {
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return '#' + Math.round(r * 255).toString(16) + Math.round(g * 255).toString(16) + Math.round(b * 255).toString(16);
};
function colorForName(name) {
var x = 0;
var p = 31;
for (var i = 0; i < name.length; i++) {
var c = name.charCodeAt(i);
x += c * p;
p *= p;
x = x % 4294967295;
}
var h = (x % 89)/89;
var color = hslToRgb(h, 0.7, 0.3)
return color;
}
function addChatMessage(m) {
var msg = $('<div class="message"><div class="user"></div><div class="text"></div></div>');
$('.text', msg).text(m.message);
$('.user', msg).text(m.from);
$('.user', msg).css('color',colorForName(m.from));
$('#chat #messages').append(msg);
var allMsgs = $('.message')
if (allMsgs.length > 15) {
allMsgs.slice(0, Math.max(0,allMsgs.length - 15)).each(function () {
var e = $(this);
e.fadeOut('slow', function () {
e.remove();
});
});
}
}
function stateUpdated(op) {
if (op) {
var ops = $('#ops');
var opel = $('<div class="op" style="display:none">');
opel.text(JSON.stringify(op));
ops.prepend(opel);
opel.fadeIn('fast')
var allOps = $('.op');
if (allOps.length > 10) {
allOps.slice(0, Math.max(0,allOps.length - 10)).each(function () {
var e = $(this);
e.fadeOut('fast', function () {
e.remove();
});
});
}
op.forEach(function (c) {
if (c.p[0] == 'chat' && c.li) {
addChatMessage(c.li)
}
})
} else {
// first run
$state.snapshot.chat.slice(0, 10).reverse().forEach(addChatMessage)
}
$('#doc').text(JSON.stringify($state.snapshot))
grid = $state.snapshot.grid
playerTurn = $state.snapshot.playerTurn;
redraw();
}
var $state;
if (!document.location.hash) {
document.location.hash = '#' + randomDocName();
}
var docname = 'hex:' + document.location.hash.slice(1)
sharejs.open(docname, 'json', function(error, doc) {
$state = doc;
doc.on('change', function (op) {
stateUpdated(op)
})
if (doc.created) {
clear()
doc.submitOp([{p:[],od:null,oi:{grid:grid,playerTurn:1,chat:[]}}])
} else {
stateUpdated()
}
begin()
})
</script>
</body>
</html>