안드로이드/cocos2d-x2016. 1. 19. 22:37

시작하기에 앞서

블록이 새로 생길 때

위에서 부터 떨어지는건 좋은데 그게 보이지는 않았으면 좋겠다

 

 

요런 식으로 말이다

 

 

 

 

puzzleTest.zip

먼저 위 파일을 다운받는다.

이번에 새로 수정한 리소스들이다.

 

CGameLyaer.h

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
void startGame()  {
        for (int x = 0; x < COLUMN_COUNT+1; x++) {
            for (int y = 0; y < ROW_COUNT+1; y++) {
                m_pBoard[x][y] = NULL;
            }
        }
 
        srand(time(NULL));
        for (int x = 0; x < COLUMN_COUNT; x++) {
            for (int y = 0; y < ROW_COUNT; y++) {
                if (x == COLUMN_COUNT - 1 && y % 2 != 0continue;
 
                Sprite* pGameObjectBack = Sprite::create("blockBack.png");
                pGameObjectBack->setAnchorPoint(ccp(0.5f, 0.5f));
                pGameObjectBack->setPosition(Common::ComputeXY(x, y));
 
                addChild(pGameObjectBack, 1);
            }
        }
 
        Sprite* pTop = Sprite::create("backgroundTop.png");
        pTop->setAnchorPoint(ccp(0.0f, 0.0f));
        pTop->setPosition(ccp(0.0f, 1470.0f));
        addChild(pTop, 4);
 
        m_countFallingObject = 0;
 
        searchMacthedStreak();
        clearRemovealObject();
        ProcessFalling();
 
        // 변수 초기화
        m_EnableTouch = 0;
        m_bTouchStarted = false;
        m_countFallingObject = 0;
    }
}
cs

 

startGame() 함수에서 GameObject를 생성하는 부분을 삭제했다.

searchMacthedStreak() /clearRemovealObject() / ProcessFalling()

함수들로 인해 게임 시작직후 위에서부터 블록이 떨어질 것이다.

 

빨간색으로 표시한 부분이 상단에 블록이 생성된는 곳을 가려주는 역할이다.

리소스 파일중 backgoundTop.png를 최상단에 출력해 가려주는 것이다.

 

 

이제 애니메이션

 블록이 떨어지는걸 보면서 뭔가 아쉬워 보였다.

블록 낙하 속도에 가속도라도 붙일까 하다가 착지 애니메이션을 추가하기로 했다.

 

애니메이션은 간단하게 위와 같이 파일을 생성했다.

포토샾에서 열심히 눌러줬다.

 

 

 

4 프레임 밖에 안되지만 자연스럽게 움직이고 있다.

 

 

애니메이션은 블록이 낙하할때 CGameObecjt::ProcessFalling()에서

Sequence::create()에 MoveBydhk callfunc_selector사이에 추가시켜

낙하->착지->콜백 순으로 실행되게 할 것이다.

 

 

CGameObject.cpp

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
Animation* CGameObject::setAnimDown(int type) {
    SpriteFrame* animDownFrame1;
    SpriteFrame* animDownFrame2;
    SpriteFrame* animDownFrame3;
    SpriteFrame* animDownFrame4;
    if (type == 0) {
        animDownFrame1 = SpriteFrame::create("Anim/blockBlueDown1.png", Rect(00150130));
        animDownFrame2 = SpriteFrame::create("Anim/blockBlueDown2.png", Rect(00150130));
        animDownFrame3 = SpriteFrame::create("Anim/blockBlueDown3.png", Rect(00150130));
        animDownFrame4 = SpriteFrame::create("Anim/blockBlueDown4.png", Rect(00150130));
    }
    else if (type == 1) {
        animDownFrame1 = SpriteFrame::create("Anim/blockBrownDown1.png", Rect(00150130));
        animDownFrame2 = SpriteFrame::create("Anim/blockBrownDown2.png", Rect(00150130));
        animDownFrame3 = SpriteFrame::create("Anim/blockBrownDown3.png", Rect(00150130));
        animDownFrame4 = SpriteFrame::create("Anim/blockBrownDown4.png", Rect(00150130));
    }
    else if (type == 2) {
        animDownFrame1 = SpriteFrame::create("Anim/blockGreenDown1.png", Rect(00150130));
        animDownFrame2 = SpriteFrame::create("Anim/blockGreenDown2.png", Rect(00150130));
        animDownFrame3 = SpriteFrame::create("Anim/blockGreenDown3.png", Rect(00150130));
        animDownFrame4 = SpriteFrame::create("Anim/blockGreenDown4.png", Rect(00150130));
    }
    else if (type == 3) {
        animDownFrame1 = SpriteFrame::create("Anim/blockPinkDown1.png", Rect(00150130));
        animDownFrame2 = SpriteFrame::create("Anim/blockPinkDown2.png", Rect(00150130));
        animDownFrame3 = SpriteFrame::create("Anim/blockPinkDown3.png", Rect(00150130));
        animDownFrame4 = SpriteFrame::create("Anim/blockPinkDown4.png", Rect(00150130));
    }
    else if (type == 4) {
        animDownFrame1 = SpriteFrame::create("Anim/blockWhiteDown1.png", Rect(00150130));
        animDownFrame2 = SpriteFrame::create("Anim/blockWhiteDown2.png", Rect(00150130));
        animDownFrame3 = SpriteFrame::create("Anim/blockWhiteDown3.png", Rect(00150130));
        animDownFrame4 = SpriteFrame::create("Anim/blockWhiteDown4.png", Rect(00150130));
    }
    else if (type == 5) {
        animDownFrame1 = SpriteFrame::create("Anim/blockYellowDown1.png", Rect(00150130));
        animDownFrame2 = SpriteFrame::create("Anim/blockYellowDown2.png", Rect(00150130));
        animDownFrame3 = SpriteFrame::create("Anim/blockYellowDown3.png", Rect(00150130));
        animDownFrame4 = SpriteFrame::create("Anim/blockYellowDown4.png", Rect(00150130));
    }
 
    Animation* anim = Animation::create();
    anim->setDelayPerUnit(0.06f);
    anim->addSpriteFrame(animDownFrame1);
    anim->addSpriteFrame(animDownFrame2);
    anim->addSpriteFrame(animDownFrame3);
    anim->addSpriteFrame(animDownFrame4);
    anim->addSpriteFrame(animDownFrame3);
    anim->addSpriteFrame(animDownFrame2);
    anim->addSpriteFrame(animDownFrame1);
    anim->addSpriteFrame(animDownFrame2);
    anim->addSpriteFrame(animDownFrame3);
    anim->addSpriteFrame(animDownFrame2);
    anim->addSpriteFrame(animDownFrame1);
 
    return anim;
}
cs

애니메이션을 출력하는데 다양한 방법이 있지만

여기선 가장 간단하게 이미지 여러장에 딜레이를 주어 출력하게 할 것이다.

 

기본적인 구조는 SpriteFrame형으로 이미지를 불러오고

Animation 타입을 생성하여 SpriteFrame을 애니메이션에 추가시킨다.

 

44행~55행 - Frame추가 순서를 1-2-3-4-3-2-1-2-3-2-1로 하여

한번 튕긴 후 작게 한번 더 튕기게 하였다.

 

CGameObject.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void CGameObject::ProcessFalling(int speed) {
    setVisible(true);
 
    Point position = getPosition();
 
    m_prevBoardX = Common::ComputeBoardX(position);
    m_prevBoardY = Common::ComputeBoardY(position);
    Point targetPosition = Common::ComputeXY(m_targetBoardX, m_targetBoardY);
 
    MoveBy* pMoveBy = MoveBy::create(0.08f*(1+speed),
        ccp(targetPosition.x - position.x, targetPosition.y - position.y));
 
 
 
    Animation* anim = setAnimDown(m_type);
 
    FiniteTimeAction* pAction = Sequence::create(pMoveBy,
        Animate::create(anim),
        CallFunc::create(this, callfunc_selector(CGameObject::FallingCompleteEvent)), NULL);
    runAction(pAction);
}
cs

이렇게 만들어진 애니메이션 생성 함수를 위와 같이 활용하였다.

Sequence에 의해

pMoveby가 실행된 후 착지 애니메이션이 실행될 것이다.

 

 

 

GIF를 잘못 만들어서 너무 빨리 움직이는데 원래 저렇진 않다

 

 

 

이제 어려운건 끝난것 같다

 남은건 콤보처리, 점수계산 및 출력 등이 남았다.

스테이지 등등은 손이 많이갈 뿐 어렵진 않을 것이다.

 

Posted by gharlic
안드로이드/cocos2d-x2016. 1. 19. 07:55

슬슬 복잡해지고 있다

또 한번 전체적으로 수정을 해야했다.

미리 다 완성한 다음 쓰는 글이 아니라서

계속 수정하고 있다

더 이상 소스를 설명할 자신이 없다.

최대한 주석을 많이 달았다.

 

CGameLayer.h

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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#ifndef PuzzleGame_GameLayer
#define PuzzleGame_GameLayer
 
#include "Common.h"
#include "GameObject.h"
#include <stdio.h>
#include <string.h>
 
#define NONE        false
#define ROLLBACK    true
 
class CGameLayer : public cocos2d::Layer {
public:
    // [ 기본 ]
    // ==============================================================================================================
    static cocos2d::Scene* createScene()  {
        auto pScene = Scene::create();
        auto pLayer = CGameLayer::create();
 
        pScene->addChild(pLayer);
 
        return pScene;
    }
 
    virtual bool init() {
        if (!Layer::init()) { return false; }
 
        // 배경 이미지 출력
        cocos2d::Sprite* pBackgroundSprite = cocos2d::Sprite::create("background.png");
        pBackgroundSprite->setPosition(cocos2d::CCPointZero);
        pBackgroundSprite->setAnchorPoint(ccp((float)0, (float)0));
        addChild(pBackgroundSprite);
 
 
        // 터치 초기화
        EventListenerTouchAllAtOnce* listener = EventListenerTouchAllAtOnce::create();
        listener->onTouchesBegan = CC_CALLBACK_2(CGameLayer::onTouchesBegan, this);
        listener->onTouchesMoved = CC_CALLBACK_2(CGameLayer::onTouchesMoved, this);
        listener->onTouchesEnded = CC_CALLBACK_2(CGameLayer::onTouchesEnded, this);
        _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
 
 
        m_winSize = Director::sharedDirector()->getWinSize();
        startGame();
        return true;
    }
 
    void startGame()  {
        for (int x = 0; x < COLUMN_COUNT+1; x++) {
            for (int y = 0; y < ROW_COUNT+1; y++) {
                m_pBoard[x][y] = NULL;
            }
        }
 
        srand(time(NULL));
        for (int x = 0; x < COLUMN_COUNT; x++) {
            for (int y = 0; y < ROW_COUNT; y++) {
                if (x == COLUMN_COUNT - 1 && y % 2 != 0continue;
 
                int type = rand() % TYPE_COUNT;
 
                Sprite* pTop = Sprite::create("backgroundTop.png");
                Sprite* pGameObjectBack = Sprite::create("blockBack.png");
                CGameObject* pGameObject = CGameObject::Create(type);
                m_pBoard[x][y] = pGameObject;
 
                pTop->setAnchorPoint(ccp(0.0f, 0.0f));
                pTop->setPosition(ccp(0.0f, 1470.0f));
                pGameObjectBack->setAnchorPoint(ccp(0.5f, 0.5f));
                pGameObjectBack->setPosition(Common::ComputeXY(x, y));
                pGameObject->setAnchorPoint(ccp(0.5f, 0.5f));
                pGameObject->setPosition(Common::ComputeXY(x, y));
                pGameObject->SetGameLayer(this);
 
                addChild(pGameObjectBack, 1);
                addChild(pGameObject, 2);
            }
        }
        m_countFallingObject = 0;
        searchMacthedStreak();
        clearRemovealObject();
        ProcessFalling();
 
        // 변수 초기화
        m_EnableTouch = 0;
        m_bTouchStarted = false;
        m_countFallingObject = 0;
    }
    CREATE_FUNC(CGameLayer);
 
protected:
    CGameObject* m_pBoard[COLUMN_COUNT + 1][ROW_COUNT + 1];
    Size m_winSize;
 
    // ==============================================================================================================
 
 
 
 
 
    // [ 터치 제어 ]
    // ==============================================================================================================
    void onTouchesBegan(const std::vector<cocos2d::Touch*>&pTouches, cocos2d::Event* pEvent) {
        std::string str;
        str = std::to_string(m_countFallingObject);
        if (m_EnableTouch<=0) {
            m_EnableTouch = 0;
            if (!m_bTouchStarted) {
                Touch* pTouch = (Touch*)pTouches.back();
                Point point = pTouch->getLocation();
 
                m_gestureStartBoardX = Common::ComputeBoardX(point);
                m_gestureStartBoardY = Common::ComputeBoardY(point);
 
                if (!m_pBoard[m_gestureStartBoardX][m_gestureStartBoardY]) return;
 
                m_bTouchStarted = true;
            }
        }
    }
    void onTouchesMoved(const std::vector<cocos2d::Touch*>&pTouches, cocos2d::Event* pEvent) {
        if (m_EnableTouch<=0) {
            m_EnableTouch = 0;
            if (m_bTouchStarted) {
                Touch* pTouch = (Touch*)pTouches.back();
                Point point = pTouch->getLocation();
 
                int boardX = Common::ComputeBoardX(point);
                int boardY = Common::ComputeBoardY(point);
 
                if (!m_pBoard[boardX][boardY]) return;
 
                if (m_gestureStartBoardX != boardX || m_gestureStartBoardY != boardY)
                if (isAdjacent(m_gestureStartBoardX, m_gestureStartBoardY, boardX, boardY)) {
                    swapObjects(m_gestureStartBoardX, m_gestureStartBoardY, boardX, boardY);
                    m_bTouchStarted = false;
                }
            }
        }
    }
    void onTouchesEnded(const std::vector<cocos2d::Touch*>&pTouches, cocos2d::Event* pEvent) {
        if (m_EnableTouch<=0) {
            m_EnableTouch = 0;
            if (m_bTouchStarted) {
                Touch* pTouch = (Touch*)pTouches.back();
                Point point = pTouch->getLocation();
                m_bTouchStarted = false;
            }
        }
    }
 
protected:
    int m_EnableTouch;    // 터치 on/off
    bool m_bTouchStarted;    // 터치가 시작되었는지
    int m_gestureStartBoardX;
    int m_gestureStartBoardY; // 터치가 시작된 블록이 어느 블록인지
    // ==============================================================================================================
 
 
 
 
    // [ 제어 - 블록 매칭 ]
    // ==============================================================================================================
public:
    bool isAdjacent(int x1, int y1, int x2, int y2) {
        if (y1 % 2 == 0) {
            if ((x1 == x2) && (y1 - 2 == y2 || y1 - 1 == y2 || y1 + 1 == y2 || y1 + 2 == y2))
                return true;
            if ((x1 - 1 == x2) && (y1 - 1 == y2 || y1 + 1 == y2))
                return true;
        }
        else {
            if ((x1 == x2) && (y1 - 2 == y2 || y1 - 1 == y2 || y1 + 1 == y2 || y1 + 2 == y2))
                return true;
            if ((x1 + 1 == x2) && (y1 - 1 == y2 || y1 + 1 == y2))
                return true;
        }
        return false;
    }    // 두 블록이 서로 인접한 블록인지
    void swapObjects(int x1, int y1, int x2, int y2, bool bRoolBack = NONE) {
        CGameObject* pTemp = m_pBoard[x1][y1];
        m_pBoard[x1][y1] = m_pBoard[x2][y2];
        m_pBoard[x2][y2] = pTemp;
 
        m_pBoard[x1][y1]->SetTargetBoardX(x1);
        m_pBoard[x1][y1]->SetTargetBoardY(y1);
        m_pBoard[x2][y2]->SetTargetBoardX(x2);
        m_pBoard[x2][y2]->SetTargetBoardY(y2);
 
        if (!bRoolBack) {
            m_pBoard[x1][y1]->ProcessSliding();
            m_pBoard[x2][y2]->ProcessSliding();
        }
        else {
            m_pBoard[x1][y1]->RollBack();
            m_pBoard[x2][y2]->RollBack();
        }
        m_EnableTouch++// 블록이 이동 중이면 터치 비활성화
    }
 
    // 블록 swap완료 이벤트 핸들러
    void SlidingCompleteEventHandler(int x1, int y1, int x2, int y2) {
        static int count = 0;
        count++;
 
        // 블록을 이동했으면 매칭된게 있는지 확인한다
        if (count % 2 == 0) {
            if (!searchMacthedStreak()) swapObjects(x1, y1, x2, y2, ROLLBACK);
                clearRemovealObject();
                ProcessFalling();
                m_EnableTouch --// 터치 활성화
        }
    }
    // 블록 rollBack완료 이벤트 핸들러
    void RollBackCompleteEventHandler(int x1, int y1, int x2, int y2) {
        static int count = 0;
        count++;
 
        // 블록을 이동했으면 매칭된게 있는지 확인한다
        if (count % 2 == 0) {
            m_EnableTouch --// 터치 활성화
        }
 
    }
 
protected:
    // 매칭된 블록이 있는지 검사하고 제거대상으로 설정
    bool searchMacthedStreak() {
        bool isAnyMatched = false;
        int x = 0, y = 0;
 
        // 1행에서 검사 (0,0 / 1,0, / 2,0 / 3,0 / 4,0)
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            if (streakWay1(x, y)) isAnyMatched = true;
            if (streakWay2(x, y)) isAnyMatched = true;
            if (streakWay3(x, y)) isAnyMatched = true;
            x++;
        }
 
        // 2행에서 검사(0,1 / 1,1 / 2,1 / 3, 1)
        x = 0; y = 1;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            if (streakWay2(x, y)) isAnyMatched = true;
            x++;
        }
 
        // 좌측 열에서 검사
        x = 0; y = 2;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            if (streakWay1(x, y)) isAnyMatched = true;
 
            y += 2;
        }
 
        // 우측 열에서 검사
        x = COLUMN_COUNT - 1; y = 2;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            if (streakWay3(x, y)) isAnyMatched = true;
            y += 2;
        }
 
        return isAnyMatched;
    }
    // 제거 대상 블록을 처리
    void clearRemovealObject() {
        for (int x = 0; x < COLUMN_COUNT; x++) {
            for (int y = 0; y < ROW_COUNT; y++) {
                if (x == COLUMN_COUNT - 1 && y % 2 != 0continue;
                if (m_pBoard[x][y]) {
                    if (m_pBoard[x][y]->isRemovalObject()) {
                        CGameObject* p = m_pBoard[x][y];
                        m_pBoard[x][y] = NULL;
                        removeChild(p, true);
                    }
                }
            }
        }
    }
 
    // 매칭 라인 - 좌대각↘ 1줄 검사
    bool streakWay1(int x, int y) {
        int i = 0;
        int countMatch = 1;
        bool isAnyMatched = false;
 
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            int nextX = x;
            int nextY = y + 1;
            i = 1 - i;
            if (i % 2 == 0) nextX = x + 1;
 
            if (countMatch > 2) {
                m_pBoard[x][y]->setRemovalObject();
                m_pBoard[(i % 2 == 0) ? x : x - 1][y - 1]->setRemovalObject();
                m_pBoard[(i % 2 == 0) ? x-1 : x - 1][y - 2]->setRemovalObject();
                isAnyMatched = true;
            }
 
            if (checkType(m_pBoard[x][y]->GetType(), nextX, nextY)) {
                if (m_pBoard[nextX][nextY]->isVisible())
                    countMatch++;
            }
            else countMatch = 1;
 
            x = nextX;
            y = nextY;
        }
        return isAnyMatched;
    }
    // 매칭 라인 - 수직↓ 1줄 검사
    bool streakWay2(int x, int y) {
        int i = 1;
        int countMatch = 1;
        bool isAnyMatched = false;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            int nextX = x;
            int nextY = y + 2;
 
            if (countMatch > 2) {
                m_pBoard[x][y]->setRemovalObject();
                m_pBoard[x][y - 2]->setRemovalObject();
                m_pBoard[x][y - 4]->setRemovalObject();
                isAnyMatched = true;
            }
 
            if (checkType(m_pBoard[x][y]->GetType(), nextX, nextY)) {
                if (m_pBoard[nextX][nextY]->isVisible())
                    countMatch++;
            }
            else countMatch = 1;
 
            x = nextX;
            y = nextY;
        }
        return isAnyMatched;
    }
    // 매칭 라인 - 우대각↙ 1줄 검사
    bool streakWay3(int x, int y) {
        int i = 1;
        int countMatch = 1;
        bool isAnyMatched = false;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            int nextX = x;
            int nextY = y + 1;
            i = 1 - i;
            if (i % 2 == 0) nextX = x - 1;
 
            if (countMatch > 2) {
                m_pBoard[x][y]->setRemovalObject();
                m_pBoard[(i % 2 == 0) ? x : x + 1][y - 1]->setRemovalObject();
                m_pBoard[(i % 2 == 0) ? x + 1 : x + 1][y - 2]->setRemovalObject();
                isAnyMatched = true;
            }
 
            if (checkType(m_pBoard[x][y]->GetType(), nextX, nextY)) {
                if (m_pBoard[nextX][nextY]->isVisible())
                    countMatch++;
            }
            else countMatch = 1;
 
            x = nextX;
            y = nextY;
        }
        return isAnyMatched;
    }
    // 블록 타입 검사
    bool checkType(int type, int x, int y) {
        if (x < 0 || x >= COLUMN_COUNT) return false;
        if (y < 0 || y >= ROW_COUNT) return false;
        if (!m_pBoard[x][y]) return 0;
 
        return (type == m_pBoard[x][y]->GetType());
    }
    // ==============================================================================================================
 
 
 
 
 
    // [ 제어 - 블록 채우기 ]
    // ==============================================================================================================
public:
    void ProcessFalling() {
        srand(time(NULL));
 
        m_countFallingObject = 0;    // 움직이고 있는 블록이 있는지 카운트
        bool isAnyEmpty = true;
        while (isAnyEmpty) {        // 빈 칸이 하나도 없을 때 까지 반복
            isAnyEmpty = false;
            for (int x = 0; x < COLUMN_COUNT; x++) {
                int fallingStepOdd = 0;
                int fallingStepEven = 0;
                for (int y = ROW_COUNT - 1; y >= 0; y--) {
                    if (x == COLUMN_COUNT - 1 && y % 2 != 0continue;
 
                    // 빈칸을 찾아서
                    CGameObject* pRemovedObject = m_pBoard[x][y];
                    if (!pRemovedObject) {
                        CGameObject* pToBeFallingObject = NULL;
 
                        // 위쪽 방향으로 가장 가까운 블록을 선택해서
                        int k = y;
                        if (y % 2 == 0) {
                            for (; k >= 0; k -= 2) {
                                pToBeFallingObject = m_pBoard[x][k];
                                if (pToBeFallingObject) break;
                            }
                        }
                        else {
                            for (; k >= 1; k -= 2) {
                                pToBeFallingObject = m_pBoard[x][k];
                                if (pToBeFallingObject) break;
                            }
                        }
 
                        // 블록이 존재하면 해당 블록을 낙하시킨다
                        if (pToBeFallingObject) {
                            m_pBoard[x][k]->SetTargetBoardX(x);
                            m_pBoard[x][k]->SetTargetBoardY(y);
 
                            m_pBoard[x][k]->ProcessFalling(y-k);
 
                            m_pBoard[x][y] = m_pBoard[x][k];
                            m_pBoard[x][k] = NULL;
                            m_countFallingObject++;
                            m_EnableTouch++// 블록이 이동 중이면 터치 비활성화
                        }
                        // 없으면 만들어서 낙하시킨다
                        else {
                            int type = rand() % TYPE_COUNT;
 
                            // 블록 생성
                            pToBeFallingObject = CGameObject::Create(type);
 
                            // 이동 목표 설정
                            pToBeFallingObject->SetTargetBoardX(x);
                            pToBeFallingObject->SetTargetBoardY(y);
                            pToBeFallingObject->SetGameLayer(this);
 
                            // 이동 시작 지점 설정
                            pToBeFallingObject->setAnchorPoint(ccp(0.5f, 0.5f));
                            if (y % 2 == 0)
                                pToBeFallingObject->setPosition(Common::ComputeXY(x,  -2 - fallingStepEven));
                            else
                                pToBeFallingObject->setPosition(Common::ComputeXY(x,  -1 - fallingStepOdd));
 
                            // 블록 그리기
                            addChild(pToBeFallingObject, 2);
 
                            // 블록 이동
                            if (y % 2 == 0) {
                                pToBeFallingObject->ProcessFalling(y - (-2- fallingStepEven));
                                fallingStepEven += 2;
                            }
                            else {
                                pToBeFallingObject->ProcessFalling(y - (-1- fallingStepOdd));
                                fallingStepOdd += 2;
                            }
                            m_pBoard[x][y] = pToBeFallingObject;
                            m_countFallingObject++;
                            m_EnableTouch++// 블록이 이동중이면 터치 비활성화
                        }
                    }
                    if (!m_pBoard[x][y]) isAnyEmpty = true;
                }
            }
        }
    }
 
    // 이동중인 블록이 하나도 없으면 매칭된 블록이 생겼는지 재 검사
    void FallingCompleteEventHandller() {
        m_countFallingObject--;
        m_EnableTouch--;
        if (m_countFallingObject == 0) {
            searchMacthedStreak();
            clearRemovealObject();
            ProcessFalling();
            //m_EnableTouch =0; // 터치 활성화
        }
    }
 
protected:
    int m_countFallingObject;
 
    // ==============================================================================================================
};
#endif
cs

 

 

 

 

CGameObject.cpp

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
#include "GameObject.h"
#include "GameLayer.h"
 
USING_NS_CC;
 
CGameObject* CGameObject::Create(int type) {
    static std::string objectNames[TYPE_COUNT] = {
        "blockBlue.png",
        "blockBrown.png",
        "blockGreen.png",
        "blockPink.png",
        "blockWhite.png",
        "blockYellow.png"
    };
    if (type<0 || type>TYPE_COUNT - 1return NULL;
    CGameObject* pGameObject = CGameObject::create(objectNames[type].c_str(),
        CCRectMake(0.0f, 0.0f, OBJECT_WIDTH, OBJECT_HEIGHT));
    pGameObject->SetType(type);
    return pGameObject;
}
 
CGameObject* CGameObject::create(const char* pszFileName, const CCRect& rect) {
    CGameObject* pSprite = new CGameObject();
    if (pSprite && pSprite->initWithFile(pszFileName, rect)) {
        pSprite->autorelease();
        return pSprite;
    }
    CC_SAFE_DELETE(pSprite);
    return NULL;
}
 
 
void CGameObject::ProcessSliding() {
    Point position = getPosition();
 
    m_prevBoardX = Common::ComputeBoardX(position);
    m_prevBoardY = Common::ComputeBoardY(position);
    Point targetPosition = Common::ComputeXY(m_targetBoardX, m_targetBoardY);
 
    MoveBy* pMoveBy = MoveBy::create(0.2f, 
        ccp(targetPosition.x - position.x, targetPosition.y - position.y));
 
    FiniteTimeAction* pAction = Sequence::create(pMoveBy,
        CallFunc::create(this, callfunc_selector(CGameObject::SlidingCompleteEvent)), NULL);
    runAction(pAction);
}
void CGameObject::SlidingCompleteEvent(){
    m_pGameLayer->SlidingCompleteEventHandler(m_prevBoardX, m_prevBoardY, m_targetBoardX, m_targetBoardY);
}
 
void CGameObject::RollBack() {
    Point position = getPosition();
 
    Point targetPosition = Common::ComputeXY(m_targetBoardX, m_targetBoardY);
    MoveBy* pMoveBy = MoveBy::create(0.2f, ccp(targetPosition.x - position.x, targetPosition.y - position.y));
 
    FiniteTimeAction* pAction = Sequence::create(pMoveBy,
        CallFunc::create(this, callfunc_selector(CGameObject::RollBackCompleteEvent)), NULL);
    runAction(pAction);
}
 
void CGameObject::RollBackCompleteEvent(){
    m_pGameLayer->RollBackCompleteEventHandler(m_prevBoardX, m_prevBoardY, m_targetBoardX, m_targetBoardY);
}
 
 
void CGameObject::ProcessFalling(int speed) {
    setVisible(true);
 
    Point position = getPosition();
 
    m_prevBoardX = Common::ComputeBoardX(position);
    m_prevBoardY = Common::ComputeBoardY(position);
    Point targetPosition = Common::ComputeXY(m_targetBoardX, m_targetBoardY);
 
    MoveBy* pMoveBy = MoveBy::create(0.1f*(1+speed),
        ccp(targetPosition.x - position.x, targetPosition.y - position.y));
 
    FiniteTimeAction* pAction = Sequence::create(pMoveBy,
        CallFunc::create(this, callfunc_selector(CGameObject::FallingCompleteEvent)), NULL);
    runAction(pAction);
}
 
void CGameObject::FallingCompleteEvent() {
    m_pGameLayer->FallingCompleteEventHandller();
}
cs

 

 

 

주요 사항

블록이 이동 중일 때 그 블록을 낚아챌 수 있었다

 블록이 이동 중일 때 터치를 비활성화 하게 했다.

 

블록 제거

 기존에 setVisible(false)를 사용해 눈에 만 안보이게 했던 것을

실제로 m_pBoard[][]에서 제외시키고 removeChild()를 통해 화면에서 삭제시켰다.

 

빈칸 채우기

 아래쪽 라인부터 검사하여

자기 위쪽으로 가장 가까운 블록을 찾아 땡겨온다.

만약 자기 위쪽으로 블록이 존재하지 않으면

블록을 생성해서 가져온다.

 

블록을 땡기는 속도

 블록을 반복문을 돌며 블록을 한칸 씩 내리는게 아니라

한번에 쭈욱 내리는거라 속도를 제어할 필요가 있다.

2칸 움직이는 블록은 2배로 3칸 움직이는 블록은 3배로 움직이게 해야한다.

 

게임이 시작된 직후 처음부터 콤보가 만들어져 있는 곳이 있다

 블록 초기화 후 매칭 검사->블록 삭제->빈칸 채우기를 수행하게 했다.

 

 

괜히 육각형으로 했다

 사각형으로 했으면 간단했을 텐데

육각형 좌표계를 잘못 구상한 건지

로직이 복잡하다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Posted by gharlic
안드로이드/cocos2d-x2016. 1. 18. 21:16

먼저 한가지 문제부터 해결하고 시작한다

 게임이 시작했을 때 이미 3개이상 연결되 있는 블록들이 존재한다.

일단 이 블록들을 매칭시켜 제거하는 것 부터 시작하겠다.

 

CGameLayer.h

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
void startGame()  {
        for (int x = 0; x < COLUMN_COUNT+1; x++) {
            for (int y = 0; y < ROW_COUNT+1; y++) {
                m_pBoard[x][y] = NULL;
            }
        }
 
        srand(time(NULL));
        for (int x = 0; x < COLUMN_COUNT; x++) {
            for (int y = 0; y < ROW_COUNT; y++) {
                if (x == COLUMN_COUNT - 1 && y % 2 != 0continue;
 
                int type = rand() % TYPE_COUNT;
 
                Sprite* pGameObjectBack = Sprite::create("blockBack.png");
                CGameObject* pGameObject = CGameObject::Create(type);
                m_pBoard[x][y] = pGameObject;
 
 
                // debug --------------------------------------------------------------
                // 각 블록의 좌표를 출력
                std::string str, str2, str3;
                str = std::to_string(x);
                str2 = ",";
                str3 = std::to_string(y);
                str.append(str2);
                str.append(str3);
                auto label = LabelTTF::create(str, "Arial"50);
                Point pos; pos.set(Common::ComputeXY(x, y));
                label->setPosition(pos);
                // end of debug -------------------------------------------------------
 
 
                pGameObjectBack->setAnchorPoint(ccp(0.5f, 0.5f));
                pGameObjectBack->setPosition(Common::ComputeXY(x, y));
                pGameObject->setAnchorPoint(ccp(0.5f, 0.5f));
                pGameObject->setPosition(Common::ComputeXY(x, y));
                pGameObject->SetGameLayer(this);
 
                addChild(pGameObjectBack, 1);
                addChild(pGameObject, 2);
                addChild(label, 3);
            }
        }
 
        searchMacthedStreak();
        clearRemovealObject();
 
        // 변수 초기화
        m_bTouchStarted = false;
    }
cs

 빨간색으로 표시된 부분이 변경된 부분이다.

startGame()에서 미리 '매칭->제거'를 해버렸다.

시작하자마자 위와 같이 매칭되는 블록들이 모두 사라졌다.

저 빈칸을 채우는 것은 다음 게시물에서 언급하겠다.

 

블록이 매칭되지 않았을 때 원래 자리로 복귀

CGameLayer.h

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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#ifndef PuzzleGame_GameLayer
#define PuzzleGame_GameLayer
 
#include "Common.h"
#include "GameObject.h"
#include <stdio.h>
#include <string.h>
 
#define NONE        false
#define ROLLBACK    true
 
class CGameLayer : public cocos2d::Layer {
public:
    // [ 기본 ]
    // ==============================================================================================================
    static cocos2d::Scene* createScene()  {
        auto pScene = Scene::create();
        auto pLayer = CGameLayer::create();
 
        pScene->addChild(pLayer);
 
        return pScene;
    }
 
    virtual bool init() {
        if (!Layer::init()) { return false; }
 
        // 배경 이미지 출력
        cocos2d::Sprite* pBackgroundSprite = cocos2d::Sprite::create("background.png");
        pBackgroundSprite->setPosition(cocos2d::CCPointZero);
        pBackgroundSprite->setAnchorPoint(ccp((float)0, (float)0));
        addChild(pBackgroundSprite);
 
 
        // 터치 초기화
        EventListenerTouchAllAtOnce* listener = EventListenerTouchAllAtOnce::create();
        listener->onTouchesBegan = CC_CALLBACK_2(CGameLayer::onTouchesBegan, this);
        listener->onTouchesMoved = CC_CALLBACK_2(CGameLayer::onTouchesMoved, this);
        listener->onTouchesEnded = CC_CALLBACK_2(CGameLayer::onTouchesEnded, this);
        _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
 
 
        m_winSize = Director::sharedDirector()->getWinSize();
        startGame();
        return true;
    }
 
    void startGame()  {
        for (int x = 0; x < COLUMN_COUNT+1; x++) {
            for (int y = 0; y < ROW_COUNT+1; y++) {
                m_pBoard[x][y] = NULL;
            }
        }
 
        srand(time(NULL));
        for (int x = 0; x < COLUMN_COUNT; x++) {
            for (int y = 0; y < ROW_COUNT; y++) {
                if (x == COLUMN_COUNT - 1 && y % 2 != 0continue;
 
                int type = rand() % TYPE_COUNT;
 
                Sprite* pGameObjectBack = Sprite::create("blockBack.png");
                CGameObject* pGameObject = CGameObject::Create(type);
                m_pBoard[x][y] = pGameObject;
 
 
                // debug --------------------------------------------------------------
                // 각 블록의 좌표를 출력
                std::string str, str2, str3;
                str = std::to_string(x);
                str2 = ",";
                str3 = std::to_string(y);
                str.append(str2);
                str.append(str3);
                auto label = LabelTTF::create(str, "Arial"50);
                Point pos; pos.set(Common::ComputeXY(x, y));
                label->setPosition(pos);
                // end of debug -------------------------------------------------------
 
 
                pGameObjectBack->setAnchorPoint(ccp(0.5f, 0.5f));
                pGameObjectBack->setPosition(Common::ComputeXY(x, y));
                pGameObject->setAnchorPoint(ccp(0.5f, 0.5f));
                pGameObject->setPosition(Common::ComputeXY(x, y));
                pGameObject->SetGameLayer(this);
 
                addChild(pGameObjectBack, 1);
                addChild(pGameObject, 2);
                addChild(label, 3);
            }
        }
 
        searchMacthedStreak();
        clearRemovealObject();
 
        // 변수 초기화
        m_bTouchStarted = false;
    }
    CREATE_FUNC(CGameLayer);
 
protected:
    int m_score;
 
 
    // ==============================================================================================================
 
    // [ 터치 제어 ]
    // ==============================================================================================================
    void onTouchesBegan(const std::vector<cocos2d::Touch*>&pTouches, cocos2d::Event* pEvent) {
        if (!m_bTouchStarted) {
            Touch* pTouch = (Touch*)pTouches.back();
            Point point = pTouch->getLocation();
 
            m_gestureStartBoardX = Common::ComputeBoardX(point);
            m_gestureStartBoardY = Common::ComputeBoardY(point);
 
            m_bTouchStarted = true;
        }
    }
    void onTouchesMoved(const std::vector<cocos2d::Touch*>&pTouches, cocos2d::Event* pEvent) {
        if (m_bTouchStarted) {
            Touch* pTouch = (Touch*)pTouches.back();
            Point point = pTouch->getLocation();
 
            int boardX = Common::ComputeBoardX(point);
            int boardY = Common::ComputeBoardY(point);
 
            if (m_gestureStartBoardX != boardX || m_gestureStartBoardY != boardY)
            if (isAdjacent(m_gestureStartBoardX, m_gestureStartBoardY, boardX, boardY)) {
                swapObjects(m_gestureStartBoardX, m_gestureStartBoardY, boardX, boardY);
                m_bTouchStarted = false;
            }
        }
    }
    void onTouchesEnded(const std::vector<cocos2d::Touch*>&pTouches, cocos2d::Event* pEvent) {
        if (m_bTouchStarted) {
            Touch* pTouch = (Touch*)pTouches.back();
            Point point = pTouch->getLocation();
        }
    }
 
protected:
    CGameObject* m_pBoard[COLUMN_COUNT+1][ROW_COUNT+1];
    Size m_winSize;
 
    bool m_bTouchStarted;    // 터치가 시작되었는지
    int m_gestureStartBoardX;
    int m_gestureStartBoardY; // 터치가 시작된 블록이 어느 블록인지
    // ==============================================================================================================
 
 
 
 
    // [ 제어 - 블록 매칭 ]
    // ==============================================================================================================
public:
    bool isAdjacent(int x1, int y1, int x2, int y2) {
        if (y1 % 2 == 0) {
            if ((x1 == x2) && (y1 - 2 == y2 || y1 - 1 == y2 || y1 + 1 == y2 || y1 + 2 == y2))
                return true;
            if ((x1 - 1 == x2) && (y1 - 1 == y2 || y1 + 1 == y2))
                return true;
        }
        else {
            if ((x1 == x2) && (y1 - 2 == y2 || y1 - 1 == y2 || y1 + 1 == y2 || y1 + 2 == y2))
                return true;
            if ((x1 + 1 == x2) && (y1 - 1 == y2 || y1 + 1 == y2))
                return true;
        }
        return false;
    }    // 두 블록이 서로 인접한 블록인지
    void swapObjects(int x1, int y1, int x2, int y2, bool bRoolBack = NONE) {
        CGameObject* pTemp = m_pBoard[x1][y1];
        m_pBoard[x1][y1] = m_pBoard[x2][y2];
        m_pBoard[x2][y2] = pTemp;
 
        m_pBoard[x1][y1]->SetTargetBoardX(x1);
        m_pBoard[x1][y1]->SetTargetBoardY(y1);
        m_pBoard[x2][y2]->SetTargetBoardX(x2);
        m_pBoard[x2][y2]->SetTargetBoardY(y2);
 
        if (!bRoolBack) {
            m_pBoard[x1][y1]->ProcessSliding();
            m_pBoard[x2][y2]->ProcessSliding();
        }
        else {
            m_pBoard[x1][y1]->RollBack();
            m_pBoard[x2][y2]->RollBack();
        }
    }
 
    // 블록 swap완료 이벤트 핸들러
    void SlidingCompleteEventHandler(int x1, int y1, int x2, int y2) {
        static int count = 0;
        count++;
 
        if (count % 2 == 0) {
            if (!searchMacthedStreak()) swapObjects(x1, y1, x2, y2, ROLLBACK);
 
            clearRemovealObject();
        }
 
    }
 
protected:
    // 매칭된 블록이 있는지 검사하고 제거대상으로 설정
    bool searchMacthedStreak() {
        bool isAnyMatched = false;
        int x = 0, y = 0;
 
        // 1행에서 검사 (0,0 / 1,0, / 2,0 / 3,0 / 4,0)
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            if (streakWay1(x, y)) isAnyMatched = true;
            if (streakWay2(x, y)) isAnyMatched = true;
            if (streakWay3(x, y)) isAnyMatched = true;
            x++;
        }
 
        // 2행에서 검사(0,1 / 1,1 / 2,1 / 3, 1)
        x = 0; y = 1;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            if (streakWay2(x, y)) isAnyMatched = true;
            x++;
        }
 
        // 좌측 열에서 검사
        x = 0; y = 2;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            if (streakWay1(x, y)) isAnyMatched = true;
 
            y += 2;
        }
 
        // 우측 열에서 검사
        x = COLUMN_COUNT - 1; y = 2;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            if (streakWay3(x, y)) isAnyMatched = true;
            y += 2;
        }
 
        return isAnyMatched;
    }
    // 제거 대상 블록을 처리
    void clearRemovealObject() {
        for (int x = 0; x < COLUMN_COUNT; x++) {
            for (int y = 0; y < ROW_COUNT; y++) {
                if (x == COLUMN_COUNT - 1 && y % 2 != 0continue;
                if (m_pBoard[x][y]->isRemovalObject()) {
                    m_pBoard[x][y]->setVisible(false);
                }
            }
        }
    }
 
    // 매칭 라인 - 좌대각↘ 1줄 검사
    bool streakWay1(int x, int y) {
        int i = 0;
        int countMatch = 1;
        bool isAnyMatched = false;
 
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            int nextX = x;
            int nextY = y + 1;
            i = 1 - i;
            if (i % 2 == 0) nextX = x + 1;
 
            if (countMatch > 2) {
                m_pBoard[x][y]->setRemovalObject();
                m_pBoard[(i % 2 == 0) ? x : x - 1][y - 1]->setRemovalObject();
                m_pBoard[(i % 2 == 0) ? x-1 : x - 1][y - 2]->setRemovalObject();
                isAnyMatched = true;
            }
 
            if (checkType(m_pBoard[x][y]->GetType(), nextX, nextY)) {
                if (m_pBoard[nextX][nextY]->isVisible())
                    countMatch++;
            }
            else countMatch = 1;
 
            x = nextX;
            y = nextY;
        }
        return isAnyMatched;
    }
    // 매칭 라인 - 수직↓ 1줄 검사
    bool streakWay2(int x, int y) {
        int i = 1;
        int countMatch = 1;
        bool isAnyMatched = false;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            int nextX = x;
            int nextY = y + 2;
 
            if (countMatch > 2) {
                m_pBoard[x][y]->setRemovalObject();
                m_pBoard[x][y - 2]->setRemovalObject();
                m_pBoard[x][y - 4]->setRemovalObject();
                isAnyMatched = true;
            }
 
            if (checkType(m_pBoard[x][y]->GetType(), nextX, nextY)) {
                if (m_pBoard[nextX][nextY]->isVisible())
                    countMatch++;
            }
            else countMatch = 1;
 
            x = nextX;
            y = nextY;
        }
        return isAnyMatched;
    }
    // 매칭 라인 - 우대각↙ 1줄 검사
    bool streakWay3(int x, int y) {
        int i = 1;
        int countMatch = 1;
        bool isAnyMatched = false;
        while (true) {
            if (x < 0 || x >= COLUMN_COUNT) break;
            if (y < 0 || y >= ROW_COUNT) break;
            if (!m_pBoard[x][y]) break;
 
            int nextX = x;
            int nextY = y + 1;
            i = 1 - i;
            if (i % 2 == 0) nextX = x - 1;
 
            if (countMatch > 2) {
                m_pBoard[x][y]->setRemovalObject();
                m_pBoard[(i % 2 == 0) ? x : x + 1][y - 1]->setRemovalObject();
                m_pBoard[(i % 2 == 0) ? x + 1 : x + 1][y - 2]->setRemovalObject();
                isAnyMatched = true;
            }
 
            if (checkType(m_pBoard[x][y]->GetType(), nextX, nextY)) {
                if (m_pBoard[nextX][nextY]->isVisible())
                    countMatch++;
            }
            else countMatch = 1;
 
            x = nextX;
            y = nextY;
        }
        return isAnyMatched;
    }
    // 블록 타입 검사
    bool checkType(int type, int x, int y) {
        if (x < 0 || x >= COLUMN_COUNT) return false;
        if (y < 0 || y >= ROW_COUNT) return false;
        if (!m_pBoard[x][y]) return 0;
 
        return (type == m_pBoard[x][y]->GetType());
    }
    // ==============================================================================================================
 
 
    // [ 제어 - 블록 채우기 ]
    // ==============================================================================================================
public:
 
 
protected:
 
    // ==============================================================================================================
};
#endif
cs

 

172행 - swapObjects()에 원래 자리로 복귀하는 기능을 추가했다.

           기존에 쓰던 CGameObject::ProcessSliding()에서 이동 전 좌표를 저장해뒀기

           때문에 가능한 일이다.

 

193행 - static int i를 사용해 짝수 번 호출될 때만 아래 코드를 실행하게 했다.

          swapObject()에서 ProcessSliding()을 두 번 사용하기 때문에

          이벤트 핸들러도 두 번 실행되기 때문이다.

 

CGameObject.cpp

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
#include "GameObject.h"
#include "GameLayer.h"
 
USING_NS_CC;
 
CGameObject* CGameObject::Create(int type) {
    static std::string objectNames[TYPE_COUNT] = {
        "blockBlue.png",
        "blockBrown.png",
        "blockGreen.png",
        "blockPink.png",
        "blockWhite.png",
        "blockYellow.png"
    };
    if (type<0 || type>TYPE_COUNT - 1return NULL;
    CGameObject* pGameObject = CGameObject::create(objectNames[type].c_str(),
        CCRectMake(0.0f, 0.0f, OBJECT_WIDTH, OBJECT_HEIGHT));
    pGameObject->SetType(type);
    return pGameObject;
}
 
CGameObject* CGameObject::create(const char* pszFileName, const CCRect& rect) {
    CGameObject* pSprite = new CGameObject();
    if (pSprite && pSprite->initWithFile(pszFileName, rect)) {
        pSprite->autorelease();
        return pSprite;
    }
    CC_SAFE_DELETE(pSprite);
    return NULL;
}
 
 
void CGameObject::ProcessSliding() {
    Point position = getPosition();
 
    m_prevBoardX = Common::ComputeBoardX(position);
    m_prevBoardY = Common::ComputeBoardY(position);
    Point targetPosition = Common::ComputeXY(m_targetBoardX, m_targetBoardY);
    MoveBy* pMoveBy = MoveBy::create(0.15f, ccp(targetPosition.x - position.x, targetPosition.y - position.y));
 
    FiniteTimeAction* pAction = Sequence::create(pMoveBy,
        CallFunc::create(this, callfunc_selector(CGameObject::SlidingCompleteEvent)), NULL);
    runAction(pAction);
}
 
void CGameObject::RollBack() {
    Point position = getPosition();
 
    Point targetPosition = Common::ComputeXY(m_targetBoardX, m_targetBoardY);
    MoveBy* pMoveBy = MoveBy::create(0.15f, ccp(targetPosition.x - position.x, targetPosition.y - position.y));
 
    FiniteTimeAction* pAction = Sequence::create(pMoveBy, NULL);
    runAction(pAction);
}
 
 
 
void CGameObject::SlidingCompleteEvent(){
    m_pGameLayer->SlidingCompleteEventHandler(m_prevBoardX, m_prevBoardY, m_targetBoardX, m_targetBoardY);
};
 
cs

 

 

빨간 색으로 표시한 부분 이 외에도 버그 수정을 많이 했지만 그건 언급하지 않겠다.

 

 

 

 

 

 

 

 

Posted by gharlic