In my program the source rectangle for drawing can either be a regular rectangle, an empty rectangle, or a rectangle with an X or Y of -1. If the rectangle is normal (example being (0, 0, 64, 64)) then it just draws that from the texture. If it is Rectangle.Empty it draws nothing and just continues with the loop. If the source rectangle has an X or Y of -1 then it is determined to be a collision tile.
The problem with this is that it -1 is not intuitive. It is confusing and a bad solution. Also if there come to be more tile types it will start getting ridiculous like -2 meaning a slow tile or -3 meaning a water tile.
Another problem is that since I did not know there were going to be collision tiles early on and regular XNA rectangles were fine, the entire system (thankfully only around 1,000 of lines of code at the moment) uses XNA rectangles. I figure I'm going to have to make a separate class at this point and update everything but I'm not sure.
What would be a good solution to this? I have not really dabbled in extension methods at all. Could they be applied to the Rectangle class and be given methods like IsCollisionTile() or IsBlankTile()? Initially I was hoping I could derive from the Rectangle class to make a Tile class but unfortunately the class is sealed. I suppose another simple solution could be just making a global constants class with -1 being CollisionTile, 0 being BlankTile, et cetera. This would at least make it slightly more understandable but this still looks ugly to me:
if (tiles[y, x].X == Constants.BlankTile)
continue;
if (tiles[y, x].X == Constants.CollisionTile)
{
Utility.DrawRectangle(spriteBatch, new Rectangle(x * TileSize, y * TileSize, TileSize, TileSize), collisionTileColor);
continue;
}
spriteBatch.Draw(tileset, new Rectangle(x * TileSize, y * TileSize, TileSize, TileSize), tiles[y, x], Color.White);
If only there was a property I could use like Tag with controls. I'd really like to not abandon using the Rectangle class because it is so embedded in to the system and the program is purely functional, just not aesthetic in this regard. Ideally, I'd prefer a solution that just allows the Rectangle class to be extended to somehow be able to communicate with its clients what kind of tile it is supposed to be.
Well then, that took a lot more typing than I had originally hoped for. Sorry for the long read x_x
I would recommend setting global constants. The problem with extension methods in this case arises because Rectangle is a struct, a value type. That means that your extension method is working with a copy of the rectangle, not the original.
If the class can't be inherited from (which would usually be the appropriate solution here. Shame on you Microsoft!) then extension methods could defiantly work as you described.
Problem is - IMO it's less in style with C# and OOP in general to use methods that function like getters. That's what getters are for.
Because of that, I think the global constants option is more in line with the general style, but that's just my opinion.
From a totally programmatic POV - both methods are valid where the global constant class might be slightly faster (though I'm not sure of this)
At the beginning, you should consider, when do you use your Methods
IsCollisionTile() and IsBlankTile()
You have two choices:
*) You wanna use it globally, then you should better write a Utility-Class to have your Methods right there where you need them:
public static class CollisionHelper
{
public static Boolean IsCollisionTile(ITile tileToCheck)
{
...
}
}
*) Second, if you wanna use it only in connection with your tiles, you should definitly write an extension method, e.g. to accept every ITile-Object. Extensions methods are a great way to widely EXTEND the capabilities of classes. A sample could be:
public class RectangleTile : ITile
{
public static Boolean IsCollisionTile(this ITile tileToCheck)
{
...
}
}
I hope you have now an idea about Extension-Methods and how you could use them to solve your problem very easily ;)
Related
I'm working on a library and I'm having some trouble finding the right way to come up with the right APIs structure that keeps the code efficient without the need to have a ton of different overloads for each available API.
Say I have this method:
public static Brush CreateDummyBrush(Color tint, float mix, float blur)
Now, I want to let the user also receive an EffectAnimation instance for both those tint and blur animations, to let him animate them in the future. Suppose that an EffectAnimation is just a delegate that starts an animation on the returned Brush. The full code is here, just in case.
public static Brush CreateDummyBrush(
Color tint, float mix, out EffectAnimation mixAnimation,
float blur, out EffectAnimation blurAnimation)
Now, this is perfectly fine if the user wants to receive a delegate for both those animations. But, say I only need to animate the blur effect, then I'd call this API like this:
Brush brush = CreateDummyBrush(Colors.Gray, 0.6f, out _, 8, out var blurAnimation);
This works, but the library ends up allocating a useless delegate that serves no purpose, as it's just discarded.
The quick solution would be to create 4 different overloads, to cover the various combinations of out parameters. But is definitely not the right approach: too much clutter, and the number of APIs becomes too large if I have, say, 3 out parameters.
So my question is: can the caller check whether an input out parameter is actually a valid reference, or if the discard identifier has been used? I know C# has a ton of hidden tricks and APIs, is there something that would be able to achieve this?
Thanks a lot!
Not exactly what you are looking for, but if you want to change the API to return a tuple...
public (Brush, EffectAnimation, EffectAnimation) CreateDummyBrush(Color tint, float mix, float blur)
{
enter code here
}
//call it like so
var (brush, _, _) = CreateDummyBrush( tint, mix, blur);
var (brush, mixAnimation, _) = CreateDummyBrush( tint, mix, blur);
It wont save the processing within the function to create the objects but at
least they will be GC'ed
For a low number of possible out parameters, I'd create an Enum and a struct:
[Flags]
public enum RequestedEffect {
None = 0,
Mix = 1,
Blur = 2,
DanceLightFandango = 4
}
public struct Effects {
public RequestedEffect Effect;
public EffectAnimation BlurEffect;
public EffectAnimation MixEffect;
public EffectAnimation DanceLightFanangoEffect;
}
You would then change you signature to be:
public static Brush CreateDummyBrush(
Color tint, float mix, float blur,
ref Effects animations){...}
It's then up to the caller if the do any initialization of this struct - the default(Effect) means that the caller is not requesting any animations. You may wish to change some of the naming.
Note that although in the above, all of the non-enum fields in Effects are of the same type, that's not required when using this pattern.
I have a large abstract class that handles weapons in my game. Combat cycles through a list of basic functions:
OnBeforeSwing
OnSwing
OnHit || OnMiss
What I have in mind is moving all combat damage-related calculations to another folder that handles just that. Combat damage-related calculations.
I was wondering if it would be correct to do so by making the OnHit method an extension one, or what would be the best approach to accomplish this.
Also. Periodically there are portions of the OnHit code that are modified, the hit damage formula is large because it takes into account a lot of conditions like resistances, transformation spells, item bonuses, special properties and other, similar, game elements.
This ends with a 500 line OnHit function, which kind of horrifies me. Even with region directives it's pretty hard to go through it without getting lost in the maze or even distracting yourself.
If I were to extend weapons with this function instead of just having the OnHit function, I could try to separate the different portions of the attack into other functions.
Then again, maybe I could to that by calling something like CombatSystem.HandleWeaponHit from the OnHit in the weapon class, and not use extension methods. It might be more appropriate.
Basically my question is if leaving it like this is really the best solution, or if I could (should?) move this part of the code into an extension method or a separate helper class that handles the damage model, and whether I should try and split the function into smaller "task" functions to improve readability.
I'm going to go out on a limb and suggest that your engine may not be abstracted enough. Mind you, I'm suggesting this without knowing anything else about your system aside from what you've told me in the OP.
In similar systems that I've designed, there were Actions and Effects. These were base classes. Each specific action (a machine gun attack, a specific spell, and so on) was a class derived from Action. Actions had an list of one or more specific effects that could be applied to Targets. This was achieved using Dependency Injection.
The combat engine didn't do all the math itself. Essentially, it asked the Target to calculate its defense rating, then cycled through all the active Actions and asked them to determine if any of its Effects applied to the Target. If they applied, it asked the Action to apply its relevant Effects to the Target.
Thus, the combat engine is small, and each Effect is very small, and easy to maintain.
If your system is one huge monolithic structure, you might consider a similar architecture.
OnHit should be an event handler, for starters. Any object that is hit should raise a Hit event, and then you can have one or more event handlers associated with that event.
If you cannot split up your current OnHit function into multiple event handlers, you can split it up into a single event handler but refactor it into multiple smaller methods that each perform a specific test or a specific calculation. It will make your code much more readable and maintainable.
IMHO Mike Hofer gives the leads.
The real point is not whether it's a matter of an extension method or not. The real point is that speaking of a single (extension or regular) method is unconceivable for such a complicated bunch of calculations.
Before thinking about the best implementation, you obviously need to rethink the whole thing to identify the best possible dispatch of responsibilities on objects. Each piece of elemental calculation must be done by the object it applies to. Always keep in mind the GRASP design patterns, especially Information Expert, Low Coupling and High Cohesion.
In general, each method in your project should always be a few lines of code long, no more. For each piece of calculation, think of which are all the classes on which this calculation is applicable. Then make this calculation a method of the common base class of them.
If there is no common base class, create a new interface, and make all these classes implement this interface. The interface might have methods or not : it can be used as a simple marker to identify the mentioned classes and make them have something in common.
Then you can build an elemental extension method like in this fake example :
public interface IExploding { int ExplosionRadius { get; } }
public class Grenade : IExploding { public int ExplosionRadius { get { return 30; } } ... }
public class StinkBomb : IExploding { public int ExplosionRadius { get { return 10; } } ... }
public static class Extensions
{
public static int Damages(this IExploding explosingObject)
{
return explosingObject.ExplosionRadius*100;
}
}
This sample is totally cheesy but simply aims to give leads to re-engineer your system in a more abstracted and maintenable way.
Hope this will help you !
I have two classes, Human and Monster.
both have a Property called MoveBehavior
Human has HumanMoveBehavior, and Monster has MonsterMoveBehavior
I want the HumanMoveBehavior to move AWAY from Monsters, and MonsterMoveBehavior to move TOWARD Humans.
The problem I'm having is where should I put my code to move?
In the Human/Monster class?
Using this approach, I had a Move() Method, which takes a List of all entities in game, decides whether it's a Monster or Human using a method called GetListOfOpponents(List allsprites) and then runs GetNearestOpponent(List opponents);
But this looks really messy.
Should I have a SpriteController that decides where the Sprites move? I'm unsure where I need to put this code :(
Thanks!
You could think of a AIManager that just says:
foreach(GameObject go in m_myObjects) // m_myObjects is a list of all objects that require updating
{
go.Update(); // standard GameObject function
}
After that, each class should take care of its own piece of code. So updating works in the class itself.
So Human says:
// just a class which is a gameObject and also has moving behaviour
// do the same with monster
public class Human : GameObject, IMoveBehaviour
{
public override Update()
{
GoMove();
}
public void GoMove()
{
// human specific logic here
}
}
// This interface describes that some movement
// will happen with the implementing class
public interface IMoveBehaviour
{
void GoMove();
}
With using an interface, you can make the specific language part of the class and you don't have need to ALSO create some class that will handle that for you. Of course it is possible. But in real life, the human/monster is the one that is moving, not some object he is carrying.
UPDATE
Answer to the comment. Because there is an AIManager, or even a complete GameObjectManager would be nice to maintain all GameObjects, you could ask the AIManager for the placed where you could not go.
Because pathfinding is most of the time done by use of some navigation mesh or a specified grid, the GameObjectManager can return the specific Grid with all navigable points on it. You should for certain not define all positions in every monster. Because most of the time, the monster does not exactly know where everyone is (in real life). So knowing where not to go is indeed good, but knowing where everyone is, will give your AI too much advantage as well.
So think of returning a grid with the points where to go and where not to, instead of maintaining such things inside the monster/human. Always check where you should leave what, by thinking about what would be the thing in real life.
The way Valve handled this for entities in Half Life 2, is one of the better ways, I think. Instead of giving each AI its own separate Move methods and calling those, it simply called the Think() method and let the entity decide what it needed to do.
I'd go with what Marnix says and implement an AIManager that loops through each active AI in the game world, calling the Think() method of each. I would not recommended interfacing your Human class with an "IMoveBehavior" simply because it would be better to abstract that into a "WorldEntity" abstract class.
You might have invisible entities that control things like autosaves, triggers, lighting, etc, but some will have a position in the world. These are the ones who will have a vector identifying their position. Have the AI's Think() method call its own move() method, but keep it private. The only one who needs to think about moving is the AI itself.
If you want to encourage the AI to move outside of the Think) method, I would suggest some kind of imperative, such as a Goal-Oriented Action Planning (GOAP) system. Jeff Orkin wrote about this fantastic concept, and it was used in games such as F.E.A.R. and Fallout 3. It might be a bit overkill for your application, but I thought it was interesting.
http://web.media.mit.edu/~jorkin/goap.html
So, I currently have a Board class that is composed of Pieces. Each Piece has a color and a string that describes the kind of piece. It also has a 2d matrix with bits either set on or off, that allows me to know which pixels to paint with the desired color or not.
My question is, which class should have the responsability to draw the pieces on the board? On one hand, I'd say the Piece class should do it. But to do it, I'd have to pass a Board as reference to Piece's Draw() method and although it's not terrible I find it kinda awkward. This raises the problem that Piece would have "to know" the Board class.
On the other hand, I could just have the Piece have a
Boolean[,] IsPixelSet(int x, int y)
and Board would then have a method of the form:
void DrawPieceOnBoard() {
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
if (piece.IsPixelSet(x, y) {
board.DrawPixelAt(x, y, piece.GetColor());
}
}
}
}
How would you do it? And why? I can't see a clear winner in any of these approaches.
Thanks
edit
I'm not talking about actually drawing things on screen. What happens is that I'm implementing a Tetris game (currently, no GUI) and I need at every moment to set the Pixels of a Square on different positions on the board as it falls to the ground. The board basically only has an accessor and a mutator for each one of the (x, y) points. Let's now say I want to draw a Square(a type of Piece) on the Board. Should the Piece know of the board and its Draw() method make the changes to the Board, or should the Board access Piece's getter method and do it itself?
FWIW, in general MVC theory, neither class should draw itself.
Presentation would be a concern of a separate view.
I'd say the Piece draws. For example, your function does not allow to enhance the Piece to allow them to have several colors.
The Piece does not have to know all the Board, just some method (maybe part of an interface) Draw(x,y,color).
In my opinion the Piece should draw the piece and the Board should draw the board.
I would have something like this:
class Piece
{
Image Render(Rectangle bounds) { /* */ }
}
class Board
{
void Render(Graphics g)
{
//Draw the base
foreach (piece in Pieces)
{
var rect = figureOutPosition(); //Positioning logic to
g.DrawImage(location, rect, piece.Render(rect));
}
//Draw any overlays
}
}
I agree with nonnb, there's no logical concept of "drawing" for a chess piece or a board, it could be argued that the board has references to all the pieces, so it should draw itself. But that argument equally says that it could be a helper object, or the environment that does the drawing.
I'd personally opt for a rendering class (for example, maybe you want to be able to print the board in ASCII for a record of all the moves), or maybe in the future upgrade to a 3d rendering engine or something... that's just my 0.2ยข
It does not matter. What you may want to do is to make it so that either board depends on piece or piece on board for everything you do.
I'd go for the Composite Design Pattern - mostly the same solution as #Pondidum.
Drawable has the method draw()
Board isA Drawable
Piece isA Drawable
Board hasA array of Drawable.
I am trying to do the design of a Bejeweled game. I have basically 3 classes. The Game class, which is what is going to be used by the player, a Board class, that represents the board, and a SwitchController class that is responsible for checking if the wanted switch on the board is valid, making the switch, counting the number of possible switches available (so I can know when the game is over, etc).
My current design is something like the following:
Game:
isGameOver()
isSwitchValid(coord1, coord2)
makeSwitch(coord1, coord2)
getPieceAt(coord)
getBoardLength()
IBoard:
getPieceAt(coord)
setPieceAt(coord, piece)
getLength()
My idea would then to have a ISwitchController:
ISwitchController:
isSwitchValid(coord1, coord2)
makeSwitch(coord1, coord2)
getAllValidSwitches()
Here is a little diagram of how the classes are to be organized:
I would have 2 different concrete classes of IBoard available for use (and for each one of them, I'd have to have an ISwitchController implementation).
The problem:
My program is to have 2 IBoard implementations:
The first, ArrayBoard, will have all the pieces of the board stored in a 2D Array. There is nothing special about it. I will define an ArrayBoardSwitchController for managing this class.
The second, ListBoard, will have for each color of pieces, a List/Set with all the coordinates of the pieces of that color. I will define a ListBoardSwitchController for managing this class.
The main issue here is that the implementation of SwitchController will be totally different on ArrayBoard and on ListBoard. For example, while for implementing getAllValidSwitches() ArrayBoardSwitchController only needs the getPieceAt() method, that would not be a good idea to do with ListBoardSwitchController(in that class I use internally lists because it's easier to check if the move is valid that way).
From what I can see, there are 2 different possible solutions:
I could either merge together the
ISwitchController and IBoard
interfaces. That way I'd only have
two classes, Game and Board (while
basically Game would just be a
controller for the Board, as it
would be the Board that had all the
game logic). It wouldn't be that nice
because the classes wouldn't be
as cohese as they could be if I had
3 distinct classes.
Let the interfaces as they are and put
all the methods I need to work with public
in the concrete classes. For example, if I need
a getYellowPiecesList() method, I'd put it public
on ListBoard so ListBoardSwitchController could
use it. ListBoardSwitchController would only
know about it because it knows it only works
against ListBoards.
What's your opinion on the matter? The focus here is not so much on how to design the Bejeweled game, but how to solve this problem, that is recurrent when you try to implement algorithms: on one hand you want to have a clear and good OOP design, and in the other sometimes that gets in the way of having a sound and effective algorithm implementation.
The main issue here is that the implementation of SwitchController will be totally different on ArrayBoard and on ListBoard.
If this is the case, then it sounds like you haven't designed the IBoard interface well enough so that classes can use an implementation of IBoard without knowing the implementation details. If the user of an IBoard needs to know what implementation is being used, then it almost defeats the purpose of having an interface!
I would strongly suggest re-visiting the methods you are exposing on IBoard to see if there is a way you can expose something like "get the piece at this coordinate" in a more generic way. Make sure that any methods a controller needs to invoke on a IBoard instance are only the methods in the IBoard interface.
For example, while for implementing getAllValidSwitches() ArrayBoardSwitchController only needs the getPieceAt() method, that would not be a good idea to do with ListBoardSwitchController(in that class I use internally lists because it's easier to check if the move is valid that way).
If an operation such as "get piece at this coordinate" is instrumental to the IBoard interface, then the implementations must be faithful to their contract and implement it correctly. It sounds as if your ListBoard is not faithfully meeting the contract set out in IBoard.
3: Let ArrayBoardSwitchController and ListBoardSwitchController be inner classes of ArrayBoard and ListBoard. The implementation of the controller is tied to the implementation of your board, thus it makes sense to keep them together. Because the controller will be an inner class you can use the implementation details from the board. Then to make it work extend the IBoard interface to return a ISwitchController.
Note that this is only slightly different from option 1. (The ISwitchController can now be used indirectly from a IBoard, merging them gives direct access to ISwitchController)
What is the purpose of ListBoard as an object decoupled from ArrayBoard? If I were going to bother with the list of gems at all, I would keep it in an object which also held an array of what was in each position, so that swapping the position of two gems could be done quickly and efficiently. Not that I'm clear on why you need the position list anyhow?
If a 6507 running at 1.19Mhz with 128 bytes of RAM and 20% CPU availability can handle Columns, finding all 3-in-a-row combinations on a 6x20 in less than 100ms, I would think more modern machines could scan for moves acceptably fast without using a list of what gems are where. I'd suggest padding your board array so you don't have to worry about edge cases, and for each gem check 16 combinations of various cells within 3 squares of it(*) to see if they both match it. Some moves may be double-reported (e.g. this algorithm may detect that moving a gem left will create a 3-in-a-row, and also detect that moving the gem to the left of the first one right will create a 3-in-a-row) but that shouldn't be a problem.
(*) If a gem can move left, then it must match either the two gems to the left of the destination, or the two gems above the destination, or the two gems below, or one above and one below. Likewise for the other directions.