I'm working on a 2D platformer in c#, as most people are, but I have got a decent start to the project I have a class called Player, I then handle all collision for that player as well as the scrolling of the blocks in the background within the gamescreen class. I have just added another player (as a different class in this case a warrior), but all of my collision is based around the players positions and velocity, how would I change the blocks movement and collision to be around the warrior's velocity and positions instead (without duplicating or creating quite a lot of code).
Thanks for any help Sam.
Inheritance is your friend. You should probably have a base Player class, or even something more low level than that. The base class implements the colision detection and movement code. Your Warrior and other player types should inherit that class and override different parts to change the behavior.
My strategy works approximately like this:
I have a Character class. It contains a HitboxSet. The HitboxSet exposes an active Hitbox. All my collision is done based on Hitbox instances. Depending on what kind of character I need, I pass in different sprites, hitboxes, movements, etc.
The result is a high degree of flexibility, while allowing you to keep your concerns thoroughly separated. This strategy is known as Composition, and is widely considered superior to inheritance based strategies in almost all cases.
The main advantage of this strategy over inheritance is the ability to mix and match components. If, one day, you decide that you need a new projectile that's smaller than a previous one, and moves in a sine pattern, you simply use a new sine movement. You can reuse such things infinitely, in any combination.
You can do something like this with inheritance: a child class can override a method and do something differently. The problem is that you either keep adding new child classes with different combinations and end up with a terrifyingly complex tree, or you limit your options.
In short, if something is naturally going to vary, as it almost certainly will in a game, those variations should be distinct classes that can be combined in different ways rather than mutually exclusive overrides.
Related
I'm learning C# and trying to do simple object oriented exercise.
I have three weapon classes, "Bow,dagger,Spear", so I made one interface and inherited from this interface IWeapon.
Now user must choose one of the weapon, so I want to make Collection of weapons and I'm trying to make list of IWeapons, is it correct way? Isn't it bad practice to make list type of IWeapon ? Because of, I know that Interfaces are like a contracts, and I think it's a bad idea to make List with Interface type. One way is to change interface to an abstract class, but I want to use Interface.
private static List<IWeapon> weapons = new List<IWeapon>();
Is it correct way or not ?
The only problem with your solution is that static members should be thread-safe. It's like a convention among C# developers. So either change it to a non-static and, preferrably, readonly:
private readonly List<IWeapon> weapons = new List<IWeapon>();
Or use a thread-safe collection:
private static ConcurrentBag<IWeapon> weapons = new ConcurrentBag<IWeapon>();
I have two thoughts on this:
I can easily imagine a situation where one would want to use a collection of a particular interface. For example, if you were writing a download queue. You would have weapons and shields and players and villages which all implement an IDownloadableThing interface. Your queue code would have a collection of IDownloadableThings because it doesn't care what its actually downloading, it just cares that that thing know what its URL or file path or whatever is.
I'm a little wary of developer edicts. There are good ideas and traps you should be aware of in any language, but context can change everything. When you are trying to figure out if 'Weapon' should be an abstract class, ask yourself a couple things. Should a class implementing Weapon also be allowed to be a Shield? If locking down multiple inheritance is important, then abstract classes are the way to do that. Will there be a lot or any common behavior that classes implementing 'Weapon' will want to share? For example, is there a CalculateDamage() method that's basically identical between all 'Weapon' implementations. Once you have answers to what a class of interface's purpose is, then it'll be easier to choose to violate a development guideline because the situation requires it or re-think your approach.
There's nothing wrong with using interfaces as values for lists.
However, this may not be appropriate to your specific case. You said you'd like the player to pick from a list of weapons. Now consider the follwing scenarios:
You have a single player in your game, and he chose a single weapon. You have created a whole list worth of weapon instances that no one will ever need or use. This just wastes memory.
You have multiple players in the game, and they both choose the same weapon. This could be even worse. If you assign the weapons like this: player.Weapon = weapons[1], then both players will have the same instance of the weapon. If one user assings buffs to his weapons, or maybe if the weapon degrades or breaks, both the players weapons will be affected, since it is, in fact, the same weapon. Think of it like this, both you and I would like a chocolate cake. The store can either give us both the same piece of cake, in this case, if you eat it, I will have none. Or they can bake us both new cakes, so each of us can have his own.
The appropriate solution in this case is to save the types of weapons and present these to the player. Then create a new weapon instance according to the player's choice.
There are several different ways to do this, the simplest of which is to create an enum with the weapon types and present these to the player.
So instead of the list, you can have:
public enum WeaponType
{
Bow,
Dagger,
Spear
}
And now you need to create the instance of the weapon the player chose:
public IWeapon CreateWeapon(WeaponType weaponType)
{
switch(weaponType)
{
case WeaponType.Bow:
// Create Bow...
case WeaponType.Dagger:
// Create Dagger...
case WeaponType.Spear:
// Create Spear...
}
}
This is the basis to the Factory design pattern. I would highly recommend you to take a look at it. Here's a good place to start: http://www.dofactory.com/net/factory-method-design-pattern
Let's say I want to replicate Planeshifting from Legacy of Kain: Soul Reaver in Unity.
There are 2 realms: Spectral realm and Material realm.
The Spectral realm is based on the Material realm, only has the geometry distorted and certain objects fade out/become non-interactive.
In Soul Reaver, it is used as means to go to areas where you normally wouldn't be able to in Material (distorting geometry), to use other powers (such as going through grates).
My question is: Is it even possible at all to implement this in Unity 3D? (I would need the Scene(level) or the objects to have 2 states somehow that I could switch beetween/distort to real-time.)
I would call this a rather advanced topic and there are multiple ways of accomplishing a at least similar effect.
But to answer your actual question straight away - Yes it is possible.
And here are some approaches i would take (i guess that would be your next question ;))
The easiest way is obviously having game object which have their collider and renderer disabled (or the whole object) when "changing
realms". But this for sure isn't the best-looking way of doing it,
even tho a lot of motion blur or other image effect could help.
(Depending on what shaders you use, animating the alpha value can
create a fading effect as well)
The more advanced way would be the actual manipulation of vertices (changing the object). There are quite a few tutorials on
how to change the geometry of object. Take a look at Mesh() in the
official documentation:
http://docs.unity3d.com/ScriptReference/Mesh.html
A class that allows creating or modifying meshes from scripts.
Another way (didn't try) thats rather easy would be using shape keys. I don't know which Software you use to create your
world/models but blender has this function which allows you to define
a base shape, then edit the verticies in blender and save it as a
second (or more) shapes. Unity can blend smoothly between those
shapes as being shown in this video:
https://www.youtube.com/watch?v=6vvNV1VeXhk
Yes it will be possible in Unity3D, but your question is quite general. You could try something like having 2 models per GameObject (perhaps as children or fields on the script) and disabling 1 of them depending on which realm the player is in. You could have 2 scenes for each level and switch between them, though that might be too slow. You could see if there are any plugins/assets that allow you to define 2 models and morph between them. There are probably a number of other routes you could take, but I can't really help more until you've chosen a path.
I'm trying to design a simple role playing game which has your typical character types like fighter, wizard, cleric, thief, etc. I need advice on a good way to setup the class hierarchy.
My initial attempt was to create a class of type "Character" and make the fighter, wizard, cleric, derived types from "Character".
But then I thought it might be better to create a "Character" class and then use the decorator pattern. So say a fighter decorator, wizard decorator, etc.
Or is there a different way that would be better?
I think you may be putting the cart before the horse on this one.
Your first order of business shouldn't be determining "How do I represent a character?" It should be determining "what is it I want to represent?" That is to say: A tool to help with d20 character creation, Shadowrun, Mongoose Traveller, GURPS character creation, WH : Dark Heresy Character Creation; "My own cool d20 based RPG video game", A character and adventure/party management suite of software for sale,...etc. Define this in implementation neutral terms.
After you've successfully determined what it is you want to make, create a detailed definition of what it is you want to make. One way of doing this is to list all the major nouns and verbs (Character, Wizard, Fighter, Create, Save, Delete, Copy....etc) and begin understanding the relationships among the various concepts you'll need to represent. Then take each major noun and decompose it into its constituent parts. (Character: can be a class can be one or more classes, has some equipment,has a Strength, has Hit Points, has Magic Points, has some Primary and Secondary Attributes.) Continue this decomposition until you're not able to use implementation neutral terms (e.g integer...etc).
Then look back at your definitions and decompositions and determine if there are any obvious contradictory statements, if so, get rid of the contradiction. If not, then organize the data by the described hierarchy. In my example, it could be appropriate to have Character, Class, Equipment and Primary Attribute as classes.
Be sure to keep all these "facts" organized and making their relationships clear, both in writing and diagramming. From there you should be able to begin considering implementation specifics such as a class hierarchy where wizard derives from character...etc.
You may also want to see how others have implemented things look at this other SO question for a link to an video game engine that implements a d20. (i.e. Baldurs Gate)
I would use a combination of strategy and decorator pattern. Your initial suggestion is something like a strategy pattern approach.
Try to distinguish between character types and character traits. Character types would be something like fighter, wizard, cleric, … and design it with a strategy pattern, which result to some hierarchy tree.
Character traits would be elements like fire elemental, water elemental, black force, …
E.g. a fighter character might choose between fire and water elemental to be his native origin, like a pirate (aarrrr!) or a blacksmith. If you design this hierarchically, then you are doomed, because this will let your hierarchy tree explode in size.
Such character traits should be rather implemented with the decorator pattern, because it’s an orthogonal concept to the character concept. So you’ll basically create a fighter character and wrap a water elemental decorator around to get a pirate (aarrrr!). Or create a wizard character and wrap a dark magic decorator around him to get a dark mage. Or: Crate a wizard character and wrap a water elemental and a dark magic decorator around him to get a swampland wizard.
Some food for thoughts:
If you decide to have all character
have magic abilities, then design
magic as character trait.
If necessary: Organize
the decorators in some kind of
hierarchical structure. You might
have an "elemental" (water, fire,
earth, wind) decorator hierarchy and
"magic type" (black, white) decorator
hierarchy.
Have fun!
I'd go along with your initial attempt, creating a Character class and then extending the functionality through inheritance. Though all characters will do the same actions (use an item, attack, use a skill), the results will differ (method overloading, i.e.). I think it'd be clearer to use this model, I'm not sure about decorators.
This is a question that can be answered on a theoretical and practical level. For theory, see http://en.wikipedia.org/wiki/Liskov_substitution_principle .
But I think you are interested in practice. In that case, ask yourself, "is a wizard a character", i.e. can you do all the things you can do with a wizard with a generic character? If so, then go ahead and inherit. This will let you use more abstract code with a Character type rather than the specific instance. The decorator is more useful when you want to compose a subset of possible extensions in a variety of ways, i.e. if in your case a character could be simultaneously a cleric, a wizard, or a cleric and something else, etc.
It depends on how flexible you want your RPG character engine to be. If you subclass your character class then you limit your character diversification to the compile time. If you however use design patterns like the decorator or behavior pattern you can also create character classes at runtime by combining decorators or behavior objects. (Although you wouldn't use a "wizard" decorator but a "magic" decorator to create a wizard, an elf, etc. Decorators are made to be reused, that is their strength.)
It really depends on what you want to learn, fundamental class design (characters by subclass) or modern object oriented design (characters by composition). If you are an absolute beginner at this go with the first method to get to know the principles. If you already know these principles you should grab yourself a good book on design patterns and apply them to your game.
I am making sims like game and right now I am trying to figure out how I will structure my objects.
Right now I am thinking to create a class called GameObject, the psuedo is below
public class GameObject {
name:String
width:int
height:int
}
This way I could create objects like bushes, trees, and buildings. But then I began to think. what if I wanted to create multiple buildings and trees of the same type ?? I would have to keep making instances of GameObject and giving it a new name and height and width. The properties would have to be the same values in order for me to duplicate one object. That seems a little tedious. Then I figure , maybe that isnt the right way to go. So I was thinking, I would have to extend GameObject like below
public class Tree extends GameObject{
birdHouse:Boolean
}
public class Building extends GameObject{
packingGarage:Boolean
stories:Number
}
public class House extends GameObject{
garage:Boolean
stories:Number
}
Now this way, I can just create multiple instances of house, or tree, without creating properties that specify that it is indeed a house or tree. This seems more logical, but at the same time it seems it allocates more memory because I am creating more classes.
I just need to know what the best practices for dealing with objects like this. If anyone can help me out with this. also if you know any resources for best practices of reducing loading on games or any application at that. I also want to use Interfaces. the second concept seems more reasonable and I was thinking about having the parent implement a interface like below
public class GameObject implement IGameObject {
name:String
width:int
height:int
}
Now this way I can create a class that has a method that loosely accept accepts any type that inherits GameObject.
Selector.loadObject(gObject:IGameObject);
Depending on what type it is (i.e tree, building, house) I can use a case statement to figure out which type it is and evaluate it accordingly.
I also created a Tile Class that will pass through the loadObject method. It also will be a child of the GameOject class. if the case statement finds that it is type Tile, it will highlight whatever Tile depending on what tile my mouse is over.
My second question is if a class inherits a class that implements a interface, is that class child class considered to be a IGameObject as well. or does it have to implement that interface directly.
does all this sound like I am going in the right directions lol, as far as organization is concerned.
Thanks for all of your help, thanks guys!
One thing you could think about is using Composition of objects over inheritance. This sort of goes along with the Flyweight answer. Rather than having all your GameObjects inherit properties from GameObject; instead, have each game object just have a reference or pointer to an object or interface that has the properties it needs. For example, all your game objects probably have some sort of "size" property - rather than inheriting this from a base class, just have each game object reference or point to a "Size" class, so that the size object can potentially be shared among similar objects.
You should look into the Flyweight pattern
From wikipedia:
Flyweight is a software design
pattern. A flyweight is an object that
minimizes memory use by sharing as
much data as possible with other
similar objects; it is a way to use
objects in large numbers when a simple
repeated representation would use an
unacceptable amount of memory.
As for your second question, the answer is yes. All Subclasses of a Class can be said to implement all interfaces that the parent class implements.
This seems more logical, but at the
same time it seems it allocates more
memory because I am creating more
classes.
Creating new classes doesn't use a significant amount of memory. It's creating instances that uses memory - but again, the amount will be negligible compared to the memory used by loading in your graphics etc. Don't worry about memory. Your only concern at this stage should be good code organisation.
You should have separate classes when they have different behaviour. If they have the same behaviour but different properties, then you use the same class and set the properties accordingly.
In this case, you don't appear to have significantly different behaviour, but if separating it into Tree, Building, and House makes life easier for you when managing which items can be included in others etc, do it.
I am relatively new to game development so I decided I wanted to create a hobby project from scratch for both experience and entertainment. The specific game is similar to poker known as Three Card Brag. The game is played in the movie Lock, Stock and Two Smoking Barrels.
I have been reading up on some of the topics on SO regarding game development, though mostly this question. This has helped revamp the original way I was creating the objects.
One particular problem I am having is defining game state. My initial approach was to separate everything (e.g. keeping chip stacks inside a Player class) but after reading the responses to the question I mentioned previously, it seems as though all possible states of the game should be maintained within a GameState object. What I came up with is essentially this:
abstract class CardGameState
{
protected List<Player> _Players;
protected Player _CurrentPlayer;
protected Dictionary<Player, int> _Chips;
protected Dictionary<Player, Hand> _CurrentHand;
protected Dictionary<Player, PlayerStatuses> _PlayerStatus; // PlayerStatuses.InHand, PlayerStatuses.Folded, PlayerStatuses.SittingOut, etc.
/* etc. */
where each CardGameState is modified by some action:
public interface IAction
{
string Name { get; }
CardGameState Apply(CardGameState state);
bool IsLegal(CardGameState state);
}
Now I'm feeling very strongly that this is defeating the purpose of object-oriented programming, because the data specifically related to the player (in this case, his chip stack, hand, and current status) is not encapsulated by the Player object.
On the other hand, if a player were to raise the bet, I would be creating a RaiseAction that implements IAction, but the IAction interface only accepts the current game state, which I don't believe would be ideal if the chip stacks were stored within the Player class.
Basically, my question is: can I have the best of both worlds such that I can have an exact representation of the game state while simultaneously keeping all data related specifically to an object within the game state inside its given object?
In online-games using the command-pattern (your IAction) is the standard, and proven, way to do it. It's not Object Oriented in the sense of the player, but the actions are Object Oriented, so from a purely theoretical point of view its a solid design pattern, I guess. And in practice thats how every successful online game I've seen implements it, but note that action games normally use very small discreet actions/packets, until it practically becomes a stream of sorts.
Edit:
A long time after I answering this, I came back here and realized another solution to this problem is to implement GameState's Players, Decks, etc... as derived from an IState class with an Apply(IAction action) member. This way objects apply actions on themselves, instead of having the application apply actions on objects, this would map actions and state to a visitor-pattern instead of a command pattern. Either solution will work, where visitor has the larger overhead and more encapsulation, while command is the easier solution with less encapsulation.
Seems like you might be Object-orientizing it for Object-orient's sake...
Seems like Bob Martin's classic bowling game problem.
EDIT: -Summary-
Its a long read, but basically, through TDD and refactoring, a bowling scoring application went from a huge cluster with lots of Classes and polymorphism to 20 or 30 elegant lines of code. Why? Because they didn't really need to be there in the first place