Currently I am trying my best programming a little video game in the style of the old Zelda games. However, I am having some trouble with the whole OOP style of thinking. To be more specific, I don't really know how to "design" the screens.
Let's say I have a class for my sprites and loaded a Wall-sprite to have a border for a certain area, should I make an extra "wall"-class, or is the wall being a "sprite" already enough? I thought it might be senseless to define an extra class since it would not have any different variables than the actual sprite class (as my wall IS only a sprite) so I didn't consider it to be a useful idea.
I am asking this because I have a little problem with the collision detection as well: What I currently do is loading a sprite for an object only once and rendering it multiple times at several locations. But the problem is that this causes the collision only to be detected at the last position the sprite was rendered at.
It gives me more problems when I render 2 cave-entrances somewhere but my game only checks for the 2nd entrance if I "entered" it.
So I thought making an extra "entrance"-class and creating 2 completely different objects of it that are treated separately might help, but should I then also create 30 objects for my wall-sprites?
Hmmm, there is really two questions, well three, but the OOP-thinking is too non-specific for a good question. So let's see if we can answer it by answering your valid ones.
Good OO Design is centered around "Patterns" (Common solutions to a variety of Problems) in the case of your sprite re-use in OO this would be known as a "Fly-weight" Pattern. Three important structural elements in good OO and understanding them is key to "getting it". They are:
Interfaces - They are free (relatively) of operational code, and provide only method and constructor signatures(generally) to allow for clean separation of coding concerns.
Classes - Only the reusable parts(ideally) of an object they are "the Mold or Pattern" that objects are instantiated (or patterned) from.
Objects - Instances (this chair or that chair as opposed, to Chair as an ideal) of the same form of Class (the ideal Chair). Objects (ideally) should keep as instance values only that which differentiates it from other instances of the same ideal.
However, because your original sprite is not an object you are having this collision problem, because it actually is the same instance rendered again and again, the graphics pipeline does not keep all of its previous locations as separate things it actual just stores pixels(usually), once they've been translated.
In this case if each instance is an object, each instance would have its location as a local instance variable(s), while its graphical representation and collision detection method would be common to all instances of the class.
Don't think of it as having 30 whole copies in memory at once, you only have thirty copies of the instance variables. This is true if you use OO or not; in a procedural solution to get proper collision detection you would have to maintain an array of all of the places you rendered that sprite and iterate through each time, further your code would be less cleanly separated and you would have to iterate through the array for every sprite interaction as well as for updating moving sprites. With OO you could handle this with one class method call that recurses it children.
A good class structure for this simple example might be:
An Abstract Sprite Class (abstract because you will never use a non-specific Sprite) containing only code common to all sprites
A Concrete Wall Sprite Class that extends Sprite, only the code for non-moving wall sprites.
A Concrete Trigger Sprite Class (whose graphic might be clear or null) for behaviors that need to be triggered in "open spaces"
A Concrete Agent Sprite Class for moving sprites (might implement a movable interface meaning all derivatives of the class have a move() method.
A Concrete Character class that extends agent for a movable sprite that is driven by user commands.
It may seem confusing at first, but it's actually cleaner, simpler, and more maintainable doing it the OO way.
:)
Related
I have been reading about inheritance vs composition. I know there is already allot about this topic on this site, but i have a question about this specific example I hope will not be seen as duplicate.
Some guidelines I have gathered so far:
Prefer composition over inheritance.
Has-a relationship will therefore almost always mean composition.
Is-a relationship CAN mean inheritance is best, but not always.
So now for the example
I have been working on a simple game engine to practice C++. For this I have made some classes:
The Image class that contains an image that can be rendered.
The Transform class is all about positioning.
The Sprite class contains an image that can be rendered, in a specific position.
There is more of course, but let’s keep it simple for the example.
So - Sprite HAS an image and HAS a position (transform). Following the guideline that would mean composition for both. BUT I think it is just so much easier to have Sprite inherit from Transform.
Because I what to do things sprite->setPosition() and sprite ->setScale().
If a Sprite inherits from Transform, I don’t have to do anything, sprite->setPosition() automatically calls Transform::setPosition() for the sprite object.
If Sprite HAS a Transform, I would have to redirect ALL of these kind of methods to the Transform! (It's how I have been doing it so far and it seems to work fine)
I don’t want to write things like this for every positioning method: (there are quite a few already)
Sprite::setPosition(Vector2 position) {
mTransform.setPosition(Vector2 position);
}
But It seems to go against convention.
What do you all think?
When you say "easier" I think you mean "faster", because let's face it, forwarding the calls from the Sprite to the Transform component it's not difficult at all, it just takes more typing (and "less typing" is good, but I would weigh other things first). The problems of choosing inheritance over composition could not be there now, but could arise later.
With public inheritance you just have to declare the inheritance, and all the public interface from Transform is available in Sprite. All. If one day you add a "Rotate" method to the Transform, but don't want Sprites to be shown upside down, then you have to hide the base class method somehow. There are good answers here from Matthieu and CodeFirst about how to do that hiding in C++. But as Matthieu points there, by hiding the method you violate the Liskov Substitution Principle. If you had used composition, you could have just ignored that "Rotate" method in the public interface for Sprite.
With private inheritance you would be a little bit better, because it represents a "is implemented in terms of" relationship between Sprite and Transform, closer to reality than the "is a" relationship represented by public inheritance. But then you would need to put "using" statements to make available the methods from Transform in Sprite (see Eugen answer also in the previous link). So you end up still having to write extra code to achieve your purpose (although less than with composition).
With composition I feel that you have easier options to deal with design problems. Do you want to simply call the component method? You forward the call. Do you want to ban the component method? You don't add it to the Sprite interface. Do you want to add functionality to one method (e.g. keeping the Transform scale from being set to such value that the size of the Sprite Image is too small)? You add the method to the interface but do some extra processing/checkings before/after calling the Transform component...
If you can get your hands on Scott Meyers' Effective C++ book, you have two items that are worth reading for this discussion: "Use private inheritance judiciously" and "Model 'has-a' or 'is-implemented-in-terms-of' through composition". A final point extracted from there in favor of composition: "Both composition and private inheritance mean is-implemented-in-terms-of, but composition is easier to understand, so you should use it whenever you can"
I am new to XNA and this is a philosophical question. In most examples I have seen, game assets are defined as private class variables, loaded in the LoadContent method, and then drawn with the Draw method. If I have a large game with a lot of screens, there could be quite a bit of declarations at the top of this class.
With that said, here are my questions
Should I use the content pipeline over Texture2D.FromFile().
What are the advantages other than faster loading.
Should I call Content.Load(Of T)([some asset name]) outside the LoadContent() sub.
How are you handling loading assets for different screens? Are you declaring all assets at the top?
Thanks in advanced,
Eric
Using the Content Pipeline allows you to compile your textures with your binary, which saves space, load time, and protects your assets from editing/unauthorized use if you care about that. On the flipside, if you wanted an asset to be editable (like texture packs), FromFile() is effective. The file must exist in the expected directory with normal use of course.
It is good practice but ultimately your decision on where you choose to load content. Remember that content loading requires reading from disk, which is not something you want to be doing every frame for sure, and not really something we like doing during the game. You will want to set up your Game State Management so that content can be loaded completely during loading screens or game startup and not during the game itself. Of course, this is precisely what level loading screens are for! If you're very clever you can sneak loading in during pauses in gameplay, a la Metroid Prime's 'door loading'. Depending on the scope and assets of your game, though, you shouldn't really need to load dynamically like that.
Finally, about dumping assets: the answer is the great trope of OO programming: abstraction. If you have trouble organizing members then move them into an inherited class or a subclass as necessary (and only when sensible). In my game design I rarely have more than 2 Texture2Ds, 1 SoundBank, and perhaps a VertexBuffer/IndexBuffer per class. If I have designed things well, these are stored in a base class like "Sprite" from which any visual objects inherit. In my latest set of tools, I've gone one level deeper, so now it looks like "Player.base(which is Sprite).Animation.Texture" if you want to access the actual texture... but you don't need to because all animation/drawing is handled completely by the Animation class and updated by Sprite along with Position, Rotation, Scale, Bounding, etc.
So, break down your game into objects. If you are storing a Texture2D PlayerTex and Vector2 PlayerPos in your Game class and in Draw you are drawing PlayerTex at PlayerPos, you are not taking advantage of OO programming. Store PlayerTex and PlayerPos in a Player class which also defines every other aspect and behavior (methods) of the player. Now all you need in Game is Player myPlayer, and in Draw you call myPlayer.Draw(SpriteBatch .. etc). You can take it even further! Here are some classes pretty much every game will have: Entity (base class of all dynamic objects), Level (stores scenery and Entities of each level and handles their interaction), GameScreen (stores and increments its Level member upon completion of each), ScreenManager (stores a stack of Screens to update, like GameScreen, but also MenuScreen, PauseScreen, LoadingScreen)... The list goes on. At this point all your Game1 class does is update ScreenManager, and if you inherit ScreenManager from IDrawableGameComponent, you don't even have to do that.
I hope I haven't dived too far into the deep end of OO 101, but if you're having trouble keeping track of all the members of your main class, you should start to break things down. It's a fundamental OO skill.
If all else fails, learn to use the #region <name>/#endregion tags liberally. Honestly, use them anyway, they make everything better.
I keep hitting this problem when building game engines where my classes want to look like this:
interface Entity {
draw();
}
class World {
draw() {
for (e in entities)
e.draw();
}
}
That's just pseudo-code to show roughly how the drawing happens. Each entity subclass implements its own drawing. The world loops through all the entities in no particular order and tells them to draw themselves one by one.
But with shader based graphics, this tends to be horribly inefficient or even infeasible. Each entity type is probably going to have its own shader program. To minimize program changes, all entities of each particular type need to be drawn together. Simple types of entities, like particles, may also want to aggregate their drawing in other ways, like sharing one big vertex array. And it gets really hairy with blending and such where some entity types need to be rendered at certain times relative to others, or even at multiple times for different passes.
What I normally end up with is some sort of renderer singleton for each entity class that keeps a list of all instances and draws them all at once. That's not so bad since it separates the drawing from the game logic. But the renderer needs to figure out which subset of entities to draw and it needs access to multiple different parts of the graphics pipeline. This is where my object model tends to get messy, with lots of duplicate code, tight coupling, and other bad things.
So my question is: what is a good architecture for this kind of game drawing that is efficient, versatile, and modular?
Use a two stages approach: First loop through all entities, but instead of drawing let them insert references to themself into a (the) drawing batch list. Then sort the list by OpenGL state and shader use; after sorting insert state changer objects at every state transistion.
Finally iterate through the list executing the drawing routine of each object referenced in the list.
This is not an easy question to answer, since there are many ways to deal with the problem. A good idea is to look into some Game/Rendering engines and see how this is handled there. A good starting point would be Ogre, since its well documented and open source.
As far as I know, it separates the vertex data from the material components (shaders) through the built-in material scripts. The renderer itself knows what mesh is to be drawn in what order and with what shader (and its passes).
I know this answer is a bit vague, but I hope I could give you a useful hint.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
You are writing a Tetris program in Java. How would you set up your class design with regards to the following aspects?
Piece class: Have one Piece class, with an internal array which determines the shape of the piece, versus having seven Piece classes, one for each of the pieces. They are all subclasses of one generic Piece class.
Piece class representation: Have an array of 4 instances of Block, representing one square of a piece, and each Block contains its location on the Board (in graphical coordinates) vs. having a 4x4 array where null means there is no block there, and location is determined by the shape of the array.
Location: Each Block in the Piece array or on the Board array stores its location vs. the Piece and the Board know the locations of the Blocks that comprise them.
Generating a Piece: Have a static method of the Piece class getRandomPiece, or have a PieceFactory which you make one instance of that has the genRandomPiece method on the instance.
Manipulating the current piece: Use the Proxy pattern, so that everything that needs access to it just uses the proxy, or have a getCurrentPiece method on the Board class and call that any time you want to do something with the current piece.
This is not homework. I'm just at odds with what the intro CS course teaches at my college and I want to see what people in general believe. What would be thought of as "good" OOP design? Ignore the fact that it's for an intro course - how would you do it?
Firstly, I wouldn't subclass the Piece class because it's unnecessary. The Piece class should be capable of describing any shape without using inheritance. IMHO, this isn't what inheritance was made for and it just complicates things.
Secondly, I wouldn't store the x/y coordinates in the Block objects because it allows two blocks to exist in the same place. The Piece classes would keep a grid (i.e. 2D array) holding the block objects. The x/y coordinates would be the indexes of the 2D array.
As for the static method vs factory object for getting a random piece, I'd go with the factory object for the simple fact that the factory object can be mocked for testing.
I would treat the board as one large Piece object. The Board class would keep the large Piece object as a member variable, and might keep other Piece objects such as the current piece being played, and the next piece to be played. This is done using composition to avoid inheritance.
All these classes and stuff... it might be making the problem way too abstract for what it really is. Many different ways to represent tetris pieces (stackoverflow.com/questions/233850/…) and many different ways to manipulate them. If it's for an intro course I wouldn't worry about OOP. Just my opinion, not a real answer to your question.
Having said that, one could suffice with simply a Board and Piece class.
Board class: Encapsulates a simple 2d array of rectangles. Properties like currentpiece, nextpiece. Routines like draw(), fullrows(), drop(), etc.. which manipulate the current piece and the filled in board squares.
Piece class: Encapsulates an array of unsigned 16 bit numbers encoding the pieces in their various rotations. You would track color, current location, and rotation. Perhaps one routine, rotate() would be necessary.
The rest, would be, depending on the environment, handling keyboard events etc...
I've found that placing too much emphasis on design tends to make people forget that what they really need to do is to get something running. I'm not saying don't design, I'm saying that more often than not, there is more value in getting something going, giving you traction and motivation to keep going.
I would say, to the class, you have X hours to make a design for a tetris game. Then they would need to turn in that design. Then I would say, you have X days, to get something running based on the design you turned in or even not based on the design.
One Piece interface, with seven classes that implement that interface for the individual pieces (which would also enable the OOP course to discuss interfaces) (EDIT: One Piece class. See comments)
I would have a BlockGrid class that can be used for any map of blocks - both the board, and the individual pieces. BlockGrid should have methods to detect intersections - for example, boolean intersects(Block block2, Point location) - as well as to rotate a grid (interesting discussion point for the course: If the Board doesn't need to rotate, should a rotate() method be in BlockGrid?). For a Piece, BlockGrid would represent be a 4x4 grid.
I would create a PieceFactory with a method getRandomShape() to get an instance of one of the seven shapes
For manipulating the piece, I'd get into a Model-View-Controller architecture. The Model is the Piece. The Controller is perhaps a PieceController, and would also allow or disallow legal/illegal moves. The thing that would show the Piece on the screen is a PieceView (hrm, or is it a BlockGridView that can show Piece.getBlockGrid()? Another discussion point!)
There are multiple legitimate ways to architect this. It would benefit the course to have discussions on the pro's and con's of different OOP principles applied to the problem. In fact, it might be interesting to compare and contrast this with a non-OOP implementation that just uses arrays to represent the board and pieces.
EDIT: Claudiu helped me realize that the BlockGrid would sufficiently differentiate pieces, so there is no need for a Piece interface with multiple subclasses; rather, an instance of a Piece class could differ from other instances based on its BlockGrid.
Piece class: I think that a single class for all the pieces is sufficient. The class functions shoudl be general enough to work for any piece, so there is no need to subclass.
Piece Class Representation: I believe that a 4x4 array is probably a better way as you will then find it much easier to rotate the piece.
Location: Location should definitely be stored by the board, not the piece as otherwise you would have to go through the entire set of blocks to ensure that no two blocks are in the same position.
Generating a Piece: Honestly for this one I do not feel that it will make too much of a difference. Having said that, I would prefer a static function as there is really not so much to this function that it warrants its own class.
Manipulating the Current Piece: I would just implement a getCurrent function as I feel that there is no need to overcomplicate the problem by adding in an extra class to serve as a proxy.
This is how I would do it, but there are many different ways, and at the end of the day, the thing to focus on is simply getting the program running.
I'll be as direct as I can concerning this problem, because there must be something I'm totally missing coming from a structured programming background.
Say I have a Player class. This Player class does things like changing its position in a game world. I call this method warp() which takes a Position class instance as a parameter to modify the internal position of the Player. This makes total sense to me in OO terms because I'm asking the player "to do" something.
The issue comes when I need to do other things in addition to just modifying the players position. For example, say I need to send that warp event to other players in an online game. Should that code also be within Player's warp() method? If not, then I would imagine declaring some kind of secondary method within say the Server class like warpPlayer(player, position). Doing this seems to reduce everything a player does to itself as a series of getters and setters, or am I just wrong here? Is this something that's totally normal? I've read countless times that a class that exposes everything as a series of getters/setters indicates a pretty poor abstraction (being used as a data structure instead of a class).
The same problem comes when you need to persist data, saving it to a file. Since "saving" a player to a file is at a different level of abstraction than the Player class, does it make sense to have a save() method within the player class? If not, declaring it externally like savePlayer(player) means that the savePlayer method would need a way to get every piece of data it needs out of the Player class, which ends up exposing the entire private implementation of the class.
Because OOP is the design methodology most used today (I assume?), there's got to be something I'm missing concerning these issues. I've discussed it with my peers who also do light development, and they too have also had these exact same issues with OOP. Maybe it's just that structured programming background that keeps us from understanding the full benefits of OOP as something more than providing methods to set and get private data so that it's changed and retrieved from one place.
Thanks in advance, and hopefully I don't sound too much like an idiot. For those who really need to know the languages involved with this design, it's Java on the server side and ActionScript 3 on the client side.
I advise you not to fear the fact, that player will be a class of getters and setters. What is object anyway? It's compilation of attributes and behaviours. In fact the more simple your classes are, the more benefits of an OOP you'll get in the development process.
I would breakdown your tasks/features into classes like that:
Player:
has hitpoints attribute
has position attribute
can walkTo(position), firing "walk" events
can healUp(hitpoints)
can takeDamage(hitpoints), firing "isHurt" event
can be checked for still living, like isAlive() method
Fighter extends Player (you should be able to cast Player to Fighter, when it's needed) :
has strength and other fighting params to calculate damage
can attack() firing "attack" event
World keeps track of all players:
listens to "walk" events (and prevents illegal movements)
listents to "isHurt" events (and checks if they are still alive)
Battle handles battles between two fighters:
constructor with two fighters as parameters (you only want to construct battle between players that are really fighting with each other)
listens to "attack" events from both players, calculates damage, and executes takeDamage method of the defending player
PlayerPersister extends AbstractPersister:
saves player's state in database
restores player's state from database
Of course, you game's breakdown will be much more complicated, but i hope this helps you to start thinking of problems in "more OOP" way :)
Don't worry too much about the Player class being a bunch of setters and getters. The Player class is a model class, and model classes tend to be like that. It's important that your model classes are small and clean, because they will be reused all over the program.
I think you should use the warpPlayer(player, position) approach you suggested. It keeps the Player class clean. If you don't want to pass the player into a function, maybe you could have a PlayerController class that contains a Player object and a warp(Position p) method. That way you can add event posting to the controller, and keep it out of the model.
As for saving the player, I'd do it by making Player implement some sort of serialisation interface. The player class is responsible for serializing and unserializing itself, and some other class would be responsible for writing the serialised data to/from a file.
I would probably consider having a Game object that keeps track of the player object. So you can do something like game.WarpPlayerTo(WarpLocations.Forest); If there are multiple players, maybe pass a player object or guid with it. I feel you can still keep it OO, and a game object would solve most of your issues I think.
The problems you are describing don't belong just to game design, but to software architecture in general. The common approach is to have a Dependency Injection (DI) and Inversion of Control (IoC) mechanisms. In short what you are trying to achieve is to be able to access a local Service of sorts from your objects, in order for example to propagate some event (e.g warp), log, etc.
Inversion of control means in short that instead of creating your objects directly, you tell some service to create them for you, that service in turn uses dependency injection to inform the objects about the services that they depend on.
If you are sharing data between different PCs for multiplayer, then a core function of the program is holding and synchronising that piece of state between the PCs. If you keep these values scattered about in many different classes, it will be difficult to synchronise.
In that case, I would advise that you design the data that needs to be synchronised between all the clients, and store that in a single class (e.g. GameState). This object will handle all the synchronisation between different PCs as well as allowing your local code to request changes to the data. It will then "drive" the game objects (Player, EnemyTank, etc) from its own state. [edit: the reason for this is that keeping this state as small as possible and transferring it efficiently between the clients will be a key part of your design. By keeping it all in one place it makes it much easier to do this, and encourages you to only put the absolute essentials in that class so that your comms don't become bloated with unnecessary data]
If you're not doing multiplayer, and you find that changing the player's position needs to update multiple objects (e.g. you want the camera to know that the player has moved so that it can follow him), then a good approach is to make the player responsible for its own position, but raise events/messages that other objects can subscribe/listen to in order to know when the player's position changes. So you move the player, and the camera gets a callback telling it that the player's position has been updated.
Another approach for this would be that the camera simply reads the player's position every frame in order to updaet itself - but this isn't as loosely coupled and flexible as using events.
Sometimes the trick to OOP is understanding what is an object, and what is functionality of an object. I think its often pretty easy for us to conceptually latch onto objects like Player, Monster, Item, etc as the "objects" in the system and then we need to create objects like Environment, Transporter, etc to link those objects together and it can get out-of-control depending on how the concepts work together, and what we need to accomplish.
The really good engineers I have worked with in the past have had a way of seeing systems as collections of objects. Sometimes in one system they would be business objects (like item, invoice, etc) and sometimes they would be objects that encapsulated processing logic (DyeInjectionProcessor, PersistanceManager) which cut across several operations and "objects" in the system. In both cases the metaphors worked for that particular system and made the overall process easier to implement, describe, and maintain.
The real power of OOP is in making things easier to express and manage in large complex systems. These are the OOP principles to target, and not worry as much whether it fits a rigid object hierarchy.
I havent worked in game design, so perhaps this advice will not work as well, in the systems I do work on and develop it has been a very beneficial change to think of OOP in terms of simplification and encapsulation rather than 1 real world object to 1 OOP class.
I'd like to expand on GrayWizardx's last paragraph to say that not all objects need to have the same level of complexity. It may very well fit your design to have objects that are simple collections of get/set properties. On the other hand, it is important to remember that objects can represent tasks or collections of tasks rather than real-world entities.
For example, a player object might not be responsible for moving the player, but instead representing its position and current state. A PlayerMovement object might contain logic for changing a player's position on screen or within the game world.
Before I start simply repeating what's already been said, I'll point towards the SOLID principles of OOP design (Aviad P. already mentioned two of them). They might provide some high-level guidelines for creating a good object model for a game.