cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <div class="controls">
  <button id="start">Start</button><button id="stop">Stop</button>
</div>
<div id="game-info">
  <div>Level: <span id="level"></span></div>
  <!-- /#level -->
  <div>Snake length: <span id="length"></span></div>
  <!-- /#length -->
  <div>Time: <span id="time"></span></div>
  <!-- /#time -->
</div>
<!-- /.game-info -->
<div class="container"></div>
<!-- /.container -->
            
          
!
            
              * {
  box-sizing: border-box;
}
#block {
  width: 20px;
  height: 20px;
  background-color: #000;
  position: relative;
}
%container {
  width: 400px;
  margin: 0 auto;
}
.controls,
#game-info {
  @extend %container;
}
.controls {
  text-align: center;
  margin-top: 50px;
}
button {
  background-color: #ffffff;
  border: 2px #000000 solid;
  padding: 5px 15px;
  margin: 0 5px;
  cursor: pointer;
}
.container {
  @extend %container;
  background-color: #efefef;
  box-sizing: content-box;
  border: 5px #000 solid;
  &::after {
    content: '';
    display: table;
    clear: both;
  }
}
.field {
  width: 20px;
  height: 20px;
  //border: 1px #000 solid;
  float: left;
}
            
          
!
            
              var xAxis = 3,
    yAxis = 0,
    direction = 'R';

var Field = function(container) {
  this.parent = container;
  this.element = document.createElement('div');
  this.create = function() {
    this.element.className = 'field';
    this.parent.appendChild(this.element);
  }
  this.filled = false;
  this.fill = function() {
    this.element.style['background-color'] = '#000';
  }
  this.clear = function() {
    this.element.style['background-color'] = 'transparent';
  }
  this.food = function() {
    this.element.style['background-color'] = '#0f0';
  }
  this.isThereFood = false;
}

var Snake = {
  length: 4,
  fields: [[0,0],[0,1],[0,2],[0,3]],
  update: function() {
    this.fields.push([yAxis,xAxis]);
    fields[yAxis][xAxis].filled = true;
    if (this.length < this.fields.length) {
      var deletedField = this.fields.shift();
      fields[deletedField[0]][deletedField[1]].clear();
      fields[deletedField[0]][deletedField[1]].filled = false;
    }
  },
  draw: function() {
    for (let i = 0; i < this.fields.length; i++) {
      fields[this.fields[i][0]][this.fields[i][1]].fill();
    }
  },
  eat: function() {
    this.length++;
    this.fields.unshift([yAxis,xAxis]);
  }
}

/* var Timer = {
  sec: 0,
  min: 0,
  hours: 0,
  timeLabel: document.getElementById('time'),
  start: function() {
    var that = this;
    setInterval(function() {
      that.sec++;
      if (that.sec > 59) {
        that.sec = 0;
        that.min++;
      }
      that.timeLabel.textContent = that.getTime();
    },1000);
  },
  getTime: function() {
    var s = this.formatTime(this.sec);
    var m = this.formatTime(this.min);
    var h = this.formatTime(this.hours);
    return h + ':' + m + ':' + s;
  },
  formatTime: function(unit) {
    if (unit < 10) {
      return '0' + unit;
    } else {
      return unit.toString();
    }
  }
} */
//obiekt powinien przyjmować inne obiekty i na ich podstawie wywoływać wartości
var Info = {
  levelLabel: document.getElementById('level'),
  lengthLabel: document.getElementById('length'),
  timeLabel: document.getElementById('time'),
  level: 1,
  length: Snake.length,
  updateLevel: function() {
    this.levelLabel.textContent = ++this.level;
  },
  updateLength: function() {
    this.lengthLabel.textContent = Snake.length;
  },
  init: function() {
    this.levelLabel.textContent = this.level;
    this.lengthLabel.textContent = this.length;
  }
}
Info.init();

function isItemInArray(array,item) {
 for (let i = 0; i < array.length; i++) {
   if(array[i][0] === item[0] && array[i][1] === item[1]) {
     return true;
   }
 }
  return false;
}

var Game = {
  createFood: function() {
    var random = [];
    //indexOf
    do {
      random[0] = Math.floor(Math.random() * 20);
      random[1] = Math.floor(Math.random() * 20);
    } while(isItemInArray(Snake.fields,random));
    
    fields[random[0]][random[1]].food();
    fields[random[0]][random[1]].isThereFood = true;
  }
}

//dodać fields do obiektu Game
var container = document.getElementsByClassName('container')[0];
var fields = [];
for (let i = 0; i < 20; i++) {
  var row = [];
  for (let j = 0; j < 20; j++) {
    var newField = new Field(container);
    newField.create();
    //dlaczego fields[i][j] nie działa?
    row.push(newField);
  }
  fields.push(row);
}
Snake.draw();
Game.createFood();
//console.log(fields);

//var myBlock = document.getElementById('block');

document.addEventListener('keydown',function(e) {
  switch(e.keyCode) {
    case 40:
      if (direction === "T") {
        break;
      }
      direction = "B";
      break;
    case 38:
      if (direction === "B") {
        break;
      }
      direction = "T";
      break;
    case 37:
      if (direction === "R") {
        break;
      }
      direction = "L";
      break;
    case 39:
      if (direction === "L") {
        break;
      }
      direction = "R";
      break;
  }
  
});
var start = document.getElementById('start'),
    stop = document.getElementById('stop'),
    interval,
    intervalTime = 500,
    levels = [6,12,20,30];
var move = function() {
  checkDirection();
  if (levels.indexOf(Snake.length) !== -1) {
    levels.shift();
    Info.updateLevel();
    clearInterval(interval);
    intervalTime *= .6;
    interval = setInterval(move,intervalTime);
  }
}
start.addEventListener('click',function() {
  /* Timer.start(); */
  interval = setInterval(move,intervalTime);
  //interval = setInterval(function() {
    //checkDirection();
    //https://stackoverflow.com/questions/1280263/changing-the-interval-of-setinterval-while-its-running
    /* if (Snake.length % 5 === 0) {
      clearInterval(interval);
      interval = setInterval(function() {
        checkDirection();
      })
    } */
    //myBlock.style.left = (myLeft + 'px');
  //},intervalTime);
});
stop.addEventListener('click',function() {
  clearInterval(interval);
});

//dodać funckje do obiektu Game
function checkDirection() {
  switch(direction) {
    case 'L':
      xAxis -= 1;
      if (xAxis < 0 || xAxis > 19) {
        alert('Game over');
        clearInterval(interval);
        break;
      }
      if (fields[yAxis][xAxis].filled) {
        alert('Game over');
        clearInterval(interval);
        break;
      }
      if (fields[yAxis][xAxis].isThereFood) {
        fields[yAxis][xAxis].isThereFood = false;
        Snake.eat();
        Info.updateLength();
        Game.createFood();
      }
      
      Snake.update();
      Snake.draw();
      break;
    case 'R':
      xAxis += 1;
      if (xAxis < 0 || xAxis > 19) {
        alert('Game over');
        clearInterval(interval);
        break;
      }
      if (fields[yAxis][xAxis].filled) {
        alert('Game over');
        clearInterval(interval);
        break;
      }
      if (fields[yAxis][xAxis].isThereFood) {
        fields[yAxis][xAxis].isThereFood = false;
        Snake.eat();
        Info.updateLength();
        Game.createFood();
      }
      Snake.update();
      Snake.draw();
      break;
    case 'T':
      yAxis -= 1;
      if (yAxis < 0 || yAxis > 19) {
        alert('Game over');
        clearInterval(interval);
        break;
      }
      if (fields[yAxis][xAxis].filled) {
        alert('Game over');
        clearInterval(interval);
        break;
      }
      if (fields[yAxis][xAxis].isThereFood) {
        fields[yAxis][xAxis].isThereFood = false;
        Snake.eat();
        Info.updateLength();
        Game.createFood();
      }
      Snake.update();
      Snake.draw();
      break;
    case 'B':
      yAxis += 1;
      if (yAxis < 0 || yAxis > 19) {
        alert('Game over');
        clearInterval(interval);
        break;
      }
      if (fields[yAxis][xAxis].filled) {
        alert('Game over');
        clearInterval(interval);
        break;
      }
      if (fields[yAxis][xAxis].isThereFood) {
        fields[yAxis][xAxis].isThereFood = false;
        Snake.eat();
        Info.updateLength();
        Game.createFood();
      }
      Snake.update();
      Snake.draw();
      break;
                  }
}
            
          
!
999px
Loading ..................

Console