CSS&JS/👀Study and Copy

[vanilla JS] 자바스크립트로 테트리스 만들기 (1)

arancia_ 2022. 6. 10. 11:26

바닐라 자바스크립트로 테트리스 구현하기(1)

유튜브 참고 영상 : https://www.youtube.com/watch?v=rAUn1Lom6dw

 

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>코드 테트리스 : 초보자를위한 JavaScript 튜토리얼</title>
    <link rel="stylesheet" type="text/css" href="./css/styles.css"/>
    <script src="./js-trial/main.js" type="module"></script>
</head>
<body>
 
    <h2 class="sect-score">SCORE : <span id="score">...</span></h2>
    <button id="btn-start" data-game="ready">START</button>
 
    <div id="game">
        <!-- GRID -->
        <section id="grid">
        </section><!-- grid -->
 
        <section id="miniGrid">
        </section><!-- miniGrid -->
    </div><!-- game -->
</body>
</html>
cs

 

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@charset "utf-8";
:root{
    --bdr:#ccc;
}
*{margin:0;padding:0;box-sizing:border-box;}
html,body{
    display:flex;flex-flow:column nowrap;
    justify-content:center; align-items:center;
    gap:1rem;
    width:100%;min-height:100vh;
    background:#f1f2f3;
}
 
 
#sect-score{position:relative;margin-top:1rem;}
 
#btn-start{
    padding:.5rem 1.5rem;
    font-family:inherit;font-weight:bold;
    cursor:pointer;
}
 
#game{
    display:flex; flex-flow:row wrap;
    justify-content:center; align-items:flex-start;
    gap:2rem;
    position:relative;
    
}
 
#grid, #miniGrid{
    display:flex;flex-flow:row wrap;
    justify-content:space-between;
    position:relative; overflow:hidden;
    border:1px solid var(--bdr);
    border-left-width:0; 
    box-shadow:
        1px 1px 0 #666,
        1px -1px 0 #666,
        -1px 1px 0 #666, 
        -1px -1px 0 #666;
}
    #grid{width:36vh; aspect-ratio:1/1.99;}
    #miniGrid{
        overflow:visible;
        margin-top:1.5rem;
        width:13vh; aspect-ratio:1/1;}
    #miniGrid::before{
        content:"UP NEXT"; display:block; position:absolute;
        top:0;left:0;
        width:100%;
        text-align:center;
        transform:translateY(-150%);
        font-size:0.875rem; font-weight:bold;
    }
 
 
.grid-cell{
    position:relative;
    width:10%; aspect-ratio:1/1;
    background:#fff;
    border:1px solid var(--bdr);
    border-top-width:0; border-right-width:0;
    transition:.1s;}
 
    #miniGrid .grid-cell{
        width:25%;
    }
 
.taken{border:none;} /* 바닥에 깔려있는 애들 */
 
.tet{background:rgb(70, 70, 83);}
.tet.red{background:red;}
.tet.yellow{background:gold;}
.tet.blue{background:dodgerblue;}
.tet.green{background:mediumaquamarine;}
.tet.purple{background:violet;}
 
.stack{filter:saturate(50%) brightness(50%);}
cs

 

main.js

1
2
3
import Game from "./Game.js";
 
const GAME = new Game();
cs

 

Game.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import Blocks from "./Blocks.js";
import Grid from "./Grid.js";
 
export default class Game{
    #SCORE
    constructor(){
        this.GRID = new Grid(this);
        this.BLOCK = new Blocks(this);
 
        this.$btn = document.getElementById('btn-start');
        this.$btn.addEventListener('click',this.on_click);
        this.playing = false;
 
        this.$score = document.getElementById('score');
        this.score = 0;
 
        this.addEvent();
    }//constructor
 
    /* [METHOD] */
    on_click = (e) =>{
        const dataGame = this.$btn.dataset.game; 
 
        if(dataGame == "playing"){
            //멈추기
            this.$btn.dataset.game = 'paused';
            this.$btn.textContent = 'PLAY AGAIN';
            this.playing = false;
            this.BLOCK.stop();
        }else{
            this.$btn.dataset.game = 'playing';
            this.$btn.textContent = 'PAUSE';
            this.playing = true;
            if(dataGame == "ready"){
                //새 시작
                this.reset_score();
                this.GRID.reset();
                this.BLOCK.reset();
                this.BLOCK.newTet();
            }else if(dataGame == "paused"){
                //재개
                this.BLOCK.moveDownCascading();
                this.addEvent();
            }
        }//if else
    };//on_click
    
    reset_btn(){
        this.$btn.dataset.game = 'ready';
        this.$btn.textContent = 'GAME OVER';
    }//reset_btn
 
    is_lost(){
        const cells = this.GRID.cell;
        const curr = this.BLOCK.curr;
        const currPos = this.BLOCK.currPos;
        for(let idx of curr){
            if(cells[idx + currPos].classList.contains('stack')){return true;}
        }//for
        return false;
    }//is_lost
 
    gameOver(){
        if(!this.playing){return;}
        this.playing = false;
        this.BLOCK.stop();
        this.reset_btn();
        console.log('GAME OVER',new Date());
    }//gameOver
 
    addEvent(){
        window.addEventListener('keydown'this.on_keydown,{once:true});
    }//addEvent
 
    on_keydown = async (e) => {
        if(!this.playing){return;}
        
        switch(e.key){
            case "ArrowLeft":
                await this.BLOCK.moveLeft();
                break;
            case "ArrowRight":
                await this.BLOCK.moveRight();
                break;
            case "ArrowUp":
                await this.BLOCK.rotate();
                break;
            case "ArrowDown":
                this.BLOCK.moveDown();
                break;
            default :
                this.addEvent();
                return;
        }//switch
 
        //add Event Again...
        this.addEvent();
    }//on_keydown
 
    /* SCORE */
    get score(){return this.#SCORE;}
    set score(value){this.#SCORE = value;}
 
    reset_score(){
        this.score = 0;
        this.display_score();}
    update_score(value){
        this.score += value;
        this.display_score();}
    display_score(){this.$score.textContent = this.score;}
}//Game
cs

 

Grid.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
export default class Grid{
    #CELL;
    #PREVIEW
    constructor(GAME){
        this.GAME = GAME;
        
        this.$grid = document.getElementById('grid');
        this.$mini = document.getElementById('miniGrid');
        //자동 실행
        this.draw_grid();
        this.draw_mini();
    }//constructor
 
    reset(){
        this.cell.forEach($cell => $cell.classList.remove('tet','stack','red','yellow','blue','green','purple'));
        this.preview.forEach($cell => $cell.classList.remove('tet','red','yellow','blue','green','purple'));
    }//reset
 
    /* 메인 그리드 */
    draw_grid(){
        const $frag = document.createDocumentFragment();
        const cell = [];
        
        for(let i=0; i<210; i++){
            const $gridCell = document.createElement('DIV');
            $gridCell.classList.add('grid-cell');
            $gridCell.dataset.number = i;
            if(i >= 200){ $gridCell.classList.add('taken');}
            $frag.appendChild($gridCell);
            cell.push($gridCell);
        }//for
 
        this.$grid.appendChild($frag);
        this.#CELL = cell;
    }//draw_grid
 
    /* 미리보기 */
    draw_mini(){
        const $frag = document.createDocumentFragment();
        const preview = [];
        
        for(let i=0; i<16; i++){
            const $gridCell = document.createElement('DIV');
            $gridCell.classList.add('grid-cell');
            $frag.appendChild($gridCell);
            preview.push($gridCell);
        }//for
 
        this.$mini.appendChild($frag);
        this.#PREVIEW = preview;
    }
    /* [GETTER, SETTER] */
    get cell(){return this.#CELL;}
    set cell(value){this.#CELL = value;}
    get preview(){return this.#PREVIEW;}
}//Grid
cs

 

Blocks.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/* 
00 [01] [02] 03 04 05 06 07 08 09
10 [11]  12  13 14 15 16 17 18 19
20 [21]  22  23 24 25 26 27 28 29
*/
 
/* 
00 [01] [02] 03 04
05 [06]  07  08 09
10 [11]  12  13 14
 */
 
//아님 https://www.youtube.com/watch?v=QDp8BZbwOqk&t=198s
//의 9:47이 더 좋아보이긴 한데 흠..
 
const width = 10;
 
const Ltet = [
    [1, width+1, width*2+12],
    [width, width+1, width+2, width*2+2],
    [1, width+1, width*2+1, width*2],
    [width, width*2, width*2+1, width*2+2]];
 
const Ztet = [
    [0,width,width+1,width*2+1],
    [width+1, width+2,width*2,width*2+1],
    [1,width,width+1,width*2],
    [width, width+1,width*2+1,width*2+2]];
 
const Ttet = [
    [1,width,width+1,width+2],
    [1,width+1,width+2,width*2+1],
    [width,width+1,width+2,width*2+1],
    [1,width,width+1,width*2+1]];
 
const Otet = [
    [0,1,width,width+1],
    [0,1,width,width+1],
    [0,1,width,width+1],
    [0,1,width,width+1]];
 
const Itet = [
    [1,width+1,width*2+1,width*3+1],
    [width,width+1,width+2,width+3],
    [1,width+1,width*2+1,width*3+1],
    [width,width+1,width+2,width+3]];
 
 
/* CLASS */
 
export default class Blocks{
    constructor(GAME){
        this.GAME = GAME;
        this.TETS = [Ltet,Ztet,Ttet,Otet,Itet];
        this.COLOR = ["red","yellow","blue","green","purple"];
 
        this.reset();
    }//constructor
 
    /* 리셋 */
    reset(){
        this.currPos = undefined;
        this.currType = undefined;
        this.currRot = 0;
        this.colorIdx = -1;
        this.currColor = undefined;
        this.curr = undefined;
 
        this.define_next();
        
        this.timeId = undefined;
    }//reset
 
    /* 새 블록을 만듦 */
    async newTet(){
        this.stop();
        
        this.currPos = 4;
        this.currRot = 0;
        
        this.currType = this.nextType;
        this.currColor = this.nextColor;
        this.curr = this.next;
        
        this.define_next();
        this.display_next();
 
        this.moveDownCascading();
    }//newTet;
 
    define_next(){
        this.nextColor = this.random_color();
        this.nextType = this.random_type();
        this.next = this.random_tet(this.nextType);
    }//define_next
 
    random_type(){
        return Math.floor(this.TETS.length * Math.random());
    }
 
    random_tet(type){
        return this.TETS[type][this.currRot];
    }//random_tet
 
    random_color(){
        // this.colorIdx = Math.floor(this.COLOR.length * Math.random());
        this.colorIdx = this.colorIdx >= this.COLOR.length - 1 ? -1 : this.colorIdx;
        this.colorIdx++;
        return this.COLOR[this.colorIdx];
    };
 
    draw(){
        return new Promise(res=>{
            setTimeout(()=>{
                const CELL = this.GAME.GRID.cell;
                this.curr.forEach(idx=>{
                    const curr_cell = CELL[this.currPos + idx]; 
                    curr_cell.classList.add('tet',this.currColor);            
                });
                res();
            },0);
        });
    }//draw
 
    undraw(){
        return new Promise(res=>{
            setTimeout(()=>{
                const CELL = this.GAME.GRID.cell;
                this.curr.forEach(idx=>{
                    const curr_cell = CELL[this.currPos + idx]; 
                    curr_cell.classList.remove('tet',this.currColor);            
                });
                res();
            },0);
        });
    }//undraw
 
    /* 자동으로 내려감 */
    moveDownCascading = async()=>{
        //플레이 안 되도록
        if(!this.GAME.playing){
            this.stop();
            return;}
 
        //패배 판정
        if(this.GAME.is_lost()){
            this.GAME.gameOver();
            return;}
 
        //내리고
        await this.moveDown();
 
        //바닥이나 블럭에 닿아 멈추는 경우
        if(this.is_stop()){
            //멈추고 쌓기
            this.stop();
            await this.stack();
 
            //점수 업데이트 (개별)
            this.GAME.update_score(this.curr.length);
 
            //한줄 완성 확인
            this.lineClear();
            
            //새 블록 생성
            this.newTet();
            return;
        }//else if
        
        //반복
        setTimeout(()=>{
            this.timeId = window.requestAnimationFrame(this.moveDownCascading);
        },500);
    }//moveDownCascading;
 
    /* 단순히 아래로 내리기 */
    moveDown = async()=>{
        await this.undraw();
        this.currPos += width;
        const CELL = this.GAME.GRID.cell;
        const isStack = this.curr.some(idx=>CELL[this.currPos + idx].classList.contains('stack'));
        const isTaken = this.curr.some(idx=>CELL[this.currPos + idx].classList.contains('taken'));
        if(isStack || isTaken){
            this.currPos -= 10;
            await this.draw();
            return;}
        await this.draw();
    }//moveDown
 
    /* 왼쪽 */
    moveLeft = async() =>{
        if(this.isAtLeft()){return;}
 
        await this.undraw();
 
        this.currPos--;
 
        const CELL = this.GAME.GRID.cell;
        const isStack = this.curr.some(idx=>CELL[this.currPos + idx].classList.contains('stack'));
        if(isStack){this.currPos++;}
        
        await this.draw();
    }//moveLeft;
 
    /* 오른쪽 */
    moveRight = async()=>{
        if(this.isAtRight()){return;}
 
        await this.undraw();
 
        this.currPos++;
 
        const CELL = this.GAME.GRID.cell;
        const isStack = this.curr.some(idx=>CELL[this.currPos + idx].classList.contains('stack'));
        if(isStack){this.currPos--;}
 
        await this.draw();
    }//moveRight
 
    /* 벽에 닿는지 */
    isAtLeft(){
        return this.curr.some(idx =>(this.currPos + idx) % width === 0);}
    isAtRight(){ 
        return this.curr.some(idx =>(this.currPos + idx) % width === width - 1);}
 
    /* 회전 */
    async rotate(){
        await this.undraw();
        this.currRot = this.currRot + 1 > this.TETS[this.currType].length - 1 ? 0 : this.currRot + 1;
        this.curr = this.TETS[this.currType][this.currRot];
        this.checkRotatedPosition();
        await this.draw();
    }//rotate
 
    /* 회전 가능 확인 및 위치 재조정 */
    checkRotatedPosition(P){
        P = P || this.currPos;
        if((P+1) % width < 4){
            if(this.isAtRight()){
                this.currPos++;
                this.checkRotatedPosition(P);}
        }else if(P % width > 5){
            if(this.isAtLeft()){
                this.currPos--;
                this.checkRotatedPosition(P);}
        }//if else 4,5
    }//checkRotatedPosition
 
    /* 멈출 때인가 */
    is_stop(){
        const CELL = this.GAME.GRID.cell;
        const isRowEnd = this.curr.some(idx => CELL[this.currPos + idx + width]?.classList.contains('taken'));
        const isStack = this.curr.some(idx => CELL[this.currPos + idx + width]?.classList.contains('stack'));
        if(isRowEnd || isStack){return true;}
        return false;
    }//is_stop
 
    /* 쌓기 */
    stack(){
        return new Promise(res=>{
            this.curr.forEach(idx=>{
                this.GAME.GRID.cell[idx + this.currPos].classList.add('stack');
            });
            res();
        });
    }//stack
 
    /* 타이머 종료 */
    stop(){
        while(this.timeId){
            window.cancelAnimationFrame(this.timeId);
            this.timeId--;
        }//while
    }//stop
 
    /* 미리보기 표시 */
    display_next(){
        const PREVIEW = this.GAME.GRID.preview;
        PREVIEW.forEach(cell=>cell.classList.remove('tet',this.currColor));
        this.next.forEach(idx=>{
            const q = Math.floor(idx / 10);
            PREVIEW[idx - (q * 6)].classList.add('tet',this.nextColor);
        });
    }//display_next
 
    /* 💥 한 줄 완성시 */
    lineClear(){
        for(let i=0; i<this.GAME.GRID.cell.length - width; i += width){
            this.isClear(i);
            for(let k=0; k<i; k+=width){
                this.isClear(k);
            }//for
        }//for
    }//lineClear
 
    isClear(i){
        const CELL = this.GAME.GRID.cell;
        const row = this.getRow(i);
        const isClear = row.every(idx=>CELL[idx].classList.contains('stack'));
        if(isClear){
            //점수 업데이트
            this.GAME.update_score(width * 10);
            //클래스 없애고
            row.forEach(idx=>{
                CELL[idx].classList.remove('tet''stack''red''yellow''blue''green''purple');
            });
            //삭제
            this.removeLine(i);
        }//if
    }//isClear
 
    removeLine(i){
        const removed = this.GAME.GRID.cell.splice(i, width);
        this.GAME.GRID.cell = removed.concat(this.GAME.GRID.cell);
        this.GAME.GRID.cell.forEach($cell => this.GAME.GRID.$grid.appendChild($cell));
    }//removeLine
 
    getRow(i){
        const row = [];
        for(let k=0; k<width; k++){
            row.push(i + k);
        }//for
        return row;
    }//getRow
 
    //1:26
}//class - Blocks
cs