Writing a Tetris game in JavaScript

In this episode I write a Tetris game in JavaScript from scratch.

If you like this tutorial you will probably also like my Super Mario Bros tutorial: https://youtu.be/g-FpDQ8Eqw8

We will look at
* Drawing on a canvas
* Rotating a matrix
* Rudimentary requestAnimationFrame listening
* Handling keyboard input

Since we are writing ES6 this code might not run on all browsers yet. I was running Chrome 53 when I wrote this and if you wish to follow I recommend you do too.

The initial HTML can be found here:
https://raw.githubusercontent.com/meth-meth-method/tetris/295e28320cd06b858e529ee6c512eeeb8526ca05/index.html

Source code with step-by-step commits:
https://github.com/meth-meth-method/tetris

Music:
Demoscene Time Machine
http://demoscenetimemachine.com

Comments

ThorG says:

3:07 how can i open this?

Sebastian Sipos says:

Don’t take it the wrong way, but your beard + js = hipster :))

매일코딩 says:

oh! It’s great!

Okhyun Lee says:

Of well, my absolute stupidity….! Apparently I’ve been saving my file to a wrong folder..LOL! But thank you so much for your tutorial! I will keep following to learn!

Hello, I am new to programming and have been trying to follow this tutorial to get the feel for it using sublime text 3.

I’ve got the black background but can’t seem to have the first tetris block to show?
I think I copied everything ok? What am I missing here? Any advice? Thanks in advance.
========================================
const canvas = document.getElementById(‘tetris’);
const context = canvas.getContext(‘2d’);

context.scale(20,20);

context.fillStyle = ‘#000′;
context.fillRect(0, 0, canvas.width,canvas.height);

const matrix = [
[0,0,0],
[1,1,1],
[0,1,0],
];

function drawMatrix(matrix, offset) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
context.fillStyle =’red’;
context.fillRect(x, y, 1, 1);
}
});
});
}

drawMatrix(matrix);

Fyleur says:

i have a probleme at 3 min xD when i go google with the link copy paste of index.html on google i have a white page i don’t know why can someone help me plz ?

Ung Yean says:

you impart lots of js knowledge in this video. Thank you. Please make more js game

Keyvel Alston says:

its not working for me tbh. I’m working in brackets that might be the issue

Insane Techniques says:

love it how you pronounce arena LUL

KPSHARMA says:

you are great, slow calm, so simply you developed a playable game !!!

Neophitos Theodorou says:

Great video!!! Just a short question. Is there any reason not to write the update function like this?

let dropInterval = 1000;

let lastTime = 0;
function update(time = 0) {
const deltaTime = time – lastTime;
if (deltaTime > dropInterval) {
player.pos.y++;
lastTime = time;
}
draw();
requestAnimationFrame(update);
}

Mateusz Uss says:

In 39.07 how does he replace ‘1’ in matrix with ‘2’ ‘3’ and so on? What keyboard shortcut he used?

Kino -Imsure1200q says:

+Meth Meth Method Was that os you were using a Windows 10? It looks like you’re using a Mac OS ide so im curious..

BTW did you notice the minor mistake you did in the player function when you added it?

const player = {
pos: {x: 5, y: 5},
matrix: matrix, <— The Comma }

Malkeum Lee says:

It keep appearing some error while i follow this video. even it had some error that i coped js file all of them and pasted…. what’s the problem?

Юрий Таловиров says:

Hello, why are you use “if else if else” constructions instance “switch case”? Thank you.

ActionSpark says:

8:00

TheFrenchPlays Hd says:

addict of cofee driven developement too?

Imagine Addis says:

Thanks so much genius. It was awesome practice of ES6 and functional programming for me to follow along with you. Thanks again :)

Yes I know I'm the best says:

What is he using to write the code?

Kamikat says:

I see the word meth three times in your name

Kino -Imsure1200q says:

I felt weird when you were talking about cool stuff and you just said “ah, lets just start ._.”

no body says:

https://youtu.be/H2aW5V46khA?t=40m35s
how change colors in code like this? it’s addon, or be pre copied?

Pablo Rodriguez says:

hey guys, I finished the game and I’m looking to style it, does anyone have a clue on how I could substitute the pieces with images of blocks? so I can customize the pieces a bit?

kennyPAGC says:

36:34 wait what?? how do you floor like that?

matthew rice says:

How on earth did you learn to do all of this?

kennyPAGC says:

this is an awesome channel, vanilla JS ES6, you don’t see that often!! it seems like the author is not publishing content anymore though :(

Chris Donuts says:

PLEASE move pomle.github.io to pomhub.io

Leon Powell says:

this looks really great and i was looking forward to it. I have no idea what it is i am doing wrong the addevent listener works a few times and then just stops. Nothing i do after that makes it work. Too bad i was looking forward to this. Cheers man

Omer Mindivanli says:

Great !! :)

Petter Bergmar says:

Sjukt bra! Thanks a lot for this!

Brønekk Brønkkonsen says:

Hi Guys. Did you have any issues with the const = matrix? I keep having this error: Cannot read property ‘forEach’ of undefined
at drawMatrix
even though everyting lloks fine.

chettout yacine says:

thanks a lot for the tutorial

Johannes W says:

lit

Ethan Treiber says:

why isn’t it working, It wouldnt make the block bigger here is the code
const canvas = document.getElementById(‘tetris’);
const context = canvas.getContext(‘2d’);

context.scale(20, 20);

context.fillStyle = ‘#000’;
context.fillRect(0, 0, canvas.width, canvas.height);

const matrix = [
[0, 0, 0],
[1, 1, 1],
[0, 1, 0],
];

matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
context.fillStyle = ‘red’;
context.fillRect(x, y, 1, 1);
}
});
});

Paweł Rafałko says:

I think I would do that on my own but in 3000 lines rather than 300 😀

Hendo4short says:

Do you mind if I copy this code, it’s for a class.

SpiderCraft53 Redstone & More says:

I’ve checked EVERYTHING and I have absolutely everything right, but when playing it’ll randomly stop and in console it says row.forEach is not a function. I’ve tried absolutely everything but it just wont work. (It says the problem is in the drawMatrix function, but I have it EXACTLY the same as yours, and I have all the latest versions of java and node.js installed)

Mn says:

Will this help me to become a better Front-end Developer?

Dawie Van Emmenes says:

Games must be the most challenging programs to write.
This gave me a headache.

Daniel Williams says:

I really enjoyed this video. There aren’t many functional programming builds like this on YouTube. Very well produced and edited too! Keep it up

Bigtombowski says:

I know you are from sweden but u sound Jamaican.

Sejoo says:

I thought im familiar with javascript

Kino -Imsure1200q says:

pomle.github.io/keycode

Ernest G. Wilson II says:

I hit like and I subscribed and I hope you continue making more videos!

Bimal Grg says:

It would be better if we have basic knowledge of html game before starting this tutorial.. check this out https://www.w3schools.com/graphics/game_intro.asp

Hendrik Aarma says:

what operating system and computer you using

Дендрай says:

Hello, I’m Russian you are a cool dude I watch every movie you have and they are cool

Rio Vesay says:

would you be interested in coding a project with me or helping/teaching me?

Write a comment

*

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.


Do you like our videos?
Do you want to see more like that?

Please click below to support us on Facebook!

Send this to a friend

▷ Other ReviewsVehicles▷ Show Cars▷ Motorbikes▷ Scooters▷ Bicycles▷ Rims & Tires▷ Luxury BoatsFashion▷ Sunglasses▷ Luxury Watches▷ Luxury Purses▷ Jeans Wear▷ High Heels▷ Kinis Swimwear▷ Perfumes▷ Jewellery▷ Cosmetics▷ Shaving Helpers▷ Fashion HatsFooding▷ Chef Club▷ Fooding Helpers▷ Coktails & LiquorsSports▷ Sport Shoes▷ Fitness & Detox▷ Golf Gear▷ Racquets▷ Hiking & Trek Gear▷ Diving Equipment▷ Ski Gear▷ Snowboards▷ Surf Boards▷ Rollers & SkatesEntertainment▷ DIY Guides▷ Zik Instruments▷ Published Books▷ Music Albums▷ Cine Movies▷ Trading Helpers▷ Make Money▷ Fishing Equipment▷ Paintball Supplies▷ Trading Card Games▷ Telescopes▷ Knives▷ VapesHigh Tech▷ Flat Screens▷ Tech Devices▷ Camera Lenses▷ Audio HiFi▷ Printers▷ USB Devices▷ PC Hardware▷ Network Gear▷ Cloud Servers▷ Software Helpers▷ Programmer Helpers▷ Mobile Apps▷ Hearing AidsHome▷ Home Furniture▷ Home Appliances▷ Tools Workshop▷ Beddings▷ Floor Layings▷ Barbecues▷ Aquarium Gear▷ Safe Boxes▷ Office Supplies▷ Security Locks▷ Cleaning ProductsKids▷ Baby Strollers▷ Child Car Seats▷ Remote ControlledTravel▷ Luggages & Bags▷ Airlines Seats▷ Hotel Rooms▷ Fun Trips▷ Cruise Ships▷ Mexico Tours