Creating Tetris in Python with pygame - Beginner Tutorial (OOP)
Вставка
- Опубліковано 4 лип 2024
- 🎮💻 Build the classic game Tetris in less than two hours with Python and Pygame! 🔥 Follow along as we code and create colorful shapes that will challenge your skills. 🚀 With step-by-step instructions and engaging graphics, this tutorial is perfect for beginners and experienced coders alike. 🤓 Join me on this fun and exciting journey of game development! 💯
Become a member to this UA-cam channel to enjoy perks:
/ @programmingwithnick
👨💻 Code: github.com/educ8s/Python-Tetr...
🚀Join the Channel to help me create even better videos: / @programmingwithnick
🎶 More Music by Spyros: assetstore.unity.com/packages...
Previous Tutorials (Watch in the following order)
📘 Python for Absolute Beginners Course: • Python for Absolute Be...
💡 Pygame 101: • Get Started in pygame ...
💥 Pygame Collisions: • Pygame Beginner Tutori...
🏓 Pong Tutorial: • Pong Game Tutorial usi...
🐍 Snake Tutorial: • Snake Game in Python T...
🦠 Game of Life Tutorial: • Conway's Game of Life ...
👾 Space Invaders: • Python Space Invaders ...
#pygame #python #tetrisgame #gamedev #tutorial
00:00 Intro to Tetris tutorial
01:06 Why build Tetris?
04:30 Install pygame-ce
06:14 Setup the Game Loop
16:09 Creating the Grid
32:15 Create the Blocks
51:51 Move the Blocks
1:10:43 Rotate the Blocks
1:14:31 Checking for collisions
1:24:44 Check for completed rows
1:32:03 Game Over
1:35:48 Create the User Interface
1:45:54 Add Score
1:51:25 Add Next Block
1:54:19 Adding Sound
This was really easy to follow and fun to program! One thing I did after is adding a storage function like in modern Tetris games. You have a window on the right for which block you are storing (you can store e.g by pressing shift) and can replace your current block with that block. You can't replace a current block that you have stored though.
Nick, your tutorials are quite unique and quite detailed, I love your videos man, I think it is much better than other similar projects on youtube, and I have a request : could you please make more of such python game or other python projects, it would be very fun to learn from you.
💯
A very clear and complete tutorial. Thank you
I really enjoyed working on this project alonside. Thank you! :D
Finally understood how object oriented programming works, thanks a lot!!
This is a fantastic tutorial. Thank you!
Great demo and fantastic code for this Tetris game. Thanks so much !
Hello guys! I hope you enjoyed the video! There is an error in the code as it appears in the video. In the block.py file the undo_rotation method should be like this:
def undo_rotation(self):
self.rotation_state -= 1
if self.rotation_state == -1:
self.rotation_state = len(self.cells) - 1
The error is fixed in the github repository. Sorry for this.
I was stuck in the error but, then I decided to check on comments and here is the answer. kkk Tks
I'm now at the automatic droping part.
I was stuck in this error lol. I thought it had something to do with me writing it in JavaScript lol. I was panicking. Then I asked chat GPT and it solved it for me, but here was the answer all the time 🤣
Thanks for the fix! I suggest you pin this comment so it's easier to find. Loved the explanation and the attention to every detail.
By far the best tutorial on OOP in Python, Pygame. Well done Nick, and thank you very much for all your work!
Wow, thanks!
Excellent tutorial, these videos will serve as a bible for me to consult how to make many types of games. Thank you very much for sharing all this material.
this was insanely helpful and helped me grasp a lot of concepts in python. Along with that, it also taught me how to approach different problems and how to implement them inside of python. Thank you so much!
Thank you, I learnt a lot and succeeded in making snake by myself after this video without any help
I love how you go into detail with this video about the code, I just started python yesterday and I'm doing well because of you! Thank you!
This tutorial was a really good starting point for my Tetris project. Thanks so much for the help!
You're very welcome!
Great video,we learn so much from this channel!
Thank you por making this amazing video. I've enjoyed it a lot.
Great work Nick, it's quite detailed, I will have to watch it in small intervals to take it all in.👍😁👍
Thank you Tim. Yes, it is a quite long video but it will definately help you understand the game mechanics of this ingenius game and a few more advanced programming practices.
Nice, love Tetris
okay , i subbed and liked , i like this side of youtube
Thank you!!!!
thank you so much for explaining the game logic with readable code, I was trying to code tetris in both C++ and python by myself, and I was struggling at the move rows down logic and clearing the rows logic, I felt like I was going insane, and most of the solutions on google searches are mostly magic values and unreadable code, witch it does not help at all, but your solution by far is the cleanest tetris code I've seen, it might take more code lines, but I do appreciate to be able to read all those class methods.
Thank you very much for your feedback!
absolutely amazing
Thank you!
amazing thank you sir 😘😘😘🥰😇
nice work dude!, now i can finish my college final tasks :)))
Glad I could help!
Thank you very much for your effort 🎉
You are welcome. I hope you will learn a few things from it!
Added a function to update the speed after reaching 2000 points and also level. Still have to work on the logic behind it because if the value modules is not equal 0 it doesn't update but if I search other it increases automatically. I moved the GAME_UPDATE to the game.py and added the code below to the update_score section
if self.score % 2000 == 0:
self.newSpeed = Game.update_speed(self.newSpeed)
self.level += 1
if self.newSpeed > 50:
pygame.time.set_timer(self.GAME_UPDATE, self.newSpeed)
else:
self.newSpeed = 50
def update_speed(current_speed):
current_speed -= 10
return current_speed
WOWWY BOWWY WOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOW.
Your tutorial so perfecto.
watch with 1.25x speed, thank me later
I am watching in 1.5x 😂
Great video, I really learned a lot! But I was wondering how I would implement a block holding feature?
In chapter "Rotate the blocks" , method rotate(self), second line - I think it should be: if self.rotation_state == len(self.cells) - 1.
I don't know why my blocks keep going (partially) out of the grid whenever I move them left or right.
you are the reason i passed my OPP assessment in com sci
I am very happy to hear that! Well done!
@@programmingwithnick thank you!!
Hello Nick! When I tried running the code by the end of step 5 (moving the blocks) if press any of the 3 keys (move_left, move_right, move down) the program ends with an error saying that the " object 'Game' does not have an attribute "move_left" for example if i press the left key. I have already defined it in the game class same as your code. I don't know what to do I can't progress to step 6 as it cannot properly run and I cannot move the blocks. Thank you
i have found a new solution for undo method. for example, when rotating at the edge, it should rotate and move the block inside the screen.
my code is:
def rotate_block(self):
self.current_block.rotate_block()
while self.block_in_screen() == False:
self.current_block.move(0,1)
seems unnecessary but hope it helps
Hi Great video, But i facing an error When move the blocks to left the boundary check is done correctly but when try to move it to the right it goes out of bound .Any reson why it might have occured
heeeeeeeelp someone help me writing the codes in vs code and in line 13 it says "sys" not defined Pylance, is it normal?what should i do?
23:01 the color of the back ground which is dark blue doesn’t appear
and also the list of lists of zeros
i wrot the same code but nothing appears
Somehow there is an error for the sound code although I created a file called Sounds with the music you implemented in.
Please could someone show me how to do the Grid file import, I use pycharm, so the ctrl n and ctrl s thing didn't work. Thanks
I keep running into this error
This is for the grid.py
return [dark_grey, green, red, orange, yellow, purple, cyan, blue]
^
IndentationError: unindent does not match any outer indentation level
[Finished in 106ms]
Hi nick I have a problem whit the creating blocks
Can you help me?
Array are used?
😎Can you use images instead of colors? I partially managed it myself, but it doesn't work with current_block and next_block.
continuosly showing this error to me ->
in grid.py file under the def draw method
pygame.draw.rect(screen , self.colors[cell_value] , cell_value)
TypeError: rect argument is invalid
also game screen is disappearing immediately but before making grid.py it was staying on the window unless i click the red cross...
can you help me out real quick please!!!!
Amazing job!! Thank you very much. Could I use this code with my students, with the credit to your work and channel?
Yes, of course. This is why I make these videos. To help as many people as possible to learn programming.
@@programmingwithnick Thank you!!! Your teaching is fantastic and the code is very organized..
👏👏
Nick I wrote the same codes you wrote but nothing appears on the screen if the game ,even the screan cames quickly and dissappears ,what should i do
Make sure you have your lines of code lined up
Hi, great tutorial... I´m doing this... however I´ve a problem... when I move the block to right, this one is left out by a rectangle. I print positions into the for of the get_cell_positions method and for LBlock in the initil position after moving evrything to the right the position are: (0,16)(1,16)(1,17)(1,18)...plopppp... Why the column are greater than 10?
solved...
Mine has a problem where after 7 blocks have landed another block doesn't spawn. Any idea what might be wrong?
Maybe you have forgotten to recreate the blocks list. Give it a check.
FileNotFoundError: No file 'Sounds/rotate.ogg' found in working directory 'C:\Users\Packard bell\Desktop\Python Örneklerim'.
Unfortunately, I received another error and my game is not working.
estas en el directorio incorrecto, ubicate en la carpeta en donde se encuentre el archio correspondiente
I am a newb to coding. How do I add a hard drop if the space bar is hit in this code? If anyone is able to help I would appreciate it
Hi. Just finnished the "Checking for Collisons" part of your video. Everything went great until I realized that if the user moves a piece into another piece from either left or right, it intertwines and locks in place. Do you have a fix for this? I'll continue on in the video in hope that maybe you also get this error. If not, hopefully you can get back to me. Thanks in advance!
I fix this problem in the video in the Checking for Collisons chapter. Are you sure you finished watching it?
@@programmingwithnick Hi, you are correct. Seems I ran into the problem and stopped paying attention to you explaining the fix. Thanks for the help.
Hello Nick big fan i am having some trouble with 29:33 with line 22 givingme an error which says -> AttributeError: 'Grid' object has no attribute 'draw' ive looked over atleast 100 times and all of my code is exact as it is on screen at this current time in the video i even completely rewrote all of main.py and grid.py any reason why this is?
i am using sublime as well
Hi, I found an error. If a block is in it's last rotation state and you try to rotate it when it's not possible then first the rotate function will set the rotation_state to 0 and next the undo_rotation function will decrease the rotation_state by 1, so the index of the dictionary will be -1 which will crash the game. The line in undo_rotation "self.rotation_state -= 1" should be after the if statement in else statement , not before. Besides that, the video is great! Much appreciated!
Good catch! You are absolutely right! I totaly missed it. I played the game for hours and never crashed. I looked over this piece of code of hours and never occured to me that the value can become negative. Thanks for sharing!
Now, that I recall me, programming this piece of code, I wanted the method to look like this:
def undo_rotation(self):
self.rotation_state -= 1
if self.rotation_state == -1:
self.rotation_state = len(self.cells) - 1
which works. I messed up the if statement.
To avoid tis you could also use the mod4-methode:
def rotate(self):
self.rotation_state = (self.rotation_state+1)%4
def undo_rotate(self):
self.rotation_state = (self.rotation_state-1)%4
nice@@olssonolov
Much better, go from 3 lines to ONLY 1 line@@olssonolov
😎
sir, i have an error, when i tried to run, this appeared
File "c:\Users\asus\Desktop\mencoba game2\main.py", line 29, in
game.draw(screen)
File "c:\Users\asus\Desktop\mencoba game2\game.py", line 43, in draw
self.current_block.draw(screen)
File "c:\Users\asus\Desktop\mencoba game2\block.py", line 29, in draw
for tile in tiles:
TypeError: 'method' object is not iterable
do u have any suggestion?
IN the block.py file you have an error. Check if you have place some () where it not needed. Check your code again very carefully.
What software did you use to code?
Sublime text
Hello, thank you for this detailed tutorial for beginners. I just want to point out one thing, I have an error in 56:45:
AttributeError: 'Tblock' object has no attribute 'column_offset'
Can anyone please provide me with a solution because I have been stuck on this error for the past 15 minutes.
Thank you dearly.
(btw I am using VScode which may differ, thank you.)
when I try to import grid from Grid it gives me import error
check for spelling mistakes
Traceback (most recent call last):
File "/Users/mac/PycharmProjects/gamee/r2.py", line 19, in
blockk = LBlock()
^^^^^^^^
File "/Users/mac/PycharmProjects/gamee/blocks.py", line 7, in __init__
super().__init__(1)
TypeError: Block.__init__() takes 1 positional argument but 2 were given
I keep getting this error and i dont know how to fix it even though i wrote every single line as the video
if self.grid[row][column] == 0:
~~~~~~~~~^^^^^
IndexError: list index out of range
First of all, it's a great example, I'm almost at the end of the game, but I can't get rid of this mistake, please help
he tell me the attribute print_grid isnt exist
Please share the Source code of this game
Please check the video description.
very hard tutorial
here i am learning python after making a tetris game in c
Nice.....i would like to know how you handled the rotation of the shapes....i want to design same using C++....
Thanks in advance
by the time i got to 49:37 i got an error at blocks.py
Block.__init__() got an unexpected keyword argument 'id'
heres the code:
from block import Block
from position import Position
class LBlock(Block):
def __init__(self):
super().__init__(id = 1)
self.cells = {
0: [Position(0, 2), Position(1, 0), Position(1, 1), Position(1, 2)],
1: [Position(0, 1), Position(1, 1), Position(2, 1), Position(2, 2)],
2: [Position(1, 0), Position(1, 1), Position(1, 2), Position(2, 0)],
3: [Position(0, 0), Position(0, 1), Position(1, 1), Position(2, 1)]
}
can anyone help?
Have you solved the problem yet?