Showing posts with label game. Show all posts
Showing posts with label game. Show all posts

Wednesday, 3 March 2010

"Bob" the Builder (pattern)

So, I've heard of Java constructors. These friendly little guys make an instance of an object when the program calls them, setting variables if necessary, making everything work the way you need to. Today, however, was the first time I'd heard of Builders.

Constructors can, sometimes, get really messy. "Setting variables if necessary" can get to the point where you have 20 variables to set and 18 of those are optional. It's nasty to program a constructor to properly handle optional variables and it's nasty to call a constructor with all of those variables. And who wants to print out a list of which variable comes when in the call to the constructor?

Hello, builders. Builders are like flexible constructors, but they require a bit more manipulation to set up properly. Basically a builder is a class placed inside the class you want to construct, and no constructor is made available for that class. Instead, you call the constructor for the builder (in Java syntax this means you call something like endgoal.builder() where endgoal is the thing being built), with any required values included in the () after builder. Then you continue calling optional values by adding .option1(), .option2(), and so on until the object is fully set up for you. All of the values that eventually go into your endgoal object are stored privately inside the builder class so as not to cause any funny business on the part of your outer class.

When you're all done, you call the endgoal.build() class to put it all together for you, as necessary.

What am I using this for? At the moment, validation on the text box used to enter Material Codes. Matcodes must be 11 characters long, consisting only of english alphabet letters. I convert the input to uppercase inside the material code interpreter's method, so it's not a big deal what case you use externally, but internally it does make a difference.

I realize that the matcode input is not the only text field I'm going to use, and in searching for the way to limit the maximum number of characters in a text field I've come to the conclusion that it requires making a so-called "Document" that tells the input box how to behave. This is easy enough, but why code a separate document for each text input when I can just create a builder?

For now I'm coding in the options to change the input to Upper/Lowercase depending on needs, to force the input to be alphabetical, numerical, or both, to set a maximum length onto the input, and finally to allow or disallow spaces in the input. In the case of my matcode text box, I'll call something like:


input.setDocument( new JTextFieldLimits.LimitBuilder()
.charLimit(11).toUpperCase().forceLetter()
.forceNoSpace().build() );

It looks a little nasty but for my sanity it's better than something more like:

input.setDocument( new JTextFieldLimits(true, 11,
true, false, true, false, false, true));

where I have to remember which position responds to which value every time I make a new input box. And that would be even longer if I come up with more options to throw in here. Don't forget that if all I want to do is disallow spaces, with the builder I can just do LimitBuilder().forceNoSpace().build() whereas with the other one I have to include all of the "false" values until the very end. And Java forbid I forget how many false values that adds up to.

The JTextFieldLimits class isn't quite finished yet, but it's progressing smoothly and I don't think I'll run into too many problems with it. Once that's done I'll get back to work on isolating the MatPolygonDraw class by having it build its own panels. I think I'll have both of those done before my next post.

Reference: http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html Thanks for the help!

Tuesday, 2 March 2010

Compartmentalization, Encapsulation, and Isolation, oh my!

I've been focusing a lot on these inheritance features today. I know, for instance, that I can create a class Planet, and that I can also create a class Moon extends Planet, so that the two are differentiated in name but don't need repetitive coding. I've been considering the pros and cons of making all of the attributes I've taken to calling low-level attributes (a planet's name, for exmaple... the things that the object stores that don't reference other objects) implement a custom interface.

Time for some explaining? I think so. In Java, a class (known as a child or a subclass) can extend another class (known as a parent or a superclass). This means that, unless an underlying method in the child overrides the parent's method (this is done simply by creating a method in the child with the same name as the parent's method), the methods defined in the parent are equally as applicable to the child. In the case of class Planet and class Moon extends Planet, as above, the method getSize() would return a number representing the planet's diameter, and would do the same for a Moon even without explicitly rewriting the code.

Now on to implementing interfaces. An interface is an abstract class, which means that it cannot be used directly. Instead, when a class implements an interface, everything written into that interface MUST be overridden by the new class. If I have attributes, to use the example above, which all have different variables within them (say, a description attribute holds text describing the object, an armor attribute holds a value representing the armor's strength), I can create an interface that defines getType() and getValue() as methods that MUST be overridden, therefore making the attributes universal in structure.

A Java class can extend only one parent lass, but can be extended by infinitely many children. A Java class can implement as many interfaces as it wishes, so long as all of the underlying methods are overridden. Because of the way these two aspects of "inheritance" work, they are known as two related but separate pathways of defining a new class. By making a new class a child of a parent class, you are inheriting behavior. That is to say, all of the 'hows' in the class are defined by the parent class, except for the occasional overriding method or additional method. By having a new class implement an interface, you are inheriting structure, because the layout of the new class must match the interface, but the specific algorithms used are specific to the new class.

There's my brief lecture on Java's inheritance. That out of the way, I haven't done coding work today, seeing as I instead attended a showing of "Willy Wonka and the Chocolate Factory" (that's right, the original) at the University. I did get a lot of (additional) thinking in and I realized one of the shortcomings in the current embodiment of the interpreter I showed yesterday. I have a button that is specialized for the window I showed you, not one I can place into just any window I place the graphic into. This also means that when I go to make a more capable "administrator" version that allows me to generate material codes on-the-fly, I'll have to completely reprogram that button.

Instead I can use some nifty features of Java's by including a specialized button subclass into the class that creates the material graphic. This subclass would be inherently tied to the material graphic that the button updates, and wouldn't require any coding except placement in the larger window.

Overall this would greatly increase the capabilities of the materials panel I've made, as well as the capabilities of any future classes I make. I consider this Compartmentalization (and I think the textbooks agree with me) because it means that any frame that uses the MatCodeInterpreter will, without extra work, be able to add the necessary buttons and fields to manipulate it.

I think tomorrow will see me working on making that a reality.

Monday, 1 March 2010

Mission Accomplished!

For the first time in my blogging career of nearly two weeks, I have something to show you that I've been promising in relation to my Simulation. That's right, I have finished my material decoder. Well, at least functionally, certainly it needs work to be implemented.


That, my reader(s), is my new MatCode Interpreter in action. Type in 11 characters, hit evaluate, and a new shape will be made for you. I admit, it has limited practical use as it doesn't supply exact values (it could, just doesn't), but it gives a good representation of approximate values. The color of the figure shows an interpretation of the material's "Workability Factor," a fancy name for cost modifier. The interpretation is that the darker/redder the color, the more expensive it is to work with. This random material apparently is very cheap to work with. The ten named values are (clockwise from right (3 o'clock)) integrity, conductivity, combustibility, heat resistance [index], transparency, elasticity, magnetism, nuclear value [index], decay resistance [index], and [intrinsic] value. Bear in mind that mid-range values are assumed to be average. In other words, the only places this material is above-average are magnetism, elasticity, heat resistance, and perhaps combustibility.

Above average isn't always better, though.

Anyway, this is my first actually vaguely complex Java program, and my first go with Java graphics aside from JFrames (basically, windows and buttons). I had made the text layout in photoshop, but I decided instead to render it using Java's graphics, in part to better acquaint myself with the system and in part because for a long time I was having trouble figuring out how to get the image into the program. I've since figured it out, but that was after setting Java up to do it.

So... what's my next step? I have no freaking clue. But I have plenty of other classes to work on. Some should be pretty easy, just the structural classes for my JDO database. Others are more involved, making frames and panels for managing different pieces. I have a lot of work to go, but I've made the first sizeable step.

Sunday, 28 February 2010

And in Health

Felt a bit better today. Still a little more playing around with graphics. I still suck, as if that's a surprise.

Given how Java implements its GUIs, I'm starting to question the usefulness of a visual GUI builder. Every component (essentially) needs to be specifically coded for its task before being placed into the GUI, and the builders don't give much help in that regard. That said, once I actually have the components built, the visual placement of each individual part will be a nice and convenient feature.

More work on the material decoder. I realize decoder is just a word I use because it sounds cool, but I'm sticking with it. Anyway, I haven't gotten far enough to test the output yet because I constantly get distracted, but in theory I'm about at the point where it does what I want it to. I hope to have, at the least, the interpretation graphic working tomorrow, which means the final build of the rest of the piece shouldn't take more than a day thereafter.

All in all, progress made, but not much of note. I'm dedicating tomorrow to working on it.

Friday, 26 February 2010

Making a Series of Menus Look Fun (also: Planet Classes)

Let's face it. Number crunching, data entry, and stat reviews aren't all that entertaining. It doesn't matter if the game they're all for is freaking awesome, it gets boring. I've been thinking about a few ways of making the management of an empire more entertaining even during peacetime.

If I can integrate messages and "forums" into the GUI, it gives the user more incentive to use the program. Also, putting in a chat system, while questionably useful for a small number of users, could occasionally make some entertainment. I intend to play background music, probably without including any files of my own. In other words, the user can integrate his/her own music library.

These features are all long-term planning, probably tough to implement, but they'd be brilliant additions to the game. Less long-term is making the game appear more entertaining.

My current hope is to develop (or find) a series of potential planet textures, as well as moon textures, and show animations of these in the background. When you're looking over your planets, you'll see an approximation of your planet and its moons rotating around. I don't think this will be too hard to implement and at the very least I'll have a static image of the planet in view. I have a friend looking into making them for me, but he doesn't promise anything. I pretended to do some work on it, but I suck with computer graphics. Hopefully I'll find, or have created, a decent set.

That said, if you can't already guess, I got distracted, so the GUI is not in any sort of displayable state.

I can, however, introduce my planet classification system. Avoiding copying a system from Star Trek or similar, I decided to derive my own. So, I give you my system:

  1. M[oon] or P[lanet]
  2. H[ospitable], I[nhospitable], C[olonizable], E[ngineer]
  3. R[ocky] or G[aseous]
  4. D[esert], A[rctic], T[emperate], B[arren], F[orest], J[ungle], W[ater], V[olcanic]
  5. Size (3 digit number, in 1000s of Kilometers (Megameters?))
In other words, a newly discovered planet will probably have a name something like: PHRT-013 and it may have a moon named MCRB-004. Follow the letters into the list above and you'll realize it's a planet vaguely similar to Earth with a moon much the same. Only thing that really needs explanation is the difference between I, C, and E. I means there's no way to settle it at all. C Means you can settle it via domes or other artificial structures. E means domes will work, but you could get more effect out of it if you terraform (sometimes called Space Engineering).

It's not ridiculously inventive or complex but I think it gets the job done. And that's all for now, tomorrow we'll see some sort of actual code progress. I cross my heart.

Thursday, 25 February 2010

CRC Cards and How I Killed a Small Forest

Class, Responsibility, Collaborator. Those are the three things that go onto a CRC Card--the name of the class to be made, what that class does (including what data it stores), and which other classes this class interacts (or, as the name suggests, collaborates) with.

These cards are recommended as a tool for designing an object-oriented program. I do see the usefulness of them. That said, writing 41 CRC cards is not exactly the most entertaining way to pass time. And that includes a couple of cards that I finally decided to generalize, since some things like Ship, Vehicle, and Troop designs all actually contain the same thing and could, as a shortcut, be written on one card.

That said, I haven't gotten to programming yet but I've already seen a payoff from the cards in the form of an organizational hierarchy starting to form. I've got a list of seven classes that don't appear anywhere in the application, but will be great to add in as abstract parent classes. That is to say, I can make these classes with a set format but no data, and then make "child" or sub-classes that take that general structure and specialize it to their needs. It should also allow me to easily compare certain values.

As an example, a station could be built at any point of interest in a system, whether it's orbiting a planet, a moon, a star, or whatever else. Rather than having to store in the station's information both the name of the object it's stationed at and the type of object that is, by having all of these other objects (stars, planets, etc) as children classes to the overall Location parent class, I can simply have the station's location compared to anything that is a child of Location.

This will also work for fleets for current, and target, locations. As I said before, I haven't coded yet, so hopefully it'll work out half as well as I'm imagining it will, but it's nice to see things like this falling into place.

My plan, for the moment, is to develop the GUI class(es) next. I hope to have all of the GUI defined in one class, so that it can share a few easily-redefined variables, and then whenever I need a certain window I'll have the code handling that window call it from the list of already-created objects in the GUI. The intention is that when the user first starts the program, they'll be prompted with a login window where they enter their username and password, as well as being given either a list of display resolutions or a full-on configuration window (depending on how many things there actually are to configure). Personally, I'd like the application to run full-screen, but one of the options will most likely be a windowed mode. I did write up a little "Hello World!" fullscreen application, because I actually was doubtful that Java could even do that. It can, and therefore I intend to work with it.

When I say  I'm developing the GUI, I mean the bare minimums. Rather than dealing with test programs for all of my stuff, I'd like to just plug in the code to the GUI I'm actually going to be using. Formatting of that GUI can come later, since as far as the code is concerned, the button can be gray with the word "Exit" on it or it can be a picture of an open door, it's still the same object.

I have a lot of time tomorrow so definitely expect some preliminary work on the GUI to be done for my next post. I might even post screenshots, not that they'll be pretty.

Wednesday, 24 February 2010

SQL Concurrency versus JDO, and why I want to make the switch

Small update tonight. I managed to not do much tonight except think. And think. And plan. The outcome is a decision to "scrap" what I have so far on the simulation and start new. Including, (most likely) the database.

And here I was promising the material decoder, huh? Not that it took very long to get nearly finished with that. Another couple of days and I'll probably have that finished, I just need to go through some organization first.

So what am I changing in starting new? Let's go into one of my standard bullet lists:


  • (Probably) Removing the SQL from my side of the coding by using Java Data Objects.
  • Creating classes for the different objects (like planets and ships) rather than tables per se.
  • Truly attempting to take advantage of the object-oriented nature of Java, a la Budd.
  • Avoiding so-called "Concurrency" issues
  • (Probably) Making the code easier on me to develop.
Java Data Objects, or JDO, are a method of storing entire Java Objects within a database. In my case, by creating a class for each in-game item, I can then store the classes in the database. This becomes useful in terms of the concurrency issues mentioned above. Concurrency in SQL is a problem where multiple users attempt to access the same data at the same time. When one person edits the data, the second person may well overwrite those changes even though the information they based it off of is no longer accurate. Generally this is handled by locking the row, so that only one person can access data at a time.

This is a major problem in my program because of the nature of the database I built, and how it would be accessed. The database is built with 'foreign keys,' or references to other tables, so that all of the data is interconnected. If one user is accessing all of the necessary data to run their empire, then a significant portion of the database is locked up while they're doing that work. Not a very user-friendly methodology. On the other hand, if the planets and ships and everything else are stored as independent objects, the user only accesses those that belong specifically to them and there aren't concerns about simultaneous edits.

I'm not too well-versed in the JDO things yet (I've just stumbled upon them today, really), so I'm not certain, but I do get the impression that using JDO means not needing to use SQL, and this simplifies my coding as well as removing the SQL altogether. Unfortunately, while I've found books that cover JDO, I can't find any at a library near me. I'm considering purchasing a copy somewhere off the web, but for now I'm going to try using the online documentation for it. Until I run into major issues, I'll probably stick with that.

My next couple of days are pretty slim in terms of time spent in-school, so hopefully I'll have a nice structure fleshed out and work started by... the weekend, at the latest? Wish me luck on that!

Sunday, 21 February 2010

Project Introduction: Java Simulation Game

While I'm doing some fine-tuning on the MATLAB project before posting the code, I figure now's a good time to introduce the other main project I'm working on. This one's a bit more complex and will probably be in production for ages (an unfortunate side-effect to lack of deadlines).

The simulation game I know and love doesn't really have much in terms of graphics. It's much more a thought-based, economy/diplomacy/strategy simulation, with rules governing interactions, extraction and deployment of resources, and the like. If you have an imagination, it's a real fun game to play because literally anything is possible--you have an administrator or two running it and keeping it balanced, but otherwise if you can think it, it can be done. My version, and all the ones I've played, are sci-fi, galactic empire style games. You rule planets, not cities, basically.

In the versions of these games that I've played, the major downfalls were (discounting admin inactivity and small player base):


  • Problems with cheat-detection. All of these I've played so far were excel-based (or worse, simply forum-based), meaning if a player modified the excel file it becomes tough to notice it.
  • Reliance on other players. As all interaction requires a response from someone else, things went slow. For diplomacy and trade, this isn't a problem. But what happens when your fleet is at another player's planet, waiting for the other player to respond to continue the battle, and another enemy comes to your planet knowing you've got no defenses?
  • Lack of 'realism.' Mostly in the fact that the player controls EVERYTHING in the past games I've played, which makes playing tougher. Sure, it's nice having absolute say over everything, but it isn't necessary and adds a lot of work.
Therefore I've set out to create my own version of the simulation-style game:

  • Programmed in Java, with no access to source code, to prevent cheating but allow essentially any computer to run it.
  • More administrator decision-making. A player entering a battle will get to dictate what the general strategy is, what the main targets are, under what circumstances the forces are to retreat, large-scale strategic things like how much of the fleet actually enters the battle to begin with and what remains as mid-fight reinforcements. The defending player then gets told what he knows of the situation (the ships currently in the fray, essentially), and issues main targets and defense objectives. The generals do the micromanaging, and the end result is a battle decision created in a short time through the administrators.
  • The concept behind my game in practice is that the leader does leader things. The economy is essentially entirely controlled by the player, but research is done more true-to-life. If a player wants to develop a new fighter craft, they don't tell the admin what exactly goes into it and receive a yes/no answer as to whether it works. Instead, they put the offer out to companies, who create prototypes and bid on contracts, and it's up to the player to choose from a few different options given to them.
Now, some of you may be thinking "this really doesn't sound like fun." For many of you, that'd actually probably be true. This style of game is certainly not everyone's cup of tea. Do bear in mind it isn't simply number crunching. Every action has an outcome on the whole of the galaxy, based on other players' political responses and the NPCs. And a battle doesn't simply go: X ships vs Y ships, Y wins, no ships remaining for X, Y-n ships remaining for Y. It's the administrator's job to narrate, tell a story, and entertain.

Some other features I'll be including in the game concept are:

  • Realistic (pythagorean-theorem based) travel times via galactic map coordinates.
  • In-depth trading system. All planets will have some of a predetermined list of resources, and most will have their own unique (though questionably useful) resources. Probably will also include a materials market much like the stock market, based on quasi-realistic supply and demand.
  • Through the material system, potentially interesting design quirks, waiting to be discovered, in nearly everything. A leader may find a nasty surprise waiting for him when he suddenly discovers his troops are carrying extremely magnetic weaponry, and his enemy knew this before he did, disarming them by way of electromagnets (for a top-of-my-head example).
  • By definition, each race will have (aside from preset starting 'equipment') completely unique armies, infrastructures, and economies.
  • Dynamic game structure--because the game is coded by the eventual administrator, things can be changed. Want to play a socialist utopia? The economy for your race can be re-coded to be more befitting. For example.
  • Espionage that provides both real and incorrect data, and most often time-sensitive. You'll be more likely to find out an enemy fleet's location than its composition. Like the real-world, using acquired intelligence is a gamble that can have huge rewards.
My current status is pretty bleak. The MySQL database structure to go behind it is essentially complete. It's a complex mess of inter-related tables, but it covers essentially everything. The Java work I had done (which was almost nothing anyway) is lost to my last computer wipe, but I've started fresh and am currently at work coding a material property display. Each material has 11 properties, with a range of values from 0-25 (Z-A respectively). I'm working on a 'decoder' that displays the properties in one of those attribute 'star-charts.' The only example I can find easily is this. Imagine the colored section moving around to fill in the shape depending on how high each stat is. Mostly I'm making this for my purposes so I can try to visually see the balance between materials found on varying planets.