Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am running a programming club at a high-school, and I have introduced my students to OOP using simplistic classes in C++. I believe at least theoretically they get the idea. I would like to be able to offer them a specific project they can work on together. The question I have is which approach to take. When I took programming classes in college, I saw two different approaches, but in my opinion they both had serious shortcomings. I ended up sleeping through most of them and learning the stuff on my own from books and examples.
Now that I am in the teacher's shoes, I would like to get your opinion on which approach is preferable or if there is a third option.
Approach 1 that was used, was to write a program on the board (or on a computer with a projection screen). The class definitions were always written first. Usually students would look really bewildered at this point, because the purpose of variables and methods would seem entirely obscure to them. The only time that they learned about what each variable and method was for and how they interacted was when the instructor would finally write the implementation (I called this the outside-in method)
Approach 2 was to explain what we are trying to achieve, and creating classes and members as needed. This has the opposite problem. He would be writing a method that would use these imaginary classes that would have to be implemented later. But the students has no idea how these other classes would work.
As it happens, I worked my way through University by working as a teacher. I am now a software engineer.
In my experience, it is paramount that the students be emotionally invested in a programming project. I'll get to your question in a minute, this is a necessary preamble.
To get there, I made the topic of the program something that really interested them, regardless of how silly it seemed, as long as it was something that connected with them in their world.
So, it could be (depending on the age of your students) about ranking singing stars by their talent level, including Justin Bieber. You can imagine the uproar at that one.
Like, Load their lyrics and count the number of times they say the word "baby". Something creative, something fun.
This will make "dry" questions come alive. Like, what should the "singer" class look like. Why it should have properties like "octave range" will be immediately intuitive.
Should the singer class have a method called 'barfOnStage'? (The Biebs barfed on stage a while ago). Sure, why not!? They will easily see the difference between methods and properties.
I mean, I'm just talking off the top of my head, I'm sure you can apply your own inventiveness and creativity to whatever's appropriate for your kids.
I would love to hear what you went with, and how the kids' project turned out.
For the beginner level I would go with a modified number 2 approach where you start with an easy problem and then build on it. Experience is the best teacher....like the time my High School teacher had us 'iterate' through twenty discrete variables as a 'list' and then taught us about arrays....
You need to select the right problem. It needs to be a problem that exercises the 'object oriented muscles' not the 'algorithm muscles'. It needs to be something that you can build requirements on it that exercise object orientation. A simple CRUD program should be adequate. You'll just have to constrain them to using objects and not arrays as I assume they'll be comfortable doing. I'll leave the exact specification up to you.
First, have them write a program that just lets them add records to the 'database'. Just by Creating a 'row' in their 'database' they'll be forced to learn how to create an object and instantiate an object.
Next, have them modify their program to display the contents of their 'database'. When they Read their 'database' they'll exercise the .show function or however you implement that capability.
Third, have them make it so they can change the contents of a 'record'. Updating will reinforce how to tell an object to modify itself.
Finally, they should modify the program to allow for 'record' removal. This will reinforce proper object destruction.
Taking it to the next level (and since this is c++) you could:
require they implement their 'database' as a linked list
write the specification so you can do something that requires objects
being added together
add to the scope of data so the program structure would be better
facilitated by a template or inheritance (vehicle 'database' that has
both cars and motorcycles for example)
From my experience doing is the best teacher. Having someone show me how to do something (or doing it as a group on a board) short circuits the learning. Wrestling with it and having some Socratic guidance teaches a deeper understanding and yields a better programming brain.
If they aren't ready to do the 'create' function then coding it out as a group on the whiteboard will work, but once they have a template of how everything fits together they need to be behind a computer figuring it out.
If it's a beginner programming course I'd say the OOP aspect is of minor issue. Focus on expressions, statements and control flow.
If the focus is on OOP I'd say begin with the history of OOP and what OOP focus is. From that one can look at how one describe these concepts in different languages. (i.e. ADT, Simula etc http://retis.sssup.it/~lipari/courses/oosd2010-1/02.oop.pdf )
...and then experiment.
"If we look at the whole history, we see that the proto-OOP stuff started with ADT, ..."
-- Alan Kay (http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en)
I am thinking about the following scheduling problem:
I have X people.
I have Y meeting slots with Z meeting roles available in every meeting.
For some roles, same person may combine two of them in a single meeting, but most are one person = one role.
For each person x in X, I know a set of facts about them:
a) The last date they attended the meeting and had a specific role (historical);
b) Their availability for any meeting y in Y;
c) Their specific preference for the roles z in Z or a set of roles (no specific dates) for the group of meetings.
I'd like to build a scheduler with the following objectives in mind:
a) All meeting roles are filled.
b) Preferences are accommodated if possible;
c) Distribution of people / roles should be uniform (i.e. if one person is scheduled every meeting and other just for one meeting once in a while -- it's unacceptable; if one person is scheduled for the same role over, and over, and over again -- it's unacceptable).
Now, I have a gut feeling that the task is not easy at all :), so my specific questions are:
What language would be better suited for the task (somehow I feel Prolog can deal with it, but I am not entirely sure).
What is the proper approach to solve this task and how close can I get to my objectives in #4 above?
Any good read on the kind of problem I am looking to solve?
Thank you!
P.S. If you are curious, the use case is scheduling a roster for a set of Toastmasters meeting (example) (I am lazy do it by hand and I'd like computer to help me in this task at least partially).
A rule engine, like Drools Expert or Prolog is good for defining the constraints (= score function). However it's terrible at finding the best solution.
Since your problem is probably NP complete (especially if the meetings need to be put into a timeslot and/or 1 person can't attend 2 meetings at the same time), you need to use a planning optimization algorithm on top of that, such as construction heuristics and metaheuristics. Take a look at the curriculum course example in Drools Planner (java, open source, ASL).
From my point of view, the language you are going to program in doesn't really matter that much: for simple problems the language to use is more of a personal preference instead of an exact science. If you like/want to learn Python, use that. If you "feel like" Prolog today, use that.
What will be a factor in your choice though is how you want to preserve and present your data. From your question it can be told that you need the following:
A database (or at least, a persistent resource) to store your available participants and roles, past and future meetings storing the roles for every participant, and some way to schedule availability.
Some way to present your data (command line, GUI, or website).
Some business logic that describes the way of assigning roles, criteria for the attendance and such.
You will want to use some third-party components for most of these, since your time is to be spent on the added value of your product; creating a shiny ORM or GUI toolkit is not your goal in this. So the programming language you will choose should have a proper support for these items (especially the first two). I can't say it for Prolog, but Python will have you fully covered in these areas. I think it goes beyond the scope of this question to suggest specific toolkits, so I'll leave it at that for now.
After this step, you analyze your problem, which you seem to have done quite nicely already. So, start implementing it. To be able to verify your specific use cases, it sounds like you could benefit from some Test or Behavior Driven Design, so you may want to read up on that.
For learning the language, just search StackOverflow for "[language] tutorial": there are already plenty of answers linking to very nice resources for getting started with any language you will choose.
Final advice: perseverance is the hardest part, so try to set yourself some goals or milestones, or try to involve other people in one way or another. That way you'll enlarge the possibility of following through with creating a nice piece of software.
Even though I'm a Python fan, I'd hardly suggest Prolog for this task. I'm familiar with Prolog, and it's definitely nicer solved with Prolog. But it depends on how you will use that program. Your choice - decide whether the installation of Python or Prolog is easier for you (if you just run it on your local PC, it doesn't matter that much I guess), or on other requirements you have.
It's farly simple with Prolog, if you know about Prolog. After you learnt Prolog, you can solve it with some thinking without much problems I guess (if you really understood Prolog!).
Basicly you should start with Prolog of course. I'd suggest to use SWI-Prolog, it's one of the most common Prolog Implementations used. Also, there is a nice tutorial for it: http://www.learnprolognow.org/
It seems to me, but I'm not 100% sure, that you are not familiar with Prolog yet. You need the time to learn Prolog first, so it also depends on how fast you need to have your program. It's possible to get through the Tutorial in less than a month, as far as I remember. Of course this hardly depends on how much time you invest per day - you can do it in less or even more time.
Prolog is based on rules. Every of your requirement can be expressed as a rule. After you have your set of rules, you can ask, which combination (of persons and meeting room) conform to all those rules. For the historical data of the different persons, you could use a small database.
This sounds like an optimization problem and I agree with Geoffrey that it would be a NP Complete problem. I recently developed a scheduling algorithm for a university that does final exam scheduling. I used a genetic algorithm with domain specific heuristics to solve that problem. My implementation performed nicely with a student count of 3000 + and course count of 500, it took about 2 hours to find a near optimal solution.
I agree with people who suggest Prolog for this task; I would suggest to take a look
at ECLiPSe (it is, besides being a Prolog implementation, a constraint programming
language which have more powerful problem solving capabilities than just Prolog).
ECLiPSe has now a very nice introduction, with many examples and very to the point,
with a free pdf, written by Antoni Niederlinski:
http://www.anclp.pl/
Among the examples on ECLiPSe site, I found the following which seems to be relevant: http://eclipseclp.org/examples/roster.ecl.txt.
ECLiPSe is thoroughly documented and, according to this documentation,
can be also integerated with C++/Java.
I was computer science student in college,one of the courses was c++.
I enjoyed learning the native c++. i studied to pointers and classes and inheritance .
After that i took data structures, it was a nightmare(code implementation).
reasons are :
1-I'm not ready (i was careless back in school before college, my math skills were worse than you may think not because i tried but because i didn't try! i don't remember myself studying except the nights before the actual exams).
2-When i took data structures i realized computer science without any doubt is not for me(NOT EVEN CLOSE TO READY).
I have interest, even though i wasted years (2 exactly) feeling guilty for applying for CS.
am i a unique case or there are regular people like me who managed to succeed?
is it possible to excel even in my age 22 ?
is it possible to be a good programmer after years of practicing?
is it possible to learn math to assist me on becoming a good developer in future years?
im now in cis major and it is way easier than CS and i could manage to pass, even though it is different than the one in your minds.
I'll tell you that, yes you can become a good programmer with practice. But I'll also tell you that it's MUCH (much much) easier to practice something you like than something you don't like.
It seems to me that, it doesn't much matter what your GPA is or how well you did in school. If you like computers and computer programming enough, you can become successful at it.
That depends on what you wish to do/accomplish and how dedicated you are. Maths will defenitely help you in certain areas of Computer Science, but you can be a good programmer, and still be average at maths.
Always remeber that any talent can be improved on with dedication and practice.
Take math classes in college, they'll help with basic fundamentals that are used in CS classes.
Learning math by yourself will be quite difficult, especially if you're new to it. If your university provides the opportunity for formal math education (as an elective course or two), I'd recommend taking advantage of it. It'll help in the long run.
While there is a lot of math in CS courses ( most CS depratments belong or once belonged to the maths faculty ) once you are out there in the field there is not much actual math done.
There are specific projects which require a lot of physics and math (oil field reserviour simulation, flight simulation, genome mapping) but these are actually quite rare.
There is another set of projects which require heavy statistics (stock market analysis, population analysis, drug trails etc.) which are more common but these projects want statistics graduates and not CS graduates.
So dont despair most programs in the real world don't require any maths more complex than
if ((balance + sale_amt) > credit limit)
Having said that data structures as in Linked Lists, Hash tables, balanced trees and graphs are probably the most useful part of your course; most of the other programming skills you can easily pick up as you go along but you really need to study these to be an effective programer.
It depends on what you're going to do with a CS degree. Most of the actual math you will use as a general programmer is algebra I. However, learning math well also requires you to learn other skills - like how to break a problem down into smaller parts, how to communicate correctly with math, and how to translate English descriptions into mathematical equations.
I was just playing an old SNES RPG (Secret of Mana, if anyone cares) and was wondering a few general things about game programming.
Sorry for some of the brain-dead questions, I'm really a beginner. :)
These questions are quite general, but use SNES-style RPGs as a "template" to get an idea of what I mean:
How do games keep track of all the objects, triggered events, etc in its "world"? For example, how does it keep track of which treasure chests have already been opened, which doors are locked, which story events have already triggered?
Does it basically create an array of elements each corresponding to a chest/door/event/etc and "mark" each (change its value from 0 to 1) when it has been opened/triggered? If there are multiple approaches, what are they?
How are "variable lists" handled? Ie, if you have a game when you can have a huge inventory of objects (ie: armor, swords) and have X of each object, how is this done?
My guess: have a struct that has a big array with a spot for every possible object (an array of X ints, where X is number of possible objects to own) where each element's value represent how many of that object you have, and then have a giant enum of every object so that an object is matched to a corresponding index, and access it, like: numberOfSwords = inventory[SWORDS] where SWORDS is part of an enum and has some integer number associated with it. How close am I?
How about the case where the number of objects can vary? Ie, if I have a game where I have some amount of enemies on the screen and they can get killed / give birth to new enemies at any point, it would seem to me like I would need an array of "enemy" objects to loop through and process, but that the number of elements would vary at any one time. What is the usual approach to this? Linked lists?
Any help / hint / pointers are really appreciated.
In a very basic manner your answers are not too far off, things could be done the way that you mention them. However space and processing power can come into play so instead of an array of bools to track which treasure chests or how far along the chain of events you are you may want to slim it down to bits being on and off and use the bitwise operators for masking to see where you are in a storyline or whether or not to show the treasure chest you are about to display as opened or close.
For inventories, instead of tracking how many of each item a player has it may be better to have a base item for everything a player can pick up; weapons, armor and even money. Then you could make a linked list of just the items the player has. Use the Enum for the item as you mentioned and then the quantity of that item. This would allow for sorting of things and would also only keep in memory the items the player's character(s) actually have/has. You could extend this data structure to also track if the item is equipped. You could likely keep more generic what the item does sort of information in an items table.
The enemies would likely be a bit more complicated as you need to do a few more things with them. A linked list here though is still likely your best bet. That way removal of an object form the list would be a mite bit easier (can simply remove the link and the like when a player kills them or add in a new enemy wherever needed in the list.)
Honestly there is no one answer and it can depend on quite a few things. The best way is really to simply try it out.. For a simple 'what if I do this for this' it really does not end up taking all that long to give it a whirl and see how far you get. If you start running into issues you can start to consider other options :)
Hope this helps.
Edit: Just wanted to add in a link to www.codesampler.com. Generally more DirectX oriented tutorial sites but as a beginner it can start you thinking or give you a set of places to start. As an added bonus alot of the DirectX SDK examples/samples started to be formatted very much like how this site's tutorials are done. Can help ease you into the whole thing.
This is a pretty advanced question for a beginner.
I'd like to echo In Silico's response that you should learn C++ language basics before you tackle this subject.
To give you a place to start, you should know about container classes (Linked Lists, Vectors, HashTables/Dictionaries, Queues etc) and how they work. Since the Standard Template Library (STL) is pretty standardized, it would be a good place for a beginner to start.
You should also know about inheritance and how to build a hierarchy of classes.
For example, you asked about inventory in a role playing game:
I'd start by defining an InventoryItem class that defines or sets up an interface for all of the code necessary for an item to participate in your inventory system.
Something like:
class InventoryItem
{
private:
std::string description; // A description of the item
bool inInventory; // True if in the players inventory, false if on the ground etc...
int weight; // How much the item weighs
int size; // How much space the item takes in inventory
// etc...
};
In the InventoryItem class you'd also define the member functions and data needed for InventoryItem to be placed in your container class of choice.
The same sort of thing holds true for triggered items, things on the ground etc. They're typically kept in a container class of some sort.
The STL containers will take care of the variable sizes of the containers mentioned in the last part of your question(s).
vector is a good place to start for a general list of items.
HashTables/Dictionaries are good for looking things up with a key.
I hope this is enough to get you started. Good luck.
In addition to James' excellent post, some keywords for you to google for
Data structures
linked list
doubly linked list
queue
for the theory of dynamic memory management.
Also, let me share my standard recommended links for people asking for aid on basic c++:
Full scale tutorial on c++
C++ Language Reference (including STL)
ANSI C Language reference for all those pesky C stuff that C++ keeps using
Your question is not specific for "games programming". You are asking how arbitrary data is organized and stored in bigger programs. There is no definite answer to this, there are lots of different approaches. A common general approach is to make a data model of all the things you want to store. In C++ (or any other languages with object oriented capabilities), one can create an object oriented class model for this purpose. This introduction to C++ contains a complete tutorial on object oriented modeling in C++.
Lots of applications in general use a layered approach - the data model is one layer in your application, separated from other layers like a presentation layer or application ("game") logic.
Your data modeling approach will have to deal with persistency (that means, you want to store all your data on disk and reload it later). This question was asked earlier here on SO. This fact will give you some restrictions, for example, on the use of pointers.
EDIT: if your data model reaches a certain complexity, you might consider using a (lightweight) database, like SQLlite, which has a C/C++ api.
Finally, here is a link that might give you a good start, seems to fit exactly on your question:
http://www.dreamincode.net/forums/topic/26590-data-modeling-for-games-in-c-part-i/
Regarding Question #1, I concur with James and others on using a database that stores the persistent state of your game objects.
Regarding questions #2 and #3, about variable numbers of objects and objects that need frequent updating: I'd suggest maintaining a registry of objects that need updating for each game "cycle" (most games operate on cycles -- loops, if you like, though a modern game uses many loops spawned as separate threads).
For instance, every time you introduce a new enemy or other object that needs to be updated to respond to the current situation or behave in a certain way, you register that object in a list. Each cycle, you iterate through your current list of updateables (probably based on some priority scheduling mechanism), and update them accordingly.
But the particular data structure you use will depend on your program. Linked lists are a valid foundation structure, but in all likelihood you'll want to use a custom compound structure that meets your particular needs. Your approach may combine any number of classic data structures to achieve the best result in performance and effect.
Considering this, I can't emphasize enough the importance of studying advanced data structures before you tackle any sort of serious programming project. There are scores of great books on the topic and you'd do well to study them. Here's a link to a tolerable overview of the classic data structures: http://randu.org/tutorials/c/ads.php
Having read up on quite a few articles on Artificial Life (A subject I find very interesting) along with several questions right here on SO, I've begun to toy with the idea of designing a (Very, very, very) simple simulator. No graphics required, even. If I've overlooked a question, please feel free to point it out to me.
Like I said, this will hardly be a Sims level simulation. I believe it will barely reach "acceptable freeware" level, it is simply a learning exercise and something to keep my skills up during a break. The basic premise is that a generic person is created. No name, height or anything like that (Like I said, simple), the only real thing it will receive is a list of "associations" and generic "use", "pick up" and "look" abilities.
My first question is in regards to the associations. What does SO recommend as an efficient way to handle such things? I was thinking a multimap, with the relatively easy set up of the key being what it wants (Food, eat, rest, et cetera) and the other bit (Sorry, my mind has lapsed) being what it associates with that need.
For example, say we have a fridge. The fridge contains food (Just a generic base object). Initially the person doesn't associate fridge with food, but it does associate food with hunger. So when its hunger grows it begins to arbitrarily look for food. If no food is within reach it "uses" objects to find food. Since it has no known associations with food it uses things willy-nilly (Probably looking for the nearest object and expanding out). Once it uses/opens the fridge it sees food, making the connection (Read: inserting the pair "food, fridge") that the fridge contains food.
Now, I realise this will be far more complex than it appears, and I'm prepared to hammer it out. The question is, would a multimap be suitable for a (Possibly) exponentially expanding list of associations? If not, what would be?
The second question I have is probably far easier. Simply put, would a generic object/item interface be suitable for most any item? In other words, would a generic "use" interface work for what I intend? I don't think I'm explaining this well.
Anyway, any comments are appreciated.
If you were doing this as a hard-core development project, I'd suggest using the equivalent of Java reflection (substitute the language of your choice there). If you want to do a toy project as a starter effort, I'd suggest at least rolling your own simple version of reflection, per the following rationale.
Each artifact in your environment offers certain capabilities. A simple model of that fact is to ask what "verbs" are applicable to each object your virtual character encounters (including possible dependence on the current state of that object). For instance, your character can "open" a refrigerator, a box of cereal, or a book, provided that each of them is in a "closed" state. Once a book is opened, your character can read it or close it. Once a refrigerator is opened, your character can "look-in" it to get a list of visible contents, can remove an object from it, put an object in it, etc.
The point is that a typical situation might involve your character looking around to see what is visible, querying an object to determine its current state or what can be done with it (i.e. "what-state" and "what-can-i-do" are general verbs applicable to all objects), and then use knowledge about its current state, the state of the object, and the verb list for that object to try doing various things.
By implementing a set of positive and negative feedback, over time your character can "learn" under what circumstances it should or should not engage in different behaviors. (You could obviously make this simulation interactive by having it ask the user to participate in providing feedback.)
The above is just a sketch, but perhaps it can give you some interesting ideas to play with. Have fun! ;-)
To the first question:
My understanding is that you have one-to-possibly-many relationship. So yes, a multimap seems appropriate to me.
To the second question:
Yes, I believe a generic interface for objects is appropriate. Perhaps use something similar to REST to manipulate object state.
I heard a podcast a while back with the developer of The Noble Ape Simulation, which may be interesting to you - conceptwise and perhaps codewise, as you can access the source code, as well as download binaries.
The podcast was FLOSS Weekly 31 with Randal Schwartz and Leo Laporte.
Life with lisp(sbcl) :)