forked from DamonOehlman/talkytowers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavatar.js
143 lines (114 loc) · 2.56 KB
/
avatar.js
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
var crel = require('crel');
var events = require('events');
var transform = require('feature/css')('transform');
var util = require('util');
var Sprite = require('spritey/sprite');
var spriteLoader = require('spritey/loader')('node_modules/spritey/sprite/3', {
scale: 3,
stance: 'walk_right'
});
var sprites = [
require('spritey/sprite/firefox.json'),
require('spritey/sprite/goblin.json'),
require('spritey/sprite/sword1.json')
].map(spriteLoader);
function Avatar() {
if (! (this instanceof Avatar)) {
return new Avatar();
}
// initialise the level
this._y = 0;
this._x = 20;
this.building = {
name: 'building1'
}
//
this._timer = 0;
this._ymove = 0;
this.frameIndex = 0;
this.spriteIdx = (Math.random() * sprites.length) | 0;
this.sprite = new Sprite([ sprites[0], sprites[2] ]);
this.el = crel('div', { class: 'avatar' });
// initialise the name
this.name = localStorage.username || window.prompt("What is your name?");
}
util.inherits(Avatar, events.EventEmitter);
module.exports = Avatar;
var proto = Avatar.prototype;
Object.defineProperty(proto, 'name', {
get: function() {
return this._name;
},
set: function(value) {
if (value !== this._name) {
localStorage.username = this._name;
if (this.canvas) {
this.canvas.setAttribute('data-name', value);
}
}
}
});
Object.defineProperty(proto, 'x', {
get: function() {
return this._x;
},
set: function(value) {
if (value !== this._x) {
var delta = value - this._x;
if (delta > 0) {
this.sprite.walk_right();
}
else {
this.sprite.walk_left();
}
this._x = value;
this._changed();
}
}
})
Object.defineProperty(proto, 'y', {
get: function() {
return this._y;
},
set: function(value) {
if (value !== this._y) {
if (value > this._y) {
this.sprite.walk_up();
}
else {
this.sprite.walk_down();
}
this._y = value;
this._changed();
}
}
});
proto.moveLeft = function() {
this.moveX(-1);
};
proto.moveRight = function() {
this.moveX(1);
};
proto.moveUp = function() {
this.moveY(1);
};
proto.moveDown = function() {
this.moveY(-1);
};
proto.moveX = function(delta) {
this.x += delta;
}
proto.moveY = function(delta) {
var avatar = this;
clearTimeout(this._ymove);
this._ymove = setTimeout(function() {
avatar.y += delta;
}, 50);
}
proto._changed = function() {
var avatar = this;
clearTimeout(this._timer);
this._timer = setTimeout(function() {
avatar.emit('change');
}, 0);
};