Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                #snakeGameContainer
  #info
    #controlsContainer
      button#upButton
        i.material-icons arrow_upward
      button#leftButton
        i.material-icons arrow_back
      button#downButton
        i.material-icons arrow_downward
      button#rightButton
        i.material-icons arrow_forward
  #gameContainer
    div#gameDetailsContainer
      p#scoreContainer
        span Score: 
        span#score 0
      p#highScoreContainer
        span High Score: 
        span#highScore ---
    div#canvasContainer
    
  //TODO
  // Fix item spawn on snake
  // Improve in game text
              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css?family=Press+Start+2P');

$padding: 1em;
$info-margin: 1em;
$button-margin: $info-margin/1.2;
$h1-margin: $info-margin/1.5;
$p-margin: $info-margin/2;
$colour-dark: #1e3833;
$colour-light: #c3cfa3;

body {
	margin: 0;
	padding: 0;
  width: 100vw;
  height: 100vh;
	overflow: hidden;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  font-family: 'Press Start 2P', cursive;
}

#snakeGameContainer {
  display: flex;
  flex-direction: row;
  padding: $padding;
  width: 100vw;
  height: 100vh;
  box-sizing: border-box;
  justify-content: center;
}

#info {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: $padding;
}

h1 {
  font-size: 1.4em;
  font-weight: 500;
  margin: $h1-margin 0 $h1-margin 0;
}

p {
  font-size: 1em;
  margin: $p-margin 0 $p-margin 0;
}

canvas {
  box-sizing: border-box;
  border: solid 1em $colour-dark;
  width: 100%;
  height: 100%;
  max-width: 400px;
  max-height: 400px;
}

#canvasPlaceholder {
  width: 300px;
  height: 300px;
  background-color: $colour-light;
  border: solid 30px $colour-dark;
}

button {
  border: 0;
  color: inherit;
  font: inherit;
  line-height: normal;
  overflow: visible;
  padding: $button-margin;
  margin: 1em 0;
  -webkit-appearance: button;
  user-select: none; 
  background: $colour-light;
  border: none;
  display: block;
  cursor: pointer;
  transition: background 0.2s;
  &:hover {
    background: $colour-dark;
  }
}

#startGameContainer {
  margin: 1em 0.5em;
}

#gameContainer {
  display: flex;
  flex-direction: column;
  padding: $padding;
  justify-content: center;
  align-items: center;
}

#controlsContainer {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-gap: 1em;
  margin: 1em 0.5em;
  #upButton {
    grid-row: 1;
    grid-column: 2;
  }
  #downButton {
    grid-row: 3;
    grid-column: 2;
  }
  #leftButton {
    grid-row: 2;
    grid-column: 1;
  }
  #rightButton {
    grid-row: 2;
    grid-column: 3;
  }
  button {
    margin: 0;
  }
}

@media screen and (max-width: 40em) and (min-height: 30em) {
  body {
    #snakeGameContainer {
      flex-direction: column-reverse;
    }
    #info, #gameContainer {
      padding: 0.25em;
    }
    #startGameContainer, #controlsContainer {
      margin: 0.25em 0;
    }
    #controlsContainer {
      grid-gap: 0.5em;
    }
    #startGameButton, #stopGameButton {
      margin: 0;
    }
  }
}
              
            
!

JS

              
                class SnakeGame {
  constructor() {
    this.options = {
      bgColour: '#c3cfa3',
      gridSize: 10,
      canvasSize: 300,
      objectSize: 30,
      defaultGameSpeed: 4,
      speedIncrease: 0.5,
      scoreIncrease: 10,
      fontSize: 20
    }
    this.state = {
      score: 0,
      highScore: 0,
      gameSpeed: this.options.defaultGameSpeed,
      paused: false,
      started: false,
      alive: false,
      snake: null,
      items: [],
      inputEventsCreated: false
    }
    this.dom = {
      canvas: document.createElement("canvas"),
      scoreElement: document.querySelector('#score'),
      highScoreElement: document.querySelector('#highScore'),
      startGameButton: document.querySelector('#startGameButton'),
      upButton: document.querySelector('#upButton'),
      downButton: document.querySelector('#downButton'),
      leftButton: document.querySelector('#leftButton'),
      rightButton: document.querySelector('#rightButton'),
      body: document.querySelector('body')
    }
  }
  createInputEvents() {
    const game = this
    document.addEventListener('keydown', (event) => {
      game.handleInput(event)
    })
    this.dom.upButton.addEventListener('click', (event) => {
      game.handleInput(event, 'w')   
    })
    this.dom.downButton.addEventListener('click', (event) => {
      game.handleInput(event, 's')   
    })
    this.dom.leftButton.addEventListener('click', (event) => {
      game.handleInput(event, 'a')   
    })
    this.dom.rightButton.addEventListener('click', (event) => {
      game.handleInput(event, 'd')   
    })
  }
  init() {
    this.createCanvas()
    this.getHighScore()
    this.drawBackground()
    
    if(!this.state.inputEventsCreated) {
      this.state.inputEventsCreate = true
      this.createInputEvents()
    }
    
    this.showTitleScreen()
  }
  showTitleScreen() {
    const x = this.options.objectSize/2
    const y = this.options.canvasSize/2
    this.drawText('black', 'Snake', this.options.fontSize*2, 'bold', x,      this.options.objectSize*2)
    this.drawText('black', 'Arrow keys or WASD to', this.options.fontSize, 'bold', x, this.options.objectSize*3)
    this.drawText('black', 'move and start the game', this.options.fontSize, 'bold', x, this.options.objectSize*4)
  }
  start() {
    this.state.started = true
    this.setUpRound()
    
    this.interval()
  }
  setUpRound() {
    this.clear()
    this.drawBackground()
    this.state.gameSpeed = this.options.defaultGameSpeed
    this.state.score = 0
    this.drawScore()
    
    const initialSnake = this.createSnake()
    const initialItem = this.createItem(initialSnake.getSegments().slice())
    this.state.snake = initialSnake
    this.state.items = [initialItem]
    
    this.state.alive = true
    this.state.paused = false
  }
  createSnake() {
    return new Snake(this.options.objectSize)
  }
  createItem(snakeSegments) {
    return new Item(this.options.objectSize,
                    this.options.canvasSize,
                    snakeSegments)
  }
  createCanvas() {
    this.dom.canvas.width = this.options.canvasSize
    this.dom.canvas.height = this.options.canvasSize
    document.querySelector('#canvasContainer').appendChild(this.dom.canvas)
    this.dom.canvas.style.borderWidth = `${String(this.options.objectSize)}px`
    this.state.ctx = this.dom.canvas.getContext('2d')
  }
  drawRectangle(colour, x, y, sizeX, sizeY) {
    this.state.ctx.fillStyle = colour
    this.state.ctx.fillRect(x, y, sizeX, sizeY)
  }
  drawText(colour, text, size, weight, x, y) {
    this.state.ctx.fillStyle = colour
    this.state.ctx.font = `${weight} ${size}px Monospace`
    this.state.ctx.fillText(text, x, y)
  }
  drawScore() {
    this.dom.scoreElement.innerHTML = this.state.score
  }
  increaseSpeed() {
    this.state.gameSpeed += this.options.speedIncrease
  }
  addScore() {
    this.state.score += this.options.scoreIncrease
    this.drawScore()
    this.setHighScore()
    this.increaseSpeed()
  }
  pauseGame() {
    this.clear()
    this.drawBackground()
    
    const x = this.options.objectSize/2
    const y = this.options.canvasSize/2
    this.drawText('black', 'Press any key to restart', this.options.fontSize, 'normal', x, y)
  }
  iterate() {
    if (!this.state.paused) {
      this.clear()
      this.drawBackground()
      this.interateObjects()
    }
  }
  handleIterate() {
    if (!this.state.paused) {
      this.iterate()
    }
    window.requestAnimationFrame(this.interval.bind(this));
  }
  interval() {
    //Render the game according the fps specified by game.gameSpeed
    setTimeout(() => { this.handleIterate()}, 1000/this.state.gameSpeed) 
  }
  interateObjects() {
    // Process snake movement and collisions
    this.iterateSnake()
    this.renderObjects()
  }
  iterateSnake() {
    if(this.state.snake) {
      
      if (this.state.snake.wallCollision(this.options.canvasSize) || this.state.snake.selfCollision()) {
        this.state.paused = true
        this.state.alive = false
        this.pauseGame()
      } else {
        this.state.snake.move()
      }
      
      if(this.state.items) {
        const items = this.state.items
        
        for(const i in items) {
          const itemLocation = items[i].getLocation()
          if(this.state.snake.itemCollision(itemLocation.x, itemLocation.y)) {
            this.addScore()
            this.state.items = []
            this.state.snake.addSegment()
            
            const segments = this.state.snake.getSegments().slice()
            
            const initialItem = this.createItem(segments)
            this.state.items = [initialItem]
            break;
          }
        }
      }
    }
  }
  renderObjects() {
    // Render items and snake
    const renderObjects = this.state.items.concat([this.state.snake])
    if(renderObjects && !this.state.paused) {
      for(const i in renderObjects) {
        if(renderObjects.hasOwnProperty(i)) {
          const object = renderObjects[i]
          if(typeof object.getRenderObjects === 'function') {
            const itemRenderObjects = object.getRenderObjects()
            for(const renderObject in itemRenderObjects) {
              if(itemRenderObjects.hasOwnProperty(renderObject)) {
                const currRenderObject = itemRenderObjects[renderObject]
                this.drawRectangle(currRenderObject.colour, 
                                   currRenderObject.x,
                                   currRenderObject.y,
                                   currRenderObject.sizeX,
                                   currRenderObject.sizeY) 
              }
            }
          }
        }
      }
    }
  }
  clear() {
    this.state.ctx.clearRect(0, 0, this.dom.canvas.width, this.dom.canvas.height)
  }
  drawBackground() {
    this.state.ctx.beginPath()
    this.state.ctx.fillStyle = this.options.bgColour
    this.state.ctx.fillRect(0, 0, this.dom.canvas.width, this.dom.canvas.height)
  }
  getHighScore () {
    const highScore = localStorage.getItem('highScore')
    if (highScore) {
      this.state.highScore = parseInt(highScore)    
      this.drawHighScore()
    } else {
      this.state.highScore = 0
      localStorage.setItem("highScore", '0');
    }
  }
  setHighScore() {
    if (this.state.score > this.state.highScore) {
      this.state.highScore = this.state.score
      localStorage.setItem("highScore", String(this.state.highScore));
      this.drawHighScore()
    }
  }
  drawHighScore () {
    this.dom.highScoreElement.innerHTML = String(this.state.highScore)
  }
  togglePause() {
    if(this.state.alive) {
      this.state.paused = !this.state.paused 
    } else {
      this.setUpRound()
    }
  }
  handleInput(event, keyName) {
    const validKeys = ['d', 'ArrowRight', 's', 'ArrowDown', 'a', 'ArrowLeft', 'w', 'ArrowUp']
    
    // Use event key if no key passed through
    if(event.key && !keyName) {
       keyName = event.key
    } 
    if(this.state.started) {
      if(keyName && this instanceof SnakeGame) {
        if (!this.state.alive && this.state.paused === true) {
          this.setUpRound()
        } else if(this.state.snake) {
          this.state.snake.directionInput(keyName)
        } 
      }
    } else if(validKeys.includes(keyName)) {
      this.start()
    }
  }
}

class GameObject {
  constructor(size, colour, x, y) {
    this.options = {
      size: size,
      colour: colour
    }
    this.state = {
      x: x,
      y: y
    }
  }
  getColour() {
    return this.options.colour
  }
  makeRenderObject(colour, x, y, sizeX, sizeY) {
    return {
      colour: colour,
      x: x,
      y: y,
      sizeX: sizeX,
      sizeY: sizeY
    }
  }
}

class Item extends GameObject {
  constructor(itemSize, canvasSize, segments) {
    super(itemSize, '#1e3833', 0, 0)
    this.options.canvasSize = canvasSize
    this.state.segments = segments
    this.setLocation()
  }
  randomLocation() {
    // Generate int within grid walls
    return (Math.floor(Math.floor(Math.random()*(this.options.canvasSize-this.options.size+1)+this.options.size)/this.options.size))*this.options.size
  }
  setLocation() {
    const newX = this.randomLocation()
    const newY = this.randomLocation()
    
    const segments = this.state.segments
    if(this.state.segments) {
      // Check if location collides with snake segments
      for(const segment in segments) {
        if(segments.hasOwnProperty(segment)) {
          const currSegment = segments[segment]
          if(currSegment.x === newX && currSegment.y === newY) {
            this.setLocation()
            return false
          }
        }
      }
    } 
    
    // If x or y outside grid walls
    if(newX > 270 || newY > 270 || newX < 0 || newY < 0) {
      this.setLocation()
    } else {
      this.state.x = newX
      this.state.y = newY
    }
  }
  getLocation() {
    return {x: this.state.x, y: this.state.y}
  }
  getRenderObjects() {
    const gap = this.options.size*0.2
    const size = this.options.size*0.4
    const colour = this.options.colour
    const x = this.state.x
    const y = this.state.y
      
    return [
      this.makeRenderObject(colour, x, y + size, size, size / 2),
      this.makeRenderObject(colour, x + size + gap, y + size, size, size / 2),
      this.makeRenderObject(colour, x + size, y, size/2, size),
      this.makeRenderObject(colour, x + size, y + size + gap, size / 2, size)
    ]
  }
}

class Snake extends GameObject {
  constructor(size) {
    super(size, '#1e3833', 0, 0)
    this.state = {
      length: 4,
      segments: [],
      newDirection: 'right',
      newX: 1,
      newY: 0
    }
    this.createSnake()
  }
  createSnake() {
    this.state.length = 4
    this.state.segments.length = 0
    this.state.newX = 1
    this.state.newY = 0
    for (let segment = this.state.length-1; segment >= 0; segment--) {
      this.state.segments.push({x: (segment*this.options.size),
                                y: (this.options.size)})
    }
  }
  getSegments() {
    return this.state.segments.slice()
  }
  changeDirection(x, y) {
    this.state.newX = x
    this.state.newY = y
  }
  getRenderHead(head, colour, baseSize, borderSize, gap) {
   const eyeSize = baseSize * 0.2
   const x = head.x
   const y = head.y
   let headRender = []
   
   // Create bg
   headRender = headRender.concat([this.makeRenderObject(colour, 
                                                         x,
                                                         y,
                                                         baseSize,
                                                         baseSize)])
   // Create center to create border effect
   headRender = headRender.concat([this.makeRenderObject('#c3cfa3',
                                           x+(borderSize/2),
                                           y+(borderSize/2),
                                           baseSize-borderSize,
                                           baseSize-borderSize)])
   
    // Create eyes based on direction
   if(this.state.newX === 1) {
     headRender = headRender.concat([this.makeRenderObject(colour,
                                                           x+gap+eyeSize,
                                                           y+borderSize, eyeSize,
                                                           eyeSize)])
     headRender = headRender.concat([this.makeRenderObject(colour,
                                                           x+gap+eyeSize,
                                                           y+gap+borderSize,
                                                           eyeSize,
                                                           eyeSize)])
   } else if(this.state.newX === -1) {
     headRender = headRender.concat([this.makeRenderObject(colour,
                                                           x+eyeSize,
                                                           y+borderSize,
                                                           eyeSize,
                                                           eyeSize)])
     headRender = headRender.concat([this.makeRenderObject(colour,
                                                           x+eyeSize,
                                                           y+gap+borderSize,
                                                           eyeSize,
                                                           eyeSize)])
   } else if(this.state.newY === 1) {
     headRender = headRender.concat([this.makeRenderObject(colour,
                                                           x+eyeSize,
                                                           y+gap+borderSize,
                                                           eyeSize,
                                                           eyeSize)])
     headRender = headRender.concat([this.makeRenderObject(colour,
                                                           x+gap+eyeSize,
                                                           y+gap+borderSize,
                                                           eyeSize,
                                                           eyeSize)])
   } else if(this.state.newY === -1) {
     headRender = headRender.concat([this.makeRenderObject(colour,
                                                           x+eyeSize,
                                                           y+eyeSize,
                                                           eyeSize,
                                                           eyeSize)])
     headRender = headRender.concat([this.makeRenderObject(colour,
                                                           x+gap+eyeSize,
                                                           y+eyeSize,
                                                           eyeSize,
                                                           eyeSize)])
   }
   return headRender
  }
  getRenderObjects() {
    const colour = this.options.colour
    const baseSize = this.options.size
    const borderSize = baseSize * 0.2
    const gap = baseSize * 0.4

    
    let renderObjects = []
    
    if(this.state.segments.length > 0) {
      const head = this.state.segments[0]
      const headerRender = this.getRenderHead(head, colour, baseSize, borderSize, gap)
      renderObjects = renderObjects.concat(headerRender)

      // Render tail
      for (let segment = 1; segment < this.state.segments.length; segment++) {
        const currSegment = this.state.segments[segment]
        const segmentBorder = this.makeRenderObject(colour, currSegment.x, currSegment.y, baseSize, baseSize)
        const segmentBackground = this.makeRenderObject('#c3cfa3',
                                                        currSegment.x+(borderSize/2),
                                                        currSegment.y+(borderSize/2),
                                                        baseSize-borderSize,
                                                        baseSize-borderSize)
        const segmentInner = this.makeRenderObject(colour,
                                                   currSegment.x+borderSize,
                                                   currSegment.y+borderSize,
                                                   baseSize-(borderSize*2),
                                                   baseSize-(borderSize*2))
        
        renderObjects = renderObjects.concat([segmentBorder, segmentBackground, segmentInner])
      }
    }
    return renderObjects
  }
  itemCollision(itemX, itemY) {
    return this.state.segments[0].x === itemX && this.state.segments[0].y === itemY
  }
  wallCollision(canvasSize) {
    return (this.state.segments[0].x < 0 || 
        this.state.segments[0].y < 0 || 
        this.state.segments[0].x >= canvasSize || 
        this.state.segments[0].y >= canvasSize)
  }
  selfCollision() {
    // Check if segment has same x and y as other segments
    for (let segment1 = 0; segment1 < this.state.length-1; segment1 ++) {
      for (let segment2 = 0; segment2 < this.state.length-1; segment2++) {
        if(segment1 != segment2) {
          const segment1Obj = this.state.segments[segment1]
          const segment2Obj = this.state.segments[segment2]
          if(segment1Obj.x == segment2Obj.x && segment1Obj.y == segment2Obj.y) {
            return true
          }  
        }
      }
    }
    return false
  }
  addSegment() {
    const lastSegment = this.state.segments[this.length-1]
    this.state.length++
    this.state.segments.push({x: lastSegment, y: lastSegment})
  }
  moveTail() {
    // Move each segment to next segments location
    for (let segment = this.state.length-2; segment >= 0; segment--) {
      this.state.segments[segment+1].x = this.state.segments[segment].x
      this.state.segments[segment+1].y = this.state.segments[segment].y
    }
  }
  moveHead() {
    // Move head segment to next location
    this.state.segments[0].x = this.state.segments[0].x + (this.state.newX * this.options.size)
    this.state.segments[0].y = this.state.segments[0].y + (this.state.newY * this.options.size)
  }
  move() {
    this.moveTail()
    this.moveHead()
  }
  directionInput(keyName) {
    if (this.state.newX != -1 && ((keyName == 'd') || (keyName == 'ArrowRight'))) {
      this.changeDirection(1,0)
    } else if (this.state.newY != -1 && ((keyName == 's') || (keyName == 'ArrowDown'))){
      this.changeDirection(0,1)
    } else if (this.state.newX != 1 && ((keyName == 'a') || (keyName == 'ArrowLeft'))){
      this.changeDirection(-1,0)
    } else if (this.state.newY != 1 && ((keyName == 'w') || (keyName == 'ArrowUp'))){
      this.changeDirection(0,-1)
    }   
  }
}

const snakeGame = new SnakeGame
loadSnakeGame()

function loadSnakeGame() {
  snakeGame.init()
}
              
            
!
999px

Console