https://yjyoon-dev.github.io/project/2020/11/19/jsgame-tetris/
yjyoon님의 코드를 참고하여 js로 테트리스를 만들어 보았다. 코드 자체는 따라 친 코드지만 데이터가 어떻게 흐르는지 주석을 일일이 달아가며 공부해보았다.
<script>
let shapeRotateMap = [
1, 0,
3, 2,
4,
6, 7, 8, 5,
10, 9,
12, 13, 14, 11,
16, 17, 18, 15];
// rotate가 가능한지 4개지 로테이트 상황을 다 비교해 false가 한 번이라도 나오면
// false를 반환하고 함수를 끝낸다.
function canRotate() {
var tempShape = shapeArray[shapeRotateMap[currentShape]];
for (var i = 0; i < 4; i++) {
var ty = shapePoint[0] + tempShape[i][0];
var tx = shapePoint[1] + tempShape[i][1];
if (!isValidPoint(ty, tx)) return false;
}
return true;
}
// 로테이션 맵을 통해서 지금 값을 회전시킨다.
// 현재 shapepoint 값과 변화시킨 로테이트 값을 업데이트 시키고
// showshape함수를 통해서 화면에 변화된 값을 그린다.
function rotateShape() {
if (!canRotate()) return;
removeShape();
shapeCell = []
currentShape = shapeRotateMap[currentShape];
let rotateShape = shapeArray[currentShape];
for (let i = 0; i < 4; i++) {
let sy = shapePoint[0] + rotateShape[i][0];
let sx = shapePoint[1] + rotateShape[i][1];
shapeCell.push([sy, sx]);
}
showShape();
}
</script>
rotatemap으로 회전할 함수들을 구분해놓는 아이디어가 너무 좋아서
마음에 드는 코드를 가져와 봤다. 또, 이 코드에서 오류가 발생해서 애먹었는데 알고보니 내가 조건절 안에 함수를 넣는 것이 어색해서 무의식중에 ()를 생략해서 오류가 난 거였다. 이렇게 여러 시도를 해보면서 코드 리뷰도 하고 따라서 해보는 시도가 중요한 것 같다.
<script>
// 속도를 변화시켜 더 빠르게 움직이게 한다.
function moveFast() {
if (fastMode) return;
clearTimeout(movingThread);
movingSpeed = fastSpeed;
movingThread = setTimeout("moveDown()", movingThread);
fastMode = true;
}
</script>
개인적으로 내가 하던 테트리스는 fastmode 보다는 특정 키를 눌렀을 때 블럭이 위치할 수 있는 제일 아래에 순식간에 이동하는 게임이라는 인식이 있는데, 이 기능은 스스로 만들어봐야겠다.
전체 코드는 github에 올려 놓았다.
https://github.com/about-joo91/about-joo91.github.io