Skip to content

Instantly share code, notes, and snippets.

@tvytlx
Last active February 2, 2019 07:02
Show Gist options
  • Save tvytlx/6f80083e006a02569146400283807eaa to your computer and use it in GitHub Desktop.
Save tvytlx/6f80083e006a02569146400283807eaa to your computer and use it in GitHub Desktop.
SCRIPT-8
// title: Snake Game
initialState = {
speed: 22,
totalElapsed: 0,
lastElapsed: 0,
score: 0,
direction: "left",
snakeBody: [
[20, 20],
[21, 20],
[22, 20],
[23, 20],
[24, 20],
],
food: {
x: 20,
y: 30
},
box: {
size: 100,
x: 5,
y: 13
}
}
var directionOpposingMap = {
up: "down",
down: "up",
left: "right",
right: "left"
}
update = (state, input, elapsed) => {
// speed control
state.totalElapsed += elapsed;
if ( state.totalElapsed - state.lastElapsed <= 1000 / state.speed){
return;
}
state.lastElapsed = state.totalElapsed;
// variables
var head = state.snakeBody[0];
var food = state.food;
const {box} = state;
var nextNode = null;
// speed custom setting
if (input.a){state.speed += 1};
if (input.b){state.speed -= 1};
// direction changing
for (var key in input){
if (key in directionOpposingMap &&
input[key]===true &&
key != state.direction &&
key != directionOpposingMap[state.direction]) {
state.direction = key;
break;
}
}
if (state.direction==="up"){ nextNode=[head[0],head[1]-1]};
if (state.direction==="down"){nextNode=[head[0],head[1]+1]};
if (state.direction==="left"){nextNode=[head[0]-1,head[1]]};
if (state.direction==="right"){nextNode=[head[0]+1,head[1]]};
// box detect
if (nextNode[0] <= box.x ) {
nextNode[0] = box.x + box.size - 1;
}else if (nextNode[0] >= (box.x + box.size - 1) ) {
nextNode[0] = box.x + 1;
}else if (nextNode[1] <= box.y ) {
nextNode[1] = box.y + box.size - 1;
}else if (nextNode[1] >= (box.y + box.size - 1) ) {
nextNode[1] = box.y + 1;
}
// snake body changing
state.snakeBody.unshift(nextNode);
if (head[0] == state.food.x && head[1] == state.food.y) {
var randomNum = Math.floor(Math.random() * Math.floor(box.size - 1));
food.x = box.x + 1 + randomNum;
food.y = box.y + 1 + randomNum;
state.score += 10;
return;
}
state.snakeBody.pop();
}
draw = (state) => {
clear();
const {box, food} = state;
print(0, 0, `score: ${state.score}`);
print(76, 0, `speed: ${state.speed}`);
print(0, 118, "press a, b to change speed");
circStroke(food.x, food.y, 1);
state.snakeBody.forEach(node => {
var x = node[0], y = node[1];
circStroke(x, y, 1);
});
rectStroke( box.x, box.y, box.size, box.size);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment