Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var Board = function() {
- var SIZE = {
- WIDTH: 30,
- HEIGHT: 30
- }
- var score = 0
- var snake
- var apples = []
- var canvas = document.querySelector('.container')
- if(canvas.getContext) {
- var ctx = canvas.getContext('2d')
- } else {
- console.error('Canvas not supported')
- }
- function addSnake(snakeObj) {
- snake = snakeObj
- }
- function addApple(apple) {
- apples.push(apple)
- apple.notify('game-start', {board: null})
- }
- function render() {
- //render snake
- var positions = snake.getPositions()
- positions.forEach(function(pos) {
- ctx.fillRect(pos.x*15, pos.y*15, 15, 15)
- })
- //render apples
- apples.forEach(function(apple) {
- var pos = apple.getPosition()
- ctx.fillRect(pos.x*15, pos.y*15, 15, 15)
- })
- }
- function clear() {
- ctx.clearRect(0, 0, 600, 600)
- }
- function getAvailablePositions() {}
- return {
- addSnake: addSnake,
- addApple: addApple,
- render: render,
- clear: clear,
- getAvailablePositions: getAvailablePositions
- }
- }
- var Snake = function() {
- var DIRECTIONS = {
- RIGHT: 'right',
- LEFT: 'left',
- DOWN: 'down',
- UP: 'up'
- }
- var direction = DIRECTIONS.RIGHT
- var snake = [
- {x: 0, y: 0},
- {x: 1, y: 0},
- {x: 2, y: 0},
- {x: 3, y: 0}
- ]
- function getPositions() {
- return snake
- }
- function advance() {
- if(direction == DIRECTIONS.RIGHT) {
- snake = snake.map(function(pos) {
- return {
- x: pos.x + 1,
- y: pos.y
- }
- })
- }
- }
- return {
- getPositions: getPositions,
- advance: advance
- }
- }
- var Apple = function() {
- var EVENTS = {
- GAME_START: 'game-start'
- }
- var apple
- function getPosition() {
- return apple
- }
- function notify(event, data) {
- if(event === EVENTS.GAME_START) {
- //TODO: use data.board to exclude random aquired squares
- var randomPosition = Math.floor(Math.random() * 30)
- apple = {
- x: randomPosition,
- y: randomPosition
- }
- }
- }
- return {
- getPosition: getPosition,
- notify: notify
- }
- }
- var Game = (function() {
- function run() {
- var board = new Board()
- var snake = new Snake()
- var apple = new Apple()
- board.addSnake(snake)
- board.addApple(apple)
- var gameloop = setInterval(function() {
- board.clear()
- board.render()
- snake.advance()
- }, 60)
- }
- return {
- run: run
- }
- })()
- Game.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement