Repository navigation
Expand file tree
/
Copy pathcell.js
More file actions
70 lines (61 loc) · 2.66 KB
/
Copy pathcell.js
File metadata and controls
70 lines (61 loc) · 2.66 KB
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
var Cell = function() {
var me = this; // 'this' can point to many, different things, so we grab an easy reference to the object
// You can read more about 'this' at:
// MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
// at http://www.quirksmode.org/js/this.html
// and in a more detailed tutorial: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
// We're going to want to know what row and column I'm in, but we won't 'til I'm added to a board
this.row = null;
this.column = null;
// Which player owns me?
this.owner = null;
// Connection to my board
this.board = null;
// Let's make the HTML that'll display me
me.html = document.createElement('div');
me.html.classList.add('cell');
// Let's create an event for when I want to submit myself to the tray
// You can read more about this on MDN at https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
var submit = new CustomEvent('cellSubmit', {
detail: {
'cell': me // and send along all my info
}
});
me.html.addEventListener('click', function(event) {
me.html.dispatchEvent(submit); // and trigger my custom event when someone clicks my HTML
});
var _letter; // the letter I actually contain
Object.defineProperty(this, 'letter', {
// Custom getters and setters; you can read more about this at:
// MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
// Yehuda Katz's tutorial: http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/
get: function() {
// when someone asks for cell.letter, just give them back _letter
return _letter;
},
set: function(letter) {
// when someone sets cell.letter = something, reset _letter
_letter = letter;
// and change what my HTML displays
me.html.innerHTML = letter;
}
});
return this;
};
Object.defineProperty(Cell.prototype, 'neighbors', {
get: function() {
var me = this;
return this.board.cells.filter(function(cell) {
return (
(cell.row === me.row && Math.abs(cell.column - me.column) === 1) ||
(cell.column === me.column && Math.abs(cell.row - me.row) === 1)
);
});
}
});
Object.defineProperty(Cell.prototype, 'surrounded', {
get: function() {
var me = this;
return this.neighbors.every(function(c) { return c.owner != null && c.owner === me.owner; })
}
});