with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

YUI Tetris!

Tuesday, May 16th, 2006

It started with a challenge. The other day as my coworkers and I were walking to lunch one of them told a story about an interview question he was once asked. That question was How long would it take for you to make a tetris game using any language of your choice? He thought about the question, and delivered an answer. It was nothing that they were proud of so they shook their heads and pardoned him off. They were more or less looking for an answer along the lines of … maybe a couple of hours. And as it turns out, one guy actually did it in about one and a half hours. Little did I know he was dropping in some tetris.pl file and made the whole thing with ascii text.

Moving right along, this same coworker looked at me and said, How long would it take you? You think you could do it in a day?

I pondered the question, quickly latched onto a language that I’m comfortable with (JavaScript), and gave a nod. Sure, I said. I can totally do it.

Needless to say, I lost the bet. But 2.5 days later, I finished it . And I did it with my favorite utilities from the Presentation Platform YUI Utilities.

Really, you made Tetris?

Yep, I totally made tetris. Using a combination of the Event Utility and the DOM Collection utility, I was able to roll out perhaps the sweetest piece of eye candy I’ve ever built. And granted, it’s not to say that it hasn’t been done before, but with the help of YUI, this bad boy works in Firefox1.0+, Opera8+, Safari2, and IE6, and yes, it only took 2.5 days! Go ahead, see it in action!

Update! I’ve now made an alternate version with sound. Enjoy!

114 Responses to “YUI Tetris!”

  1. Miguel Simoes

    You rock the block(s) Dustin :P

  2. Nathan

    So basically, you rock. My dad will be forever grateful to you - he’s loves him some Tetris.

    And honestly? This is amazingly cool.

    Oh, but since it took you 2.5 days, you should quit JavaScript development and start digging trenches. What a worthless person you are (not to mention developer). ;)

  3. Nathan Smith

    Sweet dude. My hat’s off to you. I’m totally jealous of course. At least I can still say I beat you in Web 2.0 Pyramid on the podcast. :)

  4. pete

    okay, that was badass. doesn’t freak my processor out or anything. KUDOS!

    could stand to move a little bit faster, but now i’m just being picky.

  5. Elliot Swan

    Dang…that’s freaking awesome.

  6. Andrew Dupont

    I am a Prototype aficionado. I now know what I must do.

  7. Scott

    What kind of crazy control scheme is that? Since when are you allowed to rotate right AND left? Kids today…

    Seriously, that’s wicked cool. Nice work, Dustin.

  8. eric

    Awe… slap! Oh sorry, I was in my deeply impressed daze. If you enjoy ego-pumping action without my anal QA testing, please don’t read the following:

    It seems like the pieces spawn above the header image in Safari (but behind it, mostly hidden), causing a longer waiting period between pieces than in Firefox.

    I’m still amazed though. Wow.

  9. Jim A.

    Good grief Dustin. Not only is it smooth in action and beautiful graphically, but you even branded it!

    Fantastic!

  10. ian

    Now… someone has too much time on his hands doesn’t he! :P

    Nice work! It’s good to see how far JS and AJAX are being pushed.

    Now, off you go and add in multiplayer tournament capability ;)

  11. The Auldridges » Fantastic programming

    […] My buddy Dustin, a Yahoo! developer, has written a version of Tetris in Javascript. Not only does it function beautifuly, but the graphic design is pretty slick too. […]

  12. Dustin Diaz

    Hey sweet. Thanks for the positive feedback guys. This may very well be the one thing where I don’t get some guy dissing my work for one reason or another.

    @Andrew, Just know that I did it with YUI first ;). Plus you’ll find that the hardest part is just coming up with the math - and I already did that. The most painful part of the whole process was doing the checking on rotating. That indeed, took up most of my time. YUI took care of everything else as perhaps Prototype would as well.

    @Pete: I actually ended up speeding up the timer in the beginning to one second and letting it decremement by 50 (starting at 1000) for every level you get to. Then if you just happen to make it to level 20 I just let the increments stay where they’re at… It’s highly doubtful you’ll be able to keep up the pace when the incrementer is coming down at a tenth of a second.

    @All, By far the biggest time saver was YAHOO.util.Dom.batch. That allows you to run a method on a collection of HTMLElements which came in useful quite a few times.

    Other than that, let’s hear some high scores!!??

  13. steve

    that is badass!!! i am lame…it would take me weeks (months?) to write tetris in ANY language!

  14. Elliot Swan | YUI Tetris!

    […] YUI Tetris–I feel a new tagline coming along: I can’t believe it isn’t Flash! In other words, it’s sort of like margarine. The difference? This is actually good. […]

  15. Carson

    Um…. I’m completely, and utterly speechless. WOW. U. Da. Man.

  16. Michal Hantl

    1610 :)

  17. Rickmann Design » Blog Archive » Finally, a worthwhile use for Javascript

    […] Developers have been hacking together strange utilities for some time now. The Web 2.0 revolution has brought out a whole range of tools to help small business and consumers alike; however, not until today have I been convinced of the benefits that client side scriptiing can bring. Dustin Diaz’ new application is the first truly useful client side application I have seen. […]

  18. Johan

    Maybe you could do a interactive game that teaches how to use the Yahoo Development Libs?

  19. Matthew Pennell

    Ultra cool. Now make Project Gotham Racing 3 using nothing but document.write…

  20. Frederik Raabye

    Impressive. :)

    What about adding a pause function and level adjustment?

  21. Kim Steinhaug

    Wow Dustin!

    This was sweet, and really shows your javascript skills! Your previous articles discusses functions and more hardcore javascript usage, but this really shows you putting it all into play!

    reading your comments on the aschii version, I was stunned when you infact took time to ad the graphics aswell, a well spendt 2,5 days!

  22. davidG

    what! no sound effects and music??!!!

    only jokin :-) great stuff

  23. Seb Frost

    Very nice - I can’t play much because I don’t think my boss would but “but it’s research, I’m learning javascript”… :)

    Personally I’m not sure I “trust” YUI - I’m very much of the same frame of mind that Eric was in when he posted http://meyerweb.com/eric/thoughts/2006/05/08/flummoxed-by-frameworks/ - maybe I’ll convert myself at some point!

    I feel the need to try and do a version without YUI, and to see how the end result compares. Maybe that’d help sway me to frameworks… if only there were more time in the world!

  24. Full(o)bloG » Blog Archive » Yahoo UI vs Google Web Toolkit vs Adobe Spry

    […] Yahoo con le sue User Interface Library permette una notevole interazione lato utente, tanto che c’è già chi ha realizzato giochi come il Tetris interamente in javascript, DOM e CSS. […]

  25. Salis

    Okay, who’s going to be first to try using GWT. :D

  26. Jeremy Keith

    Nice one, Dustin!

  27. Jared

    How about YUI Simon (see here: http://slayeroffice.com/arcade/simon/)

    2,5 days (did you count sleeping hours as well), during the 2,5 days did you eat, do other things.

    Sounds more like you pulled it off in 24 hours.

    Like that movie 48 hours with Nick Nolte and Eddy “I play all roles” Murphy

  28. Mislav

    All that previous talk about Y! hacking around browser bugs so the developer doesn’t have to worry about differences and how Y!Event lib is perfect … and yet you were reduced to this:

    if ( isIE ) {
    YAHOO.util.Event.on(’wrapper’,'keypress’,DED.games.tetris.press);
    } else {
    YAHOO.util.Event.on(window,’keypress’,DED.games.tetris.press);
    }

  29. Dado

    Playing area is moved up by 2 lines in Opera 9.

  30. Dustin Diaz

    @Seb Frost: Take particular note that no where in our docs are we calling these frameworks. We particular chose not to call them that, but rather “Utilities”. They specificially don’t “do it all,” but instead the team took the approach of doing one thing very well and splitting them up. Hence, Event util, DOM util, Connection Manager, etc…

    But hey, if you’re comfortable calling it a framework, then yea, sure, it’s a framework. But it’s darn simple to use and it’s been documented the hell out of.

    @Mislav: That’s not a bug in the Event util, but rather a general known issue of assigning events to the window in IE. I discussed that a bit with Adam Moore and it is indeed nothing that the Event util can address. So yea, I will stick to my claim! :p

    @Jared: YUI Simon seems simple enough. But remember I’m not in the game making business ;). The 2.5 days indeed were broken up so I might have in fact did it in 24 hours. I should mention that to my coworker :D

    @Jeremy Keith: Aww. Thanks

    @David G: I thought about adding sound effects with flash when someone told me about the Flash/JavaScript integration kit. Indeed it would have been cool if I got events to talk to Flash - I was seriously thinking of doing my own custom sounds rather than downloading midi’s etc. That would have been too much nerdy fun.

  31. Cameron Adams

    How strange, I was thinking about this earlier today, and then you went and did it. Top work!

    I might have to up the ante a bit.

  32. P.J. Onori

    That is seriously impressive. On a side note, you’ve made the internet just that much more addictive. Thanks a lot jerk! ;)

  33. Robert Otani

    Dude, 2.5 days is impressive.

  34. Shep Poor

    Very nicely done. Cool demo use of the new toolkits.
    I did the same kind of thing with minesweeper when I was learning JavaScript, but I like the idea of Tetris more as the learning app. So what’s the next guy going to do for a JavaScript learning app? Card games should be very doable. What about Pac Man or Asteroids?

  35. Andrew K.

    Nice work, but I ask of you the same question I asked Cameron Adams when he built his bunny hunt JS game — where’s the AJAX-ified scoreboard so I can see how much I suck in comparison to the rest of the world? :)

  36. Dustin Diaz

    @PJ: Haha. Thanks for the lovely comment. Indeed the game is very addicting.

    @Andrew: Too funny. I suppose I could record everyones results - sounds like a case for the YUI Connection manager :)

  37. Dustin Diaz

    Sweet. I just got 188 lines with 2720 points! :D - It was comin’ down hard so my level 20 cutoff was a pretty good estimate of when to stop the time decrementer.

  38. ucantblamem

    DUDE!!!! You deserve a crown, seriously! Simply “da bomb!”

  39. Jeffrey McManus

    Hey Dustin, you are my god for doing this.

    Could I convince you to list this on the Yahoo! gallery site at http://gallery.yahoo.com ? I want to make sure that as many people as possible get to see this.

    Jeffrey

  40. Gulp >> Desenvolvimento e diversão, os melhores vídeos, novidades …. » Tetris em AJAX

    […] Para você que ainda não viu nada de mais em desenvolvimento AJAX, que tal um tetris todo feito assim e ainda por cima em apenas 2 dias e meio? Foi o que conseguiu Dustin Diaz com seu YUI Tetris. A façanha foi ajudada pela biblioteca para desenvolvedores do Yahoo! que o poupou de reescrever boas linhas de código. Se você não é desenvolvedor ou não sabe o que é AJAX leia na Wikipedia […]

  41. Quick Online Tips

    I played this wonderful game you created. Works perfectly. Now I know how to spend some spare time. Thanks.

  42. Quick Online Tips » Play YUI Tetris Online : Created by Yahoo User Interface Library

    […] The game developer Dustin Diaz says “Yep, I totally made tetris. Using a combination of the Event Utility and the DOM Collection utility, I was able to roll out perhaps the sweetest piece of eye candy I’ve ever built. And granted, it’s not to say that it hasn’t been done before, but with the help of YUI, this bad boy works in Firefox1.0+, Opera8+, Safari2, and IE6, and yes, it only took 2.5 days!” […]

  43. Dustin Diaz

    @Cameron: I’m interested in seeing your next game. Will it be out by the next holiday?

    @Jeffrey: I’ll go ahead and get it submited to the Gallery as soon as I wrap up some final additions now that I can say that the mass audience has tested it out.

    @Shep: Funny you mention Asteroids…

  44. This Week’s Weekly Links of the Week » SOME RANDOM DUDE

    […] Javascript Tetris - Dustin Diaz […]

  45. Alan

    Nice one… errr, not quite sure what else to say as it has me stuck for words. I need to put my Javascript hat on again, been stuck in wordpress code for ages…

    You’re defninitely an inspiration to do so!

    Cheers

  46. Lee

    Excellent! Great use of advanced JavaScript!

  47. Ajaxian » Yahoo! UI Tetris

    […] Dustin Diaz is at it again. This time he has created Tetris using the Yahoo! UI utilities. […]

  48. Phil

    This kicks so much ass, dude!

  49. Dustin Diaz

    Now up to 190 lines with 3070 lines! I’m becoming a master at my own game!

  50. aNieto2K » Article » YUI Tetris!

    […] DustinDiaz (el NakedDay Man) ha hecho este tetris con las Yahoo! UI utilities. Via Ajaxian. […]

  51. TOLAXOR

    I GOT 1410 FIRST GAME…

  52. Fredrik Wärnsberg

    That’s awesome! Nice work!

  53. The_Gray_D

    This is COOL!! You seem to be the ultimate master of Javascript… I don’t suppose that you might, maybe, possibly, (probably not :) ) happen to know of any open source cross browser ‘copy any selected text to clipboard’ scripts (In Javascript)? Nevermind! Once again, Great Game!!

  54. Schmanks

    Very sweet - nice job!

    …now, how about pause functionality, please?

  55. Udi

    Very cool Dustin :) Great idea, classy execution.

    I would loooove to know where you came up with those keyboard controls though. Why not just the four arrows? What’s the story?

    Peace,
    Udi

  56. Dustin Diaz

    Udi. Thx. read this.

  57. Y! Cool Thing of the Day » Blog Archive » Code Blocks

    […] Behold, YUI Tetris. Sure, he may have lost the bet, but he’s hardly a loser, and we’re proud to say that in some small way we helped him make history. […]

  58. Anders Hovmöller

    I looked at the code of this and was quite surprised at the length of the scrollbar I was greeted with. Looking through it more closely I was immediately greeted by huge swaths of copy-paste programming. Is it javascript that sucks so bad you need to do that or something?

  59. Dustin Diaz

    @Andrew: I pondered whether or not your comment was meaningful or just a stab at my programming.

    To address both accounts:

    A) JavaScript doesn’t suck. It’s a fairly small language that can get complex tasks done. It can be as abstract or as simple as you want to make it. And that, IMO, is the beauty of it.

    B) If you’re accusing me of being a copy paster, you’re heavily mistaken. Just about every piece in the code is required to make this thing do what it does. And afterall, it is a classic video game written JavaScript, how small did you expect the code to be?

  60. La Cara Oscura del Desarrollo de Software » Tetris Ajax-style

    […] Con la ayuda del Yahoo! UI Library (YUI) y dos días y medio de trabajo, Dustin Diaz desarrollo una interesante versión AJAX del popular tetris que ofrece en dos versiones: normal y con sonido. […]

  61. Woz.es » Tetris con DOM

    […] He quedado impresionado lo que se ha currado Dustin Díaz haciendo un tetris con DOM […]

  62. Oliver

    What about this ? http://cogames.net/

  63. Dustin Diaz

    Oliver. Although I give props to the author of that version, it has quite a few quirks. I had my sound turned on, and it failed to work in Safari, where as my YUI Tetris with Sound does not. Not to mention the rotation mechanism is shot, and when I move things left and right, it moves two blocks over… kinda wonky. Nonetheless, I’m still a fan of any tetris game out there :)

  64. Justin

    @Ian and others:
    What’s with all this mention of AJAX?
    JS + DOM != AJAX

    @Dustin:
    nicely done!

  65. Rizky

    awesome….4 thumbs up for you Dustin! (with both hands and feet)

    and all this time YUI is just sitting there on my harddrive. untouched!

  66. Francesca

    Tetris is one of those games that shouldn’t be so entertaining - by premise - but is damned addictive.

    I’m not sure if anyone else here has played it, but pokemon puzzle is another massively addictive puzzle game.

  67. Nikkaii

    AAHAHHAAHHAAH i didnt know how to get to it:(

  68. mish

    ya know I don’t care what other people say, you worked hard and I am proud that you could continue such a game. YOU ROCK!!!!

  69. sonya

    That’s so cool Dust. I can’t play it so well though.

  70. Dave

    Dustin, I think that Anders may have been referring to verbose patterns in the code that could have been reduced. For example, there is a run of 37 lines in a switch in the fire() method that could have been reduced to these three lines:

    var ShapeNames = [’square’,'line’,'el1′,’el2′,’zag1′,’tri’];
    var shape = YUD.get(ShapeNames[DED.games.tetris.curShape]);
    shape.innerHTML = 1 + shape.innerHTML;

    Most of the other methods make use of large switch statements that could be simplified with a few arrays to hold the varying parts rather than duplicating everything with minor changes. For example the rotate{Left,Right} code is copied and pasted with just the few changes needed for the different direction.

    Don’t get me wrong, the game is cool. I just think the code is probably three or four times bigger than it has to be. Let Javascript do more of the work for you!

  71. Dustin Diaz

    Dave, I think when you’re trying to do a game in the least amount of possible time, you go with what’s real quick. I think you’ve missed the point entirely as many other folks have as well. It wasn’t much of the fact that I just made it, but rather the 2.5 days that it took me. Indeed I had to think about several other things when developing the game. I did in fact notice many of the code repeating AS I was doing it knowing full well that “hey, I’m just trying to get something done and this isn’t the best way.”

  72. Quick Link: JavaScript Tetris - davecentral Planet David Central & Dave Central Planet

    […] On a dare, Dustin Diaz built Tetris using the Yahoo library. Seriously sweet. And when you’re done there, cook up a little Bunny Hunt by the Man in Blue, Cameron Adams. […]

  73. Ruben colina

    Let congratulate for your Yui tetris is very nice!!!

  74. Ali

    even if I got this done in 45 mins with nd screen mode in 45 mins but NICE WORK! ;)

  75. Frode Danielsen

    Hm.. What happened to the game-demo? From what I can see some lawyers made you take it down!?

    Anyway, I was just happy to read about your enthusiasm. It’s really great to just dig down and code a classic game in a language of choice! Personally, I’ve written “Snake” in quite a few languages, and this spring I wrote it in JS as well. Took me just a few hours initially, but I refined it a bit afterwards: http://frode.no-ip.org/snake/

  76. aksival

    Screw the lawyers…change it from YUI Tetris to YUI blocks and repost.

  77. Craig

    Total Kick ASS! WOW. Just needs a pause button.

  78. Darryl

    I grew up playing this game as a kid. Thanks for peaking my interest again!

  79. tara

    its good but i dont like that u cant see the shapes the whole time they dissappear everytime u rotate it

  80. melissa ortiz

    I think you guys need to create another website of tetris because because they blocked it at our school!!! Thank you,

  81. milo317

    Since Tetris was launched, i was always a big fan, now your Tetris rocks.

  82. Trisha

    I love this gane i have it on my ps2 and on my Xbox i didnt think it would be on the internet to this is a game that i hope never goes away. Because i jnow there arent alot of people who play it anymore but i do know of at least 5 people who will sat down and play it wit me. So if u would please try to keep this game around and not change anytihng about it thanks!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  83. zee

    ehh it’s tetris.. there are many like it without all the libraries or ‘ajax’. Why does it need ajax anyway?! Umm truly boring version of tetris.

  84. Dustin Diaz

    @Zee: Nobody said there was ajax in this version. I surely didn’t claim it. Also, can you please point me to at least one other version of tetris that works in over 6 major browsers?

  85. Marc Antyki

    “I love this game i have it on my ps2 and on my Xbox” - I don’t get it - 5, maybe more hundred $ for playing tetris ??????
    BTW - I used to play in 3D tetris … quite long time ago - at the begin of 90’s. I’m looking forward to see that type of game on my browser.

  86. Michelle

    It is an awesome game!!I play it during school..

  87. Rae

    i love tetris i just hope the school doesn’t block the site now that i found my favorite game…

  88. Skeetah

    nice work! But seriously, the controls are a little awkward, the four arrow keys would be a considerable improvement…

  89. Joe

    PUT THE GAME ON HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!

  90. bob

    what is the record amount of lines in a tetris game?

  91. Ron Buses

    Nice work Dustin! It’s good to see how far JS and AJAX are being pushed. Not only is it smooth in action and beautiful graphically - great stuff.

  92. Skeetah

    The record amount of lines/max amount is 200.

  93. Amariah Gibbs

    This game is amazing…love it…i can play it at school because my school is dumb and lets us play this…most of the game sights are blocked…so cudos man.love it…

  94. Sribna

    I think it would be easier to do a whole game using flash without javascript at all. :) Great script!

  95. obrazy

    Very cool Dustin :) Great idea, classy execution.

  96. michaela

    if youre going to write about the tetris codes than at least put up a link so you can play it?

    that would be very nice :D

  97. Cecile

    Heyy. Could you put up a link for your tetris and real tetris?? My brother is wayy obsessed ith it, and the wifi in our mansion blocks it, because or parents are afraid he will play too much! This is the only site that isn’t blocked, and he keeps bugging me to find a site with tetris because our parents will think it is suspicious if he is on the computer for 3 hours straight, they just think I am on IM with all my friens =)

  98. Dustin Diaz

    The link to both Tetris games that I’ve built are in the article. But if you don’t want to scroll all the way back to the top, click here.

  99. Bourse

    You have my admirations! I really took what I read as a challenge and tried to make tetris myself. But though you lost the bet, I still admire the fact you made it in 2 days and a half. I myself thought that I would make it for about 2-3 days too but… here I am still trying to make a flash tetris. Well, obviously, I am not that advanced as I wish to be but as I already said - i just took it as a challenge and I will make it! :)

  100. Artikelverzeichnis

    I’d love some cool old scool sound! ;-)
    But the game is already cool

  101. bob

    not worth playing if there arent any high scores

  102. bob

    whats the point without highscores? Theres nothing to compete against.

  103. Finally, a worthwhile use for Javascript by Rickmann Design

    […] Developers have been hacking together strange utilities for some time now. The Web 2.0 revolution has brought out a whole range of tools to help small business and consumers alike; however, not until today have I been convinced of the benefits that client side scripting can bring. Dustin Diaz’ new application is the first truly useful client side application I have seen. […]

  104. alfren

    wow cool!!! can i put it in my site??

  105. Pina N

    wow, great! It looks great and the sound reminds me of super mario so having in mind that these were the two games I was addicted to as a little girl there is no wonder I like it. The only thing that would make it just a better would be adding a pause if it is possible. (if there is already, sorry, I couldn’t find how to pause the game)
    PS: you have my admirations for the look - it really looks better than most of the Tetris games I’ve played.

  106. donna

    damn this game is the shit

  107. adak

    Just super!! I will not write anything more ;-)

  108. Paula

    Tetris using jQuery with source:
    http://fmarcia.info/jquery/tetris/tetris.html

  109. BRIAN!

    HIGH SCORES? Haha, I got 4540.

  110. Tetris

    Nice, can you give my version of tetris online a try? Thx

  111. Graham B

    Was unbelievably impressed when I came across this first time around - so much, in fact, that I recreated Tetris in my own Flex library as confirmation it was a worthwhile framework!

    http://www.gbradley.co.uk/javascript/flex/examples/flextris

  112. Antyki

    The best game of the world and www;)

  113. Gerardo

    Hi, your tetris is cool, but i doesn’t collapse. On the real tetris when a column is separated by spaces, will collapse.

  114. Aaron

    The L piece is bugged.

    Try rotating an L piece when it’s right above your stack and you’ll find that part of it can pass through other pieces.

Leave a Reply

Phone Number:

If you're about to post code in your comment, please wrap your code with the tag-combo <pre><code>. Also please escape your html entities - otherwise they will be stripped out. I recommend using postable.

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

Flickr

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know something? Just ask.

About | Archives | Blog Search

[x] close

Loading...

Submit a prototype

By checking this prototype I agree that I am not submitting false credentials, pornography, or a hate crime website. I also understand that by submitting my entry I may or may not be accepted, and if accepted, my entry may be taken down at any given time if I violate these terms.