Snake

by Malcolm Groves

HTML

<body>
  <div class="wrapper">
    <div id='timer'>
    </div>
    
    <div class="container" tabindex="1">
    </div>
  </div>
</body>

CSS

div {
  box-sizing: border-box;
}
.wrapper {
  width: 400px;
}
.container {
  width: 100%;
  height: 400px;
  background-color: white;
  /* outline: none */
}


.square {
  /* border: solid 0.1px;*/
  width: 10px;
  height: 10px;
  float: left;
  font-size: 8px;
  text-align: center;
  border-radius: 50%;
}

.snake {
  background-color: black;
}

div.score {
  margin-bottom: 25px;
}

JavaScript

/* board objects */
const roundTime = 15;

class Snake {
	constructor() {
  	this.position = [[20, 20]];
    this.grid = [];
    this.dimension = 40;
    this.$container = $('.container');
    for(let i = 0; i < this.dimension; ++i) {
			this.grid.push(new Array(this.dimension).fill(false));
		}
    this.grid[20][20] = true;
    this.direction = 'r';
    this.gameInProgress = true;
    this.speed = 150;
    this.count = 0;
    score(this.count);
  }
  
  
  resetGame() {
    this.position = [[20, 20]];
    this.direction = 'r';
    for(let i = 0; i < this.grid.length; ++i) {
      for(let j = 0; j < this.grid[i].length; ++j) {
        this.grid[i][j] = false;
      }
    }
    this.grid[20][20] = true;
    this.gameInProgress = true;
    this.speed = 150;
    this.count = 0;
    score(this.count);
    this.placeFood();
    this.render();
  }
  
  to(position) {
    if(position[0] >= this.dimension || position[0] < 0 || position[1] >= this.dimension || position[1] < 0) {
      this.gameInProgress = false;
    }
    else if(this.grid[position[0]][position[1]]) {
      this.position.forEach(function(element) {
        if(element[0] === position[0] && element[1] === position[1]) {
          this.gameInProgress = false;
        }
      });
      if(this.gameInProgress) {
        this.position.unshift(position);
        this.makeNextMove();
        this.placeFood();
        this.speed *= 0.9;
        ++this.count;
        score(this.count);
      }
    }
    else {
      this.toggleSquare(this.position.pop());
      this.position.unshift(position);
      this.toggleSquare(position);
    }
	}
  
  makeNextMove() {
    let head = this.position[0];
    switch(this.direction) {
      case 'u':
        this.to([head[0] - 1, head[1]]);
        break;
      case 'd':
        this.to([head[0] + 1, head[1]]);
        break;
      case 'l':
        this.to([head[0], head[1] - 1]);
        break;
      case 'r':
        this.to([head[0], head[1] + 1]);
        break;
    }
  }
 ...