Jump to content
  • Advertisement
Luhan M.

Command Pattern Review

Recommended Posts

I tried to implement the command pattern explained in this book : http://gameprogrammingpatterns.com/command.html. I'm looking up for someone which could revise my code and see if I did implement it the right way, or even if I did deviate a lot from how it should be implemented.

Here's the code : https://github.com/Luhanmacedo/Command-Pattern  

Questions:

  1. I didn't understand if the base class (Command) could be modified to introduce methods as I did to facilitate implementation details in the derived classes.
  2. What would be a good way to map the buttons according to the configuration the player wants to use, such as X for Jump and Y to shoot.

 

P.S. :  If it's not possible to review the whole code, tips in some parts are welcome as well.

Edited by Luhan M.

Share this post


Link to post
Share on other sites
Advertisement
22 hours ago, Luhan M. said:

I tried to implement the command pattern explained in this book : http://gameprogrammingpatterns.com/command.html. I'm looking up for someone which could revise my code and see if I did implement it the right way, or even if I did deviate a lot from how it should be implemented.

Here's the code : https://github.com/Luhanmacedo/Command-Pattern  

Questions:

  1. I didn't understand if the base class (Command) could be modified to introduce methods as I did to facilitate implementation details in the derived classes.
  2. What would be a good way to map the buttons according to the configuration the player wants to use, such as X for Jump and Y to shoot.

 

P.S. :  If it's not possible to review the whole code, tips in some parts are welcome as well.

I was just looking quickly at the link, are you talking about just remapping 4 buttons on a game pad while still being able to operate the following actions (example):

A = Jump

B = Shoot

X = Potion

Y = Melee Attack

There are several ways to do this.

Assume you have an event manager that checks for those four buttons:

If A is Pressed -> aButton pressed is now True (will execute code outside of events)

If B is Pressed -> bButton pressed is now True (will execute code outside of events)

If X is Pressed  -> xButton pressed is now True (will execute code outside of events)

If Y is Pressed  -> yButton pressed is now True (will execute code outside of events)

And your action ids are:

Jump = 1

Shoot = 2

Potion = 3

Melee Attack = 4

You would simply map IDs to each Button.

So by default A = Jump which means A will return ID 1. If we set Shoot for A, A will return the ID 2. You can just make a object for Button, and make a function that sets the ID and gets the ID.

In our logic loop we would see if an action is pending.

if (aButton.isPressed()) {
	player1.doAction(aButton.getId());
  	aButton.togglePressed(); // Just means aButton bool pressed = !pressed
}

In your player code for doAction() you would just reference the method based on the ID

void Player::doAction(int id) {
  if (id == 1) { 
    jump(); 
  } 
  else if (id == 2) { 
    shoot(); 
  }

ect….

There are different approaches you can use to solve the same problem. I find a lot of books very "dry" and they don't explain in layman's terms well enough.

Is this what you were looking for?

 

Share this post


Link to post
Share on other sites

You are doing something a little unorthodox here, by having distinct command objects, but then boiling them back down to an enum at the back end and having specialised behaviour based on both the command object and the enum.

I'd advise sticking to one or the other. Either make command objects be pure data, and use the giant enum/switch on the backend to process them in their entirety, or encapsulate all the necessary logic in the methods invoked by the command objects. Both are reasonable strategies, although the former will result in less tight coupling than the latter.

Share this post


Link to post
Share on other sites

@Rutin Thanks, that was one of my questions, and it's very clear for me now. About the books, what way you did learn some of the patterns?

 

33 minutes ago, swiftcoder said:

You are doing something a little unorthodox here, by having distinct command objects, but then boiling them back down to an enum at the back end and having specialised behaviour based on both the command object and the enum.

I'd advise sticking to one or the other. Either make command objects be pure data, and use the giant enum/switch on the backend to process them in their entirety, or encapsulate all the necessary logic in the methods invoked by the command objects. Both are reasonable strategies, although the former will result in less tight coupling than the latter.

@swiftcoder So what I'm actually making is a base class which is focused only in these two objects: MoveUp and MoveDown right?

Just to make sure I understood the second way to do it, it's means the object in this case (MoveUp and MoveDown) would have all the methods and the necessary logic to execute the action?

P.S. : Thank you for taking the time to read my code.

Share this post


Link to post
Share on other sites
10 minutes ago, Luhan M. said:

what way you did learn some of the patterns?

Patterns are... not as important as books/courses might lead you think. It's pretty rare to see someone explicitly use a pattern per se. Its more about learning to recognise the shape of common solutions to problems.

For example, the command pattern is mostly about decoupling the source of some events from the target of those events. That's a useful thing in a number of situations, but there are many ways to accomplish it.

13 minutes ago, Luhan M. said:

So what I'm actually making is a base class which is focused only in these two objects: MoveUp and MoveDown right?

You can do it that way, yes. That's the way the article you linked did it.

14 minutes ago, Luhan M. said:

it's means the object in this case (MoveUp and MoveDown) would have all the methods and the necessary logic to execute the action?

Well, no. The actual logic probably lives in an object responsible for running the game simulation. The command objects are just inputs t that logic. You can either have the command objects wrap calls to the simulation object (as the article does), or have them contain data that the simulation object inspects.

Share this post


Link to post
Share on other sites
26 minutes ago, swiftcoder said:

Well, no. The actual logic probably lives in an object responsible for running the game simulation. The command objects are just inputs t that logic. You can either have the command objects wrap calls to the simulation object (as the article does), or have them contain data that the simulation object inspects.

I think I understand now.

27 minutes ago, swiftcoder said:

Patterns are... not as important as books/courses might lead you think. It's pretty rare to see someone explicitly use a pattern per se. Its more about learning to recognise the shape of common solutions to problems.

I started studying about patterns because I see a lot people saying that everybody should use state machine, update (), etc, and after a light read about these, I thought they would facilitate to implement a game as you get further in the development

Share this post


Link to post
Share on other sites
31 minutes ago, Luhan M. said:

...I see a lot people saying that everybody should use state machine...

/slightly offtopic: state machines are an extremely useful way of looking at problems. I wouldn't typically classify them as design patterns though - they predate the whole object oriented thing :)

Certainly nothing wrong with learning design patterns, they illustrate useful approaches to problem solving. I'm just providing a light warning, because programmers tend to go through a phase where they rigidly apply design patterns to every problem they see, and over time you'll find that not everything fits such a rigid methodology.

Share this post


Link to post
Share on other sites

  • Advertisement
  • Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By Luca Falco
      https://www.youtube.com/watch?v=UMoc52DEoC8     ABOUT THE GAME: Room54 is a first-person Horror/adventure  Videogame for pc,mac and linux users. the game is currently under development by a very small team, we put so much effort in this project and we are keep doing our best for that we are going to launch a kickstarter campaing in order to reach our ideal budget to complete the project, we hope the GameDev community can help us a lot                      STORY:   Daniel is a family father like many other, one day he decide with your wife and his daughter  to spend her winter holidays at their mountain house that they have recently buy in  mountain ,a  wonderful place surrounded by the nature of the woods,  Completely far away from the caotic city life. During their holidays Daniel and his family will understand that they are not welcome there and they will discover an  hided and disturbing part of the valley that they have never seen before                       GAMEPLAY:   You will play as Daniel, a father that will try to save his family, your gameplay will be focused on discovering secrets places around valley,investigating and trying to survive, you will find object that will help you solve enigma and to stay alive. The immersive audio and  environment will make you feel constantly follow by an high anxiety dose  during the game.                         SOCIAL PAGES:     Follow us to get the latest development news and insights     IndieDB:     http://www.indiedb.com/games/room54   Twitter:       https://twitter.com/Room54Thegame   facebook:   https://www.facebook.com/Room54/
    • By SickTwistGames
      Ok, firstly, Hi.
       
      This is my first post on this forum. I am an Indie Dev making my first game so bear with me when I say dumb stuff, I'm on a huge learning curve.
       
      My first question is about inventory systems for unity. I am trying to make a survival type game with crafting. I have purchased Inventory manager pro by devdog from the unity asset store and it seems like a pretty powerful assett but for an intermediate coder its a little tough to use.  I'm beginning to wonder if it was the right purchase.
      So my question is.... does anyone have any experience of inventory plugins / systems for unity and can anyone reccomend a system to me?
      It needs to have the following: Loot system, crafting system, character sheet, blueprint system,  character stats system. Ideally with as little coding as possible.
       
      Thanks
    • By Gnollrunner
      Hi again,  After some looking around I have decided to base my game directly on Direct X rather than using an existing game engine.  Because of the nature of the stuff I'm doing it just didn't seem to fit very well and I kept running into road blocks.  At this point I have a big blob of code for doing fractal world generation and some collision code,  and I'm trying to put it into some form that resembles a game engine.  Since I've never used one before It's a bit alien to me ..... so can someone direct me to a book, website, article, whatever... that covers this?  I'm mainly looking for stuff that covers C++ library design. I'm not adverse to using 3rd party tools for stuff I can used them for.
    • By tones31
      Hello. I am looking for an unpaid, hobbiest game developer to help me continue to work on a fully functional game prototype built in PlayCanvas that I have built as a hobby. I intend to release and monetize the game once it is complete.
      About the Game
      The game is entitled "Battle Runes."  It is some strange mixture of scrabble and word search, but instead of English letters it uses Viking runes. Each rune represents an English letter. The game takes place on a board, which is a grid of any size (4x4 for example). Not all squares on the grid are required to exist (there can be holes) but there can never be an incomplete path from one square to the other. The game starts with all squares on the board populated by random Runes. The player clicks and drags Runes around the board from one square to the other, costing them "moves" in the process. Runes can also be stacked vertically if they are the same, which adds both literal and figurative depth to the game. The main point-scoring mechanic is to create English words (like "war", "hello", "sky", etc...) using the viking Runes. Words are automatically found by the game using any of the 8 cardinal directions, just like a word search. Points are rewarded to the player for each word they create, and they get bonus points if a word has extra Runes stack on top.
      History
      The current PlayCanvas prototype is actually the third revision of this game, but it is the one that has made the most progress. The first two revisions were in Unity, and were actually multiplayer games. I abandoned Unity when I found PlayCanvas and ended up rewriting the entire thing in a few weeks versus the few months it took me with Unity. Obviously the advantage was Javascript.
      Who Am I
      I am a full time software developer with a job at an engineering firm. I code daily in C, C++, Javascript, and PHP. I am a full stack developer, creating UI, and backends on Linux, Windows, and even embedded devices (hence the C and C++). I had no idea how to program 5 years ago, and have been learning every language I can get my hands on since. I have worked my way up in my company from a software tester to my current full stack position. 

      I went to game design school about 10 years go to be an artist, so I also have a lot of 3D and 2D experience. But I rarely do that anymore, hence the amazing artwork you will see in the below screenshots. Eventually I will find an artist to replace all prototype assets.

      Why I Need You
      The game concept came from a good friend of mine who, at some point, was heavily involved in the design of the game. He has since floated away from the picture. As I enjoy focusing on programming mechanics, I need someone to help me continue to define the game, including at least a few major modifications. Currently, the game is functional. You can actually win in Adventure Mode or play "forever" in Arcade Mode. The problem is.. the game isn't really that fun. I played a lot of Farm Hero and Juice Jam, and these games kept me coming back because of the challenge and allure. Currently, the game is challenging, but mostly out of bad design. It also feels like the game is really missing some core mechanics. 
      Thus, I am looking for someone who wants to spend time playing the game and figuring out some new mechanics, major or minor, to implement. This must be more than "you should make it like this game.." I am looking for someone who really wants to develop a fun game.
      You Are a Good Fit If...
      1. You really enjoy the design aspect of game development
      2. You have original ideas, but know how to borrow existing mechanics from good games
      3. You have 2-5 hours per week to analyze the game, discuss ideas via voice chat, and create a technical document for the game mechanics
      4. You have strong writing skills (technically) 
      Bonuses
      Strong story writing skills for Adventure Mode
      Private PlayCanvas account
      Screenshots
      I always hesitate to share the game outright, because literally all the source code can be stolen when using PlayCanvas. I currently have a private account on PlayCanvas to protect this, but will share a temporary public version for those interested by PM only. So here are some screenshots (please enjoy the prototype models and art :] )

      Screenshot 1
      Level 1 starts out with an easy board. Currently, the player is trying to create the word "air" as represented by the secondary word board. Lots of "i"s available. One "a". But no "r"s. In order to get an "r", the player will have to start stacking similar Runes on top of each other to free up space. New Runes fall from the sky to fill empty squares!


      Screenshot 2
      As an example of the main mechanic, dragging and dropping Runes around, the player has clicked the "s" and has swapped it with the "i" (for no real reason..!). Without committing the move, the game has given the player a preview of what would happen if they swapped the "s" and "i".


      Screenshot 3
      In this screenshot, you can see Rune stacking in effect. The player has stacked a bunch of "i"s on top of each other... there's no limit, and it can get pretty funny when you stack lots of runes (queue gravity!).


      Screenshot 4
      Arcade Mode produces completely random boards, but ensures that there are no unreachable squares, thanks to a really amazing JS pathfinding library. You can actually see the pathfinding library in action (follow the blue highlights). Currently the player has swapped the "g" (looks like  <>) and the "b". The pathfinding highlights all the moves the player would have to make if they could only move a Rune one square at a time. This swap will cost 6 moves. Thankfully the pathfinding library finds the shortest path!!

       
      Thank you for reading this far. Please PM or reply here if you would like more information.
    • By Lode
      Hi,
      I'd like to present LogicEmu, a new logic circuit emulator working in the browser:
      http://lodev.org/logicemu/
      It's somewhat different from most logic circuit emulators, because it's cell based and internally with 2D ASCII diagrams, and it comes with a huge ton of circuits prebuilt which can be immediately selected from dropdowns to try out all kinds of cool stuff!
      How is it related to gamedev? It's an educational game, it's also vaguely like minecraft redstone, and may be useful for developing/testing/verifying such circuitry engines in games. It's open source on github to see how it works.
      Please let me know any feedback. Suggestions, bugs, overall impressions, critique, ... are all super welcome
      Thanks!

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!