Showing posts with label enumerated types. Show all posts
Showing posts with label enumerated types. Show all posts

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, position.NORTH.next() 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;
p.next();


^ Becomes possible, instead of:


p.SOUTH.next();


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. 

Thursday, 29 September 2011

Java: Enumerated Types ( The Player )

    Not much else to go! Let's think about what our player consists of. Not in a philosophical sense, mind, but only as far as the game gives a crap. The player consists of...a name (To differentiate them from each other) and a hand of cards. This is what I've then got for a player class (If you have something different, share it!):

First in this class, I've got some variables, straightforward enough. Since the size of the player's hand will change, I used an ArrayList to hold them, instead of the standard array I used for the deck. This might cause some problems with empty slots, so best to nip the problem in the bud. We can also, as a bonus, now use this class in other programs that don't require a set number of cards per hand. Next up is the constructor which is there to actually initialize the name. Next, we have newCard, to be used when being dealt cards, since cards are dealt 1 at a time, instead of a huge clump of 13 at once. the toString method is there so the players' hands can be represented, too. That's about it for the player, fairly straightforward.

So we have a player, the deck and the cards that the players will use. We need a table, at this point, as you may have astutely guessed. Y'know, from the title.

We'll want an enumeration for the compass directions of the table, To make sure the program goes in the correct (clockwise) order, we should probably also have some way to tell the program, in the enumeration, which direction is next. We need an array of players, the deck of cards and to specify where the dealer sits. We need a way to seat players where we want and we need to be able to deal cards out.

Go think about this. Try to make one yourself, and tomorrow, I'll show you my version. It's a fairly large class, at least relative to what we've seen up until this point, so I don't want to throw it at you directly after the player class.


That's all, folks!.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, 28 September 2011

Java: Enumerated Types ( The Deck )

Alright mateys, we have our card representation (No images, but lets...avoid those for now. We`re just working with basics!), Well, we can now work on our representation of a deck of these cards. The construction isn`t exactly straightforward, let alone the rest of the class, so let`s do it in parts!

Please remember, that normally, you`ll want to leave some kind of commentary in your code, I don`t just because I explain everything after the screenie, and to save space in the image, which is often over-sized.



Okay, let`s get started, line by line!

1: Declaration of the class, simple enough

3: We make this public so it can be accessed, final because there is no reason it should change and static so it can be accessed everywhere! The name is all caps, slightly out of convention just to denote its importance. Not necessary, up to the programmer.

5: Since the Card class was part of the same project in Netbeans (Or whatever IDE you use), it can be freely accessed from this class. We've got the instance initialization going on, too!


6: Counter for location in the pack!

7:  Each enumeration has this .values() function. This is the documentation for it:
:Returns an array containing the constants of this enum type, in the order they are declared. 
Simple enough to understand, it just gives back an array of all the elements in the enumeration, essentially. So this line is saying: For every suit in the list of suits (Remember, this is a foreach loop, it doesn`t require its own counter to iterate over everything), do the following:

8:  This line, similar to the last, iterates over every potential value in the list of values. Together, 7 & 8 read: "For each possible suit, do the following: For each possible value, do the following:...", or, more simply: "For each value in each suit..."

9: We are finally doing something! 9 is telling the program to actually add a card to the pack, based on which iteration its at. "For each value, in each suit, make a card" is the short form of these 4 lines.

10: This just increments our pack location to put the next card in.

 Okay, so now we have a constructor. What else do we need? In the interest of saving space, I'm compressed a lot of it, but we'll go through line by line so you don't miss anything!


18: This creates a random object. Used to generate random integers and booleans.

19-25: This is just a shuffle function. For every element in the pack, a random number is generated, then that position of card is flipped with the current position of card.

26: This is just a standard get() function.

27-33: StringBuilder is a new class for us, its part of Javas Built-In classes. It just acts as a simple way to append each card to a single string. That string is then returned, representing a shuffled deck.

You can then test this out on your own in a main function! First, create an object, print it out. You should get a list of all the cards. At this point, you can shuffle the deck and print it out again, seeing how it works.
This has been immensely long, and we aren't even done yet. Guess that gives me more time to ask you guys to give me any questions you want answered for the summary I'll be doing once this is over!

Oh well, that's it for tonight.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, 27 September 2011

Java: Enumerated Types ( Examples )

So, let's just be lazy and take the example pretty much directly out of the book! Creating bridge hands! (I don't even know how to play bridge).


Statement of Problem

Create a program that builds and prints bridge hands


Design and Implementation

Okay, so we should start with finding out about bridge. Can't write a program about it if we don't understand it! This is applicable to a wider range of things, whether you need to familiarize yourself with a genre of game you're not big on, or gene sequences. You can't just dive into stuff!

Bridge is played with a standard 52-card deck by 4 players. The players sit around a table with sides marked as compass directions (North, East, South, West). Bridge is a clockwise game, so whenever anything is done, its in order of NESW.

Just an aside, I learned this as the order when I was a kid when my South African teacher taught us his method. Never Eat Silk Worms. He also told us Naughty Elephants Spray Water, but the former stuck in my head much more clearly.

Anyway! One person is a dealer for each hand, with the person to the dealer's left shuffling the cards. The person to the right cuts the deck, and then the dealer can deal cards out, 1 at a time in order of rotation.

So we essentially need a way to create 4 hands of 13, then display each hand. Assuming the idea is to have this program evolve into a bridge-playing game, it would be good to think about the grand design. As a list of things we need to worry about, we have the suits and values, each combination of which makes a card, 52 of which make a deck, which itself needs to be shuffled, then distributed 4 ways. Then come the players, who will presumably be named, and are given the cards in rotational order. And further still, is the table, who's organization seems to be important for some reason. Dealer selection if nothing else.

From the above, we see the lowest level of object appears to be a card (Yes, the card has a suit and value, but those aren't entities, they're enumerations). So many cards in a deck, so many cards in a player's hand, what have you. So we need to represent this card, somehow!




Fairly simple as a class. The enums are a little unwieldy, but they're essentially the same as in last post. Each Suit has its own toString() method that returns whatever that suit is, and the same goes for all the values, with Jack returning "J" and so on.

Immediately underneath the enumerators, we have variables that will hold whichever enumeration some instance of the object will have, and these are initialized through the constructor immediately below that. Note that the constructor does take parameters! After the constructor, we have a generalized toString() method, and that just makes it so when you ask for the string representation of an object, it takes both the Suit and Value and squashes them together, as god intended.

Questions? Good, cause now we have a representation of a card, in the next step, I'll be moving on to making a deck of them. Wrap your heads around this first!


That's it for tonight.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. 

Java: Enumerated Types


Update 1/2 for today. Update 2 auto-posting in like....12 hours.

Very often, we'll want to represent concepts along the lines of "suits in a pack of cards", "days of the week", "pieces in a game of chess". These share something in common, namely that these concepts are types with a small, fixed number of values. (4 suits of cards, 6 types of chess pieces and 7 days of the week). This is the sort of thing described by the term enumerated type. A long time ago (and indeed, how I thought it would be done before reading about it just now), people would represent these types by creating a class for each. Well, no more!

Here's an example of creating an enumerated type for the card types, and writing a toString() method to overwrite the default one:

Click me!
Note the highlighted line, this isn't a class, you cannot instantiate it! We'll look at using an enum class in the next post! Right after you declare the enumerated type, the first part of the body should consist of all those types, separated by a comma. The semicolon denotes the end of the types. Then, we have any methods! You remember switch statements, right? Well, if not, that's okay, tomorrow, we'll be done with the chapter as it appears in the book I'm reading, so it'll be time for a review/summary/whatever. Anyway, while this method works, it kinda doesn't feel so hot. Mostly,I just don't use switch a lot, maybe I'm just not too comfortable around it, even though its way easier. Luckily for me and my silliness, the people developing Java thought to allow each value to define its own methods. This opens up the way for us to do the following: 


This might look a hell of a lot worse, and I can see how. You need to repeat the method name each time, it looks uglier and longer, but keep in mind, you won't always be working with card suits, or toString() functions. The toString() could probably stay as a general method, anyway, but say you had a video-game with several different types of spaceship, you don't want a general function for something that only 1 of them can do, right?

Note that you still need to separate each enumerated type by a comma!

Next post will be largely examples of putting this to use within a class, but first wrap your head around this general idea.

Questions welcome! Comment, follow, subscribe, share etc,


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.