SlideShare a Scribd company logo
1 of 27
Download to read offline
{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

What's hot

Sumsem2014 15 cp0399-13-jun-2015_rm01_programs
Sumsem2014 15 cp0399-13-jun-2015_rm01_programsSumsem2014 15 cp0399-13-jun-2015_rm01_programs
Sumsem2014 15 cp0399-13-jun-2015_rm01_programs
Abhijit Borah
 
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Techsylvania
 

What's hot (20)

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

Viewers also liked (6)

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

Similar to Programação de Jogos - Design Patterns

In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
anjandavid
 
how can i build this as problem 2 of my code #include iostream.pdf
how can i build this as problem 2 of my code #include iostream.pdfhow can i build this as problem 2 of my code #include iostream.pdf
how can i build this as problem 2 of my code #include iostream.pdf
mail931892
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
udit652068
 
Modified Code Game.java­import java.util.;public class Game.pdf
Modified Code Game.java­import java.util.;public class Game.pdfModified Code Game.java­import java.util.;public class Game.pdf
Modified Code Game.java­import java.util.;public class Game.pdf
galagirishp
 
Bowling Game Kata
Bowling Game KataBowling Game Kata
Bowling Game Kata
guest958d7
 
i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdf
petercoiffeur18
 
Java Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdfJava Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdf
aroramobiles1
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
fazilfootsteps
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
Yuren Ju
 
This is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdfThis is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdf
anjandavid
 
Bowling Game Kata in C# Adapted
Bowling Game Kata in C# AdaptedBowling Game Kata in C# Adapted
Bowling Game Kata in C# Adapted
Mike Clement
 
Bowling game kata
Bowling game kataBowling game kata
Bowling game kata
Carol Bruno
 
Bowling game kata
Bowling game kataBowling game kata
Bowling game kata
Joe McCall
 

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

In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
 
how can i build this as problem 2 of my code #include iostream.pdf
how can i build this as problem 2 of my code #include iostream.pdfhow can i build this as problem 2 of my code #include iostream.pdf
how can i build this as problem 2 of my code #include iostream.pdf
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
 
Modified Code Game.java­import java.util.;public class Game.pdf
Modified Code Game.java­import java.util.;public class Game.pdfModified Code Game.java­import java.util.;public class Game.pdf
Modified Code Game.java­import java.util.;public class Game.pdf
 
Bowling Game Kata
Bowling Game KataBowling Game Kata
Bowling Game Kata
 
Bowling Game Kata by Robert C. Martin
Bowling Game Kata by Robert C. MartinBowling Game Kata by Robert C. Martin
Bowling Game Kata by Robert C. Martin
 
Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3
 
Bowling Game Kata C#
Bowling Game Kata C#Bowling Game Kata C#
Bowling Game Kata C#
 
J2 me 07_5
J2 me 07_5J2 me 07_5
J2 me 07_5
 
i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdf
 
Java Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdfJava Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdf
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
 
Multimethods
MultimethodsMultimethods
Multimethods
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
 
Modern c++
Modern c++Modern c++
Modern c++
 
This is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdfThis is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdf
 
Bowling Game Kata in C# Adapted
Bowling Game Kata in C# AdaptedBowling Game Kata in C# Adapted
Bowling Game Kata in C# Adapted
 
Your Block class should exhibit the following features. Public child .pdf
 Your Block class should exhibit the following features. Public child .pdf Your Block class should exhibit the following features. Public child .pdf
Your Block class should exhibit the following features. Public child .pdf
 
Bowling game kata
Bowling game kataBowling game kata
Bowling game kata
 
Bowling game kata
Bowling game kataBowling game kata
Bowling game kata
 

More from Bruno Cicanci (8)

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

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

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