r/javascript • u/blazenite3 • Jan 12 '19
I made Tetris using pure HTML, no Canvas with Touch Controls!
https://www.neilb.net/tetrisjs/265
Jan 12 '19
"Pure HTML" implies no JavaScripts, just so ya know. If you show this at an interview I wouldn't want that to distract from your nice portfolio piece. Implement it in es6/es7 without jQuery if you want to raise an eyebrow. Honestly, most working front-end devs I know would look at me concerned if I said proudly that I had build something in jQuery. jQuery was popular at a time when there was still no good native JavaScript API for selecting elements by their CSS selector, but now we have `document.querySelector` and `document.querySelectorAll` which, if performance is of interest, will be much, much faster than downloading jQuery and invoking `$()` to do an identical operation. Just my $0.02, nice work, happy developing.
50
u/blazenite3 Jan 12 '19
Yeah you're right I probably didn't need jQuery and just used it out of expediency. I will take a look at document.querySelector, good to know.
42
u/Hendrix312002 Jan 12 '19
I wouldn’t worry about using jQuery. No one should get mad at your for using it. If you want to try and refactor without using jQuery that would be a good exercise and then you show both implementations in your portfolio which would be all the more impressive!
12
u/blazenite3 Jan 12 '19
Thanks, I am really curious now if not using jQuery would have performed better or not, I think I will test it. As much as people bash jQuery I would imagine it is pretty optimized in terms of querying and I was questioning whether I could have done any better.
9
u/ScientificBeastMode strongly typed comments Jan 12 '19
Honestly, for your use case, jQuery is probably not affecting the performance in a perceivable way. It really only slows things down when you have a large tree of nodes in the DOM, and you’re having to select elements very frequently or rapidly. I don’t think you have enough nodes in your DOM here for that to be a big issue.
That being said, the performance can be improved by storing individual element nodes into variables or objects, and referring to those variable/object names instead of querying the DOM itself to find the element. Basically you want to query the DOM as little as possible. That will improve performance even if you’re using pure vanilla JavaScript as well.
6
u/blazenite3 Jan 12 '19
Great tip! Yeah I do end up querying the Dom every frame, but storing the elements in an array would eliminate that, very good idea. Thanks!
-4
u/BeFoREProRedditer Jan 12 '19 edited Jan 13 '19
If you can, DON’T use queryselector. It’s a really expensive function.
Edit because downvotes: if it’s not a complicated query eg. querySelector(“div.special”) it’s better to just getElementByTagName(“DIV”) and then for loop through it with, if classList.contains(“special”)
It’s probably more 20x less expensive.
(wouldn’t even be surprised if it was a 100x faster. Can’t check right now since I am on mobile)
3
u/DrDuPont Jan 13 '19
Premature optimization IMO
I've yet to see this as an FPS bottleneck.
"Really expensive function" requires some context, btw. Really expensive compared to what?
2
u/portugasms Jan 12 '19
What’s the alternative?
1
u/BeFoREProRedditer Jan 13 '19
Updated it.
On small projects it really doesn’t matter, but when working on larger projects it can tank performance. Same with inner- & outerHTML assignments,
6
u/Downvotes-All-Memes Jan 12 '19
And grid instead of tables? Or is that more difficult than I’m imagining?
18
u/dimasc_io Jan 12 '19
There's still a massive fuck ton of headache that jQuery helps alleviate. While bashing jQuery is the new "in thing", go ahead and code a .toggleFade() or .fadeIn() or .next() or .closest() in ES6 with full browser support. I'm happy to expedite my development and worry about refactoring (if it's an issue) later.
4
u/guldmand Jan 12 '19
3
u/dimasc_io Jan 12 '19
The amount of code required in ES6 to do basic things like .toggleClass() is the reason why jQuery is still widely used.
3
u/midder Jan 13 '19
You mean .classList.toggle() is too hard?
0
u/dimasc_io Jan 13 '19
I'm pretty sure this doesn't work in IE10 and earlier.
2
u/DrDuPont Jan 13 '19
Just use Babel my man!
Also if you work somewhere that supports IE10 and earlier leave
1
1
u/dimasc_io Jan 12 '19
Exactly my point. Look at the ES6 code for Fade In. I would much rather just use jQuery.
5
u/DrDuPont Jan 13 '19
That's not ES6. Change "What's the oldest version of IE you need to support?" at the top of the page to IE10+.
You should really be using CSS to animate stuff these days.
toggleClass(), your other note, is as simple aselement.classList.toggle(className);jQuery is dying rapidly. There are still some things it does better and more cheaply than a quick and dirty implementation but I'd prefer to see coders use a smaller library to assist with that as needed. jQuery is an entire toolbox, and I don't really need all of those wrenches anymore.
3
u/ATHP Jan 12 '19
While I generally agree I'd like to mention that jQuery is still used on so many sites that almost all users will have it cached so I don't think the performance overhead is that much of a problem.
21
Jan 12 '19
almost all users will have it cached
Yeah, no.
Different CDNs, different URLs
Different versions, different URLs
Hosted locally, different URLs
There are so many variations on a theme, this line of thinking is not very helpful.
2
u/ATHP Jan 12 '19
Well according to this source it is used on 73% of all pages so yeah... Yes.
9
u/ScientificBeastMode strongly typed comments Jan 12 '19
That’s a lot of legacy code... most newly developed sites aren’t using jQuery as a primary library anymore.
But jQuery versioning is a thing, and plenty of sites use different versions or different CDNs to deliver jQuery functionality, so he’s right that it won’t always be cached. It also just depends on the browser and user settings, among other things.
1
u/peex Jan 12 '19
most newly developed sites aren’t using jQuery
Nope. There are still new website created using jQuery everyday. It isn't going anywhere and it's a good library for DOM manipulation. We use it everyday at work.
1
u/ScientificBeastMode strongly typed comments Jan 12 '19
Eh, you’re probably right. I mean, unless you’re building something with a ton of DOM nodes that need high performance manipulation, jQuery is usually fine. But things like smooth animation of large graphs and other uses... there are better alternatives.
6
u/Aetheus Jan 12 '19
jQuery itself as a library is okay. While you can certainly perform DOM manipulations perfectly well without it these days, it bundles several niceties that are convenient to have around.
No, the issue isn't jQuery itself - it's how jQuery is often used. Before the days where frameworks like React started getting really popular, most people (myself included) never bothered divorcing their "rendering" from their "data". It was also a time before Promises were really widespread (although jQuery had it's own, non-spec compliant Promises, IIRC), so anything that involved asynchoronous code was horrible.
So a lot of sites that use jQuery wind up being simple to read and modify at the beginning, but monstrous in a few years time. The simplest changes could break a site in unexpected ways, because you never know what DOM elements the "fetchNewsArticles" function is going to end up mutating. And what if you wanted to do X after function Y, which is being called in function Z, which is being called in function A, and all or some of these functions have to wait for some network result? I've seen many people pass around callbacks 3-5 layers deep, which ends up being massively confusing. Worse, some people add a "quick fix" of just "waiting" a few seconds after calling function Y before calling the next necessary function, which leads to all kinds of race condition bugs that are a bitch to debug.
So yeah. jQuery itself is fine. Adequate for simpler sites, and a bit clunky for larger "web apps", but you could still probably architecture a front-end app fine if you put in the time. No, the problem isn't jQuery - it's just 95% of sites that use it.
2
u/ScientificBeastMode strongly typed comments Jan 12 '19
Yeah, that’s definitely a good point. Design patterns matter more than just about anything else when it comes to performance.
2
u/DrDuPont Jan 13 '19 edited Jan 13 '19
You missed u/ripvannwinkler's point
They're not disputing the usage of jQuery, they're disputing that it will be cached if served by CDN. There are many CDNs and many different versions of jQuery that are served by those. Given those permutations, it's extremely unlikely in practice that a user will hit a warm asset (speaking from experience).
-5
Jan 12 '19
[removed] — view removed comment
6
u/ATHP Jan 12 '19
I don't understand why I can have a normal discussion on all subs except those who are about programming. There will always be someone who tells others that they are inexperienced and that they are wrong, getting personal very quickly. But whatever makes you feel better.
Let's just quickly summarize what I DIDN'T say: jQuery is good. You should use jQuery. jQuery is used on newly built websites. All websites serve jQuery via CDN.
And now what I said: jQuery is still used on the majority of websites and most users will have it cached.
Do with that whatever you want.
-2
Jan 12 '19 edited Jan 12 '19
And now what I said: jQuery is still used on the majority of websites and most users will have it cached.
Do with that whatever you want.
OK, since you really don't seem to understand my counter argument, let me put it this way.
The assumption that most users will have it cached is based on another assumption that most sites pull the jquery script file from the same place. If Site A pulls from cdnjs.com/jquery.js and site B does also, your assumption holds true. As soon as Site A pulls cdnjs.com/jquery.1.0.js and Site B pulls cdnjs.com/jquery.1.0.1.js however, your assumption falls apart. The same rings true if site A chooses cdnjs.org instead of cdnjs.com.
Then, you have to consider that any considerably large site of a private or professional nature is going to bundle and house its assets internally and render the entire assumption above irrelevant because reddit pulls its code from www.redditsatic.com which no other site in the web is going to be using for hosting its own assets. EVEN IF reddit uses the exact same version of jquery that my site uses, a user who visits both sites will be downloading two separate files. There is no caching in play.
Does it start to make sense now?
Edit:
I don't understand why I can have a normal discussion on all subs except those who are about programming. There will always be someone who tells others that they are inexperienced and that they are wrong,
It's because most of the time, people like you (typically younger folk, but not always) who continue this type of argument do so under a false premise or misunderstanding of the concept and a genuine perception that your knowledge is better than the rest and you're somehow right despite not knowing the full story. More experienced people generally grow tired of this type of argument and refuse to spend any serious time countering it. It's easier to be dismissive early and cut your losses.
Yes, I'm an ass about it. I'm not a good role model or educator in matters of this nature.
4
u/Maverick2k Jan 13 '19
To be honest you’re the type of person that thinks whatever they think is correct. It’s usually the way for those programmer type that are stuck up there own asses. There’s very rarely a reason to be a wanker like you are so early into a discussion. Simple as that really.
1
1
1
u/Azudra Jan 12 '19
most working front-end devs I know would look at me concerned if I said proudly that I had build something in jQuery
It's funny in a sad way that most devs I know wouldn't even be able to select every <p> inside a <div> with the class "main" without jQuery. :(
But that's likely because of my company, which doesn't do any effort to improve the quality of new developers. That's how you create someone with 5 years of JavaScript experience who can't do anything without external libraries. Not everyone seems to be motivated to improve themselves if not specifically asked for by an authority.
1
u/PsyEnmanuel Jan 13 '19
Don't listen that guy opinion, nice job is all about doing amazing things with any library or language you use and it works pretty fine, i would like to see some animations but other than that good work.
1
Jan 13 '19
As a JS dev who started when ES15 was already a thing, JQuery's existence has been nothing but a distracting pain for me. I've wasted so much time glancing over stackoverflow "solutions" that use some outdated JQuery rubbish to do something that the language can already do.
Seriously screw JQuery
0
15
Jan 12 '19
Nice mobile friendly app. Im glad to see it. And im intetesting to see how you did it. :) Well done!
2
u/blazenite3 Jan 12 '19
Thanks! Source is on Github
4
Jan 12 '19
I thought it was really playable, my only comment would be that when you hold down to move the piece faster, the next piece in line then shoots down right away, there should maybe be a slight delay build in there, or make it so you need to release and then hold down again before the next piece will shoot down.
3
u/blazenite3 Jan 12 '19
Totally agree I think I will update that. Thanks!
2
Jan 12 '19
good job tho, might have inspired me to try something like this! Did you find it a good way to improve your js skills? Or maybe this was a walk in the park?
4
2
u/blazenite3 Jan 12 '19
Yes it definitely improved my understanding of how JavaScript processes touch and keyboard input. Was a fun experience all around.
5
u/AlexAegis Jan 12 '19
When you hold down to speed up the drop, it should return to normal speed when the tetromino drops, requiring you to press the button again. So you wont accidentally drop down two tetromino.
2
0
u/blazenite3 Jan 12 '19
ed up the drop, it should return to normal speed when the tetromino drops, requiring you to press the button again. So yo
fixed
0
4
u/JudgeGroovyman Jan 12 '19
The key here is that you didn’t use canvas. That’s tricky and you did a great job! You nailed the touch controls too they feel fantastic.
2
3
3
u/ImCerealsGuys Jan 12 '19
Hey man, I was playing this in the car while waiting for my gf. It’s quite fun. Keep it up!
2
2
u/invisiblelemur88 Jan 12 '19
Love it. Kinda frustrated that frequently i would swipe down to drop a piece quickly but it would register a move to the right too..
2
u/blazenite3 Jan 12 '19
You're totally right I didn't notice that before. I think I'll make it so if swiping down it ignores any left/right movements. Thanks!
2
u/thisisanewaccount6 Jan 12 '19
Hey this is pretty neat! I made something similar a while back with the new CSS Grid. It's a bit janky because I was mostly just messing around and seeing how much I could rely on the grid (e.g. text scales very poorly). I also went overboard making the grid take up the entire screen as a bit of a performance test.
No mobile support unfortunately
| Key | Function |
|---|---|
| A | Move left |
| D | Move right |
| W | Hard drop |
| S | Soft drop |
| Space | Hold piece |
2
u/blazenite3 Jan 12 '19
That's really cool! I couldn't figure out how to rotate though lol
2
u/thisisanewaccount6 Jan 12 '19
Whoops, J and K rotate, not sure how I missed that for the controls list!
2
2
u/zakerytclarke Jan 12 '19
Is it open source? I'd love to contribute, make it a PWA, maybe add some sound and a scoreboard.
1
2
u/Miniotta Jan 17 '19
Nice job, I made a Tetris myself but I used a canvas to "paint" the game...
I could take some things that I really like from yours :p
Try it out if you want, it's made to play in multiplayer (because it has some debuffs to make it more fun to play)
https://github.com/albertodeago/tetris-online
1
4
1
u/ScientificBeastMode strongly typed comments Jan 12 '19
I love it, it works great!
Just a couple of suggestions, in case you’re a perfectionist. When I slide my finger down to quickly drop the Tetris piece, it seems that any slight left or right movement will cause the piece to land left or right of the intended target. I think it would be better if it could save that position and recognize the down-swipe, locking in the lateral position.
I haven’t looked at the source code, but if your control logic loops through possible touch inputs, you might consider testing whether a down-swipe occurred before allowing normal lateral movement. Although that would still allow the error to occur if there was slight lateral motion prior to the down-swipe detection.
One way you could sort of circumvent that is to implement a delay timer for controls. Basically you could set a timer each time control input is detected, and not allow the movement to change during that time (we are talking less than 0.02s). And store all the inputs that occur during that time interval into an array. Then you can see which inputs are in the array and prioritize which inputs to execute, which ones to ignore, and the order of execution.
Just a minor detail, but something to think about.
The other thing I noticed (and I could be totally wrong about this) was that the pieces wouldn’t move after they connect to set piece below. If I recall correctly, the old school Tetris game actually maintained a timer once the piece was touching another piece, allowing you to move the piece left or right until the timer ran out.
Actually, I think I’m some versions of the game, each time you moved it left or right along the pieces at the bottom, it would reset the timer to connect it, allowing you infinite time to actually set the piece as long as you kept moving it around.
3
u/blazenite3 Jan 12 '19
Thanks for the tip. Yeah I think your suggestion is good, one thing I could do is detect if the downward motion is greater than the lateral motion then prevent the left right movement altogether. The game does allow sliding while along the bottom though it's easier to do on keyboard.
2
u/ScientificBeastMode strongly typed comments Jan 12 '19
Ah yes, so I was definitely wrong about that. I bet the touch controls make it a bit more complicated, lol.
But yeah, overall I think it’s awesome!
1
u/nmehta_001 Jan 12 '19
I played it, touch controls are great! Although when I got to level 2 with ten lines completed, the whole gride was cleared and nothing happened after a minute. I was using Firefox Focus on a Note8 if it helps (Android 8.0)
1
1
u/michlsch Jan 12 '19
Great work!
You should change your gitignore settings. 😉
2
u/blazenite3 Jan 12 '19
Thanks! lol you mean because it included the .vscode folder? yeah makes sense
1
Jan 12 '19
Very cool!
But I would request simpler controls. And the game speed is a bit high for my taste. That seems to be messing up the controls for me.
Good job, though. 👍
Is source code available for study (if I ever learn how to program)?
1
1
1
Jan 13 '19
Really clean and the mobile friendly makes it better. Great work! Please share your github because this would help me a lot in learning since I am just a beginner level.
2
7
u/Hendrix312002 Jan 12 '19
For something like this performance is not an issue. People honestly make way too much noise about performance. You only need to worry about it when you do. Just keep building things and getting better and you can worry about performance later. Trust me you will know when performance is an important issue. For a game like this just have fun.
3
u/Maverick2k Jan 13 '19
You know what’s hilarious? Even huge companies like Hue go for human readable code over performance when writing in vanilla JavaScript. And why is that? Because even in tens of thousands of lines of code the performance hit of most of the various different ways you can achieve the same things in JavaScript is often negligible for the most part; the obvious ones aside.
3
u/Hendrix312002 Jan 13 '19
At the end of the day, as software developers we write code for human beings. The computer does not care what our code looks like, hence the reason we minify our JS for performance reasons. We should be more concerned with our performance as developers, with how easy it is to modify and/or maintain our existing code bases, not how to save a few milliseconds. Also code splitting is a very effective way to drastically increase performance regardless of what libraries you are using.
If using a library like jQuery really hinders your applications performance you probably designed and or architected your software poorly.
2
Jan 12 '19
I got to 70 lines and then it was too fast. It is missing the gravity lock as I tried to spin a piece into place but as soon it touched bottom it was locked in place, after a certain amount of lines you simply cannot hold up. It certainly is a Tetris but it doesn't follow the whole ruleset. Otherwise kudos for the programming.
2
u/david622 Jan 12 '19
FYI, in your js file, it might be cleaner to create HTML element objects and under them into the DOM directly rather than concatenating strings to create HTML tags
1
u/jeffw16 Jan 12 '19
Very cool! I had to make a Tetris game for my CS class recently using Java so I think this is awesome!
Do you happen to include wall kicks in this game? I tried seeing if it was implemented but I’m on mobile so the one-way rotation kind of screwed me up.
1
u/Bamboo_the_plant Jan 12 '19
Not sure why “no Canvas” is being mentioned as a handicap factor.
In my opinion it’s easier to make rectangular UI (even with animations) using HTML and styles rather than Canvas – just set your elements to position: absolute, and you’re good to go. You then benefit from a debugger-inspectable UI, too.
1
-2
u/sidi9 Jan 12 '19
Very cool but jQuery in 2019?
2
u/oopssorrydaddy Jan 12 '19
In the case of this app – why not? What is the pro/con for the user?
2
u/sidi9 Jan 13 '19 edited Jan 13 '19
Very soecifically for this app, jQuery is really heavy, not just in it's initial load proportionate to what you actually get in return, but in the way it deals with DOM elements at runtime. jQuery is a "layout thrashing" framework, which is very bad for performance that need a lot of operations related to positions of elements, like, say, a game.
Every time, you say, simply read the position of an element, or its word, it causes a total CSS reflow and the entire page has to be repainted, so imagine that multiple times a second on multiple elements, then scale that up, you can see it can start to slow a page down. Have you ever been on a mobile device and you're scrolling down a page and it freezing and a nightmare, it is because of excessive CSS reflows. jQuery is one of a few frameworks that are guilty of this because they mutate and read from the DOM in real time, rather than a shadow DOM, then apply those changes as a batch onto the real DOM.
If you've ever reverse engineered jQuery, or read the unminified code: you'll see it is guilty of a lot of this stuff and these are all the kind of methods that you need to create a "game".
This is 10 - 8 year old standard practice now when dealing with the DOM/JS in the world of shitty smart phones because the DOM/CSS/HTML/JS is single threaded (unless you use WebWorkers which won't solve this problem).
Further reading.http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/
https://gist.github.com/paulirish/5d52fb081b3570c81e3a
https://www.paulirish.com/2011/dom-html5-css3-performance/
0
Jan 12 '19
[deleted]
3
u/blazenite3 Jan 12 '19
Yes it does use JavaScript sorry, others have pointed that out. With pure html I was trying to convey the no 2D Canvas point but I probably could have phrased different
1
0
Jan 12 '19
[deleted]
1
u/blazenite3 Jan 12 '19
Thanks - yeah it's just tap for rotate but I could see how that may not be intuitive
23
u/blazenite3 Jan 12 '19
I wanted to see if I could do it using just HTML and JavaScript. Rendering is done using HTML Tables and jQuery. Also used TypeScript. Here is GitHub link if anyone is interested: https://github.com/nbarkhina/TetrisJS
I know there's a lot of these out on the web but I wanted to create something that looked minimalistic yet elegant with excellent controls and compatibility. Spent a lot of time getting the touch controls to feel just right.
Let me know what you think.
Thanks!