Jump to content

  • Log In with Google      Sign In   
  • Create Account

Banner advertising on our site currently available from just $5!

1. Learn about the promo. 2. Sign up for GDNet+. 3. Set up your advert!


Member Since 14 Oct 1999
Offline Last Active Apr 14 2015 10:52 PM

#5218758 Card game Class Structure

Posted by Xai on 24 March 2015 - 08:14 AM

The part I didn't say is that ... this is really just standard OO and polymorphism ... OO has always had factories and such ... people just think of it as "composition over inheiritance" because in 1 specific detail (the card's effects) you are composing a set of objects, instead of coding those compositions as a class ... but really this is just standard data driven OO ... no different than the way physics engines have worked since the dawn of time (A physical object is composed of a set of "parts" ... each combination is not coded manually as a separate class).


I think the reason people get confused is that OO classes all teach things wrong ... they talk about Animals with Dogs and Cats ... or Shapes with Square and Circle classes ... but that is a bad example, because it isn't based on what the computer is doing in a real world data-oriented way ... better examples would be something like a UI system that has Control, Button, TextBox ... where there is a very useful based behavior related to accepting input and knowing where you are on the screen ... but then the derived classes are actually different in their behavior ... and they have a valid logical reason to be aggregated ... I've never seen an "Animal" or "Shape" base class do anything useful ... not like a "Control" base class, which can support child control containment, etc.  Another good example might be an "Image" that has derived classes for a Bitmap (or similar) and another for a VectorDrawing ... (which in turn has a list of shapes).

#5204143 Code appearance, is it really important?

Posted by Xai on 13 January 2015 - 11:43 PM

What's funny is this:


Almost every one of the replies answered your original question (in my opinion correctly) ... but also, almost every single one either completely ignored the specific example you used, or (in my opinion incorrectly) expressed  a thought like the second version someone shows better programming than the first.  This is completely untrue.  The second version of your examples is in fact better code, and more readable.  But it does not in any way show that it was written by a better programmer.  It shows that it was written by someone who happened to be aware of a library function that exists and is useful, while the first example (yours) is exactly the type of code any decent normal recent programmer would write if that library function was not available, or they were not aware of it's existence.


It is a good idea to skim ALL the methods of any library class you are using, to see if another method might be better for you, but it is also true that 100s of times more code is out there and available to be used than any programmer is every going to know about and be able to use.


So your friend should not have "laughed at you" except in that good natured version of "man that code isn't needed because of this cool way you could do it instead".


The important thing in programming is NOT somehow having to know all the code out there and use it all correctly (although constantly working at this is important).  The important thing is CLARITY OF THOUGHT ... and the second important thing is CLARITY OF EXPRESSION.  Clarity of expression is VERY important, but always way less important than clarity of thought.  Clearly writing a program based on a poor and muddy design is not good (and is done more often than not) ... writing an unreadable mess based on a clear and good idea is not good (and is done often too) ... having a clear idea of what you want to accomplish and then a clear expression in code ... that is the goal.


Good luck.

#5201691 Requesting advice on where/how/what (sequence) to start.

Posted by Xai on 04 January 2015 - 12:32 AM

As I'm sure you know, there are DOZENS of ways to do this type of game, and it would vary by your expertise (if you had some), however your original list of "tech to use" was a sound set of tech that is A) used for this type of thing a lot .. and B) used TOGETHER with each other a lot ... and therefore C) has a LOT of online help available ... so it is a good choice.


Don't let yourself worry too much about doing things the RIGHT way at this point ... until you get something at all satisfying DONE, BY YOUR OWN HAND ... don't judge how it should be done, just try to do it BY ANY MEANS POSSIBLE.


For the client UI (in a browser) you are going to pretty much have to use either:  HTML, CSS and Javascript ... or else Adobe Flash, which requires the client to have installed the flash player to play your game ... those are really the only 2 options ... both are great ... 5-10 years ago most the simple cool games would have been Flash (which uses the language ActionScript), but recently HTML (XHTML or HTML 5 specifically) is getting to be more popular.  Neither one is a bad choice at all .... just spend 2-10 days trying the tutorials of 1 and see how it goes.  If you hate it ... try the other ... but after you've tried both, if you hate them both ... pick one anyway.


For the server side there are too many good choices to list.  But PHP and MySQL would have been the best cheap indie choice 5-10 years ago for sure, and is still fine.  


For Data - You can now use ANY of the SQL backends (MySQL, PostgressQL, MS SQL Server Express or SQL Anywhere, SQLlite) or even NoSQL options like MongoDB (and many others I've never used).  That said, the issue is not which DB you pick, that won't matter (except of course the choices between SQL based and NON-SQL based, which does matter).  The issue will be - learning RELATIONAL DATABASE MODELING / DESIGN well enough to organize your data in a way that doesn't suck for your game / goals.  Given a decent data model, I can use ANY of the existing tools with almost no issues.  So my recommendation is A) pick a tool (like MySQL) and use it ... but mainly just use simple standard ANSI SQL - don't bother learning any more custom MySQL specific stuff than you absolutely have to.


For Langauge - You can use ANY decent server supported languages.  5-10 years ago that would be either PHP, Perl, Python, ruby ... or Java or C#.  Today it's basically the same list ... except most people don't use Perl for server code much anymore.  PHP is extremely easy to use for small programs.  Python and ruby are similar but harder to start with ... however better for bigger programs.  C# (and probably Java) are great programming languages for programmers ... which I am, so I prefer C# ... but less good for people who aren't professional programmers.  If you want to learn programming in general, I recommend C#, PHP, Python or Javascript as good starting points ... but if you want to get stuff done on a webgame quickly .. I'd skip C# (even though its my personal favorite).

#5201685 "List iterator not incrementable", error enhanced for loop and remove

Posted by Xai on 04 January 2015 - 12:10 AM





each type of container has a reason to exist, don't think for a second that there is 1 choice that is "better" it simply isn't true, period ... I've read 4 sets of benchmarks and programmed in embedded C++ for over 8 years (not recently though)


The only thing you need to know though is:  The BEST container for a given job is NOT something you can figure out by using logic.  Because the performance of the use case is HEAVILY affected by object size, locality, operation ratios, and variations in data set vs cache size (and even branch predictors).  So the ONLY way to know what container is best for a job is to write the code and benchmark it.


Personally, I used to start with my default goto item "std::deque" and then switch to vector and list if I was pretty sure they were better (and in my experience about half my simple linear containers ended up being vector, most of the rest deque, and a small percentage ended up as lists - usually the obvious ones that were LARGE and had many RANDOM or FRONT inserts),  BTW occasionally you can get the most bang by not switching container types, but by switching container usage (like mentally swapping the MEANING of front and back if your vector has a lot of FRONT inserts but few back inserts)

#5183244 code for doing something while the game is off

Posted by Xai on 26 September 2014 - 11:42 PM

Pretty much all the games in this genre (including cookie clicker) are ONLINE/SERVER based games.  Meaning that you information is in a database on a server, and all the "truth" of the world is what's on that server ... so every "action" of any significance is a web request ... so the time in question here is always just the official server time  ...


so .. lets say the user does the action:  "build object A" ... it sends a request to the server which puts that in the db (with server based timestamps etc) ... then the client receives a response (usually with object A's id in it) ... and starts a local (on the client) display related to time passing.  Each message back and forth with the server includes a response, which includes the current server time, which the client uses to "sync" to (and avoid getting increasing amounts of client clock drift involved) ...


Then lets say the phone dies ... nothing "happens" when the phone is disconnected.  NOTHING.


The server is just sitting there with static rows in the db for that user, the client is just off ...


Then when the client runs the app again, it makes a "login" or "start session" or "resume" request to the server ... which then pulls all the "active/pending" builds from a list, updates their status based on current time, and sends the relevant info back to the client for updating in the UI (and notifying the user with things like flashing or pop-up displays ... etc.


The server is the holder of all truth, and runner of all important logic, the client is just a dumb data display and user input device .. which in certain areas has logic which mirrors or imitates the game logic to provide "real-time" updates to the UI (between server interactions).


There is also 1 exception to the server doing nothing except during client requests ... if the game uses push notifications (or anything like it) ... then the way that works is that the server usually has some periodic little method running to look at data that should generate a push notification (for instance when a building has just finished) ... and then package that up and send it to the client device (not a running app ... push notifications actually go to the phone, for when the app isn't running, ... then when the user clicks them, they launch the app ... which then does that "session resume" type call I spoke of earlier) ...


Servers that generate push notifications usually have some minimum threshold (like lets say 2-10 minutes) that must have passed since the last request came from the phone, else they won't send the notification (or they will send it to the app in a different format, instead of to the device as a push notification) ... systems like PubNub exist to make this stuff easy.

#5179991 Diablo type attacks

Posted by Xai on 12 September 2014 - 05:09 PM

You have probably already realized this, based on the 2 posts and your own, but just in case you didn't:


There are 2 separate ideas at play here:

1.  Determining what the targets are.

2.  Determining if the targets take damage (or how much).


For most diablo type games, number 1 is based on either a "collision template" or a function that does the same thing ... the goal being to have a quick method to determine what enemy (or set of enemies) is within the potential "hit box" (which can be a cone/sphere or whatever) ... for non-AOE weapons, the "nearest" such enemy is usually selected.  For AOE weapons, all such enemies are usually selected ...


And then the logic passes the (hit / potentially hit / targetted) units to the part of the code that computes / applies the damage ... which takes into account things like resistence, etc.


Then the output of this function is used to generate sound/graphic/particle artifacts (so that blocked attacks sound different than crits, etc) ...

#5179624 GOTO, why are you adverse to using it

Posted by Xai on 11 September 2014 - 10:37 AM

People should never discuss "goto" without first acknowleging that there are 2 different types of goto ... (that are as different as for loops and foreach loops).


The "goto" that exists in languages like (the old line numbered version of) BASIC, and a high proportion of early langauges is the unscoped goto.  It is the all-powerful, context free, danerous and evil goto.  This goto has the power to transfer execution from a line in any method in any file, to a line in any method in any other file.  This goto is "dangerous" in every sense of the word ... because it has no limits.


Just like a military grade weapon it is powerful, and appropriate at the right time (perhaps if you are writing an optimizing compiler or some such, or working in a langauge that is more efficient when using unstructured paradigms).  And because this goto is so powerful - it takes rules and training to use it without hurting people.  But this goto has been removed from nearly all modern langauges ... because its power CANNOT be used safely if you cannot trust every developer to always follow whatever rules you invent to guide its use ... and its use would deny the ability of any but the most awesome non-JIT compiler from ever being able to guarantee ANYTHING about ANYTHING ... it couldn't know how to clean up stack frames, free resources, do garbage collection, etc ... because the "jump somewhere, anywhere, whenever" feature would block any logical solutions to any but the simplest programs.  ... "tail call optimization" is kinda like a goto ... but this leads to my point.


The universal unlimited goto was REMOVED and REPLACED with other, more structured (aka limited) contructs ... that have been proven to be able to acomplish all necessary goals ... albiet without ideal efficiency in some cases ... with less danger and more guarantees.


The current GOTO in almost all currently used languages (except ASM) is a different goto entirely ... it cannot see or reference any labels outside of its own method/scope ... therefore it is just simple, weak, powerless syntactic suger for doing multiple breaks, etc ... if this goto had been named something else (perhaps "escape" or something) people would realize that it isn't the same thing written about over the years ... it is mathematically similar in structured programming consequences as the practice of using more than 1 return in a method (which violates structured programmings rules ... but since it is limited in maximum scope to a function, noone cares ... cause any real programmer can handle seeing it in any function that isn't so large it shouldn't exist anyway).


So just remember ... your goto in whatever language you currently use, probably isn't really a goto at all ... its just a slightly more powerful flow construct than a break statement, with a really bad reputation ...


but also remebmer, when they removed the POWER of the goto ... they also removed the REASON for a goto ... there is no longer any case where the current goto cannot be restructured as some other layout of code, that yields IDENTICAL performance and machine code in every way.


So goto is no longer harmfull, it is just pointless.

#5139154 No Low Level Programming is better ?, Please explain this then ?

Posted by Xai on 14 March 2014 - 11:22 PM

No professional programmer, let alone game developer, would say that all low level programming / optimizations are bad.


But experienced professionals will tell you that things similar to the saying "premature optimization is the root of all evil" ...


The gist of most professionals opinions is that you should not focus on specific target or performance concerns too early in the life cycle.  Partially because there is no point in optimizing a program or feature that may not make the cut into a final product anyway.  Partially because by the time the product comes out, the exact appropriate optimization might change.  Partially because clean logical code is easier to understand and modify, and you want to be able to change and improve as much as possible while learning what is fun and what isn't.  And Finally because it is often true that developer time is more important than efficiency in many cases and they'd rather make 3 games that are fun and for sale, then 2 highly optimized games that are just as fun and just as for sale.


Also, don't confuse "premature optimization" with "building for a platform".  An example of the type of optimization that would be discouraged is "oh man I have a great idea for how to make this highly detailed crafting system for this fantasy MMORPG i'm working on ... but I don't know which data structure or algorithm is the most efficient implementation".  An example of the type of platform utilization that is NOT bad would be "oh man, since this game is for phones and tablets I have a great idea for how we can leverage the gyroscope to control the crafting system in a unique and cool way".  See the difference is, in the first case, someone has a great idea and is letting the low level aspects reduce their ability to deliver a functional feature.  In the second case, the developer is being inspired to create a more enjoyable or fresh experience in harmony with the target platform characteristics.

#5131432 From C to ?

Posted by Xai on 14 February 2014 - 06:12 PM

I also love how people complain about C++, C# or Java version issues, and then don't comlain about Perl, Python or Ruby versions issues ... which are absolutely the worst, except most of the history of Perl 5 has been about as stable as C++,C# and Java ... hell, you can just now BARELY get a linux distro that ships with Python 3 (which is at 3.3) because they have a dependency on incompatible Python 2 code.  And ruby, a langauge I actually like, got stuck at 1.8 for more than 2 years after 1.9 was released, and now that 2.0 is released, only 1 major distro ships it.


The fact is in my entire C++ history, I had exactly 1 type of code I actually used that wasn't compatible with C++ 11 - related to how it disambiguates names in some cases.  I spent 3 hours fixing my code base, problem gone.


Also, in C#, none of my working code has ever failed to work on newer versions, except for 1 change they made with 1.1 as a security fix.

#5104254 GUI aspect ratio independence

Posted by Xai on 24 October 2013 - 10:51 PM

Depends on what you mean.  Do you mean you want letter boxing, so the actual controls are in correct aspect ratio as your base version ... or do you mean if the screen is 20% wider, you want your controls to be 20% wider?  Either way, you can see that if you just thing about it from those 2 choice, the answer is almost obvious.

#5098201 How to cut out duplicate code

Posted by Xai on 01 October 2013 - 11:20 PM

Or better yet, do not combine 2 completely separate concepts into single classes.  The responsibility to have manage a list of event handlers is a single purpose.  Aka a class.  This is a basic common pattern known by many names include Broadcaster / Listener, Publish / Subscribe or Observer pattern.  The responsibility to define a callback signature is another responsibility - usually using a function pointer typedef, a delegate, or other technique.  And the responsibility to define an actual specific slot, for a specific purpose within your program is a 3rd one.  So to put in some possible specifics.


Alvaro's EventHandler is a good class here - although for the way I plan to decompose responsibility in this example, I would rename something else, perhaps "EventManager" or something.


I would then use EventHandler or EventCallback as the base class for various event signatures, perhaps ClosedEventHandler, ResizedEventHandler, etc.  So a "ClosedEventHandler" would be a function signature for a callback that accepts the "closed event argument type" as its event argument.


I would then using INSTANCES of the EventHandler class, for each slot I had.  So perhaps:


EventManager<ClosedEventHandler> Closed;

EventManager<ResizedEventHandler> Resized;


And the OnClosed() method would iterate over the Closed EventManager calling all of the managed handlers (ie, "Raise" the event).


If you just look into how C#/.Net events and delegates work, you'll find a great example of a design like this.  But back in my C++ days I had written something quite similar to what I am posting here - although I haven't looked up all the details, and the names and such were different.

#5098199 about keyword and include

Posted by Xai on 01 October 2013 - 11:03 PM

You may wonder why / how the language designers decide what goes in the language as a "keyword" and / or "part of the core language", and what goes in the language as part of the "standard library" / aka requiring "#includes".


The normal short answer is - the language core is usually the smallest part reasonable, that can be used to write / reference the rest - they put nearly everything they can into the "standard library" instead of the language core ... but obviously if nothing is in the language itself, you couldn't do anything at all - so a certain subset of features needs to exist at a basic level, to even support the concept of writing basic code, and referencing and using already written code.


And as in Cosmic's answer ... it also includes whatever set of "rules" are needed so that the compiler / parser can just divide and understand the program's structure and content.

#5098198 Help debug multidimensional array loop?

Posted by Xai on 01 October 2013 - 10:56 PM

Here is an expanded version of Brother Bob's idea, in case you prefer to see more abstraction.  Note that all the named variables do not have to be decomposed the way I have shown them ... this is just to show all of the named concepts / values / partial values present in the domain you are working with.  In a real solution you would probably use about 1/3 to 1/2 of these actual values ... but which set depends on what is coming from your environment / configuration.  The main thing I want to encourage is - STOP USING MAGIC NUMBERS - put them in constants or #defines or something ... so that you can change them ONE PLACE and have your code still work.  So when you want to go from say 1280x800 to 1680x1050, or to a mobile devices 480x800 ... you can change you constants / config file, but not your debugged formulas / functions.

// Assuming these constant or configured values
int invMaxCols = 4;
int invMaxRows = 7;
int invCellWidth = 65;
int invCellHeight = 65;
int invGridOffsetX = ?;
int invGridOffsetY = ?;
// And these input values
int xClicked = ?;
int yClicked = ?;
// These can be easily computed - if needed
int invGridWidth = invMaxCols * invCellWidth;
int invGridHeight = invMaxRows * invCellHeight;
int invGridBoundsX = invGridOffsetX + invGridWidth;
int invGridBoundsY = invGridOffsetY + invGridHeight;
// AND THEN - version 1
bool isInGrid_v1 = 
  (xClicked >= invGridOffsetX && xClicked < invGridBoundsX
  && yClicked >= invGridOffsetY && yClicked < invGridBoundsY);
  int cellX = (xClicked - invGridOffsetX) / invCellWidth;
  int cellY = (yClicked - invGridOffsetY) / invCellHeight;
  T selectedItem = inventoryList[cellX][cellY];
  if(selectedItem != null)
// OR - version 2 = almost same as Brother Bob's great and succint suggestion.
int gridX = xClicked - invGridOffsetX;
int gridY = yClicked - invGridOffsetY;
int cellX = gridX / invCellWidth;
int cellY = gridY / invCellHeight;
bool isInGrid_v2 = 
  (cellX >= 0 && cellX < invMaxCols
  && cellY >= 0 && cellY < invMaxRows)
  T selectedItem = inventoryList[cellX][cellY];
  if(selectedItem != null)

#5096339 Implementing game objects with builder?

Posted by Xai on 23 September 2013 - 11:18 PM

I love the example Julien (not being sarcastic) ... but just so you know, Scalation is not related to the "scale" of an object.  In english it is:  Position, Rotation and Scale, not scalation.  Scalation is a visual things about the scale patterns on reptiles - similar to Coloration.

#5093829 Need architecture advice

Posted by Xai on 13 September 2013 - 12:38 PM

I think you are approching this development effort slightly backwards.  You are trying to solve the abstract development "problems" before creating your program, instead of creating your progam ... and trying to improve on problems you actual run into while doing so.  That's not how good design, architecture, patterns and experience is built.  There are general "goals" and "strategies" in programming (goals include:  don't repeat yourself, keep it simple stupid, clean readable code, consistency) (strategies include:  single responsibility principle, liskov substitution principle, tiered design, factories, polymorphism, interfaces, etc). 


Understand that the main goal is that for any given program there are a certain set of lines of code that MUST be written and executed by the machine to make the program work (such as the reading of files, bliting to screen, computing of damage, starting and stopping of sound, processing of input etc).  But these usually make up only a fraction of the actual code in a program.  The rest of the code is organizational overhead.  While there may only be a few ways to draw a texture on a triangle in a video card, there are HUNDREDS of ways to organize and layer code that eventually does so. 


These organizational structures, patterns, abstractions ... they have NO INTRINSIC VALUE.  They have value only to the extent that the humans who use them find them helpful for getting to the desired goal.  Accept that your program will not be able to be 100% perfect.  Accept that there will be "some" repitition of code, some ugliness of design, and some inconsistency and difficulty in maintenace.  When trying to get a progam working, the first question should not be how to make it fit a principle or ideal.  It should be how to make it work, to do what the computer needs to do.  And then, the second (or third or fifth) question should be "Is this code as clean, well designed, performant and or pleasing to me as it should be?". 


You don't learn to make high quality guitars by asking the luthier to explain to you the "right" ways of making them.  First you learn how to do a specific detail - staining or polishing wood perhaps, or attaching fretboards.  Then once you have done that thing, you ask as to how you might improve at that thing.  Then you move on to another.  And after years, you hopefully are good at all of the skills required to make quality quitars (or computer games).


So what I am sugesting (in a long winded and not so obovious way) - is that you bring an ACTUAL EXACT and REAL example of something you are actually doing, and ask for how to make THAT THING better.


For instance, if you have a "Sword" or "Weapon" interface or class, and perhaps have made it data driven, and perhaps are now looking at your code, unhappy because you feel like it is too much duplication, you then would be asking, "How might I generate this set of artifacts (or their equivelent) from a single source to reduce this duplication?".  By posting your existing code, and your question that way, people can help you factor out commonality in your design, or push you toward a more appropriate abstraction that would not create as much redundancy.


People cannot tell you how to generate code in general, or recommend or judge abstractions in general ... but only in specifics.


I will give you my example.  I started on some simple 2D game stuff about 15 years ago.  Early on I produced some results but had really ugly code and bad abstractions.  How do I know they were bad ... only because I had a hard time keeping strait what code was responsible for what feature and where to change things as I made my game better, without creating bugs.  So over time, my code moved toward certain shapes.  And many of these shapes eventually settled and haven't moved much in many years ... because they are now good expressions for what I need them to do (in a relative sense).  I can't remember my "bad" designs from 15 years ago.  But my current concepts are fairly simple.  These are NOT necessarily designs OTHERS should use, they just work for MY code basae.  I have "game resources" which represents things which need to be managed by resources managers (such as images and sounds), this general concept is not a class but a term, I have actual classes for the different resource domains including "ScreenResource", managed by a ScreenManager, and SoundResource by a SoundManager, etc.  There is some repitiion here, which I have factored into ResourceUtils, but mostly they are different.  I have GameObject which represents everything which interacts with the "game world" and affects the management of "game state".  I have a Game base class which represents an instance of the logical game, which is subclassed for each logical game such as ColorInvasionGame, which is different than my Application class which represents a client progam that the user uses to play or serve a game, which has derived classes such as ColorInvasionWin32App and PokerServerApp, etc.  When it comes to my simple 2D game sutff, I have IPhysicalObject which is anything with a position in the "physical" game world, and IMovableObject which is a physcial object that may change position, and IActorObject which is a movable object which may cause changes, usually via user input, AI action, or timers or other event triggers.  Of instance an asteroid is a movable object, but a pirate ship is an actor object.  Each of these adds an API to interact with the additional features it provides, while letting the common simple physics/collision engine work on physical objects.


The above has nothing to do with your original question, because I still need more details about the code you "have" that isn't as good as you'd like to have, to give you better advice.  The above is like 10% of the primary classes of my game design, which is broken into over 100 classes, about 30% of which are heaviliy data driven (and would be approprite as DB tables or configuration files) ... there is no 1 size fits all design.  My engine doesn't support 3D, doesn't do real physics, can do either turn based or real-time, and is only made to handle the small indie hobbiest stuff I like to play with in my spare time.  It is underwhelming and poorly designed in some areas, and overengineered in others ...


Just make code work, do something you like, and make it better piece by piece.