//HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
using namespace cocos2d;
class HelloWorld : public CCLayer
{
public:
virtual bool init();
static CCScene* scene();
CREATE_FUNC(HelloWorld);
CCTexture2D* texture;
CCSprite* ball;
CCSprite* paddle;
CCArray* targets;
int BRICKS_HEIGHT;
int BRICKS_WIDTH;
bool isPlaying;
bool isPaddleTouched;
CCPoint ballMovement;
~HelloWorld();
void initializeBricks();
void initializeBall();
void initializePaddle();
void startGame();
void gameLogic(float dt);
void processCollision(CCSprite* brick);
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent* event);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent* event);
};
#endif // __HELLOWORLD_SCENE_H__
//HelloWorldScene.cpp
#include "HelloWorldScene.h"
#include "GameOver.h"
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
/////////////////////////////
// 터치 활성화
this->setTouchEnabled(true);
// 어레이 초기화
targets = CCArray::createWithCapacity(20);
targets->retain();
BRICKS_HEIGHT = 4;
BRICKS_WIDTH = 5;
texture = CCTextureCache::sharedTextureCache()->addImage("Images/white-512x512.png");
// CCSprite* pMan2 = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 85, 121));
// 벽돌 초기화
this->initializeBricks();
// 공 초기화
this->initializeBall();
// 패들 초기화
this->initializePaddle();
// 2초후 게임 시작
CCFiniteTimeAction* action = CCSequence::create(
CCDelayTime::create(2),
CCCallFunc::create(this, callfunc_selector(HelloWorld::startGame)),
NULL);
this->runAction(action);
return true;
}
HelloWorld::~HelloWorld()
{
targets->release();
}
void HelloWorld::initializeBricks()
{
int count = 0;
for (int y = 0; y < BRICKS_HEIGHT; y++) {
for (int x = 0; x < BRICKS_WIDTH; x++) {
// CCSprite* bricks = CCSprite::create("Images/white-512x512.png");
//
// // 크기 지정
// bricks->setTextureRect(CCRectMake(0, 0, 64, 40));
CCSprite* bricks = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 64, 40));
// 색 지정
switch (count++ %4) {
case 0:
bricks->setColor(ccc3(255, 255, 255));
break;
case 1:
bricks->setColor(ccc3(255, 0, 0));
break;
case 2:
bricks->setColor(ccc3(255, 255, 0));
break;
case 3:
bricks->setColor(ccc3(75, 255, 0));
break;
default:
break;
}
// 좌표 지정
bricks->setPosition(ccp(x*64+32,(y * 40) + 280));
// 화면에 추가
this->addChild(bricks);
// 배열에 추가
targets->addObject(bricks);
}
}
}
void HelloWorld::initializeBall()
{
// ball = CCSprite::create("Images/white-512x512.png");
// ball->setTextureRect(CCRectMake(0, 0, 16, 16));
ball = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 16, 16));
ball->setColor(ccc3(0, 255, 255));
ball->setPosition(ccp(160,240));
this->addChild(ball);
}
void HelloWorld::initializePaddle()
{
// paddle = CCSprite::create("Images/white-512x512.png");
// paddle->setTextureRect(CCRectMake(0, 0, 80, 10));
paddle = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 80, 10));
paddle->setColor(ccc3(255, 255, 0));
paddle->setPosition(ccp(160,50));
this->addChild(paddle);
}
void HelloWorld::startGame()
{
ball->setPosition(ccp(160,240));
ballMovement = CCPointMake(4,4);
if (arc4random() % 100 < 50) {
ballMovement.x = -ballMovement.x;
}
ballMovement.y = -ballMovement.y;
isPlaying = true;
this->schedule(schedule_selector(HelloWorld::gameLogic), 2.0f/60.0f);
}
void HelloWorld::gameLogic(float dt)
{
// ballMovement.y가 음수이면 볼이 내려오고 있는 것.
// ballMovement.y가 양수이면 볼이 올라가고 있는 것.
//CCLog("tick..%f",ballMovement.y);
// 볼의 현재위치
ball->setPosition(ccp(ball->getPosition().x+ballMovement.x, ball->getPosition().y+ballMovement.y));
// 볼과 패들 충돌여부
bool paddleCollision =
ball->getPosition().y <= paddle->getPosition().y + 13 &&
ball->getPosition().x >= paddle->getPosition().x - 48 &&
ball->getPosition().x <= paddle->getPosition().x + 48;
// 패들과 충돌시 처리
if(paddleCollision) {
if (ball->getPosition().y <= paddle->getPosition().y + 13 && ballMovement.y < 0) {
ball->setPosition(ccp(ball->getPosition().x, paddle->getPosition().y + 13));
}
// 내려오던거 위로 올라가게 공의 상하 진행방향 바꾸기
ballMovement.y = -ballMovement.y;
}
// 블록과 충돌 파악
bool there_are_solid_bricks = false;
CCObject *Obj;
CCARRAY_FOREACH(targets, Obj) {
CCSprite *brick = (CCSprite*)Obj;
if (255 == brick->getOpacity()) {
there_are_solid_bricks = true;
CCRect rectA = ball->boundingBox();
CCRect rectB = brick->boundingBox();
if ( rectA.intersectsRect(rectB) ) {
// 블록과 충돌 처리
this->processCollision(brick);
}
}
}
// 블록이 없을 때 - 게임 종료 상태
if (!there_are_solid_bricks) {
isPlaying = false;
ball->setOpacity(0);
// 모든 스케쥴 제거
this->unscheduleAllSelectors();
CCLog("You win !!!");
// 게임에 이겼다. 새로운 게임 대기 화면...
CCScene* pScene = GameOver::scene();
CCDirector::sharedDirector()->replaceScene( CCTransitionProgressRadialCCW::create(1, pScene) );
}
// 벽면 충돌 체크
if (ball->getPosition().x > 312 || ball->getPosition().x < 8)
ballMovement.x = -ballMovement.x;
if (ball->getPosition().y > 450)
ballMovement.y = -ballMovement.y;
// if (ball.position.y <10) {
// ballMovement.y = -ballMovement.y;
// }
// 페달을 빠져 나갈 때
if (ball->getPosition().y < (50+5+8)) {
isPlaying = false;
ball->setOpacity(0);
// 모든 스케쥴 제거
this->unscheduleAllSelectors();
CCLog("You lose..");
// 게임에 졌다. 새로운 게임 대기 화면...
CCScene* pScene = GameOver::scene();
CCDirector::sharedDirector()->replaceScene( CCTransitionProgressRadialCCW::create(1, pScene) );
}
}
void HelloWorld::processCollision(CCSprite *brick)
{
CCPoint brickPos = brick->getPosition();
CCPoint ballPos = ball->getPosition();
if (ballMovement.x > 0 && brick->getPosition().x < ball->getPosition().x) {
ballMovement.x = -ballMovement.x;
} else if (ballMovement.x < 0 && brick->getPosition().x < ball->getPosition().x) {
ballMovement.x = -ballMovement.x;
}
if (ballMovement.y > 0 && brick->getPosition().y > ball->getPosition().y) {
ballMovement.y = -ballMovement.y;
} else if (ballMovement.y < 0 && brick->getPosition().y < ball->getPosition().y) {
ballMovement.y = -ballMovement.y;
}
brick->setOpacity(0);
}
void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent* event)
{
if (!isPlaying) {
return;
}
// 하나의 터치이벤트만 가져온다.
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->getLocation();
// 패들을 터치했는지 체크한다.
CCRect rect = paddle->boundingBox();
if (rect.containsPoint(touchPoint)) {
// 패들이 터치되었음을 체크.
isPaddleTouched = true;
} else {
isPaddleTouched = false;
}
// // 패들 sprite의 사이즈의 반을 계산합니다.
// float halfWidth = paddle->getContentSize().width / 2.0;
// float halfHeight = paddle->getContentSize().height / 2.0;
//
// // 터치된 위치가 패들 안에 들어오는 지 계산합니다.
// if (touchPoint.x >(paddle->getPosition().x + halfWidth) ||
// touchPoint.x <(paddle->getPosition().x - halfWidth) ||
// touchPoint.y <(paddle->getPosition().y - halfHeight) ||
// touchPoint.y >(paddle->getPosition().y + halfHeight) )
// {
// isPaddleTouched = false;
// } else {
// // 패들이 터치되었음을 체크.
// isPaddleTouched = true;
// }
}
void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent* event)
{
if(isPaddleTouched) {
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->getLocation();
// 패들이 좌우로만 움직이게 y값은 바꾸지 않는다.
// 또한 패들이 화면 바깥으로 나가지 않도록 한다.
if (touchPoint.x < 40) {
touchPoint.x = 40;
}
if (touchPoint.x > 280) {
touchPoint.x = 280;
}
CCPoint newLocation = ccp(touchPoint.x, paddle->getPosition().y);
paddle->setPosition(newLocation);
}
}
//GameOver.cpp
#include "GameOver.h"
#include "HelloWorldScene.h"
CCScene* GameOver::scene()
{
CCScene *scene = CCScene::create();
GameOver *layer = GameOver::create();
scene->addChild(layer);
return scene;
}
bool GameOver::init()
{
if ( !CCLayer::init() )
{
return false;
}
/////////////////////////////
CCSize s = CCDirector::sharedDirector()->getWinSize();
// 메뉴 아이템 생성 및 초기화
CCMenuItemFont* item1 = CCMenuItemFont::create("New Game",
this,
menu_selector(GameOver::doClose)
);
item1->setColor(ccc3(255, 255, 255));
// 메뉴 생성
CCMenu* pMenu = CCMenu::create( item1, NULL );
// 메뉴 위치
pMenu->setPosition(ccp(s.width / 2, s.height/2));
// 레이어에 메뉴 객체 추가
this->addChild(pMenu);
return true;
}
void GameOver::doClose(CCObject* pSender)
{
// 새로운게임을 시작하게 처음 신으로 이동
CCScene* pScene = HelloWorld::scene();
CCDirector::sharedDirector()->replaceScene( pScene );
}
//GameOver.h
#ifndef __BrickEx__GameOver__
#define __BrickEx__GameOver__
#include "cocos2d.h"
using namespace cocos2d;
class GameOver : public CCLayer
{
public:
virtual bool init();
static CCScene* scene();
CREATE_FUNC(GameOver);
void doClose(CCObject* pSender);
};
#endif /* defined(__BrickEx__GameOver__) */
//HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
using namespace cocos2d;
class HelloWorld : public CCLayer
{
public:
virtual bool init();
static CCScene* scene();
CREATE_FUNC(HelloWorld);
CCTexture2D* texture;
CCSprite* ball;
CCSprite* paddle;
CCArray* targets;
int BRICKS_HEIGHT;
int BRICKS_WIDTH;
bool isPlaying;
bool isPaddleTouched;
CCPoint ballMovement;
~HelloWorld();
void initializeBricks();
void initializeBall();
void initializePaddle();
void startGame();
void gameLogic(float dt);
void processCollision(CCSprite* brick);
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent* event);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent* event);
};
#endif // __HELLOWORLD_SCENE_H__
//HelloWorldScene.cpp
#include "HelloWorldScene.h"
#include "GameOver.h"
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
/////////////////////////////
// 터치 활성화
this->setTouchEnabled(true);
// 어레이 초기화
targets = CCArray::createWithCapacity(20);
targets->retain();
BRICKS_HEIGHT = 4;
BRICKS_WIDTH = 5;
texture = CCTextureCache::sharedTextureCache()->addImage("Images/white-512x512.png");
// CCSprite* pMan2 = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 85, 121));
// 벽돌 초기화
this->initializeBricks();
// 공 초기화
this->initializeBall();
// 패들 초기화
this->initializePaddle();
// 2초후 게임 시작
CCFiniteTimeAction* action = CCSequence::create(
CCDelayTime::create(2),
CCCallFunc::create(this, callfunc_selector(HelloWorld::startGame)),
NULL);
this->runAction(action);
return true;
}
HelloWorld::~HelloWorld()
{
targets->release();
}
void HelloWorld::initializeBricks()
{
int count = 0;
for (int y = 0; y < BRICKS_HEIGHT; y++) {
for (int x = 0; x < BRICKS_WIDTH; x++) {
// CCSprite* bricks = CCSprite::create("Images/white-512x512.png");
//
// // 크기 지정
// bricks->setTextureRect(CCRectMake(0, 0, 64, 40));
CCSprite* bricks = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 64, 40));
// 색 지정
switch (count++ %4) {
case 0:
bricks->setColor(ccc3(255, 255, 255));
break;
case 1:
bricks->setColor(ccc3(255, 0, 0));
break;
case 2:
bricks->setColor(ccc3(255, 255, 0));
break;
case 3:
bricks->setColor(ccc3(75, 255, 0));
break;
default:
break;
}
// 좌표 지정
bricks->setPosition(ccp(x*64+32,(y * 40) + 280));
// 화면에 추가
this->addChild(bricks);
// 배열에 추가
targets->addObject(bricks);
}
}
}
void HelloWorld::initializeBall()
{
// ball = CCSprite::create("Images/white-512x512.png");
// ball->setTextureRect(CCRectMake(0, 0, 16, 16));
ball = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 16, 16));
ball->setColor(ccc3(0, 255, 255));
ball->setPosition(ccp(160,240));
this->addChild(ball);
}
void HelloWorld::initializePaddle()
{
// paddle = CCSprite::create("Images/white-512x512.png");
// paddle->setTextureRect(CCRectMake(0, 0, 80, 10));
paddle = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 80, 10));
paddle->setColor(ccc3(255, 255, 0));
paddle->setPosition(ccp(160,50));
this->addChild(paddle);
}
void HelloWorld::startGame()
{
ball->setPosition(ccp(160,240));
ballMovement = CCPointMake(4,4);
if (arc4random() % 100 < 50) {
ballMovement.x = -ballMovement.x;
}
ballMovement.y = -ballMovement.y;
isPlaying = true;
this->schedule(schedule_selector(HelloWorld::gameLogic), 2.0f/60.0f);
}
void HelloWorld::gameLogic(float dt)
{
// ballMovement.y가 음수이면 볼이 내려오고 있는 것.
// ballMovement.y가 양수이면 볼이 올라가고 있는 것.
//CCLog("tick..%f",ballMovement.y);
// 볼의 현재위치
ball->setPosition(ccp(ball->getPosition().x+ballMovement.x, ball->getPosition().y+ballMovement.y));
// 볼과 패들 충돌여부
bool paddleCollision =
ball->getPosition().y <= paddle->getPosition().y + 13 &&
ball->getPosition().x >= paddle->getPosition().x - 48 &&
ball->getPosition().x <= paddle->getPosition().x + 48;
// 패들과 충돌시 처리
if(paddleCollision) {
if (ball->getPosition().y <= paddle->getPosition().y + 13 && ballMovement.y < 0) {
ball->setPosition(ccp(ball->getPosition().x, paddle->getPosition().y + 13));
}
// 내려오던거 위로 올라가게 공의 상하 진행방향 바꾸기
ballMovement.y = -ballMovement.y;
}
// 블록과 충돌 파악
bool there_are_solid_bricks = false;
CCObject *Obj;
CCARRAY_FOREACH(targets, Obj) {
CCSprite *brick = (CCSprite*)Obj;
if (255 == brick->getOpacity()) {
there_are_solid_bricks = true;
CCRect rectA = ball->boundingBox();
CCRect rectB = brick->boundingBox();
if ( rectA.intersectsRect(rectB) ) {
// 블록과 충돌 처리
this->processCollision(brick);
}
}
}
// 블록이 없을 때 - 게임 종료 상태
if (!there_are_solid_bricks) {
isPlaying = false;
ball->setOpacity(0);
// 모든 스케쥴 제거
this->unscheduleAllSelectors();
CCLog("You win !!!");
// 게임에 이겼다. 새로운 게임 대기 화면...
CCScene* pScene = GameOver::scene();
CCDirector::sharedDirector()->replaceScene( CCTransitionProgressRadialCCW::create(1, pScene) );
}
// 벽면 충돌 체크
if (ball->getPosition().x > 312 || ball->getPosition().x < 8)
ballMovement.x = -ballMovement.x;
if (ball->getPosition().y > 450)
ballMovement.y = -ballMovement.y;
// if (ball.position.y <10) {
// ballMovement.y = -ballMovement.y;
// }
// 페달을 빠져 나갈 때
if (ball->getPosition().y < (50+5+8)) {
isPlaying = false;
ball->setOpacity(0);
// 모든 스케쥴 제거
this->unscheduleAllSelectors();
CCLog("You lose..");
// 게임에 졌다. 새로운 게임 대기 화면...
CCScene* pScene = GameOver::scene();
CCDirector::sharedDirector()->replaceScene( CCTransitionProgressRadialCCW::create(1, pScene) );
}
}
void HelloWorld::processCollision(CCSprite *brick)
{
CCPoint brickPos = brick->getPosition();
CCPoint ballPos = ball->getPosition();
if (ballMovement.x > 0 && brick->getPosition().x < ball->getPosition().x) {
ballMovement.x = -ballMovement.x;
} else if (ballMovement.x < 0 && brick->getPosition().x < ball->getPosition().x) {
ballMovement.x = -ballMovement.x;
}
if (ballMovement.y > 0 && brick->getPosition().y > ball->getPosition().y) {
ballMovement.y = -ballMovement.y;
} else if (ballMovement.y < 0 && brick->getPosition().y < ball->getPosition().y) {
ballMovement.y = -ballMovement.y;
}
brick->setOpacity(0);
}
void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent* event)
{
if (!isPlaying) {
return;
}
// 하나의 터치이벤트만 가져온다.
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->getLocation();
// 패들을 터치했는지 체크한다.
CCRect rect = paddle->boundingBox();
if (rect.containsPoint(touchPoint)) {
// 패들이 터치되었음을 체크.
isPaddleTouched = true;
} else {
isPaddleTouched = false;
}
// // 패들 sprite의 사이즈의 반을 계산합니다.
// float halfWidth = paddle->getContentSize().width / 2.0;
// float halfHeight = paddle->getContentSize().height / 2.0;
//
// // 터치된 위치가 패들 안에 들어오는 지 계산합니다.
// if (touchPoint.x >(paddle->getPosition().x + halfWidth) ||
// touchPoint.x <(paddle->getPosition().x - halfWidth) ||
// touchPoint.y <(paddle->getPosition().y - halfHeight) ||
// touchPoint.y >(paddle->getPosition().y + halfHeight) )
// {
// isPaddleTouched = false;
// } else {
// // 패들이 터치되었음을 체크.
// isPaddleTouched = true;
// }
}
void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent* event)
{
if(isPaddleTouched) {
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->getLocation();
// 패들이 좌우로만 움직이게 y값은 바꾸지 않는다.
// 또한 패들이 화면 바깥으로 나가지 않도록 한다.
if (touchPoint.x < 40) {
touchPoint.x = 40;
}
if (touchPoint.x > 280) {
touchPoint.x = 280;
}
CCPoint newLocation = ccp(touchPoint.x, paddle->getPosition().y);
paddle->setPosition(newLocation);
}
}
//GameOver.cpp
#include "GameOver.h"
#include "HelloWorldScene.h"
CCScene* GameOver::scene()
{
CCScene *scene = CCScene::create();
GameOver *layer = GameOver::create();
scene->addChild(layer);
return scene;
}
bool GameOver::init()
{
if ( !CCLayer::init() )
{
return false;
}
/////////////////////////////
CCSize s = CCDirector::sharedDirector()->getWinSize();
// 메뉴 아이템 생성 및 초기화
CCMenuItemFont* item1 = CCMenuItemFont::create("New Game",
this,
menu_selector(GameOver::doClose)
);
item1->setColor(ccc3(255, 255, 255));
// 메뉴 생성
CCMenu* pMenu = CCMenu::create( item1, NULL );
// 메뉴 위치
pMenu->setPosition(ccp(s.width / 2, s.height/2));
// 레이어에 메뉴 객체 추가
this->addChild(pMenu);
return true;
}
void GameOver::doClose(CCObject* pSender)
{
// 새로운게임을 시작하게 처음 신으로 이동
CCScene* pScene = HelloWorld::scene();
CCDirector::sharedDirector()->replaceScene( pScene );
}
//GameOver.h
#ifndef __BrickEx__GameOver__
#define __BrickEx__GameOver__
#include "cocos2d.h"
using namespace cocos2d;
class GameOver : public CCLayer
{
public:
virtual bool init();
static CCScene* scene();
CREATE_FUNC(GameOver);
void doClose(CCObject* pSender);
};
#endif /* defined(__BrickEx__GameOver__) */
//HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
using namespace cocos2d;
class HelloWorld : public CCLayer
{
public:
virtual bool init();
static CCScene* scene();
CREATE_FUNC(HelloWorld);
CCTexture2D* texture;
CCSprite* ball;
CCSprite* paddle;
CCArray* targets;
int BRICKS_HEIGHT;
int BRICKS_WIDTH;
bool isPlaying;
bool isPaddleTouched;
CCPoint ballMovement;
~HelloWorld();
void initializeBricks();
void initializeBall();
void initializePaddle();
void startGame();
void gameLogic(float dt);
void processCollision(CCSprite* brick);
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent* event);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent* event);
};
#endif // __HELLOWORLD_SCENE_H__
//HelloWorldScene.cpp
#include "HelloWorldScene.h"
#include "GameOver.h"
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
/////////////////////////////
// 터치 활성화
this->setTouchEnabled(true);
// 어레이 초기화
targets = CCArray::createWithCapacity(20);
targets->retain();
BRICKS_HEIGHT = 4;
BRICKS_WIDTH = 5;
texture = CCTextureCache::sharedTextureCache()->addImage("Images/white-512x512.png");
// CCSprite* pMan2 = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 85, 121));
// 벽돌 초기화
this->initializeBricks();
// 공 초기화
this->initializeBall();
// 패들 초기화
this->initializePaddle();
// 2초후 게임 시작
CCFiniteTimeAction* action = CCSequence::create(
CCDelayTime::create(2),
CCCallFunc::create(this, callfunc_selector(HelloWorld::startGame)),
NULL);
this->runAction(action);
return true;
}
HelloWorld::~HelloWorld()
{
targets->release();
}
void HelloWorld::initializeBricks()
{
int count = 0;
for (int y = 0; y < BRICKS_HEIGHT; y++) {
for (int x = 0; x < BRICKS_WIDTH; x++) {
// CCSprite* bricks = CCSprite::create("Images/white-512x512.png");
//
// // 크기 지정
// bricks->setTextureRect(CCRectMake(0, 0, 64, 40));
CCSprite* bricks = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 64, 40));
// 색 지정
switch (count++ %4) {
case 0:
bricks->setColor(ccc3(255, 255, 255));
break;
case 1:
bricks->setColor(ccc3(255, 0, 0));
break;
case 2:
bricks->setColor(ccc3(255, 255, 0));
break;
case 3:
bricks->setColor(ccc3(75, 255, 0));
break;
default:
break;
}
// 좌표 지정
bricks->setPosition(ccp(x*64+32,(y * 40) + 280));
// 화면에 추가
this->addChild(bricks);
// 배열에 추가
targets->addObject(bricks);
}
}
}
void HelloWorld::initializeBall()
{
// ball = CCSprite::create("Images/white-512x512.png");
// ball->setTextureRect(CCRectMake(0, 0, 16, 16));
ball = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 16, 16));
ball->setColor(ccc3(0, 255, 255));
ball->setPosition(ccp(160,240));
this->addChild(ball);
}
void HelloWorld::initializePaddle()
{
// paddle = CCSprite::create("Images/white-512x512.png");
// paddle->setTextureRect(CCRectMake(0, 0, 80, 10));
paddle = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 80, 10));
paddle->setColor(ccc3(255, 255, 0));
paddle->setPosition(ccp(160,50));
this->addChild(paddle);
}
void HelloWorld::startGame()
{
ball->setPosition(ccp(160,240));
ballMovement = CCPointMake(4,4);
if (arc4random() % 100 < 50) {
ballMovement.x = -ballMovement.x;
}
ballMovement.y = -ballMovement.y;
isPlaying = true;
this->schedule(schedule_selector(HelloWorld::gameLogic), 2.0f/60.0f);
}
void HelloWorld::gameLogic(float dt)
{
// ballMovement.y가 음수이면 볼이 내려오고 있는 것.
// ballMovement.y가 양수이면 볼이 올라가고 있는 것.
//CCLog("tick..%f",ballMovement.y);
// 볼의 현재위치
ball->setPosition(ccp(ball->getPosition().x+ballMovement.x, ball->getPosition().y+ballMovement.y));
// 볼과 패들 충돌여부
bool paddleCollision =
ball->getPosition().y <= paddle->getPosition().y + 13 &&
ball->getPosition().x >= paddle->getPosition().x - 48 &&
ball->getPosition().x <= paddle->getPosition().x + 48;
// 패들과 충돌시 처리
if(paddleCollision) {
if (ball->getPosition().y <= paddle->getPosition().y + 13 && ballMovement.y < 0) {
ball->setPosition(ccp(ball->getPosition().x, paddle->getPosition().y + 13));
}
// 내려오던거 위로 올라가게 공의 상하 진행방향 바꾸기
ballMovement.y = -ballMovement.y;
}
// 블록과 충돌 파악
bool there_are_solid_bricks = false;
CCObject *Obj;
CCARRAY_FOREACH(targets, Obj) {
CCSprite *brick = (CCSprite*)Obj;
if (255 == brick->getOpacity()) {
there_are_solid_bricks = true;
CCRect rectA = ball->boundingBox();
CCRect rectB = brick->boundingBox();
if ( rectA.intersectsRect(rectB) ) {
// 블록과 충돌 처리
this->processCollision(brick);
}
}
}
// 블록이 없을 때 - 게임 종료 상태
if (!there_are_solid_bricks) {
isPlaying = false;
ball->setOpacity(0);
// 모든 스케쥴 제거
this->unscheduleAllSelectors();
CCLog("You win !!!");
// 게임에 이겼다. 새로운 게임 대기 화면...
CCScene* pScene = GameOver::scene();
CCDirector::sharedDirector()->replaceScene( CCTransitionProgressRadialCCW::create(1, pScene) );
}
// 벽면 충돌 체크
if (ball->getPosition().x > 312 || ball->getPosition().x < 8)
ballMovement.x = -ballMovement.x;
if (ball->getPosition().y > 450)
ballMovement.y = -ballMovement.y;
// if (ball.position.y <10) {
// ballMovement.y = -ballMovement.y;
// }
// 페달을 빠져 나갈 때
if (ball->getPosition().y < (50+5+8)) {
isPlaying = false;
ball->setOpacity(0);
// 모든 스케쥴 제거
this->unscheduleAllSelectors();
CCLog("You lose..");
// 게임에 졌다. 새로운 게임 대기 화면...
CCScene* pScene = GameOver::scene();
CCDirector::sharedDirector()->replaceScene( CCTransitionProgressRadialCCW::create(1, pScene) );
}
}
void HelloWorld::processCollision(CCSprite *brick)
{
CCPoint brickPos = brick->getPosition();
CCPoint ballPos = ball->getPosition();
if (ballMovement.x > 0 && brick->getPosition().x < ball->getPosition().x) {
ballMovement.x = -ballMovement.x;
} else if (ballMovement.x < 0 && brick->getPosition().x < ball->getPosition().x) {
ballMovement.x = -ballMovement.x;
}
if (ballMovement.y > 0 && brick->getPosition().y > ball->getPosition().y) {
ballMovement.y = -ballMovement.y;
} else if (ballMovement.y < 0 && brick->getPosition().y < ball->getPosition().y) {
ballMovement.y = -ballMovement.y;
}
brick->setOpacity(0);
}
void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent* event)
{
if (!isPlaying) {
return;
}
// 하나의 터치이벤트만 가져온다.
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->getLocation();
// 패들을 터치했는지 체크한다.
CCRect rect = paddle->boundingBox();
if (rect.containsPoint(touchPoint)) {
// 패들이 터치되었음을 체크.
isPaddleTouched = true;
} else {
isPaddleTouched = false;
}
// // 패들 sprite의 사이즈의 반을 계산합니다.
// float halfWidth = paddle->getContentSize().width / 2.0;
// float halfHeight = paddle->getContentSize().height / 2.0;
//
// // 터치된 위치가 패들 안에 들어오는 지 계산합니다.
// if (touchPoint.x >(paddle->getPosition().x + halfWidth) ||
// touchPoint.x <(paddle->getPosition().x - halfWidth) ||
// touchPoint.y <(paddle->getPosition().y - halfHeight) ||
// touchPoint.y >(paddle->getPosition().y + halfHeight) )
// {
// isPaddleTouched = false;
// } else {
// // 패들이 터치되었음을 체크.
// isPaddleTouched = true;
// }
}
void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent* event)
{
if(isPaddleTouched) {
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->getLocation();
// 패들이 좌우로만 움직이게 y값은 바꾸지 않는다.
// 또한 패들이 화면 바깥으로 나가지 않도록 한다.
if (touchPoint.x < 40) {
touchPoint.x = 40;
}
if (touchPoint.x > 280) {
touchPoint.x = 280;
}
CCPoint newLocation = ccp(touchPoint.x, paddle->getPosition().y);
paddle->setPosition(newLocation);
}
}
//GameOver.cpp
#include "GameOver.h"
#include "HelloWorldScene.h"
CCScene* GameOver::scene()
{
CCScene *scene = CCScene::create();
GameOver *layer = GameOver::create();
scene->addChild(layer);
return scene;
}
bool GameOver::init()
{
if ( !CCLayer::init() )
{
return false;
}
/////////////////////////////
CCSize s = CCDirector::sharedDirector()->getWinSize();
// 메뉴 아이템 생성 및 초기화
CCMenuItemFont* item1 = CCMenuItemFont::create("New Game",
this,
menu_selector(GameOver::doClose)
);
item1->setColor(ccc3(255, 255, 255));
// 메뉴 생성
CCMenu* pMenu = CCMenu::create( item1, NULL );
// 메뉴 위치
pMenu->setPosition(ccp(s.width / 2, s.height/2));
// 레이어에 메뉴 객체 추가
this->addChild(pMenu);
return true;
}
void GameOver::doClose(CCObject* pSender)
{
// 새로운게임을 시작하게 처음 신으로 이동
CCScene* pScene = HelloWorld::scene();
CCDirector::sharedDirector()->replaceScene( pScene );
}
//GameOver.h
#ifndef __BrickEx__GameOver__
#define __BrickEx__GameOver__
#include "cocos2d.h"
using namespace cocos2d;
class GameOver : public CCLayer
{
public:
virtual bool init();
static CCScene* scene();
CREATE_FUNC(GameOver);
void doClose(CCObject* pSender);
};
#endif /* defined(__BrickEx__GameOver__) */
//HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
using namespace cocos2d;
class HelloWorld : public CCLayer
{
public:
virtual bool init();
static CCScene* scene();
CREATE_FUNC(HelloWorld);
CCTexture2D* texture;
CCSprite* ball;
CCSprite* paddle;
CCArray* targets;
int BRICKS_HEIGHT;
int BRICKS_WIDTH;
bool isPlaying;
bool isPaddleTouched;
CCPoint ballMovement;
~HelloWorld();
void initializeBricks();
void initializeBall();
void initializePaddle();
void startGame();
void gameLogic(float dt);
void processCollision(CCSprite* brick);
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent* event);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent* event);
};
#endif // __HELLOWORLD_SCENE_H__
//HelloWorldScene.cpp
#include "HelloWorldScene.h"
#include "GameOver.h"
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
/////////////////////////////
// 터치 활성화
this->setTouchEnabled(true);
// 어레이 초기화
targets = CCArray::createWithCapacity(20);
targets->retain();
BRICKS_HEIGHT = 4;
BRICKS_WIDTH = 5;
texture = CCTextureCache::sharedTextureCache()->addImage("Images/white-512x512.png");
// CCSprite* pMan2 = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 85, 121));
// 벽돌 초기화
this->initializeBricks();
// 공 초기화
this->initializeBall();
// 패들 초기화
this->initializePaddle();
// 2초후 게임 시작
CCFiniteTimeAction* action = CCSequence::create(
CCDelayTime::create(2),
CCCallFunc::create(this, callfunc_selector(HelloWorld::startGame)),
NULL);
this->runAction(action);
return true;
}
HelloWorld::~HelloWorld()
{
targets->release();
}
void HelloWorld::initializeBricks()
{
int count = 0;
for (int y = 0; y < BRICKS_HEIGHT; y++) {
for (int x = 0; x < BRICKS_WIDTH; x++) {
// CCSprite* bricks = CCSprite::create("Images/white-512x512.png");
//
// // 크기 지정
// bricks->setTextureRect(CCRectMake(0, 0, 64, 40));
CCSprite* bricks = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 64, 40));
// 색 지정
switch (count++ %4) {
case 0:
bricks->setColor(ccc3(255, 255, 255));
break;
case 1:
bricks->setColor(ccc3(255, 0, 0));
break;
case 2:
bricks->setColor(ccc3(255, 255, 0));
break;
case 3:
bricks->setColor(ccc3(75, 255, 0));
break;
default:
break;
}
// 좌표 지정
bricks->setPosition(ccp(x*64+32,(y * 40) + 280));
// 화면에 추가
this->addChild(bricks);
// 배열에 추가
targets->addObject(bricks);
}
}
}
void HelloWorld::initializeBall()
{
// ball = CCSprite::create("Images/white-512x512.png");
// ball->setTextureRect(CCRectMake(0, 0, 16, 16));
ball = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 16, 16));
ball->setColor(ccc3(0, 255, 255));
ball->setPosition(ccp(160,240));
this->addChild(ball);
}
void HelloWorld::initializePaddle()
{
// paddle = CCSprite::create("Images/white-512x512.png");
// paddle->setTextureRect(CCRectMake(0, 0, 80, 10));
paddle = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 80, 10));
paddle->setColor(ccc3(255, 255, 0));
paddle->setPosition(ccp(160,50));
this->addChild(paddle);
}
void HelloWorld::startGame()
{
ball->setPosition(ccp(160,240));
ballMovement = CCPointMake(4,4);
if (arc4random() % 100 < 50) {
ballMovement.x = -ballMovement.x;
}
ballMovement.y = -ballMovement.y;
isPlaying = true;
this->schedule(schedule_selector(HelloWorld::gameLogic), 2.0f/60.0f);
}
void HelloWorld::gameLogic(float dt)
{
// ballMovement.y가 음수이면 볼이 내려오고 있는 것.
// ballMovement.y가 양수이면 볼이 올라가고 있는 것.
//CCLog("tick..%f",ballMovement.y);
// 볼의 현재위치
ball->setPosition(ccp(ball->getPosition().x+ballMovement.x, ball->getPosition().y+ballMovement.y));
// 볼과 패들 충돌여부
bool paddleCollision =
ball->getPosition().y <= paddle->getPosition().y + 13 &&
ball->getPosition().x >= paddle->getPosition().x - 48 &&
ball->getPosition().x <= paddle->getPosition().x + 48;
// 패들과 충돌시 처리
if(paddleCollision) {
if (ball->getPosition().y <= paddle->getPosition().y + 13 && ballMovement.y < 0) {
ball->setPosition(ccp(ball->getPosition().x, paddle->getPosition().y + 13));
}
// 내려오던거 위로 올라가게 공의 상하 진행방향 바꾸기
ballMovement.y = -ballMovement.y;
}
// 블록과 충돌 파악
bool there_are_solid_bricks = false;
CCObject *Obj;
CCARRAY_FOREACH(targets, Obj) {
CCSprite *brick = (CCSprite*)Obj;
if (255 == brick->getOpacity()) {
there_are_solid_bricks = true;
CCRect rectA = ball->boundingBox();
CCRect rectB = brick->boundingBox();
if ( rectA.intersectsRect(rectB) ) {
// 블록과 충돌 처리
this->processCollision(brick);
}
}
}
// 블록이 없을 때 - 게임 종료 상태
if (!there_are_solid_bricks) {
isPlaying = false;
ball->setOpacity(0);
// 모든 스케쥴 제거
this->unscheduleAllSelectors();
CCLog("You win !!!");
// 게임에 이겼다. 새로운 게임 대기 화면...
CCScene* pScene = GameOver::scene();
CCDirector::sharedDirector()->replaceScene( CCTransitionProgressRadialCCW::create(1, pScene) );
}
// 벽면 충돌 체크
if (ball->getPosition().x > 312 || ball->getPosition().x < 8)
ballMovement.x = -ballMovement.x;
if (ball->getPosition().y > 450)
ballMovement.y = -ballMovement.y;
// if (ball.position.y <10) {
// ballMovement.y = -ballMovement.y;
// }
// 페달을 빠져 나갈 때
if (ball->getPosition().y < (50+5+8)) {
isPlaying = false;
ball->setOpacity(0);
// 모든 스케쥴 제거
this->unscheduleAllSelectors();
CCLog("You lose..");
// 게임에 졌다. 새로운 게임 대기 화면...
CCScene* pScene = GameOver::scene();
CCDirector::sharedDirector()->replaceScene( CCTransitionProgressRadialCCW::create(1, pScene) );
}
}
void HelloWorld::processCollision(CCSprite *brick)
{
CCPoint brickPos = brick->getPosition();
CCPoint ballPos = ball->getPosition();
if (ballMovement.x > 0 && brick->getPosition().x < ball->getPosition().x) {
ballMovement.x = -ballMovement.x;
} else if (ballMovement.x < 0 && brick->getPosition().x < ball->getPosition().x) {
ballMovement.x = -ballMovement.x;
}
if (ballMovement.y > 0 && brick->getPosition().y > ball->getPosition().y) {
ballMovement.y = -ballMovement.y;
} else if (ballMovement.y < 0 && brick->getPosition().y < ball->getPosition().y) {
ballMovement.y = -ballMovement.y;
}
brick->setOpacity(0);
}
void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent* event)
{
if (!isPlaying) {
return;
}
// 하나의 터치이벤트만 가져온다.
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->getLocation();
// 패들을 터치했는지 체크한다.
CCRect rect = paddle->boundingBox();
if (rect.containsPoint(touchPoint)) {
// 패들이 터치되었음을 체크.
isPaddleTouched = true;
} else {
isPaddleTouched = false;
}
// // 패들 sprite의 사이즈의 반을 계산합니다.
// float halfWidth = paddle->getContentSize().width / 2.0;
// float halfHeight = paddle->getContentSize().height / 2.0;
//
// // 터치된 위치가 패들 안에 들어오는 지 계산합니다.
// if (touchPoint.x >(paddle->getPosition().x + halfWidth) ||
// touchPoint.x <(paddle->getPosition().x - halfWidth) ||
// touchPoint.y <(paddle->getPosition().y - halfHeight) ||
// touchPoint.y >(paddle->getPosition().y + halfHeight) )
// {
// isPaddleTouched = false;
// } else {
// // 패들이 터치되었음을 체크.
// isPaddleTouched = true;
// }
}
void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent* event)
{
if(isPaddleTouched) {
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->getLocation();
// 패들이 좌우로만 움직이게 y값은 바꾸지 않는다.
// 또한 패들이 화면 바깥으로 나가지 않도록 한다.
if (touchPoint.x < 40) {
touchPoint.x = 40;
}
if (touchPoint.x > 280) {
touchPoint.x = 280;
}
CCPoint newLocation = ccp(touchPoint.x, paddle->getPosition().y);
paddle->setPosition(newLocation);
}
}
//GameOver.cpp
#include "GameOver.h"
#include "HelloWorldScene.h"
CCScene* GameOver::scene()
{
CCScene *scene = CCScene::create();
GameOver *layer = GameOver::create();
scene->addChild(layer);
return scene;
}
bool GameOver::init()
{
if ( !CCLayer::init() )
{
return false;
}
/////////////////////////////
CCSize s = CCDirector::sharedDirector()->getWinSize();
// 메뉴 아이템 생성 및 초기화
CCMenuItemFont* item1 = CCMenuItemFont::create("New Game",
this,
menu_selector(GameOver::doClose)
);
item1->setColor(ccc3(255, 255, 255));
// 메뉴 생성
CCMenu* pMenu = CCMenu::create( item1, NULL );
// 메뉴 위치
pMenu->setPosition(ccp(s.width / 2, s.height/2));
// 레이어에 메뉴 객체 추가
this->addChild(pMenu);
return true;
}
void GameOver::doClose(CCObject* pSender)
{
// 새로운게임을 시작하게 처음 신으로 이동
CCScene* pScene = HelloWorld::scene();
CCDirector::sharedDirector()->replaceScene( pScene );
}
//GameOver.h
#ifndef __BrickEx__GameOver__
#define __BrickEx__GameOver__
#include "cocos2d.h"
using namespace cocos2d;
class GameOver : public CCLayer
{
public:
virtual bool init();
static CCScene* scene();
CREATE_FUNC(GameOver);
void doClose(CCObject* pSender);
};
#endif /* defined(__BrickEx__GameOver__) */
'프로그래밍' 카테고리의 다른 글
단순 연결 리스트(수정) (0) | 2013.11.05 |
---|---|
희소행렬의 전치 연산 (0) | 2013.10.29 |
JAVA 파일 읽고쓰기 (0) | 2013.10.21 |
Java 데이터 타입 (0) | 2013.10.21 |
다항식의 덧셈 프로그램 (1) | 2013.10.15 |