SlideShare a Scribd company logo
{Programação de Jogos}
Bruno Cicanci @ TDC SP 2015
{Design Patterns}
● Command
● Flyweight
● Observer
● Prototype
● States
● Singleton
{Command: Problema}
void InputHandler::handleInput()
{
if (isPressed(BUTTON_X)) jump();
else if (isPressed(BUTTON_Y)) fireGun();
else if (isPressed(BUTTON_A)) swapWeapon();
else if (isPressed(BUTTON_B)) reloadWeapon();
}
http://gameprogrammingpatterns.com/command.html
{Command: Solução}
class Command
{
public:
virtual ~Command() {}
virtual void execute() = 0;
};
class JumpCommand : public Command
{
public:
virtual void execute() { jump(); }
};
void InputHandler::handleInput()
{
if (isPressed(BUTTON_X))
buttonX_->execute();
else if (isPressed(BUTTON_Y))
buttonY_->execute();
else if (isPressed(BUTTON_A))
buttonA_->execute();
else if (isPressed(BUTTON_B))
buttonB_->execute();
}
http://gameprogrammingpatterns.com/command.html
{Command: Uso}
● Input
● Undo
● Redo
{Flyweight: Problema}
class Tree
{
private:
Mesh mesh_;
Texture bark_;
Texture leaves_;
Vector position_;
double height_;
double thickness_;
Color barkTint_;
Color leafTint_;
};
http://gameprogrammingpatterns.com/flyweight.html
{Flyweight: Solução}
class TreeModel
{
private:
Mesh mesh_;
Texture bark_;
Texture leaves_;
};
class Tree
{
private:
TreeModel* model_;
Vector position_;
double height_;
double thickness_;
Color barkTint_;
Color leafTint_;
};
http://gameprogrammingpatterns.com/flyweight.html
{Flyweight: Uso}
● Milhares de instâncias
● Tile maps
{Observer: Problema}
void Physics::updateEntity(Entity& entity)
{
bool wasOnSurface = entity.isOnSurface();
entity.accelerate(GRAVITY);
entity.update();
if (wasOnSurface && !entity.isOnSurface())
{
notify(entity, EVENT_START_FALL);
}
}
http://gameprogrammingpatterns.com/observer.html
{Observer: Solução parte 1}
class Observer
{
public:
virtual ~Observer() {}
virtual void onNotify(const Entity& entity, Event event) = 0;
};
class Achievements : public Observer
{
public:
virtual void onNotify(const Entity& entity, Event event)
{
switch (event)
{
case EVENT_ENTITY_FELL:
if (entity.isHero() && heroIsOnBridge_)
{
unlock(ACHIEVEMENT_FELL_OFF_BRIDGE);
}
break;
}
}
}; http://gameprogrammingpatterns.com/observer.html
{Observer: Solução parte 2}
class Subject
{
private:
Observer* observers_[MAX_OBSERVERS];
int numObservers_;
protected:
void notify(const Entity& entity, Event event)
{
for (int i = 0; i < numObservers_; i++)
{
observers_[i]->onNotify(entity, event);
}
}
};
class Physics : public Subject
{
public:
void updateEntity(Entity& entity);
};
http://gameprogrammingpatterns.com/observer.html
{Observer: Uso}
● Achievements
● Efeitos sonoros / visuais
● Eventos
● Mensagens
● Expirar demo
● Callback async
{Prototype: Problema}
class Monster
{
// Stuff...
};
class Ghost : public Monster {};
class Demon : public Monster {};
class Sorcerer : public Monster {};
http://gameprogrammingpatterns.com/prototype.html
class Spawner
{
public:
virtual ~Spawner() {}
virtual Monster* spawnMonster() = 0;
};
class GhostSpawner : public Spawner
{
public:
virtual Monster* spawnMonster()
{
return new Ghost();
}
};
{Prototype: Solução parte 1}
class Monster
{
public:
virtual ~Monster() {}
virtual Monster* clone() = 0;
// Other stuff...
};
http://gameprogrammingpatterns.com/prototype.html
class Ghost : public Monster {
public:
Ghost(int health, int speed)
: health_(health),
speed_(speed)
{}
virtual Monster* clone()
{
return new Ghost(health_, speed_);
}
private:
int health_;
int speed_;
};
{Prototype: Solução parte 2}
class Spawner
{
public:
Spawner(Monster* prototype)
: prototype_(prototype)
{}
Monster* spawnMonster()
{
return prototype_->clone();
}
private:
Monster* prototype_;
}; http://gameprogrammingpatterns.com/prototype.html
{Prototype: Uso}
● Spawner
● Tiros
● Loot
{States: Problema}
void Heroine::handleInput(Input input)
{
if (input == PRESS_B)
{
if (!isJumping_ && !isDucking_)
{
// Jump...
}
}
else if (input == PRESS_DOWN)
{
if (!isJumping_)
{
isDucking_ = true;
}
} http://gameprogrammingpatterns.com/state.html
else if (input == RELEASE_DOWN)
{
if (isDucking_)
{
isDucking_ = false;
}
}
}
{States: Solução}
void Heroine::handleInput(Input input)
{
switch (state_)
{
case STATE_STANDING:
if (input == PRESS_B)
{
state_ = STATE_JUMPING;
}
else if (input == PRESS_DOWN)
{
state_ = STATE_DUCKING;
}
break;
http://gameprogrammingpatterns.com/state.html
case STATE_JUMPING:
if (input == PRESS_DOWN)
{
state_ = STATE_DIVING;
}
break;
case STATE_DUCKING:
if (input == RELEASE_DOWN)
{
state_ = STATE_STANDING;
}
break;
}
}
{States: Uso}
● Controle de animação
● Fluxo de telas
● Movimento do personagem
{Singleton: Problema}
“Garante que uma classe tenha somente uma instância
E fornecer um ponto global de acesso para ela”
Gang of Four, Design Patterns
{Singleton: Solução}
class FileSystem
{
public:
static FileSystem& instance()
{
if (instance_ == NULL) instance_ = new FileSystem();
return *instance_;
}
private:
FileSystem() {}
static FileSystem* instance_;
};
http://gameprogrammingpatterns.com/singleton.html
{Singleton: Uso}
“Friends don’t let friends create singletons”
Robert Nystrom, Game Programming Patterns
{Outros Design Patterns}
Double Buffer
Game Loop
Update Method
Bytecode
Subclass Sandbox
Type Object
Component
Event Queue
Service Locator
Data Locality
Dirty Flag
Object Pool
Spatial Partition
{Livro: Game Programming Patterns}
http://gameprogrammingpatterns.com
{Outros livros}
Física
Physics for Game Developers
Computação Gráfica
3D Math Primer for Graphics and Game
Game Design
Game Design Workshop
Level Up! The Guide to Great Game Design
Produção
The Game Production Handbook
Agile Game Development with Scrum
Programação
Code Complete
Clean Code
Programação de Jogos
Game Programming Patterns
Game Programming Algorithms and Techniques
Game Coding Complete
Inteligência Artificial
Programming Game AI by Example
{Blog: gamedeveloper.com.br}
{Obrigado}
E-mail: bruno@gamedeveloper.com.br
Twitter: @cicanci
PSN: cicanci42

More Related Content

PDF
Design Patterns in Game Programming
PPTX
Mvp - типичные задачи и способ их решения в Moxy
PDF
Tutorial Open GL (Listing Code)
PDF
The Ring programming language version 1.8 book - Part 12 of 202
PDF
The Ring programming language version 1.9 book - Part 14 of 210
PDF
Programming using opengl in visual c++
PPTX
Imagine a world without mocks
DOCX
VISUALIZAR REGISTROS EN UN JTABLE
Design Patterns in Game Programming
Mvp - типичные задачи и способ их решения в Moxy
Tutorial Open GL (Listing Code)
The Ring programming language version 1.8 book - Part 12 of 202
The Ring programming language version 1.9 book - Part 14 of 210
Programming using opengl in visual c++
Imagine a world without mocks
VISUALIZAR REGISTROS EN UN JTABLE

What's hot (20)

PDF
Kotlin Overview (PT-BR)
PDF
C++ game development with oxygine
PDF
Oxygine 2 d objects,events,debug and resources
DOC
Ip project
PPTX
Алексей Кутумов, Вектор с нуля
PDF
Алексей Кутумов, Coroutines everywhere
PDF
04 - Dublerzy testowi
PDF
My way to clean android V2
DOCX
Sumsem2014 15 cp0399-13-jun-2015_rm01_programs
PDF
The Ring programming language version 1.5.2 book - Part 53 of 181
PDF
Javascript, the GNOME way (JSConf EU 2011)
PDF
My way to clean android v2 English DroidCon Spain
PDF
The Ring programming language version 1.5.4 book - Part 70 of 185
PDF
Oop bai10
PDF
What's in Groovy for Functional Programming
PDF
meet.js - QooXDoo
PDF
The Ring programming language version 1.6 book - Part 73 of 189
PDF
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
PDF
The Ring programming language version 1.5.1 book - Part 52 of 180
DOCX
Student management system
Kotlin Overview (PT-BR)
C++ game development with oxygine
Oxygine 2 d objects,events,debug and resources
Ip project
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Coroutines everywhere
04 - Dublerzy testowi
My way to clean android V2
Sumsem2014 15 cp0399-13-jun-2015_rm01_programs
The Ring programming language version 1.5.2 book - Part 53 of 181
Javascript, the GNOME way (JSConf EU 2011)
My way to clean android v2 English DroidCon Spain
The Ring programming language version 1.5.4 book - Part 70 of 185
Oop bai10
What's in Groovy for Functional Programming
meet.js - QooXDoo
The Ring programming language version 1.6 book - Part 73 of 189
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
The Ring programming language version 1.5.1 book - Part 52 of 180
Student management system
Ad

Viewers also liked (6)

PDF
Design Patterns na Programação de Jogo
PDF
O fantástico mundo de Android
PDF
Desenvolvimento de jogos com Corona SDK
PPTX
Para quem você desenvolve?
PDF
Como (não) invadirem o seu banco de dados.
PDF
A Open Web Platform em prol do seu app!
Design Patterns na Programação de Jogo
O fantástico mundo de Android
Desenvolvimento de jogos com Corona SDK
Para quem você desenvolve?
Como (não) invadirem o seu banco de dados.
A Open Web Platform em prol do seu app!
Ad

Similar to Programação de Jogos - Design Patterns (20)

PDF
An Introduction to Game Programming with Flash: Design Patterns
PDF
Missilecommand
PDF
IntroToEngineDevelopment.pdf
PDF
Game Programming I - GD4N
PPTX
Game object models - Game Engine Architecture
PPTX
Soc research
PDF
Cocos2d programming
PPT
Gdc09 Minigames
PDF
Cocos2d 소개 - Korea Linux Forum 2014
PDF
Creating physics game in 1 hour
PDF
Real-Time 3D Programming in Scala
PDF
DOCX
ontents · Introduction· Objectives·.docx
PDF
C Game Programming Learn Game Programming With C Step By Step Very Easy Am Moh
PPT
Game development
PDF
building_games_with_ruby_rubyconf
PDF
building_games_with_ruby_rubyconf
PPTX
Initial design (Game Architecture)
PPTX
Design pattern part 2 - structural pattern
PDF
Game Programming Pattern by Restya
An Introduction to Game Programming with Flash: Design Patterns
Missilecommand
IntroToEngineDevelopment.pdf
Game Programming I - GD4N
Game object models - Game Engine Architecture
Soc research
Cocos2d programming
Gdc09 Minigames
Cocos2d 소개 - Korea Linux Forum 2014
Creating physics game in 1 hour
Real-Time 3D Programming in Scala
ontents · Introduction· Objectives·.docx
C Game Programming Learn Game Programming With C Step By Step Very Easy Am Moh
Game development
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
Initial design (Game Architecture)
Design pattern part 2 - structural pattern
Game Programming Pattern by Restya

More from Bruno Cicanci (8)

PDF
Optimizing Unity games for mobile devices
PDF
It's all about the game
PDF
Game Jams - Como fazer um jogo em 48 horas
PPTX
It’s all about the game
PPTX
Desenvolvimento de Jogos com Corona SDK
PPTX
Desenvolvimento de jogos com Cocos2d-x
PPTX
TDC 2012 - Desenvolvimento de Jogos Mobile
PDF
Desenvolvimento de Jogos Para Dispositivos Móveis - UFRJ - GECOM2011
Optimizing Unity games for mobile devices
It's all about the game
Game Jams - Como fazer um jogo em 48 horas
It’s all about the game
Desenvolvimento de Jogos com Corona SDK
Desenvolvimento de jogos com Cocos2d-x
TDC 2012 - Desenvolvimento de Jogos Mobile
Desenvolvimento de Jogos Para Dispositivos Móveis - UFRJ - GECOM2011

Recently uploaded (20)

PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
KodekX | Application Modernization Development
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPT
Teaching material agriculture food technology
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation theory and applications.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
20250228 LYD VKU AI Blended-Learning.pptx
KodekX | Application Modernization Development
“AI and Expert System Decision Support & Business Intelligence Systems”
Teaching material agriculture food technology
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Big Data Technologies - Introduction.pptx
cuic standard and advanced reporting.pdf
sap open course for s4hana steps from ECC to s4
Diabetes mellitus diagnosis method based random forest with bat algorithm
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation theory and applications.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Programação de Jogos - Design Patterns

  • 1. {Programação de Jogos} Bruno Cicanci @ TDC SP 2015
  • 2. {Design Patterns} ● Command ● Flyweight ● Observer ● Prototype ● States ● Singleton
  • 3. {Command: Problema} void InputHandler::handleInput() { if (isPressed(BUTTON_X)) jump(); else if (isPressed(BUTTON_Y)) fireGun(); else if (isPressed(BUTTON_A)) swapWeapon(); else if (isPressed(BUTTON_B)) reloadWeapon(); } http://gameprogrammingpatterns.com/command.html
  • 4. {Command: Solução} class Command { public: virtual ~Command() {} virtual void execute() = 0; }; class JumpCommand : public Command { public: virtual void execute() { jump(); } }; void InputHandler::handleInput() { if (isPressed(BUTTON_X)) buttonX_->execute(); else if (isPressed(BUTTON_Y)) buttonY_->execute(); else if (isPressed(BUTTON_A)) buttonA_->execute(); else if (isPressed(BUTTON_B)) buttonB_->execute(); } http://gameprogrammingpatterns.com/command.html
  • 6. {Flyweight: Problema} class Tree { private: Mesh mesh_; Texture bark_; Texture leaves_; Vector position_; double height_; double thickness_; Color barkTint_; Color leafTint_; }; http://gameprogrammingpatterns.com/flyweight.html
  • 7. {Flyweight: Solução} class TreeModel { private: Mesh mesh_; Texture bark_; Texture leaves_; }; class Tree { private: TreeModel* model_; Vector position_; double height_; double thickness_; Color barkTint_; Color leafTint_; }; http://gameprogrammingpatterns.com/flyweight.html
  • 8. {Flyweight: Uso} ● Milhares de instâncias ● Tile maps
  • 9. {Observer: Problema} void Physics::updateEntity(Entity& entity) { bool wasOnSurface = entity.isOnSurface(); entity.accelerate(GRAVITY); entity.update(); if (wasOnSurface && !entity.isOnSurface()) { notify(entity, EVENT_START_FALL); } } http://gameprogrammingpatterns.com/observer.html
  • 10. {Observer: Solução parte 1} class Observer { public: virtual ~Observer() {} virtual void onNotify(const Entity& entity, Event event) = 0; }; class Achievements : public Observer { public: virtual void onNotify(const Entity& entity, Event event) { switch (event) { case EVENT_ENTITY_FELL: if (entity.isHero() && heroIsOnBridge_) { unlock(ACHIEVEMENT_FELL_OFF_BRIDGE); } break; } } }; http://gameprogrammingpatterns.com/observer.html
  • 11. {Observer: Solução parte 2} class Subject { private: Observer* observers_[MAX_OBSERVERS]; int numObservers_; protected: void notify(const Entity& entity, Event event) { for (int i = 0; i < numObservers_; i++) { observers_[i]->onNotify(entity, event); } } }; class Physics : public Subject { public: void updateEntity(Entity& entity); }; http://gameprogrammingpatterns.com/observer.html
  • 12. {Observer: Uso} ● Achievements ● Efeitos sonoros / visuais ● Eventos ● Mensagens ● Expirar demo ● Callback async
  • 13. {Prototype: Problema} class Monster { // Stuff... }; class Ghost : public Monster {}; class Demon : public Monster {}; class Sorcerer : public Monster {}; http://gameprogrammingpatterns.com/prototype.html class Spawner { public: virtual ~Spawner() {} virtual Monster* spawnMonster() = 0; }; class GhostSpawner : public Spawner { public: virtual Monster* spawnMonster() { return new Ghost(); } };
  • 14. {Prototype: Solução parte 1} class Monster { public: virtual ~Monster() {} virtual Monster* clone() = 0; // Other stuff... }; http://gameprogrammingpatterns.com/prototype.html class Ghost : public Monster { public: Ghost(int health, int speed) : health_(health), speed_(speed) {} virtual Monster* clone() { return new Ghost(health_, speed_); } private: int health_; int speed_; };
  • 15. {Prototype: Solução parte 2} class Spawner { public: Spawner(Monster* prototype) : prototype_(prototype) {} Monster* spawnMonster() { return prototype_->clone(); } private: Monster* prototype_; }; http://gameprogrammingpatterns.com/prototype.html
  • 17. {States: Problema} void Heroine::handleInput(Input input) { if (input == PRESS_B) { if (!isJumping_ && !isDucking_) { // Jump... } } else if (input == PRESS_DOWN) { if (!isJumping_) { isDucking_ = true; } } http://gameprogrammingpatterns.com/state.html else if (input == RELEASE_DOWN) { if (isDucking_) { isDucking_ = false; } } }
  • 18. {States: Solução} void Heroine::handleInput(Input input) { switch (state_) { case STATE_STANDING: if (input == PRESS_B) { state_ = STATE_JUMPING; } else if (input == PRESS_DOWN) { state_ = STATE_DUCKING; } break; http://gameprogrammingpatterns.com/state.html case STATE_JUMPING: if (input == PRESS_DOWN) { state_ = STATE_DIVING; } break; case STATE_DUCKING: if (input == RELEASE_DOWN) { state_ = STATE_STANDING; } break; } }
  • 19. {States: Uso} ● Controle de animação ● Fluxo de telas ● Movimento do personagem
  • 20. {Singleton: Problema} “Garante que uma classe tenha somente uma instância E fornecer um ponto global de acesso para ela” Gang of Four, Design Patterns
  • 21. {Singleton: Solução} class FileSystem { public: static FileSystem& instance() { if (instance_ == NULL) instance_ = new FileSystem(); return *instance_; } private: FileSystem() {} static FileSystem* instance_; }; http://gameprogrammingpatterns.com/singleton.html
  • 22. {Singleton: Uso} “Friends don’t let friends create singletons” Robert Nystrom, Game Programming Patterns
  • 23. {Outros Design Patterns} Double Buffer Game Loop Update Method Bytecode Subclass Sandbox Type Object Component Event Queue Service Locator Data Locality Dirty Flag Object Pool Spatial Partition
  • 24. {Livro: Game Programming Patterns} http://gameprogrammingpatterns.com
  • 25. {Outros livros} Física Physics for Game Developers Computação Gráfica 3D Math Primer for Graphics and Game Game Design Game Design Workshop Level Up! The Guide to Great Game Design Produção The Game Production Handbook Agile Game Development with Scrum Programação Code Complete Clean Code Programação de Jogos Game Programming Patterns Game Programming Algorithms and Techniques Game Coding Complete Inteligência Artificial Programming Game AI by Example