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

  Рет қаралды 41,400

Keith Galli

Keith Galli

Күн бұрын

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!
KZbin - / @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
@KeithGalli 4 жыл бұрын
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
@skulldozer1270 3 жыл бұрын
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 4 жыл бұрын
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
@wiz8058 4 жыл бұрын
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 2 жыл бұрын
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 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 ?
@abdullahraihanbhuiyan2346
@abdullahraihanbhuiyan2346 3 жыл бұрын
The way you used super is truly amazing. Very clean and efficient code.
@abdallahwallyallah5490
@abdallahwallyallah5490 3 жыл бұрын
Brilliant Explanation and shows the importance of clean code from the beginning :) Keep going mate
@jenn6997
@jenn6997 4 жыл бұрын
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 3 жыл бұрын
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 4 жыл бұрын
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
@yeshwanthraja2453
@yeshwanthraja2453 4 жыл бұрын
Very helpful, great work. Thanks
@gmorf33
@gmorf33 3 жыл бұрын
This was a really useful video. Really helps drive home the point of classes and oop
@lorraineli6353
@lorraineli6353 4 жыл бұрын
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!! 😊
@anoubhav
@anoubhav 4 жыл бұрын
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
@javanprycejavan 4 жыл бұрын
The lesson was awesome!
@laurentzerah9906
@laurentzerah9906 4 жыл бұрын
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! :)
@jpaldama9963
@jpaldama9963 4 жыл бұрын
Awesome video. Please do a unit testing video. That would be awesome. Or decorators
@ErdosainNueve
@ErdosainNueve 3 жыл бұрын
Muchas gracias. Ver este tipo de videos donde se ve el trabajo me es muy útil.
@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.
@brunomerola
@brunomerola 8 ай бұрын
Sou fã da sua didática - e dessa metadidatica, sobre a importancia do aprendizado correto
@lusk-lyngesr.5764
@lusk-lyngesr.5764 4 жыл бұрын
thanks a lot for a good intro to code refactoring in Python
@PragmaticReviews
@PragmaticReviews 4 жыл бұрын
Great content! Thanks!
@KeithGalli
@KeithGalli 4 жыл бұрын
You're welcome!!
@itzikgutzcha4779
@itzikgutzcha4779 2 жыл бұрын
The video was really nice and informative, but when I got to the Keith BOSS I had to like and comment
@moussamoise9124
@moussamoise9124 4 жыл бұрын
thank you Keith for this wonderful method of teaching (sorry not teaching but educating)
@KeithGalli
@KeithGalli 4 жыл бұрын
You're welcome! :)
@sainath66666
@sainath66666 4 жыл бұрын
Please Do More of these awesome python videos !!!
@KeithGalli
@KeithGalli 4 жыл бұрын
will do!! :)
@bisratgetachew8373
@bisratgetachew8373 2 жыл бұрын
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 4 жыл бұрын
A funny video again. Thanks for your effort. I think that you are the best.
@KeithGalli
@KeithGalli 4 жыл бұрын
Aww thank you! :)
@ryanturt
@ryanturt 3 жыл бұрын
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 3 жыл бұрын
55:20 it's not about parentheses, of course. It's about discrete jumps and
@PepperBopps
@PepperBopps 4 жыл бұрын
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.
@shabdyadav8803
@shabdyadav8803 3 жыл бұрын
very good bro... i also created one game!!
@Sam-in7ue
@Sam-in7ue 3 жыл бұрын
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
@53strat55
@53strat55 3 жыл бұрын
That intro lmao. Nice
@christiandaher2511
@christiandaher2511 3 жыл бұрын
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!
@teetanrobotics5363
@teetanrobotics5363 4 жыл бұрын
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
@KeithKazamaFlick
@KeithKazamaFlick 6 ай бұрын
good stuff
@petretrusca2
@petretrusca2 2 жыл бұрын
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 2 жыл бұрын
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 4 жыл бұрын
hey guys welcome back to my channel 🤠🤠
@KeithGalli
@KeithGalli 4 жыл бұрын
Thank you for the intro kind sir!!
@trevorhartman240
@trevorhartman240 2 жыл бұрын
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 2 жыл бұрын
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 2 жыл бұрын
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.
@planet2762
@planet2762 3 жыл бұрын
How do you put custom images in the original code and where do you put it
@annamargaritezamora28
@annamargaritezamora28 2 жыл бұрын
Hello! Could you establish codes for how to play the game again?
@tilkesh
@tilkesh 7 ай бұрын
Thx
@mikapeltokorpi7671
@mikapeltokorpi7671 2 жыл бұрын
How about Abstract Class (ABC) and Enum libraries version?
@adrianharo6586
@adrianharo6586 4 жыл бұрын
Godly
2 жыл бұрын
Is this code from Tech With Tim's channel? I feel like it is
@thghtfl
@thghtfl 4 жыл бұрын
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
@DuarteMolha
@DuarteMolha 2 жыл бұрын
why not make the colours an enum class?
@dylanjayabahu2878
@dylanjayabahu2878 3 жыл бұрын
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 kzbin.info/www/bejne/emmQpKGMm8qeqtE
@dylanjayabahu2878
@dylanjayabahu2878 3 жыл бұрын
Thank you! Your Videos are awesome by the way they have helped me learn programming a lot!
@Chiny_w_Pigulce
@Chiny_w_Pigulce 3 жыл бұрын
Why don't you just use linting so that the text won't go off the screen?
@sebastianalvarez1537
@sebastianalvarez1537 4 жыл бұрын
!!!!
@utkarshutkarsh4421
@utkarshutkarsh4421 4 жыл бұрын
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 3 жыл бұрын
Can anyone teach me Python from scratch??
7 Python Code Smells: Olfactory Offenses To Avoid At All Costs
22:10
We Got Expelled From Scholl After This...
00:10
Jojo Sim
Рет қаралды 30 МЛН
2000000❤️⚽️#shorts #thankyou
00:20
あしざるFC
Рет қаралды 14 МЛН
Which one is the best? #katebrush #shorts
00:12
Kate Brush
Рет қаралды 20 МЛН
The Ultimate Guide to Writing Classes in Python
25:39
ArjanCodes
Рет қаралды 105 М.
Beautiful Python Refactoring - Talk by Conor Hoekstra
30:05
freeCodeCamp Talks
Рет қаралды 713
10X Your Code with ChatGPT:  How to Use it Effectively
17:14
Dave's Garage
Рет қаралды 327 М.
Python 101: Learn the 5 Must-Know Concepts
20:00
Tech With Tim
Рет қаралды 1 МЛН
Чистый Код / Clean Code: # 3: Огромные функции и их рефакторинг, Extract Till You Drop
8:41
Refactoring A Tower Defense Game In Python // CODE ROAST
36:49
ArjanCodes
Рет қаралды 256 М.
Python dataclasses will save you HOURS, also featuring attrs
8:50
Lets Refactor this Telegram Bot To Use Generics | Code Review #3
37:35
Why You Shouldn't Nest Your Code
8:30
CodeAesthetic
Рет қаралды 2,6 МЛН
25 nooby Python habits you need to ditch
9:12
mCoding
Рет қаралды 1,7 МЛН
We Got Expelled From Scholl After This...
00:10
Jojo Sim
Рет қаралды 30 МЛН