5. Snake with a Queue
14631 ワード
1.Snake with a Queueは?
コード実装
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 QueueReference
この問題について(5. Snake with a Queue), 我々は、より多くの情報をここで見つけました https://velog.io/@kimkevin90/5.-Snake-with-a-Queueテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol