js 뱀 탐식 게임 canvas 지도 그리 기
사고의 방향
400 px*400 px 의 지도,20px*20px 당 단원 격 으로 뱀 몸 그리 기
이동 할 때마다 꼬리 머리 색 을 바 꿔 요.
모든 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
</style>
</head>
<body>
<canvas width="400" height="400" style="background-color: #362E3D;"> chromium</canvas>
<script>
const map = document.getElementsByTagName('canvas')[0].getContext('2d'); // 1-20 21-40 20*20
var snake = [23, 22, 21]; //
var direction = 1; // 1 -1 -20 20
var flag = 1; // bug
var food = 50; //
function draw(x, color) {
map.fillStyle = color;
// 1-400
if (x % 20 == 0) { //
map.fillRect(380 + 2, Math.floor(x / 21) * 20 + 2, 18, 18); // 1-400
} else { //
map.fillRect((x % 20 - 1) * 20 + 2, Math.floor(x / 20) * 20 + 2, 18, 18);
}
flag = 1; // draw() direction
}
let len = snake.length;
for (let i = 0; i < len; i++)
draw(snake[i], "#FDE5C5");
(function () {
let head = snake[0] + direction;
if (head % 20 == 1 && direction == 1 || head % 20 == 0 && direction == -1 || head < 1 || head > 400 ||
snake.includes(head))
return alert('GG');
snake.unshift(head);
draw(head, "#FDE5C5");
if (head == food) {
while (snake.includes(food = Math.floor(Math.random() * 400 + 1)));
// arr.includes true false
} else { //
draw(snake.pop(), "#362E3D");
}
draw(food, "#EB1A4B");
setTimeout(arguments.callee, 100); // arguments.callee
})();
document.onkeydown = function (event) {
event = event || window.event; // ie windo.event
if (flag) { // draw ( ) direction
switch (event.keyCode) {
case 37:
direction != 1 ? direction = -1 : 0;
break;
case 38:
direction != 20 ? direction = -20 : 0;
break;
case 39:
direction != -1 ? direction = 1 : 0;
break;
case 40:
direction != -20 ? direction = 20 : 0;
break;
}
}
flag = 0; // draw
}
</script>
</body>
</html>
연속 빠 른 키보드 버그 해결방향 키 상하 좌우 로 direction 의 값 을 실제 변경 합 니 다.뱀 이 다음 이동 전에 계속 바 뀌 면 자신 을 거꾸로 먹 는 bug 가 생 길 수 있 습 니 다.
그래서 flag 에 가입 해서 소스 코드 를 자세히 보 세 요.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[2022.04.19] 자바스크립트 this - 생성자 함수와 이벤트리스너에서의 this18일에 this에 대해 공부하면서 적었던 일반적인 함수나 객체에서의 this가 아닌 오늘은 이벤트리스너와 생성자 함수 안에서의 this를 살펴보기로 했다. new 키워드를 붙여 함수를 생성자로 사용할 때 this는...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.