code-katas/snake/snake.js

366 lines
12 KiB
JavaScript
Raw Normal View History

2014-12-08 19:49:28 -06:00
(function() {
var S = window.Snake = {};
2014-12-11 22:52:55 -06:00
// True constants
2014-12-09 00:00:25 -06:00
var SPACE = 0; var WALL = 1; var SNAKE = 2; var FOOD = 3;
2014-12-11 22:52:55 -06:00
// Fake constants (constant after board initialization).
2014-12-08 19:49:28 -06:00
var ROWS = S.ROWS = 50;
var COLS = S.COLS = 50;
2014-12-11 22:52:55 -06:00
var tileWidth, tileHeight;
// The current game board.
2014-12-08 19:49:28 -06:00
var board;
2014-12-11 22:52:55 -06:00
// The starting game board.
2014-12-09 00:00:25 -06:00
var startBoard;
2014-12-08 19:49:28 -06:00
var body = new Array();
2014-12-09 00:00:25 -06:00
var headCur;
2014-12-08 19:49:28 -06:00
var direction = 1;
var foodEaten = false;
2014-12-09 00:00:25 -06:00
2014-12-11 22:52:55 -06:00
// HTML Elements
2014-12-09 00:00:25 -06:00
var canvas;
2014-12-11 22:52:55 -06:00
var g;
2014-12-09 00:00:25 -06:00
var editorControls;
var editorDataTextarea;
var cursorIdx;
var cursorBlock;
2014-12-11 22:52:55 -06:00
// Flags
var editor = false;
2014-12-08 19:49:28 -06:00
var dead = true;
2014-12-09 00:00:25 -06:00
var pause = false;
2014-12-11 22:52:55 -06:00
// Time-management
2014-12-08 19:49:28 -06:00
var skipTicks;
var nextGameTick;
2014-12-09 00:00:25 -06:00
2014-12-08 19:49:28 -06:00
var cmdQueue = new Array();
2014-12-09 00:00:25 -06:00
var handers = new Array();
2014-12-08 19:49:28 -06:00
function coord2idx(row, col) { return (COLS * row) + col; }
function idx2row(idx) { return Math.floor(idx/COLS); }
function idx2col(idx) { return idx % COLS; }
2014-12-09 00:00:25 -06:00
function initialize(options) {
2014-12-08 19:49:28 -06:00
2014-12-09 00:00:25 -06:00
// Store our own copy of the canvas and get a 2D graphics context.
if (options.canvas) canvas = options.canvas;
else canvas = document.getElementsByTagName("canvas")[0];
2014-12-08 19:49:28 -06:00
g = S.graphicsContext = canvas.getContext("2d");
2014-12-09 00:00:25 -06:00
// Remove any existing handlers
canvas.removeEventListener('keydown', handleGameKey);
canvas.removeEventListener('keydown', handleEditorKey);
canvas.removeEventListener('click', handleEditorClick);
// Read in the board dimensions.
2014-12-08 19:49:28 -06:00
if (options.rows) S.ROWS = ROWS = options.rows;
if (options.cols) S.COLS = COLS = options.cols;
2014-12-09 00:00:25 -06:00
if (options.board) startBoard = options.board;
else {
// Wipe the board and draw the walls.
startBoard = new Array(ROWS * COLS);
var i;
for (i = 0; i < startBoard.length; i++ ) {
if (Math.floor(i / COLS) == 0 || (i % COLS) == 0) startBoard[i] = WALL
else if (Math.floor(i / COLS) == (ROWS - 1) ||
(i % COLS) == (COLS - 1)) startBoard[i] = WALL
else startBoard[i] = SPACE; } }
// Figure out how big each game tile is.
tileWidth = canvas.width / COLS;
tileHeight = canvas.height / ROWS;
2014-12-08 19:49:28 -06:00
2014-12-09 00:00:25 -06:00
// Mark the player as dead. This is primarily for the case where a
// player re-initializes the board during a game in progress. It
// causes any scheduled logic to quit without affecting out game state.
dead = true;
// Check to see if they want to use the editor or the game.
editor = Boolean(options.editor);
2014-12-11 22:52:55 -06:00
// Clear the canvas.
2014-12-08 19:49:28 -06:00
g.fillStyle = "white";
g.fillRect(0, 0, canvas.width, canvas.height);
2014-12-09 00:00:25 -06:00
2014-12-11 22:52:55 -06:00
// They want the game
2014-12-09 00:00:25 -06:00
if (!editor) {
canvas.addEventListener('keydown', handleGameKey);
g.font = "24px sans-serif";
g.fillStyle = "black";
g.fillText("Press Enter to begin.", 50, Math.floor(canvas.height/2), canvas.width - 100);
if (options.fps) skipTicks = Math.ceil(1000 / options.fps);
else skipTicks = 150; }
2014-12-11 22:52:55 -06:00
// They want the editor
2014-12-09 00:00:25 -06:00
else {
canvas.addEventListener('keydown', handleEditorKey);
canvas.addEventListener('click', handleEditorClick);
editorControls = document.getElementById("editorControls")
editorDataTextarea = document.querySelector("#editorControls textarea");
startEditor(); }
canvas.focus(); }
2014-12-08 19:49:28 -06:00
2014-12-09 00:00:25 -06:00
function startGame() {
2014-12-08 19:49:28 -06:00
while (body.length > 0) body.pop();
while (cmdQueue.length > 0) cmdQueue.pop();
headCur = coord2idx(Math.floor((ROWS - 1) / 2), Math.floor((COLS - 1) / 2));
direction = 1;
2014-12-09 00:00:25 -06:00
dead = pause = false;
2014-12-08 19:49:28 -06:00
nextGameTick = (new Date).getTime() + skipTicks;
body.push(headCur);
2014-12-09 00:00:25 -06:00
// Copy over a fresh board.
board = new Array(startBoard.length);
for (var i = 0; i < board.length; i++) board[i] = startBoard[i];
2014-12-08 19:49:28 -06:00
// Create a new food item and add it to the board.
2014-12-09 00:00:25 -06:00
board[newFoodLocation()] = FOOD;
// Write the initial body segment onto the board.
board[headCur] = SNAKE;
2014-12-08 19:49:28 -06:00
// Draw the board
2014-12-09 00:00:25 -06:00
paintBoard();
2014-12-08 19:49:28 -06:00
gameLoop(); }
2014-12-09 00:00:25 -06:00
function startEditor() {
board = new Array(ROWS * COLS);
cursorBlock = SPACE;
cursorIdx = headCur = coord2idx(
Math.floor((ROWS - 1) / 2), Math.floor((COLS - 1) / 2));
// Wipe the board and draw the walls.
var i;
for (i = 0; i < board.length; i++ ) {
if (Math.floor(i / COLS) == 0 || (i % COLS) == 0) board[i] = WALL
else if (Math.floor(i / COLS) == (ROWS - 1) ||
(i % COLS) == (COLS - 1)) board[i] = WALL
else board[i] = SPACE; }
board[headCur] = SNAKE;
document.getElementById("editorControls").style.display = "inline-block";
paintBoard(); }
2014-12-08 19:49:28 -06:00
function gameLoop() {
2014-12-09 00:00:25 -06:00
// Break the game loop if the player died or paused.
if (dead || pause) return;
2014-12-08 19:49:28 -06:00
if ((new Date).getTime() > nextGameTick) {
updateAndDraw();
nextGameTick += skipTicks; }
requestAnimationFrame(gameLoop); }
// For this game I want the game logic and the refresh rate to be tied
2014-12-11 22:52:55 -06:00
// together. The snake moves one step per animation frame. We do limit the
// animation frame to a given fps. This works because there are no other
// elements being animated other than the snake and no partial animation
// states.
2014-12-08 19:49:28 -06:00
function updateAndDraw() {
if (!g) return false;
foodEaten = false;
// 1. Read up to one command from the user.
if (cmdQueue.length > 0) {
var cmd = cmdQueue.shift();
if (cmd == 37) direction = -1; // Left
else if (cmd == 38) direction = -COLS; // Up
else if (cmd == 39) direction = 1; // Right
else if (cmd == 40) direction = COLS; /* Down */ }
// 2. Find the head's next spot.
headCur = headCur + direction;
// 3. First check to see if we've eaten food (since it will affect
// collision detection for the body). This is also where growth
// happens via not moving the tail.
2014-12-09 00:00:25 -06:00
if (board[headCur] == FOOD) foodEaten = true;
2014-12-08 19:49:28 -06:00
// 4. Remove the tail.
if (!foodEaten) {
var tailIdx = body.shift();
2014-12-09 00:00:25 -06:00
board[tailIdx] = SPACE
2014-12-08 19:49:28 -06:00
paintIdx(tailIdx); }
// 5. Detect wall and snake collisions
2014-12-09 00:00:25 -06:00
if (board[headCur] == WALL || board[headCur] == SNAKE) {
2014-12-08 19:49:28 -06:00
die(); return }
// 6. Move the head
body.push(headCur);
2014-12-09 00:00:25 -06:00
board[headCur] = SNAKE;
2014-12-08 19:49:28 -06:00
paintIdx(headCur);
// 7. Create more food if needed.
if (foodEaten) {
var foodLoc = newFoodLocation();
2014-12-09 00:00:25 -06:00
board[foodLoc] = FOOD;
2014-12-08 19:49:28 -06:00
paintIdx(foodLoc); } }
2014-12-11 22:52:55 -06:00
// Find a new location for a piece of food.
2014-12-08 19:49:28 -06:00
function newFoodLocation() {
2014-12-11 22:52:55 -06:00
// Find all the spaces on the board that are not occupied
2014-12-08 19:49:28 -06:00
var emptySpaces = new Array();
for (var i = 0; i < board.length; i++)
2014-12-11 22:52:55 -06:00
if (board[i] == SPACE) emptySpaces.push(i);
2014-12-08 19:49:28 -06:00
2014-12-11 22:52:55 -06:00
// Choose one of those spaces at random.
2014-12-08 19:49:28 -06:00
return emptySpaces[Math.floor(Math.random() * emptySpaces.length)] }
function die() {
paintIdxColor(headCur, "red");
dead = true;
//g.fillStyle = "white";
//g.fillRect(0, 0, canvas.width, canvas.height);
g.font = "24px sans-serif";
g.fillStyle = "red";
g.fillText("Press Enter to retry.", 50, Math.floor(canvas.height/2), canvas.width - 100); }
2014-12-09 00:00:25 -06:00
function handleGameKey(ke) {
2014-12-08 19:49:28 -06:00
var key = ke.keyCode ? ke.keyCode : ke.which;
2014-12-11 22:52:55 -06:00
// We will only intercept key events which we care about. This makes it
// safe to attach the handler to the window or anywhere else without
// worrying about the game becoming a black-hole for events.
2014-12-09 00:00:25 -06:00
var dontCare = false;
2014-12-08 19:49:28 -06:00
// Enter, start a new game.
2014-12-09 00:00:25 -06:00
if (key == 13) {
dead = true;
requestAnimationFrame(startGame); }
2014-12-11 22:52:55 -06:00
// Pause, pause or unpause the game.
2014-12-09 00:00:25 -06:00
else if (key == 19) {
if (pause == true) {
pause = false;
nextGameTick = (new Date).getTime();
gameLoop(); }
else pause = true; }
2014-12-08 19:49:28 -06:00
// Queue directions in the command queue
2014-12-09 00:00:25 -06:00
else if ((key > 36) && (key < 41)) cmdQueue.push(key);
2014-12-11 22:52:55 -06:00
// Anything else we don't care about.
2014-12-09 00:00:25 -06:00
else dontCare = true;
2014-12-11 22:52:55 -06:00
// If we *do* care about this key, consume it and prevent it from
// bubbling up.
2014-12-09 00:00:25 -06:00
if (!dontCare) ke.preventDefault();
return false; }
2014-12-11 22:52:55 -06:00
// Handle input for the game editor. The editor is entirely input driven.
// All of it's actions and logic are in response to user input. There is no
// "game" loop and most of the editor's logic happens in this function.
2014-12-09 00:00:25 -06:00
function handleEditorKey(ke) {
var key = ke.keyCode ? ke.keyCode : ke.which;
2014-12-11 22:52:55 -06:00
// Again, we will pass along input we are not interested in.
2014-12-09 00:00:25 -06:00
var dontCare = false;
switch (key) {
// Enter: place a tile.
case 13: board[cursorIdx] = cursorBlock; break;
2014-12-11 22:52:55 -06:00
// Direction keys: move the cursor.
2014-12-09 00:00:25 -06:00
case 37: cursorIdx -= 1; break; // Left
case 38: cursorIdx -= COLS; break; // Up
case 39: cursorIdx += 1; break; // Right
case 40: cursorIdx += COLS; break; // Down
2014-12-11 22:52:55 -06:00
// Number keys: select a tile type.
2014-12-09 00:00:25 -06:00
case 49: case 97: cursorBlock = SPACE; break; // 1
case 50: case 98: cursorBlock = WALL; break; // 2
case 51: case 99: cursorBlock = SNAKE; break; // 3
case 52: case 100: cursorBlock = FOOD; break; // 4
default: dontCare = true;
}
2014-12-11 22:52:55 -06:00
// Our board may have changed, let's spit out the data.
2014-12-09 00:00:25 -06:00
emitEditorLevelData();
2014-12-11 22:52:55 -06:00
// Redraw the board.
2014-12-09 00:00:25 -06:00
paintBoard();
2014-12-11 22:52:55 -06:00
// Draw the current cursor position.
2014-12-09 00:00:25 -06:00
g.strokeStyle = "solid 4px gray";
g.strokeRect(
(cursorIdx % COLS) * tileWidth,
Math.floor(cursorIdx / COLS) * tileHeight,
tileWidth, tileHeight);
2014-12-11 22:52:55 -06:00
// Consume events we care about and prevent them from bubbling up.
2014-12-09 00:00:25 -06:00
if (!dontCare) ke.preventDefault(); }
function handleEditorClick(ke) {
}
2014-12-11 22:52:55 -06:00
// Write out the editor level data as a JSON string to the textarea.
2014-12-09 00:00:25 -06:00
function emitEditorLevelData() {
editorDataTextarea.value = JSON.stringify({
board: board,
rows: ROWS,
cols: COLS,
fps: Math.ceil(1000 / skipTicks)}); }
2014-12-11 22:52:55 -06:00
// Load the editor data as a JSON string from the textarea.
2014-12-09 00:00:25 -06:00
function loadEditorLevelData() { }
2014-12-11 22:52:55 -06:00
// Draw the entire board.
2014-12-09 00:00:25 -06:00
function paintBoard() {
for (i = 0; i < board.length; i++) { paintIdx(i); } }
2014-12-08 19:49:28 -06:00
function paintCoord(row, col) {
var idx = coord2idx(row, col);
2014-12-09 00:00:25 -06:00
if (board[idx] == WALL) g.fillStyle = "black";
else if (board[idx] == FOOD) g.fillStyle = "green";
else if (board[idx] == SNAKE) g.fillStyle = "blue";
2014-12-08 19:49:28 -06:00
else g.fillStyle = "white";
2014-12-09 00:00:25 -06:00
g.fillRect(col, row, tileWidth, tileHeight); }
2014-12-08 19:49:28 -06:00
function paintIdxColor(idx, color) {
g.fillStyle = color;
g.fillRect(
2014-12-09 00:00:25 -06:00
(idx % COLS) * tileWidth,
Math.floor(idx / COLS) * tileHeight,
tileWidth, tileHeight); }
2014-12-08 19:49:28 -06:00
function paintIdx(idx) {
2014-12-09 00:00:25 -06:00
if (board[idx] == WALL) g.fillStyle = "black";
else if (board[idx] == FOOD) g.fillStyle = "green";
else if (board[idx] == SNAKE) g.fillStyle = "blue";
2014-12-08 19:49:28 -06:00
else g.fillStyle = "white";
g.fillRect(
2014-12-09 00:00:25 -06:00
(idx % COLS) * tileWidth,
Math.floor(idx / COLS) * tileHeight,
tileWidth, tileHeight); }
2014-12-08 19:49:28 -06:00
S.initialize = initialize;
})();