Skip to content

Instantly share code, notes, and snippets.

@sylvainmathieu
Created April 15, 2014 14:25
Show Gist options
  • Save sylvainmathieu/10736832 to your computer and use it in GitHub Desktop.
Save sylvainmathieu/10736832 to your computer and use it in GitHub Desktop.
state =
dir: x: 1, y: 0
canvas = ->
can = document.getElementById("game")
ctx = can.getContext("2d")
width = can.width
height = can.height
ctx.fillStyle = "black"
ctx.fillRect(0, 0, width, height)
ctx
drawBlock = (ctx, pos) ->
ctx.strokeStyle = "rgba(255,255,255, 0.5)"
ctx.strokeRect(pos.x * 10 + 0.5, pos.y * 10 + 0.5, 8, 8)
ctx.fillStyle = "rgba(255,255,255, 0.2)"
ctx.fillRect(pos.x * 10 + 0.5, pos.y * 10 + 0.5, 8, 8)
eraseBlock = (ctx, pos) ->
ctx.fillStyle = "black"
ctx.fillRect(pos.x * 10, pos.y * 10, 10, 10)
gameOver = -> false
randomCoord = -> Math.round(Math.random() * 30)
getNewFood = -> x: randomCoord(), y: randomCoord()
isCollision = (snake, newHead) ->
_.any(snake, (element) -> _.isEqual(element, newHead)) or
newHead.x < 0 or newHead.x > 30 or
newHead.y < 0 or newHead.y > 30
game = (ctx, snake, food) ->
head = _.first(snake)
newHead =
x: head.x + state.dir.x
y: head.y + state.dir.y
if isCollision(snake, newHead)
gameOver()
else if _.isEqual(newHead, food)
newFood = getNewFood()
newsnake = [newHead].concat(snake)
drawBlock(ctx, newFood)
[ctx, newsnake, newFood]
else
newsnake = [newHead].concat(_.initial(snake))
eraseBlock(ctx, _.last(snake))
drawBlock(ctx, newHead)
[ctx, newsnake, food]
gameLoop = (gameState) ->
if gameState
window.setTimeout (->
newGameState = game.apply(null, gameState)
gameLoop(newGameState)), 100
do ->
ctx = canvas()
food = getNewFood()
gameLoop([canvas(), [{x: 5, y: 5}, {x: 4, y: 5}, {x: 3, y: 5}], food])
drawBlock(ctx, food)
document.addEventListener "keydown", (event) ->
dir = state.dir
newDir = switch event.keyCode
when 39 then x: 1, y: 0 # right
when 40 then x: 0, y: 1 # down
when 37 then x: -1, y: 0 # left
when 38 then x: 0, y: -1 # up
else false
if newDir and (dir.x == 0 or dir.x != -newDir.x) and (dir.y == 0 or dir.y != -newDir.y)
state.dir = newDir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment