Created
January 5, 2017 13:06
-
-
Save dbieber/4e1c4372c80deac1d3848c390d171b15 to your computer and use it in GitHub Desktop.
Plays Snake game at dskang.com/snake/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Computer assisted snake! | |
// Paste this into the JS console at http://dskang.com/snake/ to play and win! | |
function getX() { | |
var head = gSnake.getHead(); | |
var x = head.x / 20; | |
return x; | |
} | |
function getY() { | |
var head = gSnake.getHead(); | |
var y = (head.y - 40) / 20; | |
return y; | |
} | |
function foodX() { | |
return gFood.location.x / 20; | |
} | |
function foodY() { | |
return (gFood.location.y - 40) / 20; | |
} | |
function amWound() { | |
// Am I wound up enough to safely move down? | |
var myY = getY(); | |
for (var i = 0; i < gSnake.body.length; i++) { | |
var bodyX = (gSnake.body[i].x) / 20; | |
var bodyY = (gSnake.body[i].y - 40) / 20; | |
if (bodyX > 0 && (bodyY == myY + 1 || bodyY == myY + 2 || bodyY == myY + 3)) { | |
return false; // you might run into yourself if you go down; be careful! | |
} | |
} | |
return true; | |
} | |
function getmove() { | |
var x = getX(); | |
var y = getY(); | |
// Save time by moving down toward food when there's room to do so. | |
if (amWound()) { | |
if (x != 0 && y + 1 < foodY()) { | |
return DOWN; | |
} else if (x != 0 && y < 27 && foodY() < y) { | |
return DOWN; | |
} | |
} | |
// By default we move in a zigzag fashion: | |
// - right on even rows | |
// - left on odd rows | |
// - up the left hand column to the top | |
if (x == 0 && y == 0) { | |
return RIGHT; | |
} else if (y == 0 && x == 29) { | |
return DOWN; | |
} else if (y == 0) { | |
return RIGHT; | |
} else if (x == 0) { | |
return UP; | |
} else if (x == 29 && y < 27 && y % 2 == 0) { | |
return DOWN; | |
} else if (y < 27 && y % 2 == 0) { | |
return RIGHT; | |
} else if (x == 1 && y < 27 && y % 2 == 1) { | |
return DOWN; | |
} else if (y < 27 && y % 2 == 1) { | |
return LEFT; | |
} else if (y == 27) { | |
return LEFT; | |
} | |
} | |
var lastX = getX(); | |
var lastY = getY(); | |
var lastMove = RIGHT; | |
function step() { | |
var newX = getX(); | |
var newY = getY(); | |
var newMove = getmove(); | |
if ((newX != lastX || newY != lastY) && lastMove != newMove) { | |
lastMove = newMove; | |
gSnake.directionQueue = [newMove]; | |
console.log(gSnake.directionQueue); | |
} | |
lastX = newX; | |
lastY = newY; | |
} | |
var interval; | |
clearInterval(interval); | |
interval = setInterval(step, 50); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment