5. Snake with a Queue


1.Snake with a Queueは?



  • ブロックが移動すると、
  • 個のenqueue/dequeueが励起される
    コード実装
    1.Snake本体をarrayとして構築し、キュー操作を行う
    2.Snake bodyをgridとして描画
    3.位置別キュー操作
    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