Professional Code Refactor! (Cleaning Python Code & Rewriting it to use Classes)

Sdílet
Vložit
  • čas přidán 12. 06. 2024
  • In this video we take the code from my “How to Program a Game (in Python)” tutorial and refactor it to be of a more professional quality. To do this we abstract out similar parts of the code into their own classes & files. Once the new code is written, we go through some examples of how we can extend its functionality in fun ways. We make a couple more difficult levels of the game which is made very easy by the new code architecture. The final product is a lot more similar to code you would write as a full time software developer at a company like Google, Facebook, etc…
    As always I left a video timeline in the comments! If you enjoy this video please consider giving it a like & subscribe for future content :). If you have any questions let me know in the comments!
    Follow the homies!
    / shaneboyer_
    / _neos
    Source code for Game (original & refactored):
    github.com/KeithGalli/Basic-P...
    Link to original How to Program a Game (in Python) Tutorial:
    • How to Program a Game!...
    Link to video on Classes & Object Oriented Programming:
    • Everything you need to...
    Additional information on Getters & Setters:
    • Python OOP Tutorial 6:...
    Some great resources if you want to write better/cleaner code! (affiliate links)
    www.python.org/dev/peps/pep-0...
    amzn.to/2U90SWk
    Join the Python Army to get access to perks!
    CZcams - / @keithgalli
    Patreon - / keithgalli
    ---------------------
    Follow me on social media!
    Instagram | / keithgalli
    Twitter | / keithgalli
    ---------------------
    Video Timeline! (& some additional resources)
    0:00 Video overview & code setup
    3:04 Creating a Player Class
    10:43 Creating subclasses for our Enemy & HumanPlayer
    11:26 Creating a Color class
    14:35 Creating a screen class or all our game visuals
    27:00 Creating a game class for all our game logic
    32:54 Information on Getters & Setters in Python
    38:09 Bringing it all together in our main.py file!
    43:36 Testing our code & Debugging issues
    47:20 if name == "__main__" information
    48:26 Creating more difficult game levels using our new class structure!
    54:00 Fixing the "cheat" where you can go off the screen
    55:44 Loading in custom images as the enemy blocks
    *I use affiliate links on the products that I recommend. I may earn a purchase commission or a referral bonus from the usage of these links.

Komentáře • 80

  • @KeithGalli
    @KeithGalli  Před 4 lety +12

    Video Timeline! (& some additional resources)
    0:24 - Video overview & code setup
    3:04 - Creating a Player Class
    10:43 - Creating subclasses for our Enemy & HumanPlayer
    11:26 - Creating a Color class
    14:35 - Creating a screen class or all our game visuals
    27:00 - Creating a game class for all our game logic
    32:54 - Information on Getters & Setters in Python
    38:09 - Bringing it all together in our main.py file!
    43:36 - Testing our code & Debugging issues
    47:20 - if __name__ == "__main__" information
    48:26 - Creating more difficult game levels using our new class structure!
    54:00 - Fixing the "cheat" where you can go off the screen
    55:44 - Loading in custom images as the enemy blocks
    Additional resources to write good clean Python code!
    www.python.org/dev/peps/pep-0008/
    amzn.to/2U90SWk
    Hope you guys enjoyed this video! :)
    Please like & subscribe if you did!!

    • @kulpreetsingh9064
      @kulpreetsingh9064 Před 4 lety +1

      Hey Keith, thanks for all the content, i just wanted to know whether you'll be doing more of solving real life data science projects videos anymore?

    • @KeithGalli
      @KeithGalli  Před 4 lety +1

      @@kulpreetsingh9064 Yeah I plan to! I'm going to make a neural networks tutorial next, then I'll do another real life data science project :). I'll probably release it mid-april.

  • @skulldozer1270
    @skulldozer1270 Před 3 lety +18

    I feel that most coding channels never get the respect they are due, shunned by the algorithm, for more colorful, braindead, and clickbaity videos. I hope that people realize your skill and your videos. keep up the good work!

  • @theteacher010
    @theteacher010 Před 4 lety +8

    This is such an awesome concept for teaching Python to people a little past the beginner stage! I'm sure tonnes of us have not-too-great code written out there from our newbie days, but we're not yet at the level where we can clean it efficiently just yet.
    I've barely ever used classes in Python just because I've never had the need to, and as a result I don't find myself thinking about how to use them at all. A video like this was EXACTLY what I needed to start to understand how to even begin thinking about using classes correctly!

    • @KeithGalli
      @KeithGalli  Před 4 lety +2

      Aww this comment makes me super happy! Exactly the type of audience I thought would find this video useful :). Thank you for the kind words!

  • @wiz8058
    @wiz8058 Před 4 lety +1

    My Man has done it again. This channel aint popular but in future the upcoming programmers will be checking in here for more releases and more information. Thank you Keith Galli you are on the right part of the journey.

  • @CrapE_DM
    @CrapE_DM Před 2 lety +3

    Collision detection could be simplified quite a bit. Instead of nested ifs, you simply put an "and" between the two conditions. Once you have that, instead of
    if CONDITION:
    return True
    return False
    You can do "return CONDITION"
    Also "x < y and x > z" can be simplified to "y > x > z" in Python

    • @petretrusca2
      @petretrusca2 Před 2 lety

      I was thinking also about the return CONDITION, but than I thought that "explicit is better than implicit" from Zen of Python. What do you think about that ?

  • @abdullahraihanbhuiyan2346

    The way you used super is truly amazing. Very clean and efficient code.

  • @abdallahwallyallah5490
    @abdallahwallyallah5490 Před 3 lety +1

    Brilliant Explanation and shows the importance of clean code from the beginning :) Keep going mate

  • @jenn6997
    @jenn6997 Před 4 lety +5

    Haven't watched the whole thing yet, but the intro is so funny hahaha!!! I'll have another interesting thing to watch for this upcoming week!:)

  • @kinwong6383
    @kinwong6383 Před 3 lety +2

    I did not major in CS, so this is really great for me to learn how to write good code in a fun way!

  • @jonpounds1922
    @jonpounds1922 Před 4 lety +5

    This is the channel everyone should watch

    • @dr.girthmuffin8584
      @dr.girthmuffin8584 Před 4 lety

      Jon pounds me in ass amirite?!? lol jk but yeah definitely a good channel

  • @yeshwanthraja2453
    @yeshwanthraja2453 Před 4 lety +1

    Very helpful, great work. Thanks

  • @gmorf33
    @gmorf33 Před 3 lety +1

    This was a really useful video. Really helps drive home the point of classes and oop

  • @lorraineli6353
    @lorraineli6353 Před 4 lety +5

    Finish learning 6 tutorials in your channel, LOVE IT! CAN'T STOP! from zero knowledge about python to be able to code my assignment that requires data analysis alone! Thank you so much! By the way, do you have a tutorial about statistics analyzing using python? Like drawing a normal distribution pdf, etc.

    • @KeithGalli
      @KeithGalli  Před 4 lety +2

      Check out my "generating mock data", I reference several statistics concepts there. Glad you have been enjoying the videos!! 😊

  • @anoubhav
    @anoubhav Před 4 lety +12

    Did you do the refactoring on the fly by just looking at your previous code? I was able to understand everything as the video went on ( thanks to your awesome explanation ). But I can't imagine me coming up with the big picture of 5 separate files along with the functions in each class while starting such a task from scratch.

    • @discobacon5160
      @discobacon5160 Před 2 lety

      Of course he prepared before hand and had code already written

  • @javanprycejavan
    @javanprycejavan Před 4 lety +2

    The lesson was awesome!

  • @laurentzerah9906
    @laurentzerah9906 Před 4 lety +2

    Great content 👍 Unittests tutorial would make a great addition as a future video in this series.

    • @KeithGalli
      @KeithGalli  Před 4 lety

      Glad you liked the video and thanks for the suggestion! :)

  • @jpaldama9963
    @jpaldama9963 Před 4 lety +1

    Awesome video. Please do a unit testing video. That would be awesome. Or decorators

  • @ErdosainNueve
    @ErdosainNueve Před 3 lety

    Muchas gracias. Ver este tipo de videos donde se ve el trabajo me es muy útil.

  • @kitsurubami
    @kitsurubami Před rokem

    3 minutes in and I can already tell this is a good video with quality advice. Way too many poor quality videos from novice programmers out there.

  • @brunomerola
    @brunomerola Před 8 měsíci

    Sou fã da sua didática - e dessa metadidatica, sobre a importancia do aprendizado correto

  • @lusk-lyngesr.5764
    @lusk-lyngesr.5764 Před 4 lety

    thanks a lot for a good intro to code refactoring in Python

  • @PragmaticReviews
    @PragmaticReviews Před 4 lety +1

    Great content! Thanks!

  • @itzikgutzcha4779
    @itzikgutzcha4779 Před 2 lety

    The video was really nice and informative, but when I got to the Keith BOSS I had to like and comment

  • @moussamoise9124
    @moussamoise9124 Před 4 lety +1

    thank you Keith for this wonderful method of teaching (sorry not teaching but educating)

  • @sainath66666
    @sainath66666 Před 4 lety +1

    Please Do More of these awesome python videos !!!

  • @bisratgetachew8373
    @bisratgetachew8373 Před 2 lety

    Hey Keith, How are you doing? You have not been posting videos recently. I really liked this video. My interest was code refactoring(I am coming from chapter 4 of Think python). I learned a lot from this. But, I felt you were not testing frequently so It was a bit difficult(by the standards you set) to follow for me. Take care. Thank you!

  • @mirayakinci4423
    @mirayakinci4423 Před 4 lety +1

    A funny video again. Thanks for your effort. I think that you are the best.

  • @ryanturt
    @ryanturt Před 3 lety +1

    I'm trying to make a main menu. I watched some tutorials for help but I can't get it to work. When I try to draw a button it says I can't use "screen" as argument 1?

  • @vekyll
    @vekyll Před 3 lety

    55:20 it's not about parentheses, of course. It's about discrete jumps and

  • @PepperBopps
    @PepperBopps Před 4 lety

    Some ideas that might make the game more complete in my opinion:
    -When the game.py is run the game could start with an intro screen that initializes gameplay through a button click, maybe this screen could list controls and basic rules as well.
    -Upon death be taken to a screen that shows your score and asks if you want to play again.
    -Just for funs sake the player could have a weapon to shoot blocks that(space invaders style) maybe fire using spacebar or up arrow?
    -Special power up blocks could drop that are a different color and grant a different weapon spray pattern or allow you to ignore collision for 5 seconds. (adding invincibility music 'mario style' could be a funny touch).
    -Maybe adding a local server to keep track of previous highscores, and display the top 3 on the post game screen.
    -User input on the difficulty/ window size/ enemy color/ image:
    (for difficulty I was thinking of doing something like difficulty = [1,2,3,4,5], and take in a user_difficulty[index] input that could be wrapped around the speed variable to increase or decrease speed based on difficulty. ie lvl 5 difficulty speed would be: 5* (score/5 + 1).)
    -Setting a .gif as the background to have raindrops or stars or something, after some research pygame doesn't support this natively.
    I also think it would be cool to use a flask app to load the server data onto an index.html that would allow you to run the game in browser. It would add a lot of customization options and be a good opportunity to teach html/css/js/flask/mongoDb, etc..
    I just watched your previous video on this game earlier today...then I saw this upload and got excited, and I started brainstorming features to add in my own version. I'm so glad I found your channel. I am going to keep modifying the game on my own but I wanted to share my ideas and maybe give some inspirational ideas. Thank you so much Keith!

    • @KeithGalli
      @KeithGalli  Před 4 lety +2

      These are great suggestions, thanks for sharing :). Maybe I'll do a live stream at some point where I implement some of them, not positive though.

  • @shabdyadav8803
    @shabdyadav8803 Před 3 lety

    very good bro...
    i also created one game!!

  • @Sam-in7ue
    @Sam-in7ue Před 3 lety +2

    any idea on how you could drop another shape which gives an extra point if you collide with it and then it respawns randomly?

    • @Sam-in7ue
      @Sam-in7ue Před 3 lety

      And yes I mean at the same time as the enemy is dropped

  • @53strat55
    @53strat55 Před 3 lety +1

    That intro lmao. Nice

  • @christiandaher2511
    @christiandaher2511 Před 3 lety +1

    Hi Keith , I have a problem. Sometimes when I collide with the blue blocks the game doesn't stop. Any ideas why is this happening? Great video!

  • @KeithKazamaFlick
    @KeithKazamaFlick Před 6 měsíci

    good stuff

  • @teetanrobotics5363
    @teetanrobotics5363 Před 4 lety +1

    Great Content. Love your channel. could you please make more ML libraries and frameworks videos ?

    • @KeithGalli
      @KeithGalli  Před 4 lety +4

      My next video will probably be a video on Tensorflow & Neural Networks!!

    • @teetanrobotics5363
      @teetanrobotics5363 Před 4 lety

      @@KeithGalli Damn. Love that

  • @petretrusca2
    @petretrusca2 Před 2 lety

    37:45 it is redundant to return True inside the if and False outside the if because the detect_collision is already returning them like that, you can return directly the collision detection. Do you agree?
    Or did you use the "Explicit is better than implicit." from the Zen of Python ?

  • @anindyasundarmanna6683
    @anindyasundarmanna6683 Před 2 lety +1

    The detect_collision looks bit too complicated to me. I would prefer having explicitly named variables keeping each part of the logic. Even something like x_overlap=(some logic), y_overlap=(some logic) and then using them helps.

  • @realneosi
    @realneosi Před 4 lety +1

    hey guys welcome back to my channel 🤠🤠

    • @KeithGalli
      @KeithGalli  Před 4 lety

      Thank you for the intro kind sir!!

  • @trevorhartman240
    @trevorhartman240 Před 2 lety

    I am so confused right now, I followed this tutorial and the original one exactly. but when I try to run this one i get "TypeError: Game.drop_enemies( ) missing 1 required positional argument: 'screen_width' "

  • @tobeypeters
    @tobeypeters Před 2 lety

    Ok, now take it one step further and really refactor it. I see so many improvements you can make. Anyhow, make a video on using @datatype

  • @WickedMan
    @WickedMan Před 2 lety +1

    How would we make the enemies not touch each other when they drop? For example at 53:55 all large enemies are together making it impossible to escape.

    • @petretrusca2
      @petretrusca2 Před 2 lety

      check if enemies overlap and if they do, change their positions such that they dont. Another improvement would be to check if there is a path where the player can go through instead of hoping that the enemies would randomly create one.

  • @planet2762
    @planet2762 Před 3 lety

    How do you put custom images in the original code and where do you put it

  • @annamargaritezamora28
    @annamargaritezamora28 Před 2 lety

    Hello! Could you establish codes for how to play the game again?

  • @tilkesh
    @tilkesh Před 7 měsíci

    Thx

  • @mikapeltokorpi7671
    @mikapeltokorpi7671 Před 2 lety

    How about Abstract Class (ABC) and Enum libraries version?

  • @adrianharo6586
    @adrianharo6586 Před 4 lety

    Godly

  •  Před 2 lety

    Is this code from Tech With Tim's channel? I feel like it is

  • @thghtfl
    @thghtfl Před 4 lety

    Hello! Why would you separate different classes into different modules?

    • @KeithGalli
      @KeithGalli  Před 4 lety

      It comes down to personal preference really. I thought there was enough logical separation of the classes we wrote (and their subclasses) that warranted them being in their own modules. If I wanted to use all of this code elsewhere, the next logical step of this tutorial would have been making it into a package: docs.python.org/3/tutorial/modules.html#packages

  • @DuarteMolha
    @DuarteMolha Před 2 lety

    why not make the colours an enum class?

  • @dylanjayabahu2878
    @dylanjayabahu2878 Před 3 lety

    Is there a way that you can share code with some one else so they can play the game? I am doing this for a school project but have no way of sharing it with my teacher so they can play it.

    • @KeithGalli
      @KeithGalli  Před 3 lety

      You might be able to make it an executable using the same method I demonstrate at the end of this video czcams.com/video/D8-snVfekto/video.html

    • @dylanjayabahu2878
      @dylanjayabahu2878 Před 3 lety

      Thank you! Your Videos are awesome by the way they have helped me learn programming a lot!

  • @Chiny_w_Pigulce
    @Chiny_w_Pigulce Před 3 lety +1

    Why don't you just use linting so that the text won't go off the screen?

  • @sebastianalvarez1537
    @sebastianalvarez1537 Před 4 lety

    !!!!

  • @utkarshutkarsh4421
    @utkarshutkarsh4421 Před 4 lety

    My school is using you numpy video on their channel claiming them to be by our teacher when the video is just reuploaded

  • @suvai9361
    @suvai9361 Před 3 lety +1

    Can anyone teach me Python from scratch??