Commits

Colin Copeland committed fd29c8a

snake example

Comments (0)

Files changed (5)

+function imAlive(){
+ interval = setInterval(whereShallIGo,70);
+}
+
+
+function xOffset(){
+  return suggestedPoint[0] - currentPosition['x'];
+}
+
+function yOffset(){
+  return suggestedPoint[1] - currentPosition['y'];
+}
+
+function range(value){
+  if (value > 0 ) {
+    return value
+  } else {
+    return value - (value * 2)
+  }
+}
+
+function whereShallIGo(){
+  xDirection = '';
+  yDirection = '';
+  if (xOffset() > 0) xDirection = 'right';
+  if (xOffset() < 0) xDirection = 'left';
+  if (yOffset() > 0) yDirection = 'down';
+  if (yOffset() < 0) yDirection = 'up';
+  if (range(xOffset()) > (range(yOffset()))){
+    if (xDirection == 'right' && direction != 'left') moveRight();
+    if (xDirection == 'left' && direction != 'right') moveLeft();
+  } else {
+    if (yDirection == 'down' && direction != 'up') moveDown();
+    if (yDirection == 'up' && direction != 'down') moveUp();    
+  }
+}
+<html>
+  <head>
+    <title>Snake</title>
+    <link href='style.css' rel='stylesheet'>
+    <script src='snake.js' type='text/javascript'></script>
+  </head>
+  <body onload='checkSupported();'>
+    <div id='bar'>
+      <span id='logo'>SNAKE</span>
+      <div id='score_container'>
+        Score:
+        <span id='score'>0</span>
+      </div>
+      <div id='play_menu'>
+        <button onclick="pause();document.getElementById('play_menu').style.display='none';document.getElementById('pause_menu').style.display='block';">Pause</button>
+      </div>
+      <div id='pause_menu'>
+        <button onclick="restart();document.getElementById('play_menu').style.display='block';document.getElementById('pause_menu').style.display='none';">Restart</button>
+        <button onclick="play();document.getElementById('play_menu').style.display='block';document.getElementById('pause_menu').style.display='none';">Resume</button>
+      </div>
+      <div id='restart_menu'>
+        <button onclick="restart();document.getElementById('play_menu').style.display='block';document.getElementById('restart_menu').style.display='none';">Restart</button>
+      </div>
+    </div>
+    <canvas height='300' id='canvas' width='400'>    </canvas>
+  </body>
+</html>
+function draw() {
+ canvas = document.getElementById("canvas");  
+ if (canvas.getContext) {
+   this.x = canvas.width / 2;
+   this.y = canvas.height / 2;
+   this.av = 5;
+   ctx = canvas.getContext("2d");
+   arr = ['Up', 'Down', 'Left', 'Right'];
+   setInterval(autodraw,100);
+  }  
+}
+
+function autodraw() {
+  if (arr[Math.floor(Math.random()*arr.length)] == 'Up') {
+    goUp();                                    
+  };                                           
+  if (arr[Math.floor(Math.random()*arr.length)] == 'Down') {
+    goDown();                                  
+  };                                           
+  if (arr[Math.floor(Math.random()*arr.length)] == 'Left') {
+    goLeft();                                  
+  };                                           
+  if (arr[Math.floor(Math.random()*arr.length)] == 'Right') {
+    goRight();
+  };
+}
+
+function createSquare(x, y, w, h) {
+  if (x < canvas.width && y < canvas.height) {
+    ctx.fillStyle = "rgba(200,0,0, 0.1)";
+    ctx.fillRect (x, y, w, h);
+    ctx.strokeStyle = "rgba(200,0,0, 0.5)";
+    ctx.strokeRect (x, y, w, h);
+  }
+}
+
+document.onkeydown = function(event) {
+  var keyCode; 
+  
+  if(event == null)
+  {
+    keyCode = window.event.keyCode; 
+  }
+  else 
+  {
+    keyCode = event.keyCode; 
+  }
+ 
+  switch(keyCode)
+  {
+    // left 
+    case 37:
+      goLeft();
+      break; 
+     
+    // up 
+    case 38:
+      goUp();
+      break; 
+      
+    // right 
+    case 39:
+      goRight();
+      break; 
+    
+    // down
+    case 40:
+      goDown();
+      break; 
+    
+    default: 
+      break; 
+  } 
+}
+
+function goLeft() {
+  if ((x - av) >= 0) {
+    x = x - av;
+    createSquare(x, y, 5, 5);
+  }
+}
+
+function goRight() {
+  if ((x + av) < canvas.width) {
+    x = x + av;
+    createSquare(x, y, 5, 5);
+  }
+}
+
+function goUp() {
+  if ((y - av) >= 0)
+  y = y - av;
+  createSquare(x, y, 5, 5);
+}
+
+function goDown() {
+  if ((y + av) < canvas.height) {
+    y = y + av;
+    createSquare(x, y, 5, 5);
+  }
+}
+function checkSupported() {
+  canvas = document.getElementById('canvas');
+  if (canvas.getContext){
+    ctx = canvas.getContext('2d');
+    this.gridSize = 5;
+    start();
+  } else {
+    alert("We're sorry, but your browser does not support the canvas tag. Please use any web browser other than Internet Explorer.");
+  }
+}
+
+function start(){
+  ctx.clearRect(0,0, canvas.width, canvas.height);
+  this.currentPosition = {'x':50, 'y':50};
+  snakeBody = [];
+  snakeLength = 3;
+  updateScore();
+  makeFoodItem();
+  drawSnake();
+  direction = 'right';
+  play();  
+}
+
+function restart(){
+  pause();
+  start();
+}
+
+function pause(){
+  clearInterval(interval);
+  allowPressKeys = false;
+}
+
+function play(){
+  interval = setInterval(moveSnake,50);
+  allowPressKeys = true;
+}
+
+function drawSnake() {
+  if (snakeBody.some(hasEatenItself)) {
+    gameOver();
+    return false;
+  }
+  snakeBody.push([currentPosition['x'], currentPosition['y']]);
+  ctx.fillStyle = "rgb(200,0,0)";
+  ctx.fillRect(currentPosition['x'], currentPosition['y'], gridSize, gridSize);
+  if (snakeBody.length > snakeLength) {
+    var itemToRemove = snakeBody.shift();
+    ctx.clearRect(itemToRemove[0], itemToRemove[1], gridSize, gridSize);
+  }  
+  if (currentPosition['x'] == suggestedPoint[0] && currentPosition['y'] == suggestedPoint[1]) {
+    makeFoodItem();
+    snakeLength += 1;
+    updateScore();
+  }
+}
+
+function leftPosition(){
+ return currentPosition['x'] - gridSize;  
+}
+
+function rightPosition(){
+  return currentPosition['x'] + gridSize;
+}
+
+function upPosition(){
+  return currentPosition['y'] - gridSize;  
+}
+
+function downPosition(){
+  return currentPosition['y'] + gridSize;
+}
+
+function whichWayToGo(axisType){  
+  if (axisType=='x') {
+    a = (currentPosition['x'] > canvas.width / 2) ? moveLeft() : moveRight();
+  } else {
+    a = (currentPosition['y'] > canvas.height / 2) ? moveUp() : moveDown();
+  }
+}
+
+function moveUp(){
+  if (upPosition() >= 0) {
+    executeMove('up', 'y', upPosition());
+  } else {
+    whichWayToGo('x');
+  }
+}
+
+function moveDown(){
+  if (downPosition() < canvas.height) {
+    executeMove('down', 'y', downPosition());    
+  } else {
+    whichWayToGo('x');
+  }
+}
+
+function moveLeft(){
+  if (leftPosition() >= 0) {
+    executeMove('left', 'x', leftPosition());
+  } else {
+    whichWayToGo('y');
+  }
+}
+
+function moveRight(){
+  if (rightPosition() < canvas.width) {
+    executeMove('right', 'x', rightPosition());
+  } else {
+    whichWayToGo('y');
+  }
+}
+
+function executeMove(dirValue, axisType, axisValue) {
+  direction = dirValue;
+  currentPosition[axisType] = axisValue;
+  drawSnake();
+}
+
+function makeFoodItem(){
+  suggestedPoint = [Math.floor(Math.random()*(canvas.width/gridSize))*gridSize, Math.floor(Math.random()*(canvas.height/gridSize))*gridSize];
+  if (snakeBody.some(hasPoint)) {
+    makeFoodItem();
+  } else {
+    ctx.fillStyle = "rgb(10,100,0)";
+    ctx.fillRect(suggestedPoint[0], suggestedPoint[1], gridSize, gridSize);
+  };
+}
+
+function hasPoint(element, index, array) {
+  return (element[0] == suggestedPoint[0] && element[1] == suggestedPoint[1]);
+}
+
+function hasEatenItself(element, index, array) {
+  return (element[0] == currentPosition['x'] && element[1] == currentPosition['y']);  
+}
+
+function gameOver(){
+  var score = (snakeLength - 3)*10;
+  pause();
+  alert("Game Over. Your score was "+ score);
+  ctx.clearRect(0,0, canvas.width, canvas.height);
+  document.getElementById('play_menu').style.display='none';
+  document.getElementById('restart_menu').style.display='block';
+}
+
+function updateScore(){
+  var score = (snakeLength - 3)*10
+  document.getElementById('score').innerText = score;
+}
+
+document.onkeydown = function(event) {
+  if (!allowPressKeys){
+    return null;
+  }
+  var keyCode; 
+  if(event == null)
+  {
+    keyCode = window.event.keyCode; 
+  }
+  else 
+  {
+    keyCode = event.keyCode; 
+  }
+ 
+  switch(keyCode)
+  {
+    case 37:
+      if (direction != "right"){
+        moveLeft();
+      }
+      break;
+     
+    case 38:
+      if (direction != "down"){
+        moveUp();
+      }
+      break; 
+      
+    case 39:
+      if (direction != "left"){
+        moveRight();
+      }
+      break; 
+    
+    case 40:
+      if (direction != "up"){
+        moveDown();
+      }
+      break; 
+    
+    default: 
+      break; 
+  } 
+}
+
+function moveSnake(){
+  switch(direction){
+    case 'up':
+      moveUp();
+      break;
+
+    case 'down':
+      moveDown();
+      break;
+      
+    case 'left':
+      moveLeft();
+      break;
+
+    case 'right':
+      moveRight();
+      break;
+  }
+}
+html, body div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kdb, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
+  margin: 0;
+  padding: 0;
+  font-size: 100%;
+  vertical-align: baseline;
+  border: 0;
+  outline: 0;
+  background: transparent; 
+}
+
+ol, ul {
+  list-style: none; 
+}
+
+blockquote, q {
+  quotes: none; 
+}
+
+a, a:hover {
+  text-decoration: none; 
+}
+
+table {
+  border-collapse: collapse;
+  border-spacing: none; 
+}
+
+body {
+  background: #111; 
+}
+
+canvas {
+  border: solid 1px red; 
+}