Local multiplayer in XNA - xna

Is there any tutorial or sample on how to create a local multiplayer in an XNA game(Windows)?
I often see tutorials for networking game but never on how to enter a second player. How to ask the second player to sign in, to use the same object but with different controller...
Thanks.

I've not come across any tutorials, but I can outline some basic ideas for you.
If all of your players will be identical:
Modify your 'player' objects constructor to have a parameter for some playerIndex. When checking for input inside the player class, use this index. That way, you can create a bunch of 'players' without needing to write individual classes for each. You can then write general-purpose code like:
if (inputManager.IsMoveRight(playerIndex))
{
// do some stuff etc.
}
This will require some modifications to your input management structure. You should be aiming to generalise the code you already have.
If each player will have completely different implementations:
You'll need to take advantage of polymorphism in this case. If each player should select their character in a menu screen, you'll need to have some attribute in the player class that holds their chosen character (Note: If each player should be a preset default, i.e player 1 is always mario, player 2 is always sonic, it would probably be best to subclass your player class for each player). This attribute could be moved up a layer and stored in a 'controller' class if you wanted.
Menu logic:
Handling player sign-ins is really best done before any levels are loaded. I'm going to assume that you don't need players to drop in/out during the game. Basic outline:
When the game is in a character selection screen (or just the main menus) check for input from all controllers. If a controller presses 'start', sign them in. This could involve simply adding a playerIndex to an array for example. Then, when the game loads, check the array for active players and spawn any that are found.
Character selection can be implemented in very much the same way, although you'd probably want a specific menu sign-in screen. Check for input from active players during the sign in screen and allow them to scroll through and select a character. Store the result somewhere (player or controller class for example).
Other things to consider:
Are getting input from the keyboard as well as gamepads? If this is the case, it might be easier to default the keyboard to player one, and only allow sign in/out from gamepads.
I mentioned this before, but you will need to generalise your input management to prevent a major case of spaghetti code. In order for any of this to work, you should not be checking previous/current controller states from directly within your player class. The MSDN Game State Management sample is worth examining as it uses a similar system.
This isn't a very comprehensive guide, but hopefully I've raised some points for you to consider.

Related

Clean Architecture - Robert Martin - How to connect use cases

I'm trying to implement the Clean Architecture described by Robert Martin.
More specifically I'm using VIPER which is an iOS version of Clean Architecture.
The problem I have is as follows:
The user starts looking at a map with places (pins) on it.
If he clicks a button, a pin is dropped and he is taken to another view to create (or edit if it was a click to an existent pin) the place (or cancel).
In this other view, the user can edit the place's information and then click "back" or "done" (or "edit").
If he clicks "done", the PlaceDetailsViewController sends a message to the PlaceDetailsPresenter with the place information and the PlaceDetailsPresenter uses the CreatePlaceInteractor to create the place. This interactor returns the GUID which is used to identify the place.
If the user clicks back before creating the place, he gets back to the map and the dropped pin goes up and away (since it has no GUID, it is a new place and goes away).
If he clicks back after creating, the pin stays there (because it should have a GUID).
How should I connect all that and where should the place information (including GUID) be stored?
To clarify a little bit more:
Who should inform the MapPresenter that the pin stays there or goes away?
Is it the PlaceDetailsPresenter or should I pass this information to the PlaceDetailsWireframe -> MapWireframe -> MapPresenter -> MapView ?
Before going back, where should this GUID be stored, in the PlaceDetailsPresenter or in the PlaceDetailsViewController?
Right now that's what I have:
EDIT:
Basically I think the problem is that VIPER came from Robert Martin's Clean Architecture and he comes from a Web (Rails) background, so he doesn't think much about state (or don't specify it in his talks).
Which is mainly my question, where should the state be stored, how should the different modules communicate, should it be through the Wireframe, or through the database, or through the interactors, or through the Presenters communicating with each other like here https://github.com/objcio/issue-13-viper-swift.
I don't know much about Viper, so I can't comment about that. However, the gross state of the system should be held in the entity objects and manipulated by the interactors. The detailed state of the GUI (selection rectangles, etc) should be managed by a special connection between the controller and the presenter.
In your case there are two screens. The map, and the place editor. Clicking on the map causes either the placePinController to be invoked. It gathers the location of the click, and any other contextual data, constructs a placePinRequest data structure and passes it to the PlacePinInteractor which checks the location of the pin, validates it if necessary, create a Place entity to record the pin, constructs a EditPlaceReponse object and passes it to the EditPlacePresenter which brings up the place editor screen.
If the Done button is clicked on the place editor screen it invokes the EditPlaceController which gathers up the edited data into an EditPlaceRequest data structure and passes it to the EditPlaceInteractor. etc..
You specifically asked about the GUID of the pin. That would be created by the Place entity and passed back to the editPlacePresenter PlacePinInteractor.
In pure VIPER Router should hold modules input in form of a protocol. And modules Presenter should conform to it. So when Router uses other modules Router to assemble new module it passes it's input to it.
The second Router then assigns the input to its Presenters output. So basically Presenter of the first module becomes a delegate for the second modules Presenter.
So in your case when a user selects a place MapPresenter asks MapInteractor for a GUID and tells MapRouter to navigate to details for this GUID.
MapRouter asks PlaceDetailsRouter to assemble PlaceDetailsModule for this GUID and passes MapModuleInput to it. PlaceDetailsRouter assigns MapModuleInput to PlaceDetailsPresenter. PlaceDetailsRouter puts GUID in the PlaceDetailsInteractor

Fragments and ViewModels

I am trying to have a single activity with a dynamically created fragment within its view.
I have a ActivityViewModel and a FragmentViewModel and matching views and layouts (ActivityView has a FrameLayout to host fragment). The fragment is shown by calling ShowViewModel<> from within ActivityViewModel.Start method.
I am using a CustomePresenter as described in http://enginecore.blogspot.ro/2013/06/more-dynamic-android-fragments-with.html.
It works fine from cold start and after resume. However, it won't work after activity is destroyed.
This is the sequence that happens in this problematic situation:
Activity is created, Mvx finds a cached ViewModel and attaches it to the Activity. Since ViewModel was cached it won't fire Start method (which triggers fragement creation). That's fine. But in next step Android recreates the fragment but it won't get its associated ViewModel because neither CustomPresenter (which takes care of that when fragment is created) or MvxFragment.OnCreate won't create it - like MvxActivity mechanism does. And thus I get a ViewModel-less fragment.
So I wonder, shouldn't be good if MvxFragemnt creates its own ViewModel upon create like MvxActivity does? Furthermore it should handle Save,Resume (call to adjacent ViewModel's methods).
Or perhaps I am handling this in wrong way or missing something.
I created a sample which describes the same problem, you are describing. You can alter the sample, to support multiple regions with multiple fragments in it. These regions can be used in presenter as well.
Please take a look at this presenter sample, which shows of a simple implementation of using fragments in an Android project: https://github.com/JelleDamen/CustomMvxAndroidPresenter
FYI:
I used the same tutorial as an inspiration. Let me know if you need any help with it.
Sorry, you are correct.
This behavior can be reproduced when creating a simple app with an activity and a fragment and then in the 'developer options' choose to always destroy activity. Now switch to another app and then switch back.
Init and Start are not called, the activity view-model is obtained from the cached view model.
This isn't related to fragments, it's about how view-model works for activity.
Now, regarding the fragment lifecycle and the fact that it doesn't get the view-model bound, as you mentioned, currently this is not available in Mvvmcross.

Delphi - Running code without showing form

What do you think about this programming practice:
- I need to execute one transaction at first form and after that to force some updates that are placed at another form (for each item that is shown at another form). I.e. it would be like show that form and click at some button. Because it is mandatory to execute these functionalities from second form, I thought to do it without showing second form. Is that good programming practice or you have some other recommendation?
Also, is it enough just to set property> Visible:=False before ShowModal for the second form or I need to do some other actions?
Well, it's unusual to have a form that you don't show. Normally you separate your business logic from the UI.
To answer your question, I don't think you need to call ShowModal at all. Just define a method on the form class and call that. Ultimately forms are just Delphi objects and you can use them as such. If you don't want to show them, don't call ShowModal or Show.
Second question first: Setting Visible := False is of no benefit because the point of all ShowXXX methods is to make the form visible. As David says, you could perform the actions without calling Show at all, provided of course your form doesn't rely on any OnActivate or OnShow code in order to do it's job properly.
As for whether this is a good idea, I say no!
As I've already pointed out there is a concern you have to watch out for. I.e. that currently (or even due to maintenance at some point in the future) your form relies on being visible to do its job properly.
Of course, you could work around that by letting the form flicker open, and be programatically closed. Clearly an aesthetically poor choice.
Not to mention the problems of getting it right. You'll end up writing a bunch of patch-work code to wrap the form so that it can do what you need to do, when you should rather do the following...
Correct Approach
Your form is currently doing at least 2 distinct things:
Visual UI control (call it A)
and "mandatory functionalities" (call it B)
It doesn't matter much whether B is doing validation rules, extra processing, or whatever.
B is a process that does not require user interaction.
Therefore, you need to:
Copy B into a non-UI location (either a simple unit with a custom object or a data module). Call it B*
Modify the form to call B* instead of using B.
Test that your form still behaves correctly.
Delete B
And now you can have your new form call B* instead.
The above approach will save you huge headaches in the future.

How much logic do you put in views?

I am currently unconfident, if I can put a "if/else"-construct into my view?
How much logic do you put in your views?
My dilemma:
I am rendering a navigation. So, I have to differ between the current/active menu item and the rest. The current menu item gets a special css class. I don't know how to handle this in a better way than using if-else.
If you are doing MVC (hopefully you do), than the question is "Do I put the logic in the view or the controller?". I use a simple rule to find out the answer of that:
What if my view was not HTML, but an XML document?
If I will need this logic in both circumstances - its place is in the controller. If not - it's in the view.
In good MVC design you should be able to swap the views without touching the controller.
As much as is necessary to display the information. Just remember that the view is just a window into the internal state of the program. If you stripped the view layer completely away, the program should still be able to operate as usual, just without being able to see what it's doing.
edit: re your navigation, that seems like an okay use of an if statement. The information about which is active is still coming from the model, you're simply using the if statement to decide how to display it. You might consider a little bit about how you're rendering your navigation: is the information about which navigation items available, and which to render living in your view or your model?
One way you might choose to approach the situation is to have the model give you a list of navigation items, along with which one is active, and program the view to know how to generate appropriate HTML from that. That code might contain precisely one if statement total. (instead of one for each nav item).
I wouldn't worry about putting an if statement in a view. In fact, I think there's a bit too much hand-wringing (in general) about responsibilities in these kinds of situations.
If you make your views too dumb then your model can become too view-sentric (tightly coupled).
IMHO a view can do what it likes but the guiding principle should be: where does it get its information from? If the answer is "the model" then use as much logic as you like.
An "if/else" construct is fine if the view is alternating modes, e.g. formatting a U.S. address vs. a foreign address in an order screen.
However, any logic that you place into a view should not alter the model.
Add this helper to your application_helpers.rb It will surround your links with <li> and <li class="active"> if the link is the current page.
Use it in place of a link_to.
link_to 'home', root_url, optional_condition_argument_goes_here
def active_link_to(text, url, condition = nil)
if condition.nil? and String === url
condition = url == request.path
end
content_tag :li, link_to(text, url), :class => (condition && 'active')
end
(Courtesy of Mislav)
I might put if-else in a view. In most cases not. The real question in my mind is whether the logic could go anywhere else without being messier.
I tend to avoid putting control-flow logic in my views (ASP.NET MVC) except under circumstances where I may want a portion of the interface visible/not visible based on the presence or absence of data. In this case, it is view logic -- I'm determining the layout of the page, the elements of the page that are available, etc. I think that this is perfectly acceptable and preferable to having the controller determine this or multiplying views to account for minor variants. The controller needs to give the view enough information for it to be able to render the view and its variants as needed.
What I wouldn't put into the view is business logic that determines how to calculate something or whether to perform some action (except, perhaps, for role-based decisions -- these seem to crop up just about everywhere). Other than client-side validation, my business logic resides in the controller/model.
An example of where I might use if/then logic in a view is a view which displays events. In my app, events can have subevents, but subevents can't have further subevents: a two level hierarchy. On my display page, I have tabs for Details, Groups, Participants, and Subevents. These are the same for both events and subevents, with the exception of the Subevent tab. It shouldn't exist for a subevent. Rather than repeat myself by having two different views that are virtually identical except for that one tab, I've added a tiny amount of logic to the view to not render the Subevent tab if an event has none.
By the same token, I wouldn't go so far as to have a single "view" that uses logic to determine whether to show an overview or details or editing pane, etc. based on the value of some view data item. This seems an abuse of the single responsibility principle as applied to views. Each view should have a single-purpose, IMO.
Logic that is in the view should not be required to fully describe the current state of the model.
Said another way, logic in the view is acceptable if that logic is used to format or alter the visualization of the information. Logic in the view might also have a use in vetting data that is entered before taking the expense of transmitting that data to the controller (in a client/server or web application).
For instance, the view might include logic to split a list of items into multiple columns when the list is longer than N items. That split could be done in several different ways according to the exact nature of the view (e.g. http, mobile device, pdf, voice reader, Morris Code, etc, etc, ad nasium). The full view information might need to be paginated - and that can only be done in the view. Formatting logic should not ever be included in the controller or the model.
As a corner case, the view might include logic to check that a password entered for a new user meets the current security requirements (e.g. double entry of password matches; at least N characters long; does not include spaces or the "*" character; includes at least three of the following: lower case letters, upper case letters, numbers, symbols; is different than the last N passwords, no based on a dictionary word, etc, etc). Depending on the nature of the logic, vetting a password could be thought of as "formatting" or as "business logic". It might be that the check happens in two passes - one set of checks for formatting in the view, and another set of checks in the controller with info from the model (the last N passwords).

How to sort data as I want in a VirtualExplorerTreeview (VirtualShellTools)

This is probably a very "dumb" question for whoever knows VirtualShellTools but I only started using it and couldn't find my answer in the demos' code. Please note that I'm also unfamiliar with virtualtreeview.
I use a VirtualExplorerTreeview to display a directory structure, linked with a VirtualExplorerListview to display a certain type of files in the selected directory as well as specific informations about them
I've been able to point them at the right place, link them as I wanted, filter everything in the listview, and looking at the demos I have a pretty good idea about how to add my own columns and draw it to display my custom data.
My issue lies with the Treeview: I would like to sort the directories displayed in the order I want; specifically, I want "My Docs" and other folder to appears first, then drives, then removable media. Looking in the TNamespace property I found how to distinguish them (Directory and Removable properties), but I don't know how to implement my own sort/what event I need. I tried CompareNode but that doesn't even seem to be called.
If you want to do everything yourself, then set toUserSort in the TVirtualExplorerTree.TreeOptions.VETMiscOptions property. That causes the control to just use the DoCompare method inherited from the virtual tree view, and that should call the OnCompareNodes event handler.
A better way is to provide a custom TShellSortHelper. Make a descendant of that class and override whichever methods you need. Create an instance of that class and assign it to the tree's SortHelper property. (The tree takes ownership of the helper; free the old one, but not the new one.) If the items are being sorted on a column that that class doesn't know how to compare, then handle the tree's OnCustomColumnCompare event.
To help you figure out exactly which methods you need to override or events you need to handle, set a breakpoint in TCustomVirtualExplorerTree.DoCompare and step through to see what gets called in various situations.

Resources