msgbartop
by Joe Zack
msgbarbottom

29 Dec 08 JavaScript Deck of Cards Pt 2

A co-worker of mine sent me some advice on the JavaScript deck of cards I set up a while back. Everything he said was spot on. Jim, if you're out there, you're insight and advice is always welcome and highly respected. Thanks!

Read your blog. :)

In the interest of academic feedback (don't take any of this in a negative way), I have a few comments.

It's hard to tell from the current function names, but if the "same_suit" and "same_type" Card methods are meant to be "is_same_..." functions, they you need to change the "=" to "==".

Card = Class.create({
	initialize: function(type,suit) {
		this.type = type;
		this.suit = suit;
	},
	same_suit: function(suit) {
		return this.suit == suit;
	},
	same_type: function(type) {
		return this.type == type;
	},
	toString: function(){
		return this.type + ' of ' + this.suit;
	}
});

JS supports the '+=' operator for strings, so you could change the "message = message + ..." to "message += ..." in the Deck::toString method.


The first time through the Deck::toString function, the modulo check will be true, resulting in message beginning with a '\n' character. Wasn't sure if that is what you wanted.

Here's a minor optimization for the Deck::toString function. It removes the modulo operation from the loop, which is performed 52 times on a full deck, and handles the all of the leading/trailing whitespace (tabs and newlines) automatically:

toString: function() {
	var message = '';
	var i = 0, n = this.cards.length - 2;
	for(; i < n; ) {
		message += this.cards[i++] + '\t\t' + this.cards[i++] + '\n';
	}
	if (i < this.cards.length) {
		message += this.cards[i++];
	}
	if (i < this.cards.length) {
		message += '\t\t' + this.cards[i];
	}
	return message;
}

The following code:

var face_cards = "King,Queen,Jack"
face_cards     = face_cards.split(',');

Could be:

var face_cards = ["King","Queen","Jack"];

I don't think you need the "var i" in the Deck::add_card method.

PS: One other minor update, I got started thinking about UNO and decided to break out the French or Anglo American deck specifications out to a separate class and file.

PPS: Jim caught me using a "=" in place of a "==". These were methods that I hadn't tried yet, but knew that I would need in the future. This is exactly the sort of thing that would have been instantly caught had I written out some tests. I'm a bit late to the game on TDD, but it's something I've been toying with in Ruby and I'm starting to come around. I don't even know where to start unit testing in JavaScript, but I plan on doing a bit of homework on the matter so stay tuned!

Download the code!
JavaScript Deck of Cards V2
Current Version

Tags: , ,

07 Dec 08 Ganymede JSEclipse Alternatives

I've been having memory issues since setting up JSEclipse on eclipse. As I always, I tried googling around first but had a hard time finding any plugins that supported Ganymede.

Once again, stackoverflow came to my rescue by suggesting (free for commercial use) Spket and while I haven't used it extensively yet it's been working great so far!

Tags: ,

23 Nov 08 JavaScript Game Of Life Pt 3

I've made a small date to my interpretation of Conway's Game of Life yet again. Now instead of generating a random graph you can actually click on tiles to turn them "on" or "off".

Here's the code and here's how it do.

You can find the older versions of the files here: http://joezack.com/index.php/tag/game-of-life/

Tags: ,

20 Nov 08 JavaScript Deck of Cards

I wrote up a basic model for a 52 card deck of playing cards in JavaScript (using beloved Prototype. I plan on using it to make some very simple card games in the near future. I thought it'd be interesting to post this before I actually used it anywhere so I could take a look at how much it changed after I actually implemented it.

There's not much to see at the moment. You can just shuffle and get a card dump:

<html>
    <head>
        <title>JavaScript Deck of Cards</title>
        <script src="/common/prototype.js" type="text/javascript"></script>
        <script src="deck_of_cards_v1.js" type="text/javascript"></script>
    </head>
    <body>
        <script>
            d = new Deck();
            alert(d);
            d.shuffle();
            alert(d);
        </script>
    </body>
</html>

Download the code!
JavaScript Deck of Cards V1
Current Version

Tags: , ,

01 Nov 08 JavaScript Tile Puzzle

I was tinkering a bit while watching the tube tonight and I thought it might be fun to make a simple JavaScript tile puzzle. Might look terrible in other browsers.

First step was to write a little ruby script (using the GD Graphics Library) to read in a file and cut it up into individual tiles. (Photoshop is for wussies)

if __file__ = $0
  #pass the image name, tile size through the command line
  t = Tile_Cropper.new ARGV[0], ARGV[1].to_i
  t.crop_tiles
end

Then I used a slightly modified method I read about in Ben Nadel's blog to scramble the tiles.

<cffunction name="ShuffleArray" output="no">
	<cfargument name="tiles" required="yes"/>
	<cfset var random = StructNew()/>
	<cfset var i = ""/>
	<cfloop from="0" to="#arguments.tiles - 1#" index="i">
		<cfset random[i] = RandRange( 1111, 9999 ) />
	</cfloop>
	<cfreturn ArrayToList(StructSort(random, "numeric"))>
</cffunction>

A little bit of CSS magic:

#puzzle {
	width:      500px;
	margin:     0px;
	padding:    0px;
}
.piece {
	list-style: none;
	display:    inline;
	margin:     0px;
	padding:    0px;
}
img {
	border:     1px solid gray;
}

And finally I used scriptaculous and prototype for the obnoxious drag-and-drop sorting. Not that I'm complaining. the Sortable methods weren't intended to be used for something like this.

function init() {
	Sortable.create('puzzle');
}

Complete the puzzle to find out what I was watching!. Here, I'll give you a hint. It's Dexter.

Download the code.

Tags: , , , , , ,

13 Oct 08 JavaScript Game Of Life Pt 2

I changed up the code up a little bit for implementation of Conway's Game Of Life. Turns out I had misread the rules a bit. My original code turned all cells on when they had 2 or 3 neighbors, regardless of their current state. That's how live cells are supposed to work, but dead cells are only supposed to change their state when they have exactly 3 neighbors.

Also I've updated my JavaScript objects to use the Prototype Class.create method. As far as I know the method I had been using works in all browsers, but I like Prototypes implementation of constructors and inheritance.

Finally, I increased the number of live starting cells, shrunk the number of boxes and increased the time delay between frames to hopefully grant a better user experience. It probably still looks terrible in Internet Explorer. Once again, that's what you get.

So check it out and download the code!

PS: You can still download and view the original version if you like.

Tags: , ,

12 Oct 08 JavaScript Game Of Life Pt 1

I thought it would be fun to implement Conway's Game Of Life. I used ColdFusion a bit in my example to ease some typing but the "engine" is all JavaScript. Beloved Prototype is also being used a bit behind the scenes.

So without further ado, here's a

// set up a game of size 30 x 30
 
g = new Game_Of_Life(30);
 
// set some random tiles, note that you
// have way more of these for a size
// 30 board.
 
g.set_tile(2,26,1);
g.set_tile(19,20,1);
 
// draw inital board
 
g.draw();
 
// run the game, 1/25s "frame-rate"
g.run(.25);

Click to see a demonstration.

And, as always: Download the code!

PS: It looks like terrible in Internet Explorer. No comment.

Tags: , , ,

04 Oct 08 Sarah Palin Response Generator

I always get jealous whenever I see one of those mildly funny internet random text generators. I've finally done something about it. Now hopefully it'll be (even more) trivial for me to make one of these in the future.

For the time being I've filled it up with some juicy Sarah Palin quotes. The question area is irrelevant. Apt.

Sarah Palin Response Generator

and as always...download the code!

Tags: ,

23 Sep 08 JavaScript List Utility

Here's a little something I was working on today. The goal was to model an HTML unordered list in JavaScript so I could easily add/remove and display elements. I haven't gotten around to actually writing all of the display methods because I haven't exactly figured out how I want to use it yet.

PS: I kinda re-remembered the toString method on this one.

PPS: Requires prototype

Example Usage:

set up the list

list1 = new List();
list1.add('a');
list1.add('b');
 
list2 = new List();
list2.add('b1!');
list2.add('b2!');
 
// nest away!
list1.add(list2);
list1.add('c');
list1.add('d');

li data

alert(list1.get_at(1).data);

remove li

list1.remove(4);

alert the list

alert(list1);

BAM!

Download the code!

Tags: ,

18 Sep 08 Simple JavaScript Slider/Iterator…Thing

In keeping with my current "blog-more-about-less" stratagem I thought I'd post a little JavaScript utility I wrote. The idea was just to add "next" and "previous" buttons to an existing gallery, but I thought I'd have a little fun with it, as it may come in handy in the future.

The idea was to create a simple slider object that would keep track of the users position in an array of items. I could cycle through the items, backwards and forwards and fire of item methods. For the gallery I only had to worry about a few basic properties and methods, but I wanted to design this in such a way that adding properties and functionality to my objects would be a breeze.

PS: Current the slider object expects your items contain the methods "update" and "show". I *know* this is bad, but I've had a hard time coming up with a solution that I liked better.

PPS: The example code I'm posting below was done using Prototype and ColdFusion, neither of which are required but are there because I thought it made it easier to get the point across.

Alright, enough gibber jabber.

Image Object:

function Image(thumb,large,caption) {
      this.thumb = thumb;
      this.large = large;
      this.caption = caption;
      this.show = function() {
          showPhoto(this.large,this.caption);
      }
      this.update = function() {
          $('largeImg').src = this.large;
          $('photoCaption').update(this.caption);
      }
  }

Create and fill it up!

gallery = new Slider();
// don't forget to escape those special javaScript characters!!!!
<cfloop query="gallery">
      gallery.add(
          new Image('#thumb#','#large#','#caption#')
      );
</cfloop>

Attach the "previous" and "next" methods to my links. <3 unobtrusive JavaScript!

Event.observe(
      'previous',
      'click',
      function() {
          gallery.previous();
      }
  );
  Event.observe(
      'next',
      'click',
      function() {
          gallery.next();
      }
  );

And finally, on the actual thumbnails on the page:

<cfloop query="gallery">
      <!--- This should probably be done unobtrusively,
               but it's just so darn convenient! --->
      <a onclick="gallery.show(#gallery.currentRow - 1#); return false;" href="##">
            <img src="#thumb#" alt="" />
      </a>
</cfloop>

Download the code!

As always, this solution is far from perfect, and I'd love feedback!

Tags: ,