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

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!
KZread - / @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.

Пікірлер: 80

  • @KeithGalli
    @KeithGalli4 жыл бұрын

    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

    4 жыл бұрын

    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

    4 жыл бұрын

    @@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
    @skulldozer12703 жыл бұрын

    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
    @theteacher0104 жыл бұрын

    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

    4 жыл бұрын

    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
    @wiz80584 жыл бұрын

    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.

  • @jenn6997
    @jenn69974 жыл бұрын

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

  • @abdallahwallyallah5490
    @abdallahwallyallah54903 жыл бұрын

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

  • @abdullahraihanbhuiyan2346
    @abdullahraihanbhuiyan23463 жыл бұрын

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

  • @CrapE_DM
    @CrapE_DM3 жыл бұрын

    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 z" can be simplified to "y > x > z" in Python

  • @petretrusca2

    @petretrusca2

    2 жыл бұрын

    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 ?

  • @kinwong6383
    @kinwong63833 жыл бұрын

    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
    @jonpounds19224 жыл бұрын

    This is the channel everyone should watch

  • @dr.girthmuffin8584

    @dr.girthmuffin8584

    4 жыл бұрын

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

  • @lorraineli6353
    @lorraineli63534 жыл бұрын

    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

    4 жыл бұрын

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

  • @gmorf33
    @gmorf333 жыл бұрын

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

  • @laurentzerah9906
    @laurentzerah99064 жыл бұрын

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

  • @KeithGalli

    @KeithGalli

    4 жыл бұрын

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

  • @anoubhav
    @anoubhav4 жыл бұрын

    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

    2 жыл бұрын

    Of course he prepared before hand and had code already written

  • @javanprycejavan
    @javanprycejavan4 жыл бұрын

    The lesson was awesome!

  • @yeshwanthraja2453
    @yeshwanthraja24534 жыл бұрын

    Very helpful, great work. Thanks

  • @jpaldama9963
    @jpaldama99634 жыл бұрын

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

  • @lusk-lyngesr.5764
    @lusk-lyngesr.57644 жыл бұрын

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

  • @bisratgetachew8373
    @bisratgetachew83732 жыл бұрын

    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!

  • @ryanturt
    @ryanturt3 жыл бұрын

    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?

  • @PragmaticReviews
    @PragmaticReviews4 жыл бұрын

    Great content! Thanks!

  • @KeithGalli

    @KeithGalli

    4 жыл бұрын

    You're welcome!!

  • @PepperBopps
    @PepperBopps4 жыл бұрын

    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

    4 жыл бұрын

    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.

  • @ErdosainNueve
    @ErdosainNueve3 жыл бұрын

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

  • @mirayakinci4423
    @mirayakinci44234 жыл бұрын

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

  • @KeithGalli

    @KeithGalli

    4 жыл бұрын

    Aww thank you! :)

  • @brunomerola
    @brunomerola9 ай бұрын

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

  • @christiandaher2511
    @christiandaher25113 жыл бұрын

    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!

  • @sainath66666
    @sainath666664 жыл бұрын

    Please Do More of these awesome python videos !!!

  • @KeithGalli

    @KeithGalli

    4 жыл бұрын

    will do!! :)

  • @moussamoise9124
    @moussamoise91244 жыл бұрын

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

  • @KeithGalli

    @KeithGalli

    4 жыл бұрын

    You're welcome! :)

  • @vekyll
    @vekyll3 жыл бұрын

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

  • @petretrusca2
    @petretrusca22 жыл бұрын

    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 ?

  • @itzikgutzcha4779
    @itzikgutzcha47792 жыл бұрын

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

  • @planet2762
    @planet27624 жыл бұрын

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

  • @Sam-in7ue
    @Sam-in7ue3 жыл бұрын

    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

    3 жыл бұрын

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

  • @shabdyadav8803
    @shabdyadav88033 жыл бұрын

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

  • @kitsurubami
    @kitsurubami Жыл бұрын

    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.

  • @trevorhartman240
    @trevorhartman2402 жыл бұрын

    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' "

  • @anindyasundarmanna6683
    @anindyasundarmanna66832 жыл бұрын

    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.

  • @WickedMan
    @WickedMan2 жыл бұрын

    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

    2 жыл бұрын

    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.

  • @KeithKazamaFlick
    @KeithKazamaFlick7 ай бұрын

    good stuff

  • @53strat55
    @53strat553 жыл бұрын

    That intro lmao. Nice

  • @annamargaritezamora28
    @annamargaritezamora282 жыл бұрын

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

  • @mikapeltokorpi7671
    @mikapeltokorpi76713 жыл бұрын

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

  • @teetanrobotics5363
    @teetanrobotics53634 жыл бұрын

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

  • @KeithGalli

    @KeithGalli

    4 жыл бұрын

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

  • @teetanrobotics5363

    @teetanrobotics5363

    4 жыл бұрын

    @@KeithGalli Damn. Love that

  • @tobeypeters
    @tobeypeters2 жыл бұрын

    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

  • 3 жыл бұрын

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

  • @DuarteMolha
    @DuarteMolha3 жыл бұрын

    why not make the colours an enum class?

  • @thghtfl
    @thghtfl4 жыл бұрын

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

  • @KeithGalli

    @KeithGalli

    4 жыл бұрын

    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

  • @dylanjayabahu2878
    @dylanjayabahu28783 жыл бұрын

    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

    3 жыл бұрын

    You might be able to make it an executable using the same method I demonstrate at the end of this video kzread.info/dash/bejne/dmxh1dCPlsjRpNI.html

  • @dylanjayabahu2878

    @dylanjayabahu2878

    3 жыл бұрын

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

  • @adrianharo6586
    @adrianharo65864 жыл бұрын

    Godly

  • @tilkesh
    @tilkesh9 ай бұрын

    Thx

  • @realneosi
    @realneosi4 жыл бұрын

    hey guys welcome back to my channel 🤠🤠

  • @KeithGalli

    @KeithGalli

    4 жыл бұрын

    Thank you for the intro kind sir!!

  • @Chiny_w_Pigulce
    @Chiny_w_Pigulce3 жыл бұрын

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

  • @utkarshutkarsh4421
    @utkarshutkarsh44214 жыл бұрын

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

  • @suvai9361
    @suvai93613 жыл бұрын

    Can anyone teach me Python from scratch??

  • @sebastianalvarez1537
    @sebastianalvarez15374 жыл бұрын

    !!!!