Friday, 30 December 2011

Java: Texas Hold Em (31)

Okay, today I'll try leaving in the commentary to the code, leaving my posting text to stuff like this, that's not directly code related!

Today we'll be looking at the method that handles showdowns in the game, enjoy!

Thursday, 29 December 2011

Java: Texas Hold Em (30)

Okay, in the receding phase of my migraine, which means I can stick around longer, but I'm still not at full operating capacity! Still, I figure we can get through the huge method, which will actually take a little bit OVER the 2 screenshots I wanted to limit my posts to, but only by like, 2-3 lines.

The reason the method is so large is that it's responsible for the entire round of betting, so there's a big chunk of stuff and a switch statement to boot. Also, switch statements make use of "break;" so that inflates the length of the code a bit.

Here it is:

Wednesday, 28 December 2011

Java: Texas Hold Em (29)

Well, got a migraine today, so sorry, folks, can't give you the big one I promised. Instead, I'll cover it whenever this blasted thing is gone, and cover the method that returns a player's allowed actions tonight.

Here it is, short as possible:

Tuesday, 27 December 2011

Java: Texas Hold Em (28)

Yar, hope everyone had themselves a good weekend, I sure did! If I recall right, we left off at the table dealing out the community cards, which means today we'll be covering a method to reset the hand, and another to switch players for turn rotation and such. Let's get to it, no more partying for you!

Friday, 23 December 2011


Hey, so, a friend I've not seen in a long time just made it into town! I'll be skipping today's posts, and Monday's post in the interest of having a pretend social life for half a week!

Maybe I should have packaged this as a long weekend for the purposes of Christmas? Yeah, let's do that! See you guys on Tuesday, and Merry fuckin' Christmas to all!

Thursday, 22 December 2011

Java: Texas Hold Em (27)

Okay, back for a second post, it's late and I'm busy though, so deal with it being short! Four short methods totaling about 30 lines of code! We'll be covering a method to deal with each of the blinds and 2 for dealing out cards:

Java: Texas Hold Em (26)

Okay, post 1 of 2 for today! I'll take a break after this to type up the second, since I had this prepared for yesterday! This one contains a few administrative methods, the main game loop, a way to add players and a way to start the game over. The second screenshot is a huge method to take care of actually playing an individual hand. Here goes:

Wednesday, 21 December 2011

Technical Difficulties

Something is wrong with my computer, so I can't write a post; all my info is on there! It's being fixed, though, so I'll double post tomorrow, see you then!

Tuesday, 20 December 2011

Java: Texas Hold Em (25)

Okay, so it turns out the ConsoleClient is pretty confusing, and requires the Table anyway, so we'll be doing the Table! Yay! Ooh, there's a problem though. You probably don't remember (I didn't), but when the Hand class was created, I left out the constructor that takes an ArrayList or something as a parameter. We need to go back and fix that so our table runs smoother!

Monday, 19 December 2011

Java: Texas Hold Em (24)

What's up, guys? Today we're back to the card game! We can probably finish it up today, but be aware that the actual act method is long, although it is just a switch statement, so not necessarily complex. I'll leave it to last so we can get the easy stuff out of the way, first.

Sunday, 18 December 2011

Java: String Formatting (Pictures!) and the Switch Statement

Okay so, apparently no pictures is a huge no-no, so I'll briefly show you how string formatting works with the power of screenshots! And yeah, looking back on yesterday's post, I agree, it was kinda shitty, so, sorry about that :P

So, string formatting! First, we need to formulate a template string in which data will be entered later!

Saturday, 17 December 2011

Java: String Formatting

First off: To Damian in the comments: The game could kick the player when its discovered they're broke, but that's not up to the player class! It's up to either the Table or the ConsoleClient!

Okay! Short post today, just covering string formatting. We saw in some code there was a string returned that looked roughly like:

"This is the message, %s, %f"

...within a method that took 2 more parameters. When printed out this way, the first parameter, the string, is the format of the message to be printed out. A percentage sign followed by a letter denotes where you'll want to put data in afterwards.

Friday, 16 December 2011

Java: Texas Hold Em (23)

Hey hey, time for another post. Last time we left off at getCash for the Player class, after a number of get methods and some other crap. Luckily, there's a buttload more of get methods to go through, so we still have some easy stuff around. Just a heads up though, on Monday we'll go through a larger method that uses the switch-statement.

This week is my final make-up week where I make weekend posts, so tomorrow, as promised, I'll cover string formatting in more detail, and on Sunday I'll actually refresh us all on the switch statement, just in case you need it!

Thursday, 15 December 2011

Java: Texas Hold Em (22)

Hi, people! Going to just make this as brief as I can today, don`t feel up to much. The Player class has 177 lines when I got rid of all the (rightfully present) comments, so you can keep track of how far we have to go before the end.

Let`s get right into some methods now, with a few get...() methods and reset...() methods (among others) as you might expect would be needed in a round-based game:

Wednesday, 14 December 2011

Java: Texas Hold Em (21)

Alrighty, I looked over the ConsoleClient class, and uh, I was lost, so let's do the Player class instead! It's a little long, about 300 lines before I do anything to it, like make it ugly and remove vast amounts of comments, but we'll get through it.

After that, we can just do the Table class, leaving ConsoleClient to the end of the functional code, at which point we have bots and GUIs to do. See, this is why people rarely code from scratch, and just modify other peoples' code, it takes way too long otherwise. But I suppose in the heart of learning...

Tuesday, 13 December 2011

Java: Texas Hold Em (20)

Hey now, the Client isn't empty, only everything that it does is! Wait, does that make it sadder? Who cares, it probably deserves it. That's right folks, it's time to get the Client done, and therefore officially the start of the "What the fuck am I doing, and why?" part of the project! At least we're not at the "What am I doing, and how am I supposed to work out how?" part?

Here we go!

Monday, 12 December 2011

Java: Texas Hold Em (19)

Hey hey, post as promised, late as promised! I'm so awesome! Today we're continuing with our HandValue class, and we'll be done with it tonight! I do hope after all this time wasted this project doesn't end up being a flop :P

After this, we could move on to the Table, but that is what Players sit at, so we should do those. However, it looks like the Player class needs a Client interface to work with. Being an interface, and not a class, if you remember, this means that Client will be a collection of related methods, but empty.

We`re starting to get into territory that I don`t quite get, so...good luck? We'll see how this pans out!

Monday - Late post

So, I've had to stay up until midday before I could sleep, so just a heads up, todays post will be superlate, because fuck writing it up now!

Sunday, 11 December 2011

Java: Texas Hold Em (18) - Weekend Post

Whoops, lost track of time, but here's the second weekend post! We'll keep this one short too, and tomorrow we'll move back to the standard posts. One more week with weekend posts, then back to the 5/week schedule.

Working from the pseudo-blueprint we constructed yesterday, let`s get through the instance variables and the constructor for the HandValue class:

Saturday, 10 December 2011

Java: Texas Hold Em (17) - Weekend Post

Heh, almost forgot about saying I'd do this for 2 weekends :P Since it's the weekend and everyone probably just wants to chill, I'll keep it short and sweet.

We're starting with the HandValue class, and what this does, basically, actually gives some representation to the value got by the evaluator, complete with a toString() method and a way to compare hands! As a general blueprint, we need:

Friday, 9 December 2011

Java: Texas Hold Em (16) - HandEvaluator Finished.

Okay, so, today we finish this class up, finally. That's the good news. The bad news is, there's still a HandValue class to get through, which will put together the HandValueType and the HandEvaluator, so we're not totally out of the woods.

The HandValue class should be finished in 2-3 days though, so it's not so bad. Enough talk of the future, let's get done with the now!

Thursday, 8 December 2011

Java: Texas Hold Em (15)

Busy, busy! Just gonna throw my post out there today, and be done with it :P Today we get through Four of a Kind and Straight Flush, tomorrow, we finish this class (bloody finally) with the Royal Flush and the Constructor that actually uses everything we've made!

Fwoomp (That's the sound of code falling into place):

Wednesday, 7 December 2011

Java: Texas Hold Em (14)

There appears to be some trouble with understanding the coding that's been going on. That's fine, I'm not exactly 100% on everything, either. The thing to remember is you need to know exactly what you're trying to do with some code, and then work out all the steps required for getting there, bit by bit. Computers are dumb, you can't just say "Throw me the ball". You need to take it in small steps. "This is the ball. Picking something up involves... Now pick up the ball. Swing your arm in x direction and release the ball..."

Luckily, a lot of the time, coding involves modifying someone else's code instead of creating stuff from scratch, so you have the option of looking at what steps are being taken, then thinking of how you can do whatever you want from that point onward. Here's today's code:

Tuesday, 6 December 2011

Java: Texas Hold Em (13)

Ahoy there. Today we're going to continue on the same train of thought as yesterday, this time making a boolean method for the next 2 hand value types: Three of a Kind and Straight. Let's dive right into it, since there's no administrative stuff to go through:

Monday, 5 December 2011

Java: Texas Hold Em (12)

Okay, back on track! To make up for the previous week, I'll be doing Sat-Sun updates for the next 2 weeks! We should be done with the evaluator comfortably this week, allowing us to move on, and we'll soon be out of the comfort zone of someone else's code, which I'm kinda worried about, but oh well.

We left off last week at calculating any duplicates, as well as the high card of a hand, so the progression from this point would be to have a bunch of private methods for use in the constructor that actually as "Does this hand contain x?" for each of the possible hand value types. Here we go:

Wednesday, 30 November 2011


Sorry there was no post yesterday, without warning! But uh, here's your warning! I'll also be out for the rest of the week for various reasons. Sorry about that, stuff came up that can't be avoided (And I'm really good at avoiding things), see you Monday!

Monday, 28 November 2011

Java: Texas Hold Em (11)

Ugh, late post, sorry! I spent the better part of 2 days asleep, and I don't even know why, so doing this wasn't exactly a priority! Still, today we get to continue with our Hand Evaluator! Let's see, we had just finished finding straights and flushes, so let's continue that thread of thought and grab a method to find duplicates (encompassing single/double pairs, triples and four-of-a-kinds, thanks Mr. Stigter, for more efficiency!), and then something to calculate the high card in the hand to further calculate the hand's value.

Here's what I got (Yes, I did basically just use Stigter's code, but understanding it took time!):

Friday, 25 November 2011

Java: Texas Hold Em (10)

Hi hi, this is the last post for the week, because I'm lazy and went down to only 5 posts a week, remember. Going to be continuing with our HandEvaluator, which is fairly big, as far as what we've seen goes, and it'll be made longer by me messing around and looking for better ways to do what Stigter did! At least, for my own uses.

Now, we want our evaluator to work straight off, on being created, without calling any special methods on the object, which means our constructor is actually going to need to make use of methods we declare in the class. For this reason, it's probably best that we don't work on the constructor until we finish our methods! Here's what I got so far:

Thursday, 24 November 2011

Java: Texas Hold Em (9)

Happy Thanksgiving to all the Yanks in the audience. Today we're moving onto the evaluation part of the program. This one's a little big, so it'll be more than 1 post dedicated to it! To keep things concise (or at the very least, available in small chunks), I'll keep posts to 2 screenshots worth of code per day, as I've been more or less doing for a while, anyway.

Fixing things in previous posts won't count, unless its a ridiculous amount! Speaking of which...

Wednesday, 23 November 2011

Java: Texas Hold Em (8)

To comments: Yeah, going to work on base functionality before everything else, then add in the visual and actual user interactivity. Also, thanks for info on the blinds!

So today I wanted to start on the HandEvaluation, since it is a rather big class. Complex, kind of, but mostly just big (As far as I know, which revolved entirely around guesswork), but the enumeration to hold the types of hand values is probably better off in its own class. It's similar to the Action we had yesterday, take a look:

Tuesday, 22 November 2011

Java: Texas Hold Em (7)

In response to a question from yesterday's post: I don't think the evaluation will be the toughest part, since the player clients all need to come together, or the GUI itself, using actual graphics might be a pain in the ass. We'll see, though.

For today: Action class! I'm gonna follow the example program for this one, since it looks simple, and much easier than what I was planning to do with it, but since the example program isn't fully functional (because I'm stupid and take inspiration from all the wrong places), it may need some tweaking later on.

Monday, 21 November 2011

Java: Texas Hold Em (6)

Short one today, I wanted to make a Player class, but realized I'd probably need a Client class to handle the, well, client for the player(s), so I'm putting that off.

I could work on the Client, but who wants to think on a Monday? I could work on the Table that the players "sit" at, but that requires players, and I'll be damned if I'm working on the GUI before a huge chunk (all?) of the functionality is complete. This leaves very few things for me to look at. From what I can think of, something to handle the evaluation of the hands, to determine who wins, and the actual Actions a player can take.

It seems like the Action class will be the shortest, since it'll just be an enumeration with a couple of parameters, so I'll get on that tomorrow. Honestly, thinking of what required what and how I'd go about it (though I have a feeling I'm wrong about a lot) took longer than it appears given the paragraph and a half above :P Quite enough time out of my busy schedule for today!

See you tomorrow!

Thursday, 17 November 2011

Java: Texas Hold Em (5)

Uh, so it's now Friday. I have no idea what happened. I apparently passed out or something, and had been down and out for a full day. I am a bastion of physical health, I know. So after a while at the doctor it looks like the verdict is "Man up, bitch", so to celebrate, I'm going to write more code. And also mention here that I'll be dropping my posts to 5/week instead of 6!

So we were on the Hand class, and here`s how the rest of that goes:

Tuesday, 15 November 2011


No new material today, sorry, folks! Coming down with another migraine, and if I don't do something about it right the hell now it's liable to spiral out of control and incapacitate me for a while!

Monday, 14 November 2011

Java: Texas Hold Em (4)

Today (Almost tomorrow >_>) is gonna be short, mostly because its so late! We're gonna start off with the Hand class! Over the next day or two we'll finish it up, and then we can move on to something else! Hand Value, or Player or Table, I dunno, we'll see. Let's get this show on the road:

Saturday, 12 November 2011

Java: Texas Hold Em (3)

Hi, today, we're going to (I think) finish off the Deck class, for happy fun times. Might need to change the toString() of Card since it looks kinda ugly, BUT it does work, as does the shuffling., so yeah. It's okay, though, I suppose, since the end result will hopefully be graphically represented.

Here's the Deck beyond the constructor:

Friday, 11 November 2011

Java: Texas Hold Em (2)

I COULD find a fully working game that's open source (probably), but that would be too easy! I did, however, decide to add the comparison method to Card, since that means we can compare them to decide which hand is worth more (if they're both the same hand. Triples or something), which we definitely need!

An important thing to note is the order in which I did the enumerations yesterday. I wrote them out in order from lowest to highest, both for Rank and Suit. The suit one was frankly luck, but apparently the ranking of those from bottom to top is:

Thursday, 10 November 2011

Java: Texas Hold Em (1)

Welp, let's do this. I'm basically looking at someone else's source code, which is incomplete. So I hope to get my framework from this other person's work, while being forced to do the actual building myself! I should mention that since I don't have a working copy, if I fuck up, there'll be a lot of going back to find things. Programming isn't very good as a linear progression, unless you're beyond amazing at it. There'll always be small errors that you missed, or that require some odd fix that doesn't seem to make sense.

Having said that, we should get going!

Wednesday, 9 November 2011

Java: Screw the Network Application

O hi, there! Last night I realized that holy shit, this teaches me NOTHING, so I'm moving our day of bullshit up one! Like, seriously, it was useless, and I didn't read more than 1 day ahead, so I only realized this yesterday. Bah, waste of time. I suppose it was a little more practice with Threads and stuff, but eh. So instead, today I'm looking at Texas Hold Em and what classes would be required to get it.

So while I'm doing that, I'm peppering my time with random bouts of LoL and Minecraft (Which I only just got), and I'm more or less addicted to creative mode. Not even got the hang of the circuitry bullshit, I just build mazes galore. Good stuff.
I did try survival mode, but after trying to be a nomad from the spawn area (too many people around) like....8 times, and getting killed each time, I thought fuckit, and made a hovel in the ground. Then went back to creative :D

Anyway, see ya tomorrow for the first of Texas Hold Em (Y) I do think that the graphics will be the more annoying part of it, though.

Tuesday, 8 November 2011

Java: A Network Application (4)

Aah, had a migraine last night and now I don't. Best feeling ever. So I can happily move on to the NodeListener today, as promised! Meaning tomorrow we have the actual faux-application, then we're done. One day of bullshitting and stuff, then onto actual game stuff.

This is actually a very short class, and it's not ideal, since it uses the Application itself, before it's been created. I just fixed the errors popping up using the automatic stuff Netbeans does. Just created an empty class and method as a placeholder until I actually get around to making the application later tonight.

Monday, 7 November 2011

Java: A Network Application (3)

Somehow, I didn't get enough sleep, still. Oh well, time for more postin'! Today, we're continuing right off the network node from Saturday, and we'll be done with that. Tomorrow, we go to the node listener, then Wednesday we write the actual application. I'll give you until then to throw out any questions or requests about anything before we move on to those (in all probability, shitty) games!

So, diving into it:

Saturday, 5 November 2011

Java: A Network Application (2)

Today's an early one, but also short, since I've had no sleep yet! Let's start at...well, the start. We'll want the lowest level of objects first, which is the NetworkNode itself, so we can have a Listener listen for it, and then the application to interact with it. This should be the only class I'm doing in 2 parts, the others look short, at a glance.

We're going to be using Random, which is in the Java libraries. I don't think we've used it yet, but it's fairly straightforward. Create a random object, then use the next...() method, you'll see below:

Friday, 4 November 2011

Java: More Multithreading: A Network Application (1)

This is the last example in the book, and I sure hope it helps me understand multithreading better than the other ones... Also while I remember: Texas Hold 'Em might be easier than I at first imagined, since, like 21 sticks (which I also realized is normally played with 1-4 sticks...oops!), it's (sort of) turn based. Nothing needs to happen simultaneously, so yay!

For now though, one more example on multithreading: A Network Application. From the text:
"The main purpose of this section is not to solve any particular problem but to show what an event is,

Thursday, 3 November 2011

Java: Let's All Go On A Tangent!

Man, someone mentioned how often I used the word simple yesterday, but I only meant to use it for very select, small parts. The bigger picture is still....not. Don't worry, I'm as lost as you! Or more so, because I'm forced to write code despite not knowing quite what half of it does.

EDIT: Holy crap I use that word a lot, especially given how little I understand. Fuck. I guess if I 
say it enough I hope it'll come true?

I am frankly sick of multithreading at this point, so, lets relax for today. I looked up someone's 21 sticks game, then modified it to make it prettier. 21 sticks is a game with 2 players, where, oddly enough, there are 21 sticks. Each player then takes turns removing either 1 or 2 sticks from the pile until none are left. The player to take the last stick(s) is the loser.

Wednesday, 2 November 2011

Java: Shared Queue 4: Complete Test + Source Code

Gah, late thread, sorry! This one's a bit of a doozy, so bear with me! I'll start off with a brief overview:

Step 1: We need to actually create the thread-safe queue to use.
Step 2: Set up all the producers (don't run them yet, we don't want threads to start running before all are in place)
Step 3: Set up all the consumers. We can start them running now, since both producers and consumers are ready. Since the queues are as of yet, empty, this isn't an issue. Seeing an empty queue, the consumers will yield.
Step 4: Start the producers.
Step 5: Wait for the producers to finish. Once they are, no new values are going to be added to the queue.

Tuesday, 1 November 2011

Java: Shared Queue's 3: Testing Classes

Apparently, no one did shit, so I guess discussing that is outta the question :P So straight onto how I tested it! I'll put both the consumer and producer classes into an umbrella class just so its all together. I'll leave the actual running of the tests to tomorrow, since I'm a bum (or a tortoise?) and haven't actually like, got there yet. I mean, for your benefit, so we aren't moving too fast. Clearly.

I do have the actual classes to be used in the testing though, and here they are:

Monday, 31 October 2011

Java Threads: Shared Java Queue 2: Queue Harder

Sorry, couldn't help myself with the title.

Anyway, just a short post today, and that's because our Synchronized Queue object basically already conforms to the Queue objects (or rather the interface). Its methods are monitored forwarding methods. That is, they deal with all the necessary object locking (synchronize), but that's it. Beyond that, they just call the methods of the actual Queue.
TL;DR: It's now up to actual Queues to be doing this right. We've already protected everything with our wrapper class.

Sunday, 30 October 2011

Java: MultiThreading Example 2: A Shared Queue

In response to one of the comments: Yes. I was either going to go to html after we were done with making a simple game or 2, or to python. Python really should have been done first, its a much nicer language, but...I didn't! So there.

Back to another Java example, until this whole multithreading thing is understood properly, I looked at the dumbass book again, but I found something that looked plausible: A shared queue. I mentioned this when going over potential difficulties you may encounter without synchronizing, so this seems like a great way to learn how to make something thread-safe. On top of that, there'll be flipping between threads, unlike the clock program!

Saturday, 29 October 2011

Early Day Off!

I think I'll take my free day early this week. I need to read ahead before I get on the next example, after all!

Friday, 28 October 2011

Java: Text Clock Complete!

Oh god, the pain. I did far too many squats from a huge period of not doing anything, and to add to it, I didn't stretch properly. My legs are in so much pain right now :( You'll also notice that I changed the layout again! Black background is easier on my eyes, I assume it's not a problem for anyone else, either? Let me know if it is.
And Bersercules! Not to worry, for I am a man of my word, I will at least ATTEMPT to make the Texas Hold 'Em game!

Most of the space in these screenies is going to be taken up by comments, because, honestly, I did not understand half of what I was doing at the time. They were largely for my own benefit, but I assume you could learn from them too! As teachers go, I'm terrible, given how little I know of the subject before attempting to teach :D

Continuing with our text clock for now, though, we've just got the frame to go!

Thursday, 27 October 2011

Java: Multithread Clock (Cont)

Pfft, overslept. I am not good with that, and reading DWei's blog on his sleeping troubles made me more acutely aware of my own :-(

Anyway, the problem I was mentioning yesterday was in the region of "I need to make my own JFrame for this to work, but the GUI builder is a pile of dicks, and won't let me customize JFrame code.
Unfortunately, I've not found a way around this, so its probably a good thing I manually did the GUI stuff that one time, right? :D

Wednesday, 26 October 2011

Java: A Clock Example

Well, I may have mentioned before that the book was a load of shit when it came to threads, after all, and it's completely thrown me off how to proceed! The code we have is essentially useless because of this, but I have been looking into it.

It turns out that having a class use "implements Runnable" instead of extends Thread is the preferable way to do things like this. The class is then not an extension of a thread, but can be run by one!

I've actually completed my clock, but it's not very pretty, and annoying to understand. Here's the file if you want to look at it, though. I'll save the actual code and source for when it's not as confusing a mess as it currently is :D

Tuesday, 25 October 2011

No Java: Brain Problems!

The day's technically not over! I just kinda...passed out at like 4pm and only just came to, with this page still up, so I have a legit reason to skip today's post :D Before you mention, though, I don't find telling you guys more important than going to the doc's to find out wtf is wrong with me, I'm just waiting on someone who can drive me there safely. And there he is now!


Monday, 24 October 2011

Java: Thread Scheduling & an Example (Part 1)

What's up? We're going to go right into the last bit of technical information before an example program, since those are frankly easier to learn from (for me, at least!).

Thread Scheduling
A program that uses many threads needs to be subject to some set of rules to determine which thread should be running at any one time, and how to switch between threads. Without this switching around (scheduling), there's no real reason to use threads in the first place, since some threads will never have a chance to run.
Because of this, threads are given priority levels (higher priority runs before a lower priority thread).
TL;DR: Needs to be a way to flip between threads, and to prioritize them, otherwise, pointless.

Saturday, 22 October 2011

Java: Concurrency with Threads: Using Threads

Yay, I have a cold! Luckily, tomorrow is my day off. There's a lot of tech detail I'm getting through before it comes to the examples, but I paraphrase a lot, so hopefully I can squeeze all (or most) of it in today, meaning at the start of the new week, we can delve into actually playing around with stuff again!

Back to threads, a thread of control is just a single path of execution through a program. So, for all the programs we've looked at and fiddled with, we had 1 thread, which started in the main method, and ended with the program.

Every program has 1 thread when it begins running (the main method), but in this method, we can call further threads, and those can make threads of their own etc. as needed by the application. Normally, you'll want your main thread to do all the real work, with other threads sitting there to monitor incoming connections or whatever.

Java, of course, provides full support for threads which are integrated into the language as well as class libraries.

Friday, 21 October 2011

Java: Concurrency with Threads (Intro)

This is a bit late, and short, as I have unexpected company over :/
Hey, at least its the introductory section, so it's naturally short!

Do date, our only programs have done one thing at a time, which is a little limited. It allows us to actually do pretty cool things, perform calculations etc. But the more interesting programs, such as simple games (and actual important things) would need us to do many things at once. As y'know, we've mentioned.

Thursday, 20 October 2011


Woop, well we have everything in place, so the only things left to do are "New" and "Close", put them in a menu bar (along with everything else), and give them shortcuts! After today, we'll start work on Threads, which will allow us, hopefully, to work on some of the simpler games.

An issue I don't feel like working on is when you hit new/close/load, an option to save doesn't come up. Also there's no Save vs. Save As. But that's okay, since I wasn't planning on this replacing Notepad anyway, and its more of a matter of building it than learning anything new.

Here's the new and close methods:

Wednesday, 19 October 2011

Java: Completing the Text Editor Functionality II

As per the comments a couple days ago: Yes, we absolutely can get to simple games, but to do that, we need to learn about threads! So I'll do that right after this text editor is done! I suppose turn based games require it less, but still.

Okay, let's get to finishing this thing. Since load() was just a version of reading files, it follows that save will be a similar version of saving (durr) them. Keep in mind that our finished project will be very rudimentary, and you'll probably still be better off using notepad and stuff, but its still functional, right?
I changed a line in the code for load, when initializing the JFileChooser. It is identical to the initialized JFileChooser in the following:

Tuesday, 18 October 2011

Java: Completing the Text Editor Functionality I

Well, we have our text editor, which looks like:

Now, we need to add functionality to the buttons, but we want our methods of save/load etc. to be just that, their own methods, which the buttons call, so first, we need to actually make the methods, and have the action listeners come in later!

Let's go in order, starting with Load. This is some new material, so pay attention: JFileChooser is what we're using. This took me a while to figure out, too, so we`ll only be doing Load today, Save will be easier with this knowledge, so I can probably do the remaining 4 tomorrow!

Monday, 17 October 2011

Java: More GUI Stuff!

So it turns out, in discovering and using the Netbeans GUI creator, I skipped like, a bajillion pages in the textbook, which are all about bringing up buttons and setting up events, and the proper way to put things together (A jFrame being the bottom level, to hold everything, then a jPanel for each section on the Frame and so on.). So uh. I'm kinda out of the GUI chapter, save a couple of examples!

I guess we'll do those (its some relatively cool stuff), until someone in the comments section has a specific request, or we can just move on to multi-threading and such, which will be the final thing to learn about.

Anyway, for now, we can have a simple text editor! Let's start off by designing it, visually.

Sunday, 16 October 2011

Java: Core GUI Concepts III - Example Program (The easy-ish way: Functionality)

I feel that I should note this GUI builder isn't part of the textbook. I just looked at the generating of code and thought "Fuck this, there's gotta be a better way!" And then there was! Also, post on Sunday since I had that day-off earlier in the week.

Anyway, now that we have the visuals more or less done, we should work on functionality. First off, we want to get out of the design tab, and move into the code tab, like so:

Saturday, 15 October 2011

Java: Core GUI Concepts II - Example Program (The easy-ish way: Visuals)

Okay, I think I got this worked out! Let's have a shitload of screenshots!

Let's start off by making a new file in Netbeans. But instead of the regular Java file, scroll down to the Swing GUI Frame, then select JFrame. This will, predictably, give you a JFrame to work with. Fun times.

Friday, 14 October 2011

Java: Core GUI Concepts I - Example Program

Well, good to know that TL;DR is a hit! Moving on, GUIs themselves are complicated to teach beyond "Here's the libraries, get to it", so we'll start off with an example program! This should hopefully give us an idea of how certain aspects are used and whatnot.

The example we'll be using is just a window with a button. The button will toggle between 2 text messages, "Hello" and "Goodbye". It's surprisingly complex, so I'll only be doing this for example purposes, so you can see how the code works. Tomorrow, I'll be recreating the program the easy way (I hope), so don't fret if this is ridiculous. Here is the end result:

Thursday, 13 October 2011

Java: GUI Introduction

Well, the voters have spoken! GUIs first it is. Which is good, I didn't have much of a stomach for a day of gaming. Ended up going for a "jog". Turns out I'm much less fit than I remember! So I just played Men of War:Vietnam before a whole bunch of TF2 (Which I also suck at).

Feel free to read the TL;DR: sections at the end of sections to get the gist of it and move on. :D I might do them more often, just 'cause I know my posts are often long and could be summed up more concisely.

Anywho, let's get on with the GUI stuff. As most of you know, the user interface of a program is what the user sees and interacts with when trying to use a program. There are two fundamentally different types of user interface. Thee's the command line interface, which is how we'd be using our programs so far, if they weren't processed in Netbeans:

Wednesday, 12 October 2011

Boom, poll done!

I actually totally forgot about the poll last night, but it's up now! Place your votes etc.

Man, until I know what to look at next, I dunno what to do :( Maybe play a video game or 2 for the first time in a long-ass while! See ya tomorrow, folks!

Tuesday, 11 October 2011

Java: Catching Exceptions and the Finally Block

Last post before we move on to the chapter about either more intricate processes (multiple things happening at once, basically) OR we can go right into the GUI material (Graphic User Interfaces, click on buttons to do things etc.). Either way doesn't matter to me, they're both going to get done, but which would you guys like to see first? I'll put up a poll later if I work out how, and I'll spend all of tomorrow either answering questions or bullshitting so you have time to vote on it!

For now, let's get into the material. Catching exceptions, first. Well, we've already done throwing, right, so naturally something needs to catch it. I think we've seen this in the Stack program way earlier, the try-catch block. How this works is, you have a series of statements (the body) that has some chance of triggering an exception throwing, and you stuff that inside a try block, which is just a compound statement preceded by

Monday, 10 October 2011

Java: Representing and Throwing Exceptions

To comments people: Sure I might be able to do all kinds of apps, but I'll look into it more when I like...can.
And no, I don't work as a programmer (yet), I'm barely ahead of what I post, so I still have a way to go :(

Guess how exceptions are represented in Java? Like everything else, pretty much, as objects! This actually allows information about what happened to cause an exception as well as where in the source code it happened, to be transferred easily around a program. A built-in Java class in the libraries contain quite a few exception classes, all of which are subclasses (direct or indirect) of the superclass
Throwable. Most exceptions are a subclass of Exception, itself being a subclass of Throwable (hence the indirect). There is another set of exceptions that you really don't want to come across, and those are of the class Error. These, however, are based more around internal errors, and really really should not happen. If it does, the only way to deal with it tends to be termination of the program.

So what do we do when an exceptional event occurs?

Saturday, 8 October 2011

Java: Exceptions: Kinds of Errors

Whoa, this is late, I overslept like crazy! And yes, I suppose with my new found knowledge I could do android apps Y'know, when I'm done with these last 3 chapters. I'll make a whole segment about it, where you vote for what you want made etc. But that's for the (near?) future, not now! :D

So basically, we're on the chapter dealing with exceptions now, and the basic idea is that an exception is an error, and occurs when shit goes bad. I paraphrase, but its much better to "throw" an exception, that is, to stop a program running when it encounters an error, than just simply leave a message and continue as if nothing went wrong. Primarily, this is because we would, without throwing the exception, be covering up the fact that a problem occurred. Further, without throwing an error, you're more than likely going to be forced to return a valid value that will cause problems elsewhere!

For instance, back to our Stack<Car>. Say we popped a value off the stack, but the stack is empty. Normally, in a fully functional program, we'd have safeguards stopping this from being possible, but then again, ideally, no errors would occur either. So we pop a value off an empty stack, using that value to perform some other piece of functionality. We'd get a "null" returned, most likely.
Now, if the stack was to say, create a setup of Cars, like, you only want 8 cars in a room, you're going to end up with an infinite amount of cars that have no object type. The room will never be created, because, while putting in "null", which is basically nothing, takes basically no time, values are going to keep popping off this empty stack, and it'll be such a goddamn mess. BUT, if you had error throwing in place, you'd be fine. The program would stop and tell you to fix your shit. Ideally, it wouldn't end the program unexpectedly, though, but first save all current data and whatnot so as to not lose current progress.

Convinced? Good.

Errors themselves can be put into a few different categories:


Let's go through them briefly, shall we?

Syntax Errors
These are easiest to deal with, I think. They are caused by the non-conformity of your source code with Java rules and regulations. A little order is a good thing in code! Missing brackets or a semicolon could cause this, or keywords in a wrong place etc. Your IDE should spot these as you type, so it's rarely an issue beyond figuring out why you're getting the error.

Type Errors
These tend to be caused by mismatching, you guessed it, types. For example, assigning the value "a" to something initialized as an integer. Or perhaps calling a method that the class of a certain object just doesn't have (calling pop() on a Car).

Logic Errors
These are very different to the first 2. These are errors in your algorithms or implementations of the algorithms in your code. These, unfortunately, cannot be detected by the Java compiler, since they only manifest when the program is running, and noticed when it doesn't end., for instance. Or computes the wrong value. Popping off an empty stack, as above, for instance. Or an infinite loop (while 1 is greater than 0, do...)
This is pretty much up to the programmer to find and deal with. Normally through exceptions, and just generally checking your loops etc.

Run-time Errors
Similar to logic errors, except not caused by the program being constructed poorly. Instead, this is caused by an event that occurred either totally unexpectedly (Why would you divide by 0?) or outside the range of conditions the program was designed to deal with (Write us a program that will give all the Fibonacci sequence until a maximum of the 15th term. User asks for a sequence 16 long). This is normally a question of handling user input well, since your users are idiots, probably, and can't be trusted at all, with anything.

The last 2 are normally the source of exceptions. Unexpected events that suck. Exceptions that aren't handled are the bane of everyone's existence. These normally end up in a not-fun termination of the program. Nothing saved, nothing completed, just all around bad mojo. Very annoying. Ideally, we'll want to recover the situation and soldier on. Failing that, save data before safely terminating.

Now that we got the basic concept, I think I'll get to work, so that's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you on Monday!

And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Friday, 7 October 2011

Java: End of the Chapter

Someone asked in the comments for yesterday's post what my end goal is. I, uh....don't know. I just like learning shit, application can come afterwards. I do have a few ideas for things I want to make, but I'm not sure if Java will be the language I use to make them, or if some other language will be better suited. I suppose time will tell, but basically, I'm doing this whole thing for the sheer fuck of it. Enjoy!

We're more or less done with inheritance. There's more info in the book about overriding methods (If you have a subclass with a different implementation of a method available in the superclass) and hiding names (Same deal, but for variables and how then to access the super-variable), but I seriously doubt they'll be of any use in most cases. Just use a different method/variable name, right? If you feel like I should go over these things anyway (and more, but again, things I think will find very little use), let me know. 

Otherwise, we have 3 more chapters to get through before it gets REALLY technical, or based more on testing units of code and the programming process for large projects and groups. Shit like that. Good to know, but more on a case-by-case basis, I plan on looking them up if I ever need them, but relying on basics otherwise. The 3 chapters we have left are to do with exceptions, concurrency with threads and finally, Graphic Interfaces. I can't wait for that last one, personally.

I'll get on it tomorrow, though, my brother borrowed my textbook, and he won't be back home until late in the evening.

Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Thursday, 6 October 2011

Java: Inheritance IV

Today, we get to talk about the super keyword, and how static variables work with inheritance!


Remember our Car had an int parameter, for whatever reason. Well if we had a constructor for Vehicle with an integer parameter that we wanted to use, our Car constructor would throw an error.. This is because a default constructor is looked for, but not found (we only have an integer parameter one). What we need to do instead is call the superclass constructor with either a parameter in the Car constructor, or some other value.

The super expression (heh) replaces the automatic call to the superclass constructor so the superclass constructor with the matching parameter is called instead. Just remember that if you are going to use super, it should be the first statement in your subclasses constructor.


Since static variables and methods are inherited, we should probably know how they work when inherited. Well, pretty much the same as always, 1 variable is shared between all instances of a class, including subclasses. It doesn't work in reverse though. A subclass is an extension of its superclass, but a superclass is not an extension of a subclass. Example:

...would lead to each new instance of Vehicle AND Car to increase the count, since Car uses the Vehicle constructor, but a similar counter inside Car would not increase for a Vehicle being created.

I'm tired now, so that's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Wednesday, 5 October 2011

Java: Inheritance III

Since it's hard to work with a bunch of the private variables from Vehicle, when in Car, but we don't want to make them public, in the name of encapsulation, and keeping the, I guess, there is another way that's supported! Private variables are pretty hard core, they, as we've seen, can't be used by anything but the class they're declared in, even in subclasses, which are just extensions. So instead, we use "protected". Like public and private, protected specifies the degree of encapsulation. Specifically, protected variables are usable by subclasses as well as any other classes within the same package. It's kind of like an in-between level of encapsulation!

Ta-da! No more error! So we have that idea down, I think we can fit in one more today, and that'll be on the constructors. Constructors are fairly straightforward for single classes, but when it comes to inheritance, how is everything coordinated? Java enforces some rules of construction to ensure a deterministic, as well as sensible, initialization:

a) After any parameter variables have been initialized, a call is immediately made to a superclass constructor before any other statements in the constructor body are executed. (This can be done explicitly with with "super" keyword, but we'll get to that tomorrow. Otherwise, it's done automatically).

b) All directly initialized instance variables are initialized and any initializer blocks evaluated, in the order they appear.

c) Statements in the subclass constructor are executed.

So, say with our Car, the class implemented via inheritance from Vehicle, creating a Car using the "new" operator (After giving it's constructor an integer parameter, just for display purposes):

This results in the Car constructor being called, which itself immediately calls the Vehicle constructor. Any directly initialized instance variables declared by Vehicle are now initialized, with statements in the Vehicle constructor body being executed. At this point, control returns to the Car constructor where direct initialization of instance and class variables declared in Car happens, followed by execution of the constructor.

What you want to take from this is less the technical info, but more: "Objects are initialized top down, from superclass to subclass."

Now we've got that in, I think it's time to relax, with the "super" keyword (and more!) coming tomorrow! So that's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Tuesday, 4 October 2011

Java: Inheritance II

Sorry for the late update, been sick again, but its passed!

To look at how inheritance is used, how it works and how its supported, we'll continue with the Car example we used yesterday. Since this is just for quick examples, don't expect me to have a fully functioning Car class by any stretch of the imagination, though.

I put the AirFilter and Thermostat classes (empty) inside the vehicles package just so I could show you this without a whole bunch of red lines everywhere! The point to take from this is, we have this Vehicle class, it contains a bunch of private elements that make up a vehicle, as well as an array to hold its location. I figured it would be as coordinates, but that really isn't important! Then, there's a bunch of public methods the class has, one of which is a constructor. Got it? Good.

Say now, we want to make a Car. It`s kind of like a Vehicle, but we have 4 wheels, a paint job, some headlights, whatever else. So we could just make another class from scratch, but if we were to do that (And we aren't), we'd notice a lot of similarities between the 2. Both would need to move, both would have air filters and thermostats and whatever else. The similarities are such that a Car is everything a Vehicle is, but more, as opposed to being just similar in some ways, and different in others, its just an extension. 

To make something a subclass of some other class, which is the superclass, we need to make to add in an "extends SuperClass" to the class declaration. As so:

Let's go through it bit by bit. First off, we have the class declaration. As you see, just a simple "extends Vehicle" is all we need. Car is now a subclass of Vehicle. The main method here is only for demo purposes. First, we create a Car object, and then we apply methods available to Vehicle on it. And that's all fine and dandy. Remember, the methods were all public. However, when we try to do something to one of the private variables in the Vehicle, we get an error message telling us as much.

Well, I could go on, but I'm finding it way easier to absorb information in smaller chunks, since there's more time to mull over each bit before being thrust onward, so that's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Monday, 3 October 2011

Java: Inheritance

Java has a few possible different relationships between classes, possibly the 2 most important types being packages and inheritance. We`ve already seen packages, where several separate classes in the same package are essentially connected, such as in our Bridge Hand program. The latter, inheritance, is essentially a way to make a class an extension of another. This may not sound like much, but its a pretty key part of object oriented programming.

Inheritance, as the name suggests, allows a class (the subclass, the child) to take on, or inherit, all of the features of another class (the superclass, the parent), often demonstrated with the following simple diagram:

Don`t know why the arrow is pointing up, it seems like it would make more sense the other way around. But hey, doesn`t stop how the whole inheritance thing actually works. The subclass inherits all the variables and methods from the superclass, excepting the constructor. To make this something useful, the subclass can also  declare its own variables and methods, as well as redefining some superclass methods, normally known as overriding. This allows the subclass to specialize to its own needs, while holding the same general structure of the superclass.

Let`s have a couple of examples so its easier to understand. Say we have a very very general class: Vehicle. Then we can have several subclasses to fit the role of vehicle, but be specialized depending on what we want. We can have a Truck, Motorbike or a Car defined as a subclass of vehicle. We can say that our Car is a Vehicle. It`s everything a Vehicle needs to be, but more, its specialized. Size, seating, number of wheels, windshield, whatever. It`s not just the difference between 2 Cars, the difference isn`t only the color or whatever.

Inheritance isn`t limited to one level (When is anything, in coding? Goddamn recursion, man.), you can have a subclass of a subclass. We can now have a SportsCar if we want, as an extension of Car, with it's own specializations. One important limitation to keep in mind, though, is that a subclass can only have 1 superclass. I can't have, say, a Harvester be a subclass of both a Vehicle and FarmEquipment. Yech, think of the insurance rates you'd get on that thing. Worse if your harvester was red, I'd imagine. Anyway, tangent! Moving on.

This is all very awesome, but what does it mean for particular objects? If, say, an object, myCar, is an instance of a subclass, Car, then it'll contain all the variables and methods as available in Car, as well as Vehicle. On top of this, any methods declared by any class can be called for objects of the subclass (myCar), providing they are public. This remains true however far the line you go.

There's apparently quite a few complex rules we'll be subjected to soon, so I think it's time for me to understand the core idea fully before moving on, that's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Sunday, 2 October 2011

Day Off!

I think 1 day off a week is a good idea, and I'll probably make it Sunday! So no post for you!

Saturday, 1 October 2011

Java: A Summary so Far

Quick summary! Java is object oriented. This means it works based on objects, which are just abstract representations of...whatever. Like in our program to deal out a bridge hand. Could have just used a shuffled deck and then randomly split them into 4, but based on how Java works, we needed a table for players, players to play, and a deck made up of cards to play with.

Performing an action in java is done through use of statements. You can add, subtract or use methods on various variables (containers that hold either abstract values, or location in memory of where an object (in terms of its own abstract code) is stored. Each statement ends with a semi-colon so the program knows when to move on, since whitespace does not matter.

There are several special statements you can use, some of which are method creation, conditionals and loops. Methods are a collection of statements that can be called all at once at any point by calling the method name on the object in question. Example: We have a class representing a deck of cards. To shuffle this deck, in terms of programming, we would need to get a random number, and then flip the card at that number with the current card. Instead of requiring this every time you want to shuffle, put it in a method named shuffle, then call Deck.shuffle().

If-statements take the form: if ( condition ) { action }; with any subsequent cases being noted with else if, and the final case being noted with just else.
Loops consist of while loops, and for loops. While loops take the form: while ( condition ) { action }; and repeats until the condition is no longer true. Thus, we need to make sure that within the action body, we modify the condition (often an integer) such that eventually, it'll break the while loop.
For loops have 2 types, there's the for-each loops, taking the form: for ( Type : list ) { action }; which takes every element of the list or array provided with Type's type, and performs the action on it.
The regular for loops takes the form: for ( int i = startingValue ; condition tied to i's value ; how to modify i at the end of each iteration ) { action }; which can be used for a set number of iterations.

Methods in Java can call other methods and even themselves. The latter is known as recursion and often simplifies code, although it is more stressful on the machine to run.

Declaring a variable requires you to place the type of the variable before the variable name. This is because each variable type or object takes up a different amount of space on disk and you want to assign the right amount of space. Similarly, if you want a method to return a value when it's done, such as a method to add 2 numbers that you actually want to use, you need to declare the returned values type when declaring the method.

There's a bunch of stuff on data files, but there's not really a way to easily summarize that, so go back and find it, I guess, as well as anything else I missed! Unless there's a specific question anyone has?

Otherwise, that's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Friday, 30 September 2011

Java: Enumerated Types ( The Table )

Let's dive right into it, tonight! This is what I have for my table class:

Okay, this isn't all of it, but there's some new info in this chunk! Let's start with the enumeration. We have us our positions, but to ensure we have the right rotation later on, instead of having a buttload of conditional statements (if current position is south, next position is west, if current position is west....), we can just set them here with a function, using the return type of the enumeration. Oh god, what's this outlined in red?!? Well, that's (as you can see) an abstract method.

Recall that when we used functions on enumerated types previously, we had to specify which enumeration we were using. Without abstract, we'd still be there, and we'd have to specify everywhere, or whatever. With this abstract, as long as we have a variable of type Position, we can use next() directly on it.

Position p = Position.SOUTH;;

^ Becomes possible, instead of:;

Next, we need to set an array to hold all our players, as well as tell the game where to place our dealer. A new pack is just a given.

The method after that is to actually place the players at the table. An array of null-types isn't much use, so we have to actually initialize the players. This will give the player a name and a position on the table. The method I use within, .ordinal(), is build into the enumerated types. It returns a numerical value of where in the enumeration the (in this case) position is.

Position p = Position.NORTH;
System.out.println( p.ordinal() );

....would return 0 (Remember, programmers count from 0!). We use this since the array needs a numerical position to set the players at.

Now we get into the old stuff again! Dealing the cards. First, we need to shuffle the deck, at which point the dealing position is set to start from the left of the dealer. The for loop is a little messy. For every card, pass one to the current player, then move to the next player. We're almost done! We just need a toString() method for convenience.

We just have a stringbuilder here,  and it creates a string for us with the players position, followed by more stuff.
The line:

p == dealer ? "* " : "  "

is a compressed conditional statement. It's saying: "Is p (current position) the dealer? If so, give me an asterisk. Otherwise, give me a space". In regular if-statements, this could be represented as:

if ( p == dealer ) {
    return "* ";
} else {
    return "  ";

And uh....that's it! Now all we need to do is create a class to join everything together and actually get to dealing cards. Or, what I did was put that functionality within the main method of table, but you should have a main class to actually do things with, normally. I'm just lazy. This you can do on your own, whichever way you decide to do it. Just create an instance of a Table, make sure to seat your players, then deal the cards. At this point, you can print the table and you can see the players' hands.

Fucking...finally. For the next couple of days, I'll be doing some quick review from start to here, very compressed, but just as a recap. If you've got any specific questions, let me know, otherwise:

That's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us.