Non-object-oriented game tutorials - oop

I've been tasked with writing an essay extolling the virtues of object oriented programming and creating an accompanying game to demonstrate them.
My initial idea is to find a tutorial for a simple game written in a programming language which does not follow the OOP paradigm (or written in an OOP language but not in an OOP way) and recreate it in an OOP way using either C# or Java (haven't yet decided). This would then allow me to make concrete comparisons between the two.
The game doesn't have to be anything complex; Tetris, Pong, etc. that sort of thing. The problem I've had so far is finding a suitable tutorial, any suggestions?

Let's say that you found source code for a game not in OOP. There are some OOP virtues that you can point out in your essay:
Organization.
Since a game has many tasks, it is a good idea to assign a responsibility to one class. This means write one class that keeps score, one class that does file access (reading and writing game state, for example), classes to represent your characters, etc. Otherwise, you will have one huge text file with thousands of lines of code. It would be a nightmare to even look at it, let alone find what you need and fix it.
Encapsulation.
This is grouping together properties and functions for better organization. We used to have a different array to store each property - (example) one array for aircraft names, one array for firepower, another array for top speed, etc. That sucks because you need to make sure that the same index across all those arrays actually describes the correct aircraft. It's better to create an Aircraft object and give it those property names. You'll then have one array that holds aircraft - no need to keep track of too many arrays.
Reusability.
As you write more games (and even other apps), you will come across the need to reuse classes. For example, you would use the same Card class in your Solitaire game as any card game you'll write in the future.
Polymorphism/Inheritance.
Say that you want to display each character - both heroes and villains in some sort of a grid. You will want both Hero and Villain to inherit Character. Character will have common properties and even a[n abstract] Display() function. You would then write the custom Display() function for Character and Villain (that access class-specific data for drawing). You then create an array of Character objects, and you may store either a Villain or Hero in each slot. When the game goes through that list to display, each item.Display() call will automatically pick the correct Display() function based on the Character's actual type. Try to do this without OOP and you'll end up with a long if-else (and probably even nested) statement and all drawing routines in one place.
That's just from the type of my head from experience in general programming that you can definitely apply in game programming. There are probably more OOP aspects than mentioned, so you may want to research. Best of everything for your essay!

You can try grabbing a (simple) TI-Basic game from TICalc, Omnimaga, or most other calculator programming websites and try to understand its code.

Try a BASIC game from this site:
http://www.atariarchives.org/basicgames/

Related

Can polymorpism be applied to composition in c++?

I was planning on making a 2d chessboard game using classes and other OOP techniques. I know a little on polymorphism and was wondering if the technique used in polymorphism whereby I can delegate duties to the children class from the base class is applicable via composition.
[Edited]
A chessboard has players.I want to polymorphically call method functions move defined in both players without having to say player1.move(), player2.move()
Preface
Don't get lost in design patterns or design techniques. This question seems like an XY problem. Always take a step back and consider what you want to achieve.
Target
A single call to ask both players to move.
TL;DR
If there is no other context, I'd say just call them!
Explanation
In general:
A chess board always have two players. ( unless you're designing a specialized rule )
A chess flow is always operated in round robin ( first, then second, and then repeat ).
So what's wrong a chess flow controller to call two players to move in fixed order?
What would you gain from applying polymorphism to replace following code?
void begin_round(){
player1.move();
player2.move();
}
You'd save two line of type by calling a move... Hey wait! That's what begin_round() does!
Polymorphism approach does not save anything but increase complexity of the system which is a bad sign for system design.
Most of time, an as stupid as possible design is better than a complex approach, unless the design would save a lot of maintaining or developing resource. If a design saves nothing, then don't use it until it's a must.
Others
Composition is quite common in your case since a game is a composition for a board and two players.
Yes it can be implemented, what is your example?

how to model my game project in functional programming concept with OCAML?

I'm currently in a project of making a video game, to be specific, a turn-based strategy in OCAML. It's a coursework about functional programming, so the more functional programming the better, but if I can't do it with functional programming, I can use OOP if REALLY needed.
Here's the model of my game at the basic level :
In the following, when I say type, I actually mean instance/type/module, i.e. I don't know how I should implement it, but I know that they should be at least packaged into different sections.
There will be a Main type. It's role is to switch between menus, settings, and the actual game.
The Game type will run the game. In context, it will iterate over each Faction of the game, and iterate, within the Faction, each Unit that the faction has. Each Unit will have a specific behaviour attached to it.
Every game object ( that can be rendered in a 2D screen ) will have the GameObject type. Ideally, I can attach a bunch of video/audio/etc. renderer and I will be able to know their position on the map.
Grid will be an array of array composed of Tile. Grid has a global view over the game, from Grid, I can, for example, know the location of every GameObject in the Game
Tile is a tile on the grid. Eventually, I would like them to have special features, for example, a terrain type.
Unit ( not to be confused with unit type from OCAML ) is an entity controlled by a Faction. It has many attributes, such as health, mana, strength etc... and can do certain actions depending on who they are.
Faction represents either the player or one of the opponents. Some bonus apply depending on the faction. e.g. a faction could have greater health, but lower strength and vice-versa.
Action is a type that represents an action. It has a source and a destination attributes. It can represent, any type of action, from self healing to an AOE spell. It has access to Game so that it can be free to do whatever it pleases within the Game.
My goal is to make a game model that I can improve on progressively. For instance, I would like to make subclasses of unit, those who can attack from afar, and those who can only attack in melee etc.
If this was a OOP project, it would be pretty straightforward, albeit inefficient if I understood the previous comments. As you can see, my way of thinking is biased towards OOP because I haven't done any project of this scale without OOP. My goal here is to make it in Functional Programming.
I require your advice on how to implement what I described, or part of it so I can figure out the rest on my own.
Thank you.
EDIT: Edited the whole question
EDIT2: Some spelling and backticks
Your question is filled with imperative and OOP idioms: iterate, array, object, subclasses, ... So your mind set seems to be already made up.
Not surprising as GUIs and games are the most obvious examples for OOP. They have state and mutate over time and thrive on inheritance. And while you can do all those things functionally, with functors or with with first class modules I don't think it is worth it.
Luckily ocaml lends itself well to this. Records and classes can have mutable fields and ocamls classes can model your objects and inheritance nicely. And you still can use all the functional concepts of ocaml alongside the classes. It mixes well.

Best OOP way to represent chess pieces

Consider a Chess application that has a Board containing an array of chess Pieces. Which of the following is the best object-oriented way of designing the Piece object, taking into account the advantages/disadvantages of each choice:
One class for all pieces, with a piece_type attribute that enumerates the types of chess pieces,
A Piece interface that all pieces inherit from, which would have the overhead of creating 6 other classes each corresponding to a unique chess piece.
The first option has the advantage of being lightweight and uses the fact that there is a lot of similar code involved with each chess piece, but is less "OOP". The second option defines an object for each chess piece, but would probably have to contain a lot of copied code and additional source files.
Considering the above, which method would be the most "OOP" design for a chess Piece?
Definitely the second one. The reason is that different chess pieces aren't just different types, they have completely different behavior.
So breaking it down into different classes allows you to specify correct movement (no two units move alike) and attack (e.g. pawn attacks diagonally) behavior for each piece nicely with polymorphism without having giant switch/case clauses in single class.
As for copied code, that is definitely bad; if you find yourself in the need to copy code, it is best to move that particular code to separate class, however I'm not sure what would be needed to copy here - each piece is different.
And as for additional source files, that is something you should almost never worry about. If you are getting lost in all the files it is best to organize it differently, e.g. putting all chess piece classes in their own folder.
Update (from comment):
The game should decide that the piece moves, but the piece decides how. So for example if you wanted to be provide feedback for the user, the user would click on a unit, and the game would ask the unit where it can move (because only the unit knows where it can move), and once the user would confirm the target, the game would tell the unit to move to the (valid!) target. So the game provides interaction between the pieces and user, but the pieces provide behavior particular to each piece.
Indeed great answer, however, I would omit any "Definitely" from an answer, especially to OO related subjects...I assume that each time you address such a problem you'll reach a different design concept.
IMO, there are several options, and any mix and match may work and be reasonably implemented. For instance, defining class "Movement" to stereotype the different moves a Piece can make. Different pieces can actually utilize same movement in certain game play.
Interface vs. Base class definition, again, depending on whether you see any attributes to the classes or not. I see several (Type, assigned movement, Active/Inactive etc.) - and that actually shouts "Base Class"...
For the actual game play, is there a "Player" class that actually instantiate "Moves"? just something to think about.

How should I model pathfinding in the object oriented paradigm

My goal is to implement a (very simple) strategy game.
For the moment, I'll start with the map and two characters (I want the terrain to affect them differently) to experiment with pathfinding
The problem is that I have very little or no experience in object oriented design. I've used C++ classes before, but it was pretty straightforward: for instance, a class Graph implemented using an array of sets, with a method AStar. I didn't have in mind the concept of "several players".
I've thought of the following elements/classes: Game, Map and Character. Eventually a Pathfinder class.
First question: the position of a character is something the game should know? The map? or each character?
( I think the game should )
Second question: where would it be a good choice for a "findPath" method?
The Game?
Should a pathfinding algorithm be a method of Map? Something like map.findPath(character, srcpos, dstpos)
In the Character class? It makes more sense to do character1.findPath(map, srcpos, dstpos)
If I added a Pathfinder class, it would have to build its own representation of the map in order to determine the shortest path. And before doing that, it would have "to ask" the map how the terrain affects each player.
( I prefer the latter )
It seems the construction of an auxiliary structure (and asking the map) to apply, let's say, A* is something that I can't avoid.
Making things object-oriented is not a goal, it's a tool to be used when it makes sense. C++ is a language with lots of functionality that you can easily drown yourself with, so my advice is to keep things simple and easy.
This can mean keeping data and logic tightly together sometimes, or separating it completely other times.
First question: My initial reaction is that the character should know its position. But how you represent it with data depends on how you intend to use it, so both the game, the character and potentially also the map needs to know where the character is.
Second question: It depends on what the Map class is. Is it an object representing the map itself with necessary functionality exposed to the rest of your program, or is it a toolbox of functions that works on a simple data representation of the map?
If the Map class represents the map, it should have the necessary functionality exposed for a Pathfinder class to work on it (the pathfinding algorithm will need to have some additional data derived from the map, maybe temporary, maybe persistent).
If the Map class does not represent the map, you can put the pathfinding functionality in it. I think it would belong there in that case. If the pathfinding code causes the Map class to get too big, you should separate it into its own class anyway.
First Question: The position of the character should be a part of character itself (makes sense this way) for me.
Second Question: Finding a path logically cannot be a part of Map. Then you would be violating one of OOP principles i.e. Single Responsibility.
According to me you should create the PathFinder class. You can design it in this way
class PathFinder{
PathFinderAlgorithm algorithm;
//other required values according to your design
Path findPath(){
algorithm.apply();
}
//other required methods according to your design
}
PathFinderAlgorithm is an interface.
Using this you can also change the algorithm that you are using to find the path. Like if you in future need to find the longest path, all you have to do is create another class which will find the longest path and replace it in the PathFinder class.

Object Oriented Programming beyond just methods?

I have a very limited understanding of OOP.
I've been programming in .Net for a year or so, but I'm completely self taught so some of the uses of the finer points of OOP are lost on me.
Encapsulation, inheritance, abstraction, etc. I know what they mean (superficially), but what are their uses?
I've only ever used OOP for putting reusable code into methods, but I know I am missing out on a lot of functionality.
Even classes -- I've only made an actual class two or three times. Rather, I typically just include all of my methods with the MainForm.
OOP is way too involved to explain in a StackOverflow answer, but the main thrust is as follows:
Procedural programming is about writing code that performs actions on data. Object-oriented programming is about creating data that performs actions on itself.
In procedural programming, you have functions and you have data. The data is structured but passive and you write functions that perform actions on the data and resources.
In object-oriented programming, data and resources are represented by objects that have properties and methods. Here, the data is no longer passive: method is a means of instructing the data or resource to perform some action on itself.
The reason that this distinction matters is that in procedural programming, any data can be inspected or modified in any arbitrary way by any part of the program. You have to watch out for unexpected interactions between different functions that touch the same data, and you have to modify a whole lot of code if you choose to change how the data is stored or organized.
But in object-oriented programming, when encapsulation is used properly, no code except that inside the object needs to know (and thus won't become dependent on) how the data object stores its properties or mutates itself. This helps greatly to modularize your code because each object now has a well-defined interface, and so long as it continues to support that interface and other objects and free functions use it through that interface, the internal workings can be modified without risk.
Additionally, the concepts of objects, along with the use of inheritance and composition, allow you to model your data structurally in your code. If you need to have data that represents an employee, you create an Employee class. If you need to work with a printer resource, you create a Printer class. If you need to draw pushbuttons on a dialog, you create a Button class. This way, not only do you achieve greater modularization, but your modules reflect a useful model of whatever real-world things your program is supposed to be working with.
You can try this: http://homepage.mac.com/s_lott/books/oodesign.html It might help you see how to design objects.
You must go though this I can't create a clear picture of implementing OOP concepts, though I understand most of the OOP concepts. Why?
I had same scenario and I too is a self taught. I followed those steps and now I started getting a knowledge of implementation of OOP. I make my code in a more modular way better structured.
OOP can be used to model things in the real world that your application deals with. For example, a video game will probably have classes for the player, the badguys, NPCs, weapons, ammo, etc... anything that the system wants to deal with as a distinct entity.
Some links I just found that are intros to OOD:
http://accu.informika.ru/acornsig/public/articles/ood_intro.html
http://www.fincher.org/tips/General/SoftwareEngineering/ObjectOrientedDesign.shtml
http://www.softwaredesign.com/objects.html
Keeping it very brief: instead of doing operations on data a bunch of different places, you ask the object to do its thing, without caring how it does it.
Polymorphism: different objects can do different things but give them the same name, so that you can just ask any object (of a particular supertype) to do its thing by asking any object of that type to do that named operation.
I learned OOP using Turbo Pascal and found it immediately useful when I tried to model physical objects. Typical examples include a Circle object with fields for location and radius and methods for drawing, checking if a point is inside or outside, and other actions. I guess, you start thinking of classes as objects, and methods as verbs and actions. Procedural programming is like writing a script. It is often linear and it follows step by step what needs to be done. In OOP world you build an available repetoire of actions and tasks (like lego pieces), and use them to do what you want to do.
Inheritance is used common code should/can be used on multiple objects. You can easily go the other way and create way too many classes for what you need. If I am dealing with shapes do I really need two different classes for rectangles and squares, or can I use a common class with different values (fields).
Mastery comes with experience and practice. Once you start scratching your head on how to solve particular problems (especially when it comes to making your code usable again in the future), slowly you will gain the confidence to start including more and more OOP features into your code.
Good luck.