웹 개발 메모장

[자바스크립트] snake game (꼬리물기 게임 / 뱀 게임) 본문

옛날../자바스크립트

[자바스크립트] snake game (꼬리물기 게임 / 뱀 게임)

도로롱주 2018. 2. 5. 19:56





Snake Game / 뱀 게임 / 꼬리물기 게임



웹에 최적화 되어있어 모바일에선 느리거나 안될 수 있습니다.



Snake 게임





페이지 전체 코드입니다.


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
<html>
    <head>
        <style type="text/css">
            #menuTable {border-collapse: collapse; display: inline-block; width: 340px;}
            #menuTable td{width: 170px;}
            #menuTable td button{font-weight: bold; height: 30px; border: 1px solid blue;
                                    width: 70px; background: #5AAFFF; color: white; cursor: pointer;}
            #snakeTable {border-collapse: collapse; display: inline-block;}
            #snakeTable td{border: 1px solid blue; width: 13px; height: 13px;}
            .snake{background-color: #5AAFFF;}
            .food{background-color: #CCCCCC;}
            .center{text-align: center;}
            #controller {border-collapse: collapse; display: inline-block; margin-top: 20px;}
            #controller td{border: none; text-align: center; font-size: 20pt; color: white;}
            .btn{width: 80px; height: 80px; background: #CCCCCC; border-radius: 50px;}
            .alignLeft{text-align: left;}
            .alignRight{text-align: right;}
 
        </style>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
        <script>
            //난수 생성 함수
            function generateRandom (min, max) {
                var ranNum = Math.floor(Math.random()*(max-min+1)) + min;
                    return ranNum;
            }
 
            ////뱀게임///
 
            var score = 0;
 
            var LR = 0// 좌우 방향
            var TB = 1// 위아래 방향
 
            var mapSize = 21//map size
 
            var gameInterval;
 
 
            // init map
            function initMap(){
                var tableCode = '';
                for(var i=0; i<mapSize; i++) {
                    tableCode += '<tr>';
 
                    var rowCode = '';
                    for(var j=0; j<mapSize; j++) {
                        rowCode += '<td id="block'+i+'_'+j+'"></td>';
                    }
 
                    tableCode += rowCode + '</tr>';
                    $('#snakeTable').html(tableCode);
                }
            }
 
            //snake
            var snake = new Array();
            //food
            var food = new Array();
 
            // init snake
            function initSnake(){
                snake = [];
                snake.push([0,1]);
                drawSnake();
            }
 
            //뱀 그리기
            function drawSnake() {
                var state = '';
                $('#snakeTable td').removeClass('snake');
                for(var i=0;i<snake.length;i++) {
                    $('#block'+snake[i][0]+'_'+snake[i][1]).addClass('snake');
                    //먹이 먹었을 때
                    if($('#block'+snake[i][0]+'_'+snake[i][1]).hasClass('food')){
                        score++// 점수 증가
                        $('#score').text(score); //점수 반영
                        food.pop(); // 먹이 제거
                        initFood(); // 새로운 먹이 추가
                        //뱀 꼬리 늘리기
                        state = 'eat';
                    }
                }
                return state;
            }
 
            // 먹이 초기화
            function initFood(){
                var x;
                var y;
 
                do{
                     x = generateRandom(0,mapSize-1);
                     y = generateRandom(0,mapSize-1);
                }while($('#block'+x+'_'+y).hasClass('snake')); // 뱀이랑 겹치면 다시
 
                food = [];
                food.push([x, y]);
                drawFood();
            }
 
            //먹이 그리기
            function drawFood() {
                $('#snakeTable td').removeClass('food');
                for(var i=0;i<food.length;i++) {
                    $('#block'+food[i][0]+'_'+food[i][1]).addClass('food');
                }
            }
 
 
            // move
            function move() {
                var head = new Array();
                head[0= snake[0][0];
                head[1= snake[0][1];
 
                // 벽을 만난건지 체크
                var tmp = head[0]+1*TB;
                if(tmp >= 0 && tmp < mapSize) {
                    head[0= tmp;
                }else {
                    alert('점수 : '+score);
                    end();
                    initAll();
                    return;
                }
 
                tmp = head[1]+1*LR;
                if(tmp >= 0 && tmp < mapSize) {
                    head[1= tmp;
                }else {
                    alert('점수 : '+score);
                    end();
                    initAll();
                    return;
                }
 
                // 몸통을 만난건지 체크
                if($('#block'+head[0]+'_'+head[1]).hasClass('snake')){
                    alert('점수 : '+score);
                    end();
                    initAll();
                    return;                    
                }
 
 
                snake.unshift(head);
 
                if(drawSnake() != 'eat') { //먹은게 아니면
                    snake.pop(); //꼬리 연장 X
                }
            }
 
 
            function left() {
                if(TB == 0return// 반대방향으로 방향전환 불가
                LR = -1;
                TB = 0;
            }
            function right() {
                if(TB == 0return// 반대방향으로 방향전환 불가
                LR = 1;
                TB = 0;
            }
            function up() {
                if(LR == 0return// 반대방향으로 방향전환 불가
                LR = 0;
                TB = -1;
            }
            function down() {
                if(LR == 0return// 반대방향으로 방향전환 불가
                LR = 0;
                TB = 1;
            }
 
 
            $(document).on('click''#startBtn'function(){
                end();
                start();
            });
 
            $(document).on('click''.btn'function(){
                var key = $(this).attr('data-key');
                if(key == 'up') {
                    up();
                }else if(key == 'down') {
                    down();
                }else if(key == 'left') {
                    left();
                }else if(key == 'right') {
                    right();
                }
            });
 
            $(document).on('mouseover''.btn'function(){
                $(this).css('background''#5AAFFF');
 
                var key = $(this).attr('data-key');
                if(key == 'up') {
                    up();
                }else if(key == 'down') {
                    down();
                }else if(key == 'left') {
                    left();
                }else if(key == 'right') {
                    right();
                }
            });
 
            $(document).on('keydown''body'function(event){
                if(event.key == 'ArrowUp') {
                    $('#up_btn').css('background''#5AAFFF');
                    up();
                }else if(event.key == 'ArrowDown') {
                    $('#down_btn').css('background''#5AAFFF');
                    down();
                }else if(event.key == 'ArrowLeft') {
                    $('#left_btn').css('background''#5AAFFF');
                    left();
                }else if(event.key == 'ArrowRight') {
                    $('#right_btn').css('background''#5AAFFF');
                    right();
                }
            });
 
            $(document).on('mouseout''.btn'function(){
                $(this).css('background''#CCCCCC');
            });
 
            $(document).on('keyup''body'function(){
                $('.btn').css('background''#CCCCCC');
            });
 
            function initAll() {
                score = 0// 점수 초기화
                initMap(); // 맵 초기화
                initFood(); // 먹이 초기화
                initSnake(); // init snake
                LR = 0// 좌우 방향 초기화
                TB = 1// 위아래 방향 초기화
            }
 
            function start(){
                gameInterval = setInterval(move, 70);
            }
 
            function end() {
                clearInterval(gameInterval);
            }
 
            $(document).ready(function(){
                initAll();
            });
 
        </script>
    </head>
    <body>
        <div class='center'>
            <h2>Snake 게임</h2>
            <table id='menuTable'>
                <tr>
                    <td class='alignLeft'>
                        <button id='startBtn'>시작</button>
                    </td>
                    <td class='alignRight'>
                        <span>점수 : <span id='score'>0</span></span>
                    </td>
                </tr>
            </table>
        </div>
        <div class='center'>
            <table id='snakeTable'>
            </table>
        </div>
        <div class='center'>
            <table id='controller'>
                <tr>
                    <td></td><td id='up_btn' class='btn' data-key='up'></td><td></td>
                </tr>
                <tr>
                    <td id='left_btn' class='btn' data-key='left'></td><td></td><td id='right_btn' class='btn' data-key='right'></td>
                </tr>
                <tr>
                    <td></td><td id='down_btn' class='btn' data-key='down'></td><td></td>
                </tr>
            </table>
        </div>
    </body>
</html>
cs





Comments