OOD and subject-object confusion - c#

Suppose I have a definition for a door:
class Door
{
public void Lock()
{
// lock the door
}
}
This appeared to make sense to me, at least for awhile. But now, I'm not so sure. If I had a Person object that wanted to lock a Door, he would call aDoor.Lock(). But in real life, we do not lock doors by telling the door to lock itself.
It seems like a more accurate model of the situation would be the person being able to directly modify the state of aDoor, provided he has sufficient power to lock doors. For example, aCat should not be able to set aDoor.IsLocked = true. I could see how to do this with properties, if they supported parameters:
class Person
{
public void LockDoor(Door door)
{
door.IsLocked(this) = true;
}
}
class Door
{
bool isLocked;
public bool IsLocked(Person person)
{
set
{
if(person != null) // ensure there is a real person trying to lock the door
{
this.isLocked = value;
}
}
}
}
static void Main()
{
Person personFromThinAir = new Person();
Door doorFromThinAir = new Door();
personFromThinAir.LockDoor(doorFromThinAir);
}
Instead, what we can do is this:
class Person
{
public void LockDoor(Door door)
{
door.SetLocked(this, true);
}
}
class Door
{
bool isLocked;
public void SetLocked(Person person, bool locked)
{
if(person != null)
{
this.isLocked = locked;
}
}
}
Obviously these two classes are strongly coupled and both would probably have interfaces extracted in actual code, but that's not what I'm getting at. My question is, is this a better way to model the relationship between the two objects? Is there an even better way than this? The more I think about it, the less sense of aDoor.Lock() I can make; it seems to violate object-oriented design.

Although the person "locks" the door, in reality the person is toggling (or frobbing) on an element of the door (the lock handle) and that manipulation causes the lock to lock the door. You can think of this where, although the person is moving the deadbolt, the deadbolt is what is locking the door - not the person. So a better representation might be that a door has a lock, and the person calls lock.lock(), which then sets the lock being closed (locked).
The basic premise here is that, although the person is manipulating the lock, that is external (the function call). The lock's internal changes (the code inside the function) is what is actually causing the door to lock. The person is not taking off the handle and manipulating the inside to lock the door every time - they are simply toggling a state on the outside and expecting the machinery internal to handle it.

OOP isn't really about modelling how things work in the "real world". Its more about managing complexity. Considering this, it is perfectly acceptable for the door to lock itself. Even in the real world, a person locking a door doesn't need to know anything about how the lock works other than turning the knob or the key.
Hiding the details of a complex idea behind an abstraction is what makes OOP so useful. The abstractions you use differ with the problem domain. In the example you gave the Person shouldn't need to know anything about the door other than how to operate it:
class Door
{
public bool Open(){}
public bool Close(){}
public void Lock(){}
public void Unlock(){}
}

The most interesting design issue here to me is how to handle the coupling between the locker and the lockee since there are requirements which must be met for the locking/unlocking to be allowed. I look at this question and imagine a game where a player might sometimes be a human but other times be a cat (per the example given), and maybe is_human is the only requirement for locking/unlocking. But you might also want to have doors which require the matching key to be in the player's possesion in order for locking/unlocking to happen. If so, you have to add that to the criteria. Perhaps some doors can only be locked from one side and not the other, so the player's location must be added to the criteria. You could further add a lockpicking skill which some players might have (cat burglars, no doubt) to allow them to have a chance to unlock (but not lock) a door even if they didn't have the key. Etc. etc.
One can envision a conversation between the objects like:
Player: "I am trying to unlock you."
Lock: "Do you meet requirement A?"
Player: "Yes"
Lock: "Do you meet requirement B?" // Only some doors would ask this.
Player: "Yes"
Lock: "OK, you succeed. I am unlocked!"
But, you probably don't want to expose the involved fields publicly or clutter up the Player interface seen by objects that don't need to know about locking/unlocking requirements.
I am not a C# programmer, and it has been a while since I did Java, but I think an approach in Java which may also apply in C# would be to have the Player object pass an instance of a lock_unlock_credentials inner class as a parameter to the get_locked/get_unlocked methods of the Door object (or Lock object as has been suggested.) The lock_unlock_credentials object would have callback methods which, by virtue of its being an inner class of Player, could access relevant fields of the Player object, but those fields would otherwise not be exposed outside of Player. The Lockable object could then use those callback methods to check to see if the requirements it cares about are met. You can't avoid the coupling resulting from the requirements, but this way keeps the details internal to the interaction between the Player and the Lockable object.
Not sure if the same inner class approach applies to C#, but presenting this as something to think about.

Related

C# Variable Scope Question, and Text-based RPG Attempt

I am trying to write a text-based RPG in C#. I am having issues understanding how I could make the character data accessible to many other objects in an effective manner.
I am fairly new to programming, and I certainly lack information. I've been reading guides and questions online and it got me so far, but I feel like I am either thinking about this the wrong way or missing something completely.
I am trying to write everything as flexible as possible since I am planning on adding a lot to this project if I can get past this stage. But it seems difficult for me to allow all of these objects to actively communicate with each other. Would using Unity help with this? I am mostly doing this to learn the language so I can later use it w/ Unity, but I wanted to learn the language directly so I opted out of starting with Unity. If there are any suggested resources to learn about the language I could really use recommendations.
I am sorry if the question is too open ended, but I can't really find anything regarding the mindset behind how I should be building a system like this. The last thing I've learned is ref but I feel like that isn't the best answer.
namespace GameMain
{
public class Game
{
static void Main()
{
MainMenu Game = new MainMenu();
Game.Menu();
return;
}
}
public class MainMenu
{
Character CurrentPlayer = new Character();
public void Menu()
{
Music MusicPlayer = new Music();
LocationEngine Location = new LocationEngine();
Tester Testman = new Tester();
MusicPlayer.Track("0");
while (true)
{
Menu:
Console.WriteLine("Welcome to the main menu. Enter 'create' to create a character and begin the game. Enter 'play' to log in.\r\nSaving features are to be implemented.\r\n");
while (true)
{
string MenuSelection = Console.ReadLine();
if (MenuSelection == "create")
{
CurrentPlayer.Creation();
goto Menu;
}
else if (MenuSelection == "play")
{
if (CurrentPlayer.CharacterPass != "")
{
Console.Write("\r\nEnter your password: ");
string Password = Console.ReadLine();
bool Check = CurrentPlayer.Login(Password);
if (Check == true)
{
Console.WriteLine("\r\nAdd transition to location here.");
break;
}
else
{
break;
}
}
else
{
Console.WriteLine("Please create a character first.\r\n");
break;
}
}
}
while (true)
{
Console.WriteLine("\r\nPress any key to continue.\r\n");
Console.ReadKey();
string TownSelection = "";
Console.WriteLine("\r\nYou are in Town.\r\n\r\nYou can 'explore' for encounters\r\nYou can use 'stats' to check your character\r\nOr you can 'sleep' to return to the main menu\r\n");
TownSelection = Console.ReadLine();
if (TownSelection == "sleep")
{
Console.WriteLine("");
break;
}
else if (TownSelection == "stats")
{
CurrentPlayer.CharacterStats();
}
}
}
}
}
}
I don't know how I can make the CurrentPlayer object accessible to the other objects such as Location. Is it better to pass every relevant bit as reference all the way down the rabbit hole?
I have posted the entire thing on github here if you are feeling extra patient: https://github.com/Slocknog/rpgproject
...and thank you for the help. Please do comment on anything else that you think I should be doing differently or reading up on.
I would take a step back and make sure you understand the purpose of each class you write. (This may sound patronizing, but it's really not trying to be. This is a difficult part of design.)
The purpose of each class should be clear and constrained: it should be reasonably obvious whether any piece of functionality belongs in a particular class or not, and no class should take on too much responsibility. I'd encourage you to write documentation comments on each class to explain its purpose - this will make it easier for you to come back and ask yourself whether some aspect of state and functionality really makes sense for that class.
Next, think about three ways data can be available to the class:
Through static variables. This is effectively global state, and is best restricted to natural constants. Global state should usually be immutable (unless it's something like a cache) as otherwise it can make testing and reasoning about your code fairly difficult.
Through instance variables. This is the state for an instance of the class (an object). It should be state that feels like it naturally belongs to an instance for its whole lifetime.
Through method parameters. This is information that is useful just for the duration of a single method call. For example, I don't think a LocationEngine should really know about the Character as part of global or instance state, but it might make sense to pass a Character reference into a method. (It might make more sense to pass a Location reference into the method, which might be obtained from a Character - it's hard to say without effectively trying to do a large portion of design for you.)
It's definitely worth putting significant thought into these decisions early on - although you should still expect to make mistakes. If you find yourself having to write code that feels ugly quite a lot of the time, in terms of how it accesses information, think about whether that information currently "lives" in the right place.
(Oh, and you're wise to separate "learning C#" from "learning Unity" in my view. Quite a lot of Unity uses idioms/techniques/conventions that would raise eyebrows in other C# codebases. Learning about them only when you move into Unity means you're less likely to carry them over to writing C# code elsewhere. Additionally, debugging "regular" C# code, particularly console applications, is somewhat simpler than having to worry about the Unity editor etc.)
you could have all those "other objects" Constructors accept a Character object to which you'll provide CurrentPlayer
supposing you have the following Character class
class Character
{
public string Name { get; set; }
}
then your LocationEngine class would be:
class LocationEngine
{
Character _player;
public LocationEngine(Character player)
{
_player = player;
}
public void SomeMethod()
{
string playerName = _player.Name;
}
}
and in your MainMenu class you'd code:
public class MainMenu
{
Character CurrentPlayer = new Character();
LocationEngine location = new LocationEngine(CurrentPlayer);
...
}

Checking a private value in another class [C#]

I'm making a simple dart game in the console for an assignment where I am to practice using private lists and variables everywhere. The basic flow of the program for some context is as follows:
User lands in a menu
User chooses from 1-4. (1 = Add player, 2 = Add CPU, 3 = Start game, 4 = Quit)
Game starts. Players manually add their 3 throws per turn, and CPU gets theirs randomly.
When a player or CPU reaches 301 score, the loop ends and you now see every throw made by the winner.
UML diagram for class structure context: https://i.imgur.com/bL5pZV5.png
Everything is pretty much complete. I've made the program to such an extent that both players and CPUs are getting random values (are treated as CPU players), it prints out everything correctly and follows the flow to the end.
My issue now is that I want to be able to reach the is_CPU variable which is private in the Player class from the Game class and use it in an IF check, directing whether or not the values are manually added or randomly generated.
Pseudo-code:
FOREACH (var player in player_list)
IF (is_CPU == TRUE)
THEN Assign random values
ELSE
THEN Manually enter values
I tried messing around with the get-set stuff, but I don't fully understand how to use them and how they work. I have looked around on here and still don't see how I should be using them in this case, if at all.
I can think of one way to work around this and that is by making a method just for this where it checks that value and returns true/false, but that seems like a 'lazy' or improper way to do this, and comes with several downsides. I feel like there should be a better way to do this, one that won't come back to bite me in the ass later. Hopefully there is, and I can learn it by asking here.
EDIT: The variables and lists HAVE to be private. It is part of the exercise where we learn how to handle these.
I think you just want a get property on your player class.
public bool IsCpu { get { return is_CPU; }}
See also c# properties
In order to access private members of a class instance, you either have to define properties on that class with a public getter, as follows:
public class Player
{
private Boolean m_IsCPU;
public Boolean IsCPU
{
get { return m_IsCPU; }
}
// ...
}
or to change these members in order to make them public, as follows:
public class Player
{
public Boolean IsCPU;
// ...
}
Whatever you choose (I suggest you to go for the first approach), in any part of your code in which you have to check the IsCPU property/member for each instance of the Player class, you can just do as follows:
foreach (Player player in players)
{
if (player.IsCPU)
// Do Something...
else
// Do Something Else...
}
Some interesting links:
Access Modifiers
C# Properties
Why prefer Properties to public variables?
Redesign your app like this:
Class Game
List<IPlayer> Players
ShowMenu()
AddPlayer()
StartGame()
IsGameOver(): boolean
Interface IPlayer
Turn() : Score
CpuPlayer: IPlayer
Player: IPlayer
Split your logic into two different classes: you dont need to check. Treat every player the same in the game. Later if you come up with 'NetworkPlayer', 'AIPlayer', 'SuperPlayer' you can easily add to your system.
In your menu:
switch (userInput) {
case AddUser:
AddPlayer(new Player());
break;
case AddCpuPlayer:
AddPlayer(new CpuPlayer());
break;
In your gameplay:
while (!IsGameOver)
{
var nextPlayer = ... next player
nextPlayer.Turn() ...
}

Am I missing some benefits of static fields? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am working through C# in a Nutshell from Joseph Albahari & Ben Albahari which has been a great book by the way and am reading through the topic on static fields in C#. They have this example code,
public class Panda
{
public string name;
public static int population;
public Panda(string n)
{
name = n;
population = population + 1;
}
}
So I understand that the more instances of Panda that you instantiate the greater population will be become since it is shared amongst all objects of type Panda but now to my question.
Why? I just can't understand why I would ever want to utilize such behavior in an application. It seems like a confusing way to track a global variable within the object itself. Am I misunderstanding the potential benefits of a static field? What are some cases where this would be useful and not confusing?
I think it's best to review what happens under the hood first.
If you create a static class, a single instance is created at runtime. It happens whenever you try to use the type the first time and is used from there on. This can come in handy if you want to, say, lazy load a shared resource for instance. It also guarantees (via compiler and runtime) that you have one and only one instance at all times.
If the class is not static but you use static members, you can construct new instances, but a "static version" is maintained for you in the background. This is useful for situations in which you need to either keep track of something or if you want to share something across instances or even other code if you make the member public.
In terms of performance for instance, it could be really useful if you need to speed up your program and realize (through object count) that you are instantiating an object that never changes 100 times. Maybe you want to show your user how many Pandas have been born. You could in theory keep a count somewhere else but if you think about it, you will need another object anyways so it makes sense to keep all related information and logic together. Besides, you could have a more general type that breaks into derived ones and you may want to track all of them without having to keep adding logic.
Consider the following example:
public abstract class Animal
{
private static int _count;
protected Animal()
{
IncrementCount();
}
protected static void IncrementCount()
{
_count++;
}
public int WorldPopulation()
{
return _count;
}
}
public class Dog : Animal
{
}
public class Cat : Animal
{
}
public class Bird : Animal
{
}
If I was to create a Dog, Cat and Bird instance and then check the value of the WorldPopulation() method, I would get 3.
The Singleton pattern is also commonly implemented using this approach. It allows you to maintain a single instance while containing the construction internally:
public class SingletonSample
{
private SingletonSample()
{
}
private static SingletonSample _instance;
public static SingletonSample Instance
{
get
{
if(_instance == null)
_instance = new SingletonSample();
return _instance;
}
}
public bool IsThisTrue()
{
return true;
}
}
Notice you can't access the IsThisTrue() method via Class name, you need an instance and it cannot be created directly. It can only be created internally by the class itself:
//Object construction occurs the first time you access the "Instance" property
SingletonSample.Instance.IsThisTrue();
I hope that helps.
I just can't understand why I would ever want to utilize such
behavior in an application.
You'd never want to know the panda-count in a game? What about high-score?
Now, whether static fields are the best approach is a different manner - there are alternative patterns, but they tend to be far more complex to build and manage.
Short answer:
Consider that a cache is a place to store the result of computation. Caches are useful whenever the computation is expensive, but the storage is cheap. In C#, a static variable is just a cache for computations about a live system.
Longer answer:
Theoretically, we could discover anything that we wanted to know about a running system by searching for all objects, and then performing a computation with respect to some subset. Since this is exactly what the garbage collector does, a hypothetical CLI that provided the right hooks into the garbage collector would obviate the need for static variables.
For example, suppose we wanted to know how many Widget objects that we’ve created. Well, all we would need to do is ask the GC for a list of all of the live objects, then filter the list for objects of type Widget, and then count the Widgets.
But there are a couple of problems in the example: Firstly, some of the Widget objects might not be live (not reachable, thus not able to undergo state changes), but we would need to keep them around just for counting purposes. Even if the size of each Widget instance was only a single bit, we would still need 122KB of memory if we needed to keep a count of, say, one million Widgets (since a CLR object is at least 4 bytes, we would need almost 4MB just to keep track of the count). On the other hand, a 20-bit variable is enough to count up one million. This is a savings of 99.99% (actually 99.99999% in the case of the actual CLR). Secondly, garbage collection can be an expensive operation. Even if we avoid the overhead of memory compaction, we would just need to pause the system in general.
So, hopefully, it’s now easy to see why we would want to have the ability to cache certain computations about a live system, and hence the usefulness of static variables.
Having said all that, it is often the case that it's better to just recompute things rather than caching the results in a static variables because of the way CPU caching works.
here is an example of how i used static objects.
I had task to create an uploader handler with progress bar.
and progress bar had show up to all users that are in the site.
so a created the upload operation in a new thread and then appended the result of the operation to a static object(Progress bar) that are outside the thread, the progress bar will show up to all users that are viewing the site.
more info and exemplar could be found here
What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

How to avoid casting from interface to class

In trying to design a collision detection component for a game, I came up with the following solution. I define an interface ICollideable that looks something like:
interface ICollideable
{
Sprite Sprite { get; }
int Damage { get; }
void HandleCollision(ICollideable collidedWith);
}
Basically, any game objects that want to participate in collision detection have to implement this interface, then register themselves with the detector, which maintains a list of ICollideables. When it detects a collision, it calls the HandleCollision method on the object and passes in a reference to the object it collided with.
I like this, because it lets me keep all my collision algorithms in one place, and lets the game objects themselves decide how to handle the collision. But because of the latter, I find I am having to check the underlying object type. For example, I don't want Players to collide with each other, so in the Player class there might be something like:
void HandleCollision(ICollideable collidedWith)
{
if (!(collidedWith is Player)) { // do stuff }
}
and so on, and I am wondering if this is telling me that I have a bad design and what the alternatives might be.
Second question, further along the lines of the first. For scoring purposes, if an Enemy is destroyed by a Projectile, someone needs to know the "Owning Player" member of the Projectile class. However, none of my other collideables have or need this property, so I find myself wanting to do (in the Enemy HandleCollision):
void HandleCollision(ICollideable collidedWith)
{
if (collidedWith is Projectile) {
Health -= collidedWith.Damage;
if (Health <= 0) {
Player whoDestroyedMe = (collidedWith as Projectile).FiredBy
// ...
}
}
}
I haven't a clue as to how to handle this with a better design. Any insights would be appreciated.
EDIT: I wanted to pull focus towards the second question, because my gut tells me a way of handling this will solve the first question. As for the first question, I thought of a way to abstract this behavior. I could define an enum:
enum Team
{
Player,
Enemy,
Neither
}
and have ICollideables implement this property. Then the collision detector simply doesn't register collisions between collideables on the same "Team". So, Player and Player Projectiles would be on one team, Enemy and Enemy Projectiles on the other, and the environment (which can damage both) can be on neither. It doesn't have to be an enum, could be an int or a string or anything, with the idea that objects with the same value for this property do not collide with each other.
I like this idea of modeling behavior with a simple attribute. For instance, if I want to turn "allow friendly fire" on, all I have to do is create Projectiles with a Team value other than the Player's Team value. However, I still may have cases where this is not enough. For example, a Player may have shields that are temporarily impervious to projectiles but will not protect against a direct collision with an enemy, and so on.
I think you're going the wrong way altogether in handling the collision inside of the class of one of the colliders. I would put this logic into a third object, outside of the entity objects. You could do all of the checking of the types in this third object, and even handle most of the logic there too. Why should a Ship or a Projectile have a monopoly over the logic that happens when one hits the other?
The following is how I might handle this, although it means using an object for each style of collision (Ship vs Ship, Ship vs Projectile, Ship vs Asteroid, etc.) You might be more comfortable putting all that logic into a single object, or even a single method on that object.
public interface ICollisionHandler
{
bool HandleCollision(Entity first, Entity second);
}
public class PlayerShipVsProjectile : ICollisionHandler
{
private GameOptions options;
public PlayersOwnShipHandler(GameOptions options)
{
this.options = options;
}
public bool HandleCollision(Entity first, Entity second)
{
// Exactly how you go about doing this line, whether using the object types
// or using a Type property, or some other method, is not really that important.
// You have so much more important things to worry about than these little
// code design details.
if ((!first is Ship) || (!second is Projectile)) return false;
Ship ship = (Ship)first;
Projectile projectile = (Projectile)second;
// Because we've decided to put this logic in it's own class, we can easily
// use a constructor parameter to get access to the game options. Here, we
// can have access to whether friendly fire is turned on or not.
if (ship.Owner.IsFriendlyWith(projectile.Shooter) &&
!this.options.FriendlyFire) {
return false;
}
if (!ship.InvulnerableTypes.Contains(InvulnerableTypes.PROJECTILE))
{
ship.DoDamage(projectile.Damage);
}
return true;
}
}
Like this, you can then do...
// Somewhere in the setup...
CollisionMapper mapper = new CollisionMapper();
mapper.AddHandler(new ShipVsProjectile(gameOptions));
mapper.AddHandler(new ShipVsShip(gameOptions));
// Somewhere in your collision handling...
mapper.Resolve(entityOne, entityTwo);
The implementation of CollisionMapper is left as an exercise for the reader. Remember that you might need to have Resolve call the ICollisionHandler's "Handle" method twice, with the second time reversing the entities (otherwise your collision handler objects will need to check for the reverse situation, which might be ok as well).
I feel this makes the code easier to read. A single object describes exactly what will happen when two entities collide, rather than trying to put all this info into one of the entity objects.
For the first case, I would add the following extra method to ICollidable:
bool CanCollideWith(ICollidable collidedWith)
As the name suggests, it would return true or false depending upon whether it can collide with the passed in object.
Your Player.HandleCollision method would just do its stuff because the calling method could do that test and not even call the method if it wasn't required.
How about something like this?
Collidable.cs
abstract class Collidable
{
public Sprite Sprite { get; protected set; }
public int Damage { get; protected set; }
protected delegate void CollisionAction(Collidable with);
protected Dictionary<Type, CollisionAction> collisionTypes = new Dictionary<Type, CollisionAction>();
public void HandleCollision(Collidable with)
{
Type collisionTargetType = with.GetType();
CollisionAction action;
bool keyFound = collisionTypes.TryGetValue(collisionTargetType, out action);
if (keyFound)
{
action(with);
}
}
}
Bullet.cs
class Bullet: Collidable
{
public Bullet()
{
collisionTypes.Add(typeof(Player), HandleBulletPlayerCollision);
collisionTypes.Add(typeof(Bullet), HandleBulletBulletCollision);
}
private void HandleBulletPlayerCollision(Collidable with)
{
Console.WriteLine("Bullet collided with {0}", with.ToString());
}
private void HandleBulletBulletCollision(Collidable with)
{
Console.WriteLine("Bullet collided with {0}.", with.ToString());
}
}
Player.cs
class Player : Collidable
{
public Player()
{
collisionTypes.Add(typeof(Bullet), HandlePlayerBulletCollision);
collisionTypes.Add(typeof(Player), HandlePlayerPlayerCollision);
}
private void HandlePlayerBulletCollision(Collidable with)
{
Console.WriteLine("Player collided with {0}.", with.ToString());
}
private void HandlePlayerPlayerCollision(Collidable with)
{
Console.WriteLine("Player collided with {0}.", with.ToString());
}
}
I think this is a good question #idlewire and I have to say that I don't think there is anything fundamentally wrong with your original solution. In asking whether object Foo should be allowed to cast the ICollideable to a Bar, the important question is only: is undesirable to have Foo knowing anything at all about Bar? If the answer is 'no' because Foo already knows about Bars (for behaviours other than collisions, perhaps) then I see no problem in the cast and, as you say, it allows you to better encapsulate the behaviour of both.
Where you need to be wary is only where this would introduces a dependency between two things you'd like kept apart - which would make re-use of either without the other (in a different game application for example) impossible. There you might want to either have more specific sub-interfaces from ICollideable (e.g. IElastic and IInelastic), or use properties on the interface as you have proposed with the Enum.
In short, I think your original posting shows good evidence of OO thinking, not bad.
Sometimes the simplest method is the best method. Unless you want to separate your collision interactions into numerous subtypes, you could instead place a bool IsPlayer property within the Interface.
The upside here is that you have a cheaper, and type safe method of determination over casting.
If (isplayer == true)
{
Handlethisway;
}
The downside is that you're still having to do some sort of state checking, but this is more efficient.
To avoid any state checks, you'd need to do the following: Make an ICollidablePlayer Interface which accepts generic Icollideable and handles them differently. Since the Icollideable is your injected dependency, the ICollideablePlayer dependencies are inherent. The objects of Icollideable would have no knowledge of this separate process, and interact with each other in the same manner.
ICollideablePlayer:ICollideable
{
//DependenciesHere
HandlePlayerCollision(ICollideable)
{
HandleDifferently
{
}
ICollideable
{
//DependenciesHere
HandleCollision(ICollideable)
}
}
}
In an interaction, the ICollideable will treat the player as any other ICollideable, but the ICollideablePlayer will reject the interaction when it does the check itself.
For things like shields and all that, You're talking about state changes which implies that those such things should be properties within either of those Interfaces such that something like bool ColliderOff to temporarily change the state.

Help on implementing how creatures and items interact in a computer role playing game

I am programming a simple role playing game (to learn and for fun) and I'm at the point where I'm trying to come up with a way for game objects to interact with each other. There are two things I am trying to avoid.
Creating a gigantic game object that can be anything and do everything
Complexity - so I am staying away from a component based design like you see here
So with those parameters in mind I need advice on a good way for game objects to perform actions on each other.
For example
Creatures (Characters, Monsters, NPCs) can perform actions on Creatures or Items (weapons, potions, traps, doors)
Items can perform actions on Creatures or Items as well. An example would be a trap going off when a character tries to open a chest
What I've come up with is a PerformAction method that can take Creatures or Items as parameters. Like this
PerformAction(Creature sourceC, Item sourceI, Creature targetC, Item targetI)
// this will usually end up with 2 null params since
// only 1 source and 1 target will be valid
Or should I do this instead?
PerformAction(Object source, Object target)
// cast to correct types and continue
Or is there a completely different way I should be thinking about this?
This is a "double dispatch" problem. In regular OO programming, you "dispatch" the operation of a virtual method call to the concrete type of the class implementing the object instance you call against. A client doesn't need to know the actual implementation type, it is simply making a method call against an abstract type description. That's "single dispatch".
Most OO languages don't implement anything but single-dispatch. Double-dispatch is when the operation that needs to be called depends on two different objects. The standard mechanism for implementing double dispatch in OO languages without direct double-dispatch support is the "Visitor" design pattern. See the link for how to use this pattern.
This sounds like a case for polymorphism. Instead of taking Item or Creature as an argument, make both of them derive (or implement) from ActionTarget or ActionSource. Let the implementation of Creature or Item determine which way to go from there.
You very rarely want to leave it so open by just taking Object. Even a little information is better than none.
You can try mixing the Command pattern with some clever use of interfaces to solve this:
// everything in the game (creature, item, hero, etc.) derives from this
public class Entity {}
// every action that can be performed derives from this
public abstract class Command
{
public abstract void Perform(Entity source, Entity target);
}
// these are the capabilities an entity may have. these are how the Commands
// interact with entities:
public interface IDamageable
{
void TakeDamage(int amount);
}
public interface IOpenable
{
void Open();
}
public interface IMoveable
{
void Move(int x, int y);
}
Then a derived Command downcasts to see if it can do what it needs to the target:
public class FireBallCommand : Command
{
public override void Perform(Entity source, Entity target)
{
// a fireball hurts the target and blows it back
var damageTarget = target as IDamageable;
if (damageTarget != null)
{
damageTarget.TakeDamage(234);
}
var moveTarget = target as IMoveable;
if (moveTarget != null)
{
moveTarget.Move(1, 1);
}
}
}
Note that:
A derived Entity only has to implement the capabilities that are appropriate for it.
The base Entity class doesn't have code for any capability. It's nice and simple.
Commands can gracefully do nothing if an entity is unaffected by it.
I think you're examining too small a part of the problem; how do you even determine the arguments to the PerformAction function in the first place? Something outside of the PerformAction function already knows (or somehow must find out) whether the action it wants to invoke requires a target or not, and how many targets, and which item or character it's operating upon. Crucially, some part of the code must decide what operation is taking place. You've omitted that from the post but I think that is the absolute most important aspect, because it's the action that determines the required arguments. And once you know those arguments, you know the form of the function or method to invoke.
Say a character has opened a chest, and a trap goes off. You presumably already have code which is an event handler for the chest being opened, and you can easily pass in the character that did it. You also presumably already ascertained that the object was a trapped chest. So you have the information you need already:
// pseudocode
function on_opened(Character opener)
{
this.triggerTrap(opener)
}
If you have a single Item class, the base implementation of triggerTrap will be empty, and you'll need to insert some sort of checks, eg. is_chest and is_trapped. If you have a derived Chest class, you'll probably just need is_trapped. But really, it's only as difficult as you make it.
Same goes for opening the chest in the first place: your input code will know who is acting (eg. the current player, or the current AI character), can determine what the target is (by finding an item under the mouse, or on the command line), and can determine the required action based on the input. It then simply becomes a case of looking up the right objects and calling the right method with those arguments.
item = get_object_under_cursor()
if item is not None:
if currently_held_item is not None:
player_use_item_on_other_item(currently_held_item, item)
else
player.use_item(item)
return
character = get_character_under_cursor()
if character is not None:
if character.is_friendly_to(player):
player.talk_to(character)
else
player.attack(character)
return
Keep it simple. :)
in the Zork model, each action one can do to an object is expressed as a method of that object, e.g.
door.Open()
monster.Attack()
something generic like PerformAction will end up being a big ball of mud...
What about having a method on your Actors (creatures, items) that Perform the action on a target(s). That way each item can act differently and you won't have one big massive method to deal with all the individual items/creatures.
example:
public abstract bool PerformAction(Object target); //returns if object is a valid target and action was performed
I've had a similar situation to this, although mine wasn't Role playing, but devices that sometimes had similar characteristics to other devices, but also some characteristics that are unique. The key is to use Interfaces to define a class of actions, such as ICanAttack and then implement the particular method on the objects. If you need common code to handle this across multiple objects and there's no clear way to derive one from the other then you simply use a utility class with a static method to do the implementation:
public interface ICanAttack { void Attack(Character attackee); }
public class Character { ... }
public class Warrior : Character, ICanAttack
{
public void Attack(Character attackee) { CharacterUtils.Attack(this, attackee); }
}
public static class CharacterUtils
{
public static void Attack(Character attacker, Character attackee) { ... }
}
Then if you have code that needs to determine whether a character can or can't do something:
public void Process(Character myCharacter)
{
...
ICanAttack attacker = null;
if ((attacker = (myCharacter as ICanAttack)) != null) attacker.Attack(anotherCharacter);
}
This way, you explicitly know what capabilities any particular type of character has, you get good code reuse, and the code is relatively self-documenting. The main drawback to this is that it is easy to end up with objects that implement a LOT of interfaces, depending on how complex your game is.
This might not be something that many would agree upon, but I'm not a team and it works for me (in most cases).
Instead of thinking of every Object as a collection of stuff, think of it as a collection of references to stuff. Basically, instead of one huge list of many
Object
- Position
- Legs
- [..n]
You would have something like this (with values stripped, leaving only relationships):
Whenever your player (or creature, or [..n]) wants to open a box, simply call
Player.Open(Something Target); //or
Creature.Open(Something Target); //or
[..n].Open(Something Target);
Where "Something" can be a set of rules, or just an integer which identifies the target (or even better, the target itself), if the target exists and indeed can be opened, open it.
All this can (quite) easily be implemented through a series of, say interfaces, like this:
interface IDraggable
{
void DragTo(
int X,
int Y
);
}
interface IDamageable
{
void Damage(
int A
);
}
With clever usage of these interfaces you might even ending up using stuff like delegates to make an abstraction between top-level
IDamageable
and the sub-level
IBurnable
Hope it helped :)
EDIT: This was embarassing, but it seems I hijacked #munificent's answer! I'm sorry #munificent! Anyway, look at his example if you want an actual example instead of an explanation of how the concept works.
EDIT 2: Oh crap. I just saw that you clearly stated you didn't want any of the stuff that was contained in the article you linked, which clearly is exactly the same as I have written about here! Disregard this answer if you like and sorry for it!

Categories

Resources