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

КОМЕНТАРІ • 101

  • @DandaMan2022
    @DandaMan2022 13 днів тому +1

    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.

  • @shravanpanchal8920
    @shravanpanchal8920 Рік тому +5

    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.
    💯

  • @gianmarcoferraro2544
    @gianmarcoferraro2544 5 місяців тому

    A very clear and complete tutorial. Thank you

  • @thegrayfox666
    @thegrayfox666 5 місяців тому +1

    I really enjoyed working on this project alonside. Thank you! :D

  • @Flanx-ul5hj
    @Flanx-ul5hj 2 місяці тому

    Finally understood how object oriented programming works, thanks a lot!!

  • @anke4347
    @anke4347 7 місяців тому

    This is a fantastic tutorial. Thank you!

  • @paulthomas1052
    @paulthomas1052 8 місяців тому

    Great demo and fantastic code for this Tetris game. Thanks so much !

  • @programmingwithnick
    @programmingwithnick  Рік тому +21

    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.

    • @jeffersonfuckner3617
      @jeffersonfuckner3617 10 місяців тому +1

      I was stuck in the error but, then I decided to check on comments and here is the answer. kkk Tks

    • @jeffersonfuckner3617
      @jeffersonfuckner3617 10 місяців тому +1

      I'm now at the automatic droping part.

    • @armandoherrera1717
      @armandoherrera1717 9 місяців тому

      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 🤣

    • @mrgary4u819
      @mrgary4u819 Місяць тому

      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.

  • @ericleboullenger9348
    @ericleboullenger9348 6 місяців тому +2

    By far the best tutorial on OOP in Python, Pygame. Well done Nick, and thank you very much for all your work!

  • @manuelgarciagarcia2501
    @manuelgarciagarcia2501 Рік тому

    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.

  • @antoniobordamonte3952
    @antoniobordamonte3952 Місяць тому

    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!

  • @antoinesadarnac5652
    @antoinesadarnac5652 11 місяців тому +2

    Thank you, I learnt a lot and succeeded in making snake by myself after this video without any help

  • @andgelerieee
    @andgelerieee 10 місяців тому +6

    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!

  • @claireoneill3955
    @claireoneill3955 5 місяців тому

    This tutorial was a really good starting point for my Tetris project. Thanks so much for the help!

  • @SpirosLymperopoulos
    @SpirosLymperopoulos Рік тому

    Great video,we learn so much from this channel!

  • @manoloexplaintome6348
    @manoloexplaintome6348 2 місяці тому

    Thank you por making this amazing video. I've enjoyed it a lot.

  • @Tims_Projects
    @Tims_Projects Рік тому

    Great work Nick, it's quite detailed, I will have to watch it in small intervals to take it all in.👍😁👍

    • @programmingwithnick
      @programmingwithnick  Рік тому

      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.

  • @oum_iyad
    @oum_iyad 4 місяці тому

    Nice, love Tetris

  • @freesoftwares6042
    @freesoftwares6042 2 місяці тому

    okay , i subbed and liked , i like this side of youtube

  • @alejo_skrt772
    @alejo_skrt772 2 місяці тому

    Thank you!!!!

  • @commandprompt7171
    @commandprompt7171 10 місяців тому +1

    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.

  • @practicalbong1497
    @practicalbong1497 Рік тому

    absolutely amazing

  • @AnonymousPerson-wf8lp
    @AnonymousPerson-wf8lp День тому +1

    amazing thank you sir 😘😘😘🥰😇

  • @ItsMeKippun
    @ItsMeKippun 7 місяців тому

    nice work dude!, now i can finish my college final tasks :)))

  • @stocothedude
    @stocothedude Рік тому +1

    Thank you very much for your effort 🎉

  • @Wayko6217
    @Wayko6217 6 місяців тому +1

    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

  • @HangThuy-mw2zh
    @HangThuy-mw2zh 21 день тому

    WOWWY BOWWY WOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOW.
    Your tutorial so perfecto.

  • @DaCom3AK
    @DaCom3AK 7 місяців тому +15

    watch with 1.25x speed, thank me later

  • @trevorgardner9466
    @trevorgardner9466 Рік тому

    Great video, I really learned a lot! But I was wondering how I would implement a block holding feature?

  • @daisyb1469
    @daisyb1469 7 місяців тому

    In chapter "Rotate the blocks" , method rotate(self), second line - I think it should be: if self.rotation_state == len(self.cells) - 1.

  • @daisyb1469
    @daisyb1469 7 місяців тому +1

    I don't know why my blocks keep going (partially) out of the grid whenever I move them left or right.

  • @quinnfly1708
    @quinnfly1708 2 місяці тому

    you are the reason i passed my OPP assessment in com sci

  • @nathanapiag511
    @nathanapiag511 8 місяців тому

    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

  • @robin3883
    @robin3883 6 місяців тому +1

    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

  • @RAKSHITHNPOOJARY
    @RAKSHITHNPOOJARY 7 місяців тому +1

    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

  • @geencaiilemalaguena2474
    @geencaiilemalaguena2474 9 місяців тому

    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?

  • @SaraMohamed-qz4pk
    @SaraMohamed-qz4pk 6 місяців тому

    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

  • @jinnij2328
    @jinnij2328 7 місяців тому

    Somehow there is an error for the sound code although I created a file called Sounds with the music you implemented in.

  • @zeellynwokenta
    @zeellynwokenta 2 місяці тому

    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

  • @IronDragon2940
    @IronDragon2940 10 місяців тому +1

    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]

  • @netaduvinsky2833
    @netaduvinsky2833 Місяць тому

    Hi nick I have a problem whit the creating blocks
    Can you help me?

  • @gauravdhamsekar3802
    @gauravdhamsekar3802 Рік тому

    Array are used?

  • @wasgehtdaab
    @wasgehtdaab 5 місяців тому

    😎Can you use images instead of colors? I partially managed it myself, but it doesn't work with current_block and next_block.

  • @itsmanyashukla2546
    @itsmanyashukla2546 8 місяців тому

    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!!!!

  • @ravilapieri
    @ravilapieri 2 місяці тому

    Amazing job!! Thank you very much. Could I use this code with my students, with the credit to your work and channel?

    • @programmingwithnick
      @programmingwithnick  2 місяці тому

      Yes, of course. This is why I make these videos. To help as many people as possible to learn programming.

    • @ravilapieri
      @ravilapieri 2 місяці тому

      ​@@programmingwithnick Thank you!!! Your teaching is fantastic and the code is very organized..
      👏👏

  • @SaraMohamed-qz4pk
    @SaraMohamed-qz4pk 6 місяців тому

    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

    • @Bonana991
      @Bonana991 4 місяці тому

      Make sure you have your lines of code lined up

  • @fvelez78
    @fvelez78 9 місяців тому

    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?

    • @fvelez78
      @fvelez78 9 місяців тому

      solved...

  • @isaacleydon7301
    @isaacleydon7301 10 місяців тому

    Mine has a problem where after 7 blocks have landed another block doesn't spawn. Any idea what might be wrong?

    • @programmingwithnick
      @programmingwithnick  10 місяців тому +1

      Maybe you have forgotten to recreate the blocks list. Give it a check.

  • @EmirKayaloglu
    @EmirKayaloglu 9 місяців тому +1

    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.

    • @GrooveProducciones
      @GrooveProducciones 3 місяці тому

      estas en el directorio incorrecto, ubicate en la carpeta en donde se encuentre el archio correspondiente

  • @nymaztek0315
    @nymaztek0315 5 місяців тому

    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

  • @edm8535
    @edm8535 Рік тому

    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!

    • @programmingwithnick
      @programmingwithnick  Рік тому +2

      I fix this problem in the video in the Checking for Collisons chapter. Are you sure you finished watching it?

    • @edm8535
      @edm8535 Рік тому +1

      @@programmingwithnick Hi, you are correct. Seems I ran into the problem and stopped paying attention to you explaining the fix. Thanks for the help.

  • @jimmyting1103
    @jimmyting1103 2 місяці тому

    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

  • @ks111541
    @ks111541 Рік тому +4

    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!

    • @programmingwithnick
      @programmingwithnick  Рік тому +1

      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!

    • @programmingwithnick
      @programmingwithnick  Рік тому +2

      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.

    • @olssonolov
      @olssonolov 11 місяців тому +3

      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

    • @hypebeaver4150
      @hypebeaver4150 7 місяців тому

      nice@@olssonolov

    • @David-fq5un
      @David-fq5un 3 місяці тому

      Much better, go from 3 lines to ONLY 1 line@@olssonolov

  • @wasgehtdaab
    @wasgehtdaab 5 місяців тому

    😎

  • @rayhanfathurrizki4154
    @rayhanfathurrizki4154 Рік тому +1

    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?

    • @programmingwithnick
      @programmingwithnick  Рік тому +1

      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.

  • @Abubakr2007
    @Abubakr2007 Рік тому

    What software did you use to code?

  • @kookie.dough09
    @kookie.dough09 2 місяці тому

    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.

    • @kookie.dough09
      @kookie.dough09 2 місяці тому

      (btw I am using VScode which may differ, thank you.)

  • @GamingGOATS-ly4kf
    @GamingGOATS-ly4kf 10 місяців тому

    when I try to import grid from Grid it gives me import error

  • @user-ok5bu7dh6x
    @user-ok5bu7dh6x 6 місяців тому

    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

  • @EmirKayaloglu
    @EmirKayaloglu 9 місяців тому

    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

  • @amrnagy248
    @amrnagy248 6 місяців тому

    he tell me the attribute print_grid isnt exist

  • @Randomfacts7b
    @Randomfacts7b 8 місяців тому

    Please share the Source code of this game

  • @kapykta842
    @kapykta842 4 місяці тому

    very hard tutorial

  • @Rafael-oq9vu
    @Rafael-oq9vu 10 місяців тому +1

    here i am learning python after making a tetris game in c

    • @b.c.34
      @b.c.34 9 місяців тому

      Nice.....i would like to know how you handled the rotation of the shapes....i want to design same using C++....
      Thanks in advance

  • @andrewanimatesstuff
    @andrewanimatesstuff 6 місяців тому

    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?

    • @gasoline27
      @gasoline27 3 місяці тому

      Have you solved the problem yet?