A prototype of the Snake Game using JavaScript/ES5, HTML5 WebGL
by Ivan Enzhaev
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"></script>
<canvas width="200" height="200" id="gameCanvas">
Your browser does not support HTML5 Canvas. Please shift to a newer browser.
</canvas>
<p>Click on this window to activate keyboard handlers to control the snake by WASD and arrow keys.</p>
JavaScript
// Canvas element and gl context
var canvas, gl;
// Snake list of (x, y) positions
var snake = [{ x: 10, y: 10 }];
// Snake movement direction
var snakeDir = { x: 10, y: 0 };
// Snake step
var cellSize = 10;
// Food
var food = { x: 0, y: 0 };
var vertexShaderSource =
"attribute vec2 aPosition;" +
"uniform mat4 uProjMatrix;" +
"uniform mat4 uScaleMatrix;" +
"uniform mat4 uTranslateMatrix;" +
"void main()" +
"{" +
" gl_Position = uProjMatrix * uTranslateMatrix * uScaleMatrix * vec4(aPosition, 1.0, 1.0);" +
"}";
var fragmentShaderSource =
"precision mediump float;" +
"uniform vec3 uColor;" +
"void main()" +
"{" +
" gl_FragColor = vec4(uColor, 1.0);" +
"}";
canvas = document.getElementById("gameCanvas");
gl = canvas.getContext("webgl");
// Compile shaders, link a shader program and get the shader program
var shaderProgram = initShaders();
if (shaderProgram < 0)
{
console.log("Failed to get a shader program");
}
initVertexBuffers();
// Get location of a aPosition variable in the vertex shader
var aPosition = gl.getAttribLocation(shaderProgram, "aPosition");
if (aPosition < 0)
{
console.log("Failed to get aPosition variable");
}
gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, gl.FALSE, 0, 0);
gl.enableVertexAttribArray(aPosition);
// Field size
var fieldWidth = canvas.width;
var fieldHeight = canvas.height;
gl.viewport(0, 0, fieldWidth, fieldHeight);
// Get locations of matrixes and set values for them
// Projection matrix
var projMatrix = mat4.create();
mat4.ortho(projMatrix, 0.0, fieldWidth, fieldHeight, 0.0, -100.0, 100.0);
passMatrixToShader("uProjMatrix", projMatrix);
// Scale matrix
var scaleMatrix = mat4.create();
// Translate matrix
var translateMatrix = mat4.create();
function passMatrixToShader(matrixName, matrix)
{
var uLocation = gl.getUniformLocation(shaderProgram, matrixName);
if (uLocation == null)
{
console.log("Failed to get a location variable: " +...