/
snake_ui.js
105 lines (84 loc) · 2 KB
/
snake_ui.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
(function(root){
var SnakeGame = root.SnakeGame = (root.SnakeGame || {});
var View = SnakeGame.View = function(el, outter){
this.$el = el;
this.$outter = outter;
}
View.prototype.start = function(size) {
this.board = new SnakeGame.Board(size);
var that = this;
this.$el.keydown(function(event){
that.handleKeyEvent(event)
});
setInterval(this.step.bind(this), 300);
}
View.prototype.step = function() {
if (this.board.update() == false) {
this.$outter.empty();
} else {
this.board.update();
this.render();
}
}
View.prototype.render = function() {
var that = this;
this.$outter.empty();
this.board.grid.forEach(function(row){
var div = $('<div>');
that.$outter.append(div);
row.forEach(function(tile){
var span = $('<span>');
span.addClass('tile');
if(tile == 'S'){
span.addClass('snake');
}
if(tile == 'M'){
span.addClass('mouse');
}
div.append(span);
});
});
}
View.prototype.handleKeyEvent = function(event) {
var dir = this.board.snake.dir;
switch(event.keyCode){
case 87:
dir = 'N';
break;
case 83:
dir = 'S';
break;
case 65:
dir = 'E';
break;
case 68:
dir = 'W';
break;
}
if (this.validMove(dir))
this.board.snake.turn(dir);
}
View.prototype.validMove = function(dir) {
var snakeDir = this.board.snake.dir
if (dir === 'S' && snakeDir === 'N') {
return false
} else if (dir === 'N' && snakeDir === 'S') {
return false
} else if (dir === 'E' && snakeDir === 'W') {
return false
} else if (dir === 'W' && snakeDir === 'E') {
return false
}
return true
}
})(this)
$(function(){
var outter = $('.container');
var doc = $(document)
var view = new window.SnakeGame.View(doc, outter);
view.start(20);
})
// 87 - W
// 83 - S
// 65 - A
// 68 - D