Skip to content

Instantly share code, notes, and snippets.

@ACPixel
Created May 28, 2018 04:58
Show Gist options
  • Save ACPixel/845916704f8170ff78d07e1e1addea12 to your computer and use it in GitHub Desktop.
Save ACPixel/845916704f8170ff78d07e1e1addea12 to your computer and use it in GitHub Desktop.
Snake on launchpad
var midi = require('midi');
// Set up a new output.
var output = new midi.output();
var input = new midi.input();
output.openPort(0);
input.openPort(0)
const layout = [
[81, 82, 83, 84, 85, 86, 87, 88, 89],
[71, 72, 73, 74, 75, 76, 77, 78, 79],
[61, 62, 63, 64, 65, 66, 67, 68, 69],
[51, 52, 53, 54, 55, 56, 57, 58, 59],
[41, 42, 43, 44, 45, 46, 47, 48, 49],
[31, 32, 33, 34, 35, 36, 37, 38, 39],
[21, 22, 23, 24, 25, 26, 27, 28, 29],
[11, 12, 13, 14, 15, 16, 17, 18, 19]
]
var cw = 1;
var d;
var food;
var score;
var level;
var w = 9;
var h = 8;
var snake_array;
function init()
{
d = "none";
create_snake();
create_food();
score = 0;
level = 1;
if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 150);
}
init();
function create_snake()
{
var length = 1;
snake_array = [];
snake_array.push({x: 4, y:4});
}
function create_food()
{
food = {
x: Math.round(Math.random()*(w-cw)/cw),
y: Math.round(Math.random()*(h-cw)/cw),
};
}
function paint()
{
for (let i = 2; i < 90; i++) {
output.sendMessage([144,i,0]);
}
output.sendMessage([144,16,1])
output.sendMessage([144,27,1])
output.sendMessage([144,18,1])
output.sendMessage([144,17,1])
var nx = snake_array[0].x;
var ny = snake_array[0].y;
if(d == "right") nx++;
else if(d == "left") nx--;
else if(d == "up") ny--;
else if(d == "down") ny++;
if(check_collision(nx, ny, snake_array))
{
init();
return;
}
if (nx == -1) {
nx = w-1
} else if (nx == w/cw) {
nx = 0
} else if (ny == -1) {
ny = h-1
} else if (ny == h/cw) {
ny = 0
}
if(nx == food.x && ny == food.y)
{
var tail = {x: nx, y: ny};
score++;
create_food();
}
else
{
var tail = snake_array.pop();
tail.x = nx; tail.y = ny;
}
snake_array.unshift(tail);
for(var i = 0; i < snake_array.length; i++)
{
var c = snake_array[i];
paint_cell(c.x, c.y, 21);
}
paint_cell(food.x, food.y, 50);
}
function paint_cell(x, y, color)
{
output.sendMessage([144,layout[y][x],color]);
}
function check_collision(x, y, array)
{
for(var i = 0; i < array.length; i++)
{
if(array[i].x == x && array[i].y == y)
return true;
}
return false;
}
input.on('message', function(deltaTime, message) {
let key = message[1]
if(key == "16" && d != "right") d = "left";
else if(key == "27" && d != "down") d = "up";
else if(key == "18" && d != "left") d = "right";
else if(key == "17" && d != "up") d = "down";
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment