5. Snake with a Queue

임쿠쿠·2021년 11월 22일
0

1.Snake with a Queue란?

  • 해당 블럭이 움직일 때, enqueue/dequeue 발생

코드구현
1. Snake 바디를 array로 구현 후 queue 조작
2. Snake body를 grid로 그림
3. 위치에 따른 queue 조작

class Snake {
  constructor() {
    this.snakeBody = [
      [4,1],
      [4,2],
      [4,3],
      [4,4]
    ];
  }
  // 10 X 10 Grid
  draw() {
    const grid = [];
    for (let i = 0; i < 10; i++) {
      const row = [];
      for (let j = 0; j < 10; j++) {
        row.push(' ');
      }
      grid.push(row);
    }

    this.snakeBody.forEach(position => {
      const [row, col] = position;
      grid[row][col] = 'O';
    });

    console.clear();
    grid.forEach(row => console.log(row.join('|')))
  }

  move(direction) {
    const delta = {
      up: [-1, 0],
      down: [1, 0],
      left: [0, -1],
      right: [0, 1]      
    };

    const currentHead = this.snakeBody[this.snakeBody.length -1];
    const [ currentRow, currentCol ] = currentHead;
    const [ changeRow, changeCol ] = delta[direction];
    const newHead = [ currentRow + changeRow, currentCol + changeCol] ;
    this.snakeBody.push(newHead);
    this.snakeBody.shift();
  }

  play() {
    const stdin = process.stdin;
    stdin.setRawMode(true);
    stdin.resume();
    stdin.setEncoding('utf8');
    stdin.on('data', (keypress) => {
      if(keypress === 'w') this.move('up');
      if(keypress === 'a') this.move('left');
      if(keypress === 's') this.move('down');
      if(keypress === 'd') this.move('right');
      if(keypress === 't') process.exit();

      this.draw();
    })    
  }
}

const snakeGame = new Snake();
snakeGame.draw();

참고 : codebyte - Implementing Snake with a Queue

profile
Pay it forward

0개의 댓글