This repository has been archived by the owner on Jul 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-snake.js
79 lines (66 loc) · 2.07 KB
/
server-snake.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
var pixelScreen = require('./screen-36x24.js');
var screenWidth = pixelScreen.width / 2;
var screenHeight = pixelScreen.height / 2;
var keypress = require('keypress')
, Snake = require('./lib/snake')
, snake = new Snake(screenWidth, screenHeight, 120);
// make `process.stdin` begin emitting "keypress" events
keypress(process.stdin);
// listen for the "keypress" event
process.stdin.on('keypress', function (ch, key) {
switch(key.name) {
case 'up':
snake.cmd('up');
break;
case 'down':
snake.cmd('down');
break;
case 'left':
snake.cmd('left');
break;
case 'right':
snake.cmd('right');
break;
case 'space':
snake.cmd('restart');
break;
case 'p':
snake.cmd('pause');
break;
default:
break;
}
if (key && key.ctrl && key.name === 'c') {
process.exit(0);
}
});
// Display Game State
snake.stream.on('update', function (state) {
// Create Empty Screen
var array = [];
for (var i = 0; i < pixelScreen.height; i++) {
array.push([]);
for (var j = 0; j < pixelScreen.width; j++) {
array[i].push([]);
for (var k = 0; k < pixelScreen.channels; k++) {
array[i][j].push(0);
}
}
}
// Draw Body
for (var i = 0; i < state.body.length; i++) {
array[state.body[i].y*2][state.body[i].x*2] = [30,30,30];
array[state.body[i].y*2][state.body[i].x*2+1] = [30,30,30];
array[state.body[i].y*2+1][state.body[i].x*2] = [30,30,30];
array[state.body[i].y*2+1][state.body[i].x*2+1] = [30,30,30];
}
// Draw Food
array[state.food.y*2][state.food.x*2] = [10,50,10];
array[state.food.y*2][state.food.x*2+1] = [10,50,10];
array[state.food.y*2+1][state.food.x*2] = [10,50,10];
array[state.food.y*2+1][state.food.x*2+1] = [10,50,10];
// Update Screen
pixelScreen.update(array);
});
process.stdin.setRawMode(true);
process.stdin.resume();