-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource.html
executable file
·114 lines (95 loc) · 2.49 KB
/
source.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
<pre id="e" style="transform:scaleY(.5);text-align:center">
<script>
var fieldSize = 14, s = ' ', b = 0, n = "\n", direction, newDirection, snake = curtain = [], foodX, foodY, timer, m = Math, d = m.random, reset = clearInterval, launch = setInterval, content = 'innerHTML';
r = (n, f) => {
for (j = 0; j++ < n; f(j));
};
t = t => e[content] += t;
redraw = _ => {
e[content] = n;
r(fieldSize + 2, _ => t(b)); t(n);
for (y = fieldSize - 1; y >= 0; y--) {
t(b);
for (x = 0; x <= fieldSize - 1; x++)
isSnakeAtCoordinates(x, y) || foodX == x && foodY == y || ~curtain.indexOf(y) ? t(b) : t(s);
t(b); t(n);
}
r(fieldSize + 2, _ => t(b));
};
onkeydown = event => {
/*
keycodes | constant (=code-36) | direction
37 | 1 | left
38 | 2 | up
39 | 3 | right
40 | 4 | down
*/
temp = event.keyCode - 36;
if (m.abs(temp - direction) != 2)
newDirection = temp;
};
coordinateLoopIncrement = crd => crd == fieldSize - 1 ? 0 : crd + 1;
coordinateLoopDecrement = crd => crd == 0 ? fieldSize - 1 : crd - 1;
step = _ => {
if (newDirection) {
direction = newDirection;
newDirection = 0;
}
newX = snake[0][0];
newY = snake[0][1];
if (direction == 1) newX = coordinateLoopDecrement(newX);
if (direction == 2) newY = coordinateLoopIncrement(newY);
if (direction == 3) newX = coordinateLoopIncrement(newX);
if (direction == 4) newY = coordinateLoopDecrement(newY);
if (!isSnakeAtCoordinates(newX, newY)) {
snake.unshift([newX, newY]);
snake[0][0] == foodX && snake[0][1] == foodY ? addFood() : snake.pop();
} else {
restart(reset(timer));
}
};
isSnakeAtCoordinates = (x, y) => {
for (k = 0; k < snake.length; k++)
if (snake[k][0] == x && snake[k][1] == y) return 1;
};
getRandomCoordinate = _ => ~~(d() * (fieldSize - 1));
addFood = _ => {
do {
foodX = getRandomCoordinate();
foodY = getRandomCoordinate();
} while (isSnakeAtCoordinates(foodX, foodY));
};
prepareField = _ => {
snake = [];
direction = 3;
r(3, (i)=>(snake.push([~~(fieldSize/2-i), ~~(fieldSize/2)])));
addFood();
redraw();
};
startGame = _ => {
timer = launch(() => {
step();
redraw();
}, 150);
};
startGame(prepareField());
restart = _ => {
l = 0;
up = 1;
timer = launch(() => {
redraw();
if (up) {
curtain.push(l);
l++;
if (l == fieldSize) up = 0;
} else {
if (l == fieldSize) prepareField();
curtain.pop();
l--;
if (!l) {
startGame(reset(timer));
}
}
}, 20);
};
</script>