Message Bus vs Layered - message-queue

hoping for some advice on my architecture
Currently I used a layered architecture but somethings are getting a bit complex and was thinking a message bus would be far more useful
I have a controller action called "CreateTeam" on the TeamControler
Which fires of the to TeamService method CreateTeam and then also fires of to the PlayerService method "CreatePlayers".
Which means my TeamController method "CreateTeam" has two responsilibites
But when the user creates a team, I need players to be created also.
So would it be better that CreateTeam, also fires an event TeamCreated which was picked up elsewhere? Giving single responsibility and separating concerns?
Also, I have never used Message bus pattern before so hope im not confusing anyone but is it right that events are raised which the bus picks up and anything listening then gets? So this would be Tell don't ask?
And finally, the listeners on the message bus, could they be web api controllers? Rather then lots of seperate applications? So my PlayerController method with CreatePlayers, could be fired of when CreateTeamEvent is raised?

Somewhere in your system you have to have the knowledge (responsibility) embedded to call your 2 separate functions. The Servicebus could be used to do this but in my experience that would be an overly complex and more difficult to understand resolution.
I would stick with a layer (service class) as suggested by #S. Baggy.

Related

How to avoid tight coupling?

I have been trying to get my head around this problem for the last week and can't seem to find a solution that doesn't either require a singleton or tight coupling.
I am developing a 3D space game, an early demo of which is here...
www.sugarspook.com/darkmatters/demo.html
... and I'm getting to the point of adding Missions which the player will be able to select from the heads up display (Hud class).
The structure of the game is:
The Game class contains the Hud and the ObjectsList class.
The ObjectsList class contains various game Objects, including the Player, the various kinds of ship, planets, and Orbitals (space stations).
Missions get instantiated when the Player gets to within a certain distance of an Orbital.
Missions are added to a MissionsList class, itself within the ObjectsList.
Missions can become unavailable and expire without warning (as if they are selected by another pilot) so the list displayed on the Hud is dynamic and updated regularly.
Previously I've had the Missions dispatching events up to Game which in turn informs Hud of the change. This seems a little clunky to me, as there are various deeper 'levels' to the Hud that the information needs to be passed down to. I end up with a lot of the same functions all the way down the chain.
The solution I was thinking of involved injecting a reference to the MissionsList class into the Hud, enabling it to listen for updates from the Missonslist. I've heard that it's bad practise to mix the state of something with its display, but I don't see how else to get the 'live' list of Missions to the Hud. In contrast, if the Hud contains only display details without reference to the Mission object that generated those details, when a player selects a Mission from the Hud how can I determine which Mission has been chosen?
Is tight coupling in this case OK? Or should I use a singleton to communicate to the Hud?
If there is something fundamentally wrong with anything I'm suggesting I welcome being told what that is and what is the best solution.
Thanks.
Well the simple answer is why not couple via an intermediate interface?
interface IMissionList
{
ObservableCollection<IMission> Missions{get;}
}
Then in your Dependency Injection bind that to something that can resolve to a instance, singleton or constant or etc...
then inject it into your Hud's constructor
Hud(IMissionList missionList){}
Now you are loosely coupled to a contract, the implementation of-which can be changed at any point, so long as the implementation adheres to the contract. Also, due to injection your Hud only has to concern it self with using IMissionList rather than also finding it.
[Edit] Sorry, this is C#, but hopefully the idea is of use. See for actionscript interfaces and Dependency Injection for Actionscript

Starting with HTML5 Game Development - Very confused

I'd like to start developing a "simple" game with HTML5 and I'm quite confused by the many resources I found online. I have a solid background in development, but in completely different environments (ironically, I started programming because I wanted to become a game developer, and it's the only thing I've never done in 13 years...).
The confusion derives from the fact that, although I know JavaScript very well and I have some knowledge of HTML5, I can't figure out how to mix what I know with all this new stuff. For example, here's what I was thinking of:
The game would be an implementation of chess. I have some simple "ready made" AI algorithm that I can reuse for single player; the purpose here is to learn HTML5 game development, so this part is not very important at the moment.
I'd like build a website around the game. For this I'd use a "regular" CMS, as I know many of them already and it would be faster to put it up.
Then I'd have the game itself, which, in its "offline" version, has nothing to do with the website, as, as far as I understand, it would live in a page by itself. This is the first question: how to make the Game aware of User's session? The login would be handled by the CMS (it should be much easier this way, as User Managememt is already implemented).
As a further step, I'd like to move the AI to the server. This is the second question: how do I make the game send player's actions to the Server, and how do I get the answer back?
Later on, I'd like to bring a PVP element to the game, i.e. one-against-one multiplayer (like the good old chess). This is the third question: how to send information from a client to another, and keep the conversation going on. For this, people recommended me to have a look at Node.js, but it's one more element that I can't figure out how to "glue" to the rest.
Here's an example of a single action in a PVP session, which already gives me a headache: Player 1 sends his move to the Server (how does the game talk to Node.js?). I'd need to identify the Game Id (where and how should I store it?), and make sure the player hasn't manually modified it, so it won't interfere with someone else's game (how?).
I'm aware that the whole thing, as I wrote it, is very messy, but that's precisely how I feel at the moment. I can't figure out where to start, therefore any suggestion is extremely welcome.
Too many things and probably in the wrong order.
A lot of the issues don't seem to me to be particularly related to HTML5 in the first instance.
Start with the obvious thing - you want a single page (basically a javascript application) that plays chess, so build that. If you can't build that then the rest is substantially irrelevant, if you can build (and I don't doubt that you can) then the rest is about building on that capability.
So we get to your first question - well at the point at which you load the page you will have the session, its a web page, like any other web page, so that's how you get the session. If you're offline then you've persisted that from when you were online by whatever means - presumably local storage.
You want to move the AI to the server? Ok, so make sure that the front end user interaction talks to an "interface" to record the player moves and retrieve the AI moves. Given this separation you can replaces the AI on the client with an ajax (although I'd expect the x to be json!) call to the server with the same parameters.
This gets better, if you want to do player to player you're just talking about routing through the server from one user/player to another user/player - the front end code doesn't have to change, just what the server does at the far end of the ajax call.
But for all this, take a step back and solve the problems one at a time - if you do that you should arrive where you want to go without driving yourself nuts trying to worry about a bucket full of problems that seem scary that you can probably easily solve one at a time and I'd start by getting your game to run, all on its own, in the browser.
About question one: You could maybe give the user a signed cookie. E.g. create a cookie that contains his userid or so and the SHA2 hash of his userid plus a secret, long salt (e.g. 32 bytes salt or so).
About question two: For exchanging stuff and calling remote functions, I'd use the RPC library dnode.
About question three: Use the same thing for calling methods between clients.
Client code (just an example):
DNode.connect(function (remote) {
this.newPeer = function(peer) {
peer.sendChatMessage("Hello!");
};
});
You don't have to use game IDs if you use dnode - just hand functions to the browser that are bound to the game. If you need IDs for some reason, use a UUID module to create long, random ones - they're unguessable.

Component Based Architecture in game development

I have been thinking of trying out component based architecture for game development. I have read some blog posts and articles about it but I have a few things I have not sorted out yet. When I say component based I mean that you can add components to a ComponentManager that updates all components in its list. I want to try this to avoid getting classes that inherits variables and functions that they don´t need. I really like the idea of having an really simple entity class with a lot of components working side by side without getting bloated. Also, it is easy to remove and add functionality at runtime wich makes it really cool.
This is what I am aiming for.
// this is what the setup could be like
entity.componentManager.add(new RigidBody(3.0, 12.0));
entity.componentManager.add(new CrazyMagneticForce(3.0));
entity.componentManager.add(new DrunkAffection(42.0, 3.0));
// the game loop updates the component manager which updates all components
entity.componentManager.update(deltaTime);
Communication: Some of the components need to communicate with other components
I can´t rely on the components to be self-sustaining. Sometime they will need to communicate with the other components. How do I solve this? In Unity 3D, you can access the components using GetComponent().
I was thinking of doing it like this, but what happens if you have two components of the same type? Maybe you get a Vector back.
var someComponent : RigidBody = _componentManager.getComponent(RigidBody);
Priority: Some components need to update before others
Some components need to update before others to get the correct data for the current game loop. I am thinking of adding a PRIORITY to each component, but I am not sure that this is enough. Unity uses LateUpdate and Update but maybe there is a way to get an even better control of the order of execution.
Well, thats it. If you have any thoughts don´t hesitate to leave a comment. Or, if you have any good articles or blogs about this I will gladly take a look at them. Thanks.
Component based game engine design
http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
EDIT:
My question is really how to solve the issue with priorities and communication between the components.
I settled for an RDMBS component entity system http://entity-systems.wikidot.com/rdbms-with-code-in-systems#objc
It is so far working really well. Each component only holds data and has no methods. Then I have subsystems that process the components and do the actual work. Sometimes a subsystem needs to talk to another and for that I use a service locator pattern http://gameprogrammingpatterns.com/service-locator.html
As for priorities. Each system is processed in my main game loop and so it is just a matter of which gets processed first. So for mine I process control, then physics, then camera and finally render.

Stateless vs Stateful

I'm interested in articles which have some concrete information about stateless and stateful design in programming. I'm interested because I want to learn more about it, but I really can't find any good articles about it. I've read dozens of articles on the web which vaguely discuss the subject, or they're talking about web servers and sessions - which are also 'bout stateful vs stateless, but I'm interested in stateless vs stateful design of attributes in coding. Example: I've heard that BL-classes are stateless by design, entity classes (or at least that's what I call them - like Person(id, name, ..)) are stateful, etc.
I think it's important to know because I believe if I can understand it, I can write better code (e.g. granularity in mind).
Anyways, really short, here's what I know 'bout stateful vs stateless:
Stateful (like WinForms): Stores the data for further use, but limits the scalability of an application, because it's limited by CPU or memory limits
Stateless (Like ASP.NET - although ASP tries to be stateful with ViewStates):
After actions are completed, the data gets transferred, and the instance gets handed back to the thread pool (Amorphous).
As you can see, it's pretty vague and limited information (and quite focussed on server interaction), so I'd be really grateful if you could provide me with some more tasty bits of information :)
Stateless means there is no memory of the past. Every transaction is performed as if it were being done for the very first time.
Stateful means that there is memory of the past. Previous transactions are remembered and may affect the current transaction.
Stateless:
// The state is derived by what is passed into the function
function int addOne(int number)
{
return number + 1;
}
Stateful:
// The state is maintained by the function
private int _number = 0; //initially zero
function int addOne()
{
_number++;
return _number;
}
Refer from: https://softwareengineering.stackexchange.com/questions/101337/whats-the-difference-between-stateful-and-stateless
A stateful app is one that stores information about what has happened or changed since it started running. Any public info about what "mode" it is in, or how many records is has processed, or whatever, makes it stateful.
Stateless apps don't expose any of that information. They give the same response to the same request, function or method call, every time. HTTP is stateless in its raw form - if you do a GET to a particular URL, you get (theoretically) the same response every time. The exception of course is when we start adding statefulness on top, e.g. with ASP.NET web apps :) But if you think of a static website with only HTML files and images, you'll know what I mean.
I suggest that you start from a question in StackOverflow that discusses the advantages of stateless programming. This is more in the context of functional programming, but what you will read also applies in other programming paradigms.
Stateless programming is related to the mathematical notion of a function, which when called with the same arguments, always return the same results. This is a key concept of the functional programming paradigm and I expect that you will be able to find many relevant articles in that area.
Another area that you could research in order to gain more understanding is RESTful web services. These are by design "stateless", in contrast to other web technologies that try to somehow keep state. (In fact what you say that ASP.NET is stateless isn't correct - ASP.NET tries hard to keep state using ViewState and are definitely to be characterized as stateful. ASP.NET MVC on the other hand is a stateless technology). There are many places that discuss "statelessness" of RESTful web services (like this blog spot), but you could again start from an SO question.
The adjective Stateful or Stateless refers only to the state of the conversation, it is not in connection with the concept of function which provides the same output for the same input. If so any dynamic web application (with a database behind it) would be a stateful service, which is obviously false.
With this in mind if I entrust the task to keep conversational state in the underlying technology (such as a coockie or http session) I'm implementing a stateful service, but if all the necessary information (the context) are passed as parameters I'm implementing a stateless service.
It should be noted that even if the passed parameter is an "identifier" of the conversational state (e.g. a ticket or a sessionId) we are still operating under a stateless service, because the conversation is stateless (the ticket is continually passed between client and server), and are the two endpoints to be, so to speak, "stateful".
Money transfered online form one account to another account is stateful, because the receving account has information about the sender.
Handing over cash from a person to another person, this transaction is statless, because after cash is recived the identity of the giver is not there with the cash.
Just to add on others' contributions....Another way is look at it from a web server and concurrency's point of view...
HTTP is stateless in nature for a reason...In the case of a web server, being stateful means that it would have to remember a user's 'state' for their last connection, and /or keep an open connection to a requester. That would be very expensive and 'stressful' in an application with thousands of concurrent connections...
Being stateless in this case has obvious efficient usage of resources...i.e support a connection in in a single instance of request and response...No overhead of keeping connections open and/or remember anything from the last request...
We make Webapps statefull by overriding HTTP stateless behaviour by using session objects.When we use session objets state is carried but we still use HTTP only.
I had the same doubt about stateful v/s stateless class design and did some research. Just completed and my findings has been posted in my blog
Entity classes needs to be stateful
The helper / worker classes should not be stateful.

Synchronize Changes To A Textfield

I'm experimenting with P2P on Flash, and I've come across a little hurdle that I'd like to clarify before moving forward. The technology itself (Flash) doesn't matter for this problem, as I think this problem occurs in other languages.
I'm trying to create a document that can be edited "live" by multiple people. Just like Google Docs pretty much. But I'm wondering, how would you suggest synchronizing everyone's text? I mean, should I message everyone with all the text in the text field every time someone makes a change? That seems very inefficient.
I'm thinking there has to be a design pattern that I can learn and implement, but I'm not sure where to start.
Optimally, the application should send the connected clients only the changes that have occurred to the document, and have some sort of buffer or error correction that can be used for retrieving earlier changes that may have been missed. Is there any established design pattern that deals with this type of issue?
Thanks,
Sandro
I think your "Optimally" solution is actually the one you should go for.
each textfield has a model, the model has a history (a FILO storing last, let's say, 10 values).
every time you edit that textfield you push the whole text into the model and send the delta to other connected clients.
as other clients receive the data they just pick the last value from the model and merge it to the received data.
you can refine the mechanism by putting an idle timer in the middle: as a user types something in the textfield you flag that model as "toBeSentThroughTheNet" and you start a timer. as the timer "ticks" (TimerEvent.TIMER) you stop it, collect the flagged data and send it to other clients. just remember to reset the timer everytime the user is actually typing (a semplification coul be keydown = reset, keyup = start).
one more optimization could be send the data packed in a compressed bytearray, but this requires you write your own protocol and may be not so an easy and quick path :)
If the requirement is that everyone can edit the document at the same time and the changes should be propagated to everyone and no changes should be lost, then it is a non-trivial problem. There are few different approaches out there, but one that is quite robust is Operational Transformation. This is the same algorithm that Google Docs uses for collaborative editing.
Understanding and Applying Operational Transformation and the attendant hacker news discussion are probably other good places to start.
The Wave Protocol was released as open source so you can take a look on how it is implemented.
You could of course forgo the tricky synchronization and just allow people to take turns and only one person can edit the document at a time and this person just pushes the changes to the remainder of the group.