Learn Python Classes With a Text-Based Battle - OOP Tutorial
HTML-код
- Опубликовано: 17 май 2024
- I'll guide you through object-oriented programming in Python, featuring classes, objects, attributes, methods, inheritance and subclasses - all in a fun way of creating a text-based ASCII battle scene!
Find the code I made for the video here 👇👇👇
github.com/orkslayergamedev/p...
×oOo×-----------------------👽SOCIALS👽-----------------------×oOo×
☕ SUPPORT ME: ko-fi.com/orkslayergamedev/ (be the first one ever, lol)
👾 PM FOR COMMISSIONS: www.fiverr.com/astral_freak/ (out of office)
🎮 TRY OUT MY GAMES: orkslayergamedev.itch.io/ (100% free)
Instagram: / orkslayergamedev
GitHub: github.com/orkslayergamedev/
Reddit: / orkslayergamedev
×oOo×--------------------🎞TIMESTAMPS🎞---------------------×oOo×
00:00 - Classes Basics
01:39 - Character Class
05:20 - Weapon Class
06:53 - Class Inheritance: Hero & Enemy
10:24 - HealthBar Class
14:57 - Final Result
×oOo×--------------------------✨TAGS✨--------------------------×oOo×
#python #tutorial #classes #ascii #gamedev
#objectorientedprogramming #oop
#indiedev #indiegame #indiegames
#indiegamedev #pixelart #gamedevelopment
#orkslayer #orkslayergamedev
#videogame #game - Хобби
utf-8: chr(9608) = ord("█") - for those who can't get it by typing "alt+0219" ASCII because in utf-8 hex it's 'e2 96 88' (©- by typing "alt+0169" is works fine). This issue may happens with using local languages keyboard.
once again: self.color = self.colors.get(color, self.colors.get("default")) - dict.get() takes the default value by the 2nd argument if missed the key.
and to get full right OOP experience, wrap all main code to some function:
def run():
name = input("Enter the name: ")
hero = Hero(name=name, health=100)
hero.equip(iron_sword)
enemy = Enemy(name="Enemy", health=100, weapon=short_bow)
while True:
hero.attack(enemy)
enemy.attack(hero)
hero.health_bar.draw()
enemy.health_bar.draw()
if not input("Press Enter to quit: "):
break
if __name__ == '__main__':
run()
\m/. .\m/
structure if __name__ == '__main__' is equal:
to C/C++:
int main( void ) {
// some code
return 0;
};
to Java:
public class Main {
public static void main (String[] args) { // some code};
}
to C#:
class TestClass
{
static void Main(string[] args) { // some code }
}
Hey there, thanks for the useful additions again! Let me share my thoughts:
👉🏻 The best way to use the .get method of dictionaries is the one you just mentioned - seems like I slipped over this simplification when making the video.
👉🏻 Wrapping the game in a run function is a nice way to handle it. I usually create a Game class for this and call it from the main.py that serves as the entry point of the project.
And with this, you won another pin 🤙🏻
criminally underrated video
Thank you, it really means a lot to me! 🙏🏻
You are goddam right RUclips algorithmic really gone potato mode with this one video quality is godly
You are 100% correct. It’s nice to see a developer showing love to another developer instead of looking for faults and being so petty. There’s never just 1 way to do a thing. ABSOLUTELY underrated!!!
holy sht, best OOP tutorial . Glad youtube recommended you 😁
And I'm glad that you're here! Thanks a lot for the kind words, I appreciate it! 😊
If you don't learn about classes with this video, just forget about it 😂. Cleanest video about classes that I ever watched
Your video is the perfect proof that when you're looking for a good tutorial video you shouldn't always care about the views on it, because there's might be a hidden gem like this. Thanks for the upload!
Thanks a bunch for the kind comment, I really appreciate it!
I'm still grateful for my handful of views and will continue to upload cool content for my audience 🙏🏻
Cheers from Hungary! 👋🏻
I've been learning Python for the past month and this is easily the best tutorial for Classes I've seen so far.
Thank you for sharing your thoughts, I really appreciate it!
I'm so glad that many people are enjoying my tutorial 🙏🏻
Ah! You know so many Python features. It disturbs me a little bit when some big time RUclipsrs seem unaware of these things. Thank you!
Thank you for the kind words, it sure feels great to have a wider knowledge in Python! I try to represent as many of the little tricks as I can 🙏🏻
I have watched a lot of beginner programming tutorials, and haven't been busy with it for two years. And then this video gets recommended that teaches me concepts that just wouldn't "click".
Thank you so much for creating this video, and keep it going. You deserve a lot more views and subscribers, just keep going and you probably get notices by the algorithm.
Thanks so much for the great feedback, I really appreciate it 🙏🏻
I'm really happy that my video helped you with your programming journey!
Feel free to drop any question in the future if you need help 👋🏻
Finally i understand classes in python after 3 years thanks
Also I love the new style of your video, this time it actually fits perfect
Wow, I'm really happy to hear this! I struggled with classes for a long time and I wanted to make a video with clear explanation. Thanks a lot for the feedback, I'm glad you like the editing too :)
Absolutely best explanation of OOP for Python I have come accross (maybe its just because I understand it better in gaming terms), thank you so much for this!
Hey, thanks a lot for the feedback, I really appreciate it! 🙏🏻 I wanted to create such a tutorial that if I watched it years ago, I understood classes much faster 😁 Based on the comments, I achieved this goal, so I'm really happy!
Just started with OOP and this video bangs 🤘. Quality upload, will subscribe for more.
I appreciate your support, thank you so much! 🙏🏻
Your channel is an absolute bliss ! , So glad I stumbled upon you .. Cheers !
Wow, you're so kind! Thanks for joining us, I'm glad to have you here 🙏🏻❤️
Making a complicated subject easy to understand and fun while at it is incredible.
I'm glad you had fun with the video, happy coding to you! 🐍
Hooray! Thank you very much for the new video!
And thanks a lot to you for the feedback! I'm happy you enjoyed the content 😊
This video really helped me understand to the point where I could go back and find my mistakes on my own. Thanks a lot!!
I'm glad my video was helpful to you! Good luck with coding! 🐍
Wow!! Thank you. That was a quick, concise, and extremely educational demonstration of OOP! Cheers!!
I'm glad you found it educational and helpful - part 2 coming soon! Until then, happy coding! 🙌🐍
Nice video, I appreciate you example was more realistic than a lot of other class tutorials I have seen.
Thank you! I’m happy to hear you found the video useful! 🙌 Stay tuned for more! 🐍
Woooow I am 5 min in and it's amazing how it makes sense and easy it's to understand, keep up the good work ❤
Thank you so much! ❤ I'm happy to hear it's helping you out. Keep your eyes open as there's more to come soon! 🙌🐍
Thank You. Great Example and easy to understand !👍
Thank you for the feedback, I greatly appreciate it! 🙌🏻
wow thats the video i were waiting for, thanks man
So glad to hear that! I appreciate your feedback! 🙌
Excelent content, i hope this channel explode so i can see you guide to recreate dwarf fortress in the future 😊
Thank you so much! 🙏🏻 Let's find that out in the future! With enough time and effort, everything is possible 😁
Subscribed, finnaly understand classes, thanks mate!
That's fantastic to hear! 🙌 Thanks for subscribing and happy coding! 🐍
This video deserves a million views and you Sir deserve a million subscribers. Thanks to your video I was able to understand Python's OOP and this is coming from a person who's third language is English. Your video presentation together with your explanation made this complex topic easy to understand. Subscribed.
Wow, such kind and encouraging words! Thank you so much for the support, it truly means a lot to me! I'm glad the video helped you on your programming journey and I hope to see you around the channel 🙏🏻
this video is so underrated for what it delivers.
I really appreciate your words, thank you so much! 🙏🏻
Very cool!
Its quick, concise and clear!
Instant Subscribe!
Thanks for joining us, I appreciate it!
Have fun coding! 🐍
I think this is about as simple explanation as one can get for this. I still don't understand the classes fully, but this video definitely helped a lot. I just wish you were talking slower and explaining things more as you do them cuz ngl I got lost A LOT watching this.
I learned it the hard way unfortunately so I wanted to share my knowledge the most fun way possible!
Thanks for the feedback and sorry if the pace was too fast, it's hard to find the right one most of the time 😓
Let me know if you have Python related questions along your learning journey! 🐍
Super cool video. Really loved it
Well though and well realized. Please, continue ! 🙏🏻
I will for sure! Thank you very much for the feedback, I really appreciate it! 🙏🏻
Super useful, just started programming, and OOP is amazing because it makes everything more flexible. The video and the examples are awesome also. It gave me ideia to make of on my own, like a spaceship project.
Thanks a lot for the amazing feedback, I really appreciate it! That spaceship project you mentioned sounds epic, feel free to share it with me anytime if you make it public! 🚀
what an awesome tutorial on OPP. well done.
Thank you very much for the feedback, much appreciated! 🙏🏻
Wow, I did now know how much I needed this
I'm glad you found it useful! Have fun with your new knowledge 🙌🏻
Thank you for this great tutorial, i'm very happy with it.. this game logic, architecture is exactly what i wanted to learn i followed along by using C# to challenge myself amazing again tysm.
Wow, that was surely a great challenge, good job!
I appreciate your feedback and thanks for joining us! 🙌🏻
I'm actually working on a text-based adventure game, and this is exactly what I need! :D
Already got most of what you've shown, but it's much better written and you expand upon things I couldn't have done
Hey! I'm glad you found the video helpful, I appreciate your feedback!
Good luck with your game and feel free to drop any questions if you need help 😊
@@orkslayergamedev
Hi thank you!
I might need some advice sometimes if I get stuck.
How would be the most convenient way for reaching out?
Well, I check the youtube comments daily and if there's a question, I respond asap (yet yt studio only shows new comments and not answers unfortunately)
You can also contact me on Ko-fi via direct messages, there I can even send code snippets via screenshots if needed :)
Lastly there's my instagram and social email adress, but I check those rarely.
You can find all my contacts on my channel page 🙌🏻
Köszi a segítséget!
Mindig újra és újra belekezdtek a Python programozásba, de mindig megakadok amikor jön egy nehezebb feladat és a végén feladom. Remélhetőleg ezúttal sikerül megtartani a motivációt. Eddig nagyon tetszik a channel, remélem lesznek még videók. Könnyen érthető a magyar akcentussal. :DD
Az elején fogalmam sem volt hogy magyar vagy, aztan a videó felénél klikkelt az agyam.
Szívesen! 😊 Ne aggódj, gyakran futunk falakba, ami elég gyorsan alá tudja ásni a tanulás iránti elkötelezettségünket. 5 év tapasztalattal sincs ez máshogy - ilyenkor egy lépés hátra és meg kell próbálni vagy máshonnan megközelíteni a problémát, vagy esetleg kisebb lépésekben haladni.
Őszintén örülök, hogy rám találtál és hogy tetszik a csatorna! Lassan, de biztosan érkeznek az új tartalmak :)
Addig pedig keress bátran bármilyen kérdéssel, igyekszem figyelni a kommenteket minél gyakrabban. Sok sikert a Pythonhoz! 🙌🐍
You nailed it! I am interested in the Code Patterns. It is hard to find a tutorial, that shows you how to construct that whole thing WITH PURPOSE! Most tutorials just type a code and you habv no Idea about the WHY that and NOT that? So you filled a gap here! Thanks!
Hey there, thanks a bunch for your awesome feedback! I always try to deliver meaningful content with context, answering all possible questions in-the-go. So I'm really happy that you discovered this video and that it lived up to your expectations! I love design patterns too, it's fun to construct the code in different ways to reach the best efficiency. Happy coding! 🚀💻
Great explanations
Better than my CS teacher
Thanks so much for the kind words! 🙏
its really cool video i will bookmark this for learn again in future
Thanks a lot, hope to see you around the channel soon! 🙏🏻
Excellent and informative!!
Thank you very much! 🙏🏻
Thank you for this video as It’s really well done. I’m dyslexic, among other things, and been learning to code. Material like this is very appreciated. =]
Thank you for your kind comment, it means a lot! Feel free to leave questions anytime! 🙌🏻
Hope to see you around and good luck with your coding experience! 😊
I love how you implemented game development in a python oop tutorial.
Thanks a lot! My aim is to make coding fun! 🐍
Okay ! this video is much better that others which has million of views , such a gem you are
edit: and you got a sub ~~
I really appreciate your kind words, thank you so much! 🙏🏻 Welcome aboard! 🐍
Looking forward for the next chapter for this like adding RNG (Critical, dodge, block). Thanks for this kind of lesson.
Thank you, much appreciated! I hope to create more content like this as it's huge help to lots of people. If you have any suggestions or requests regarding topics you would like to see on the channel, feel free to share them with me anytime!
@@orkslayergamedev Please create tutorial on how to make game with RNG with programming.
Alright! I'll add it to the topic poll and see if people like the idea!
Amazing tutorial!
Thank you very much, I appreciate it! 🙏🏻
love it! btw what's theme is this? I like the way of highlighting style
Thank you! 🙌 I recently switched from this one but I believe it was the One Dark Italic style from the One Dark Theme plugin.
Here's the link: plugins.jetbrains.com/plugin/11938-one-dark-theme
The naming convention for class names is called Pascal case. It takes the form of MyCoolClass, while Camal case takes the form myCoolClass (lower case starting letter). Use Pascal case!
I know that PascalCase exists, although there's some misconception on the web about camelcase actually being camelCase or CamelCase. We even had a debate with my co-workers. Although camelCase would make more sense, so you're most probably right!
EXCELENT TUTORIAL I DIDNT KNOW THAT I COULD CHANGE THE COLOR OF MY TEXT LIKE THAT!
Thank you very much for the feedback! Coloring console text adds so much to any project/game, have fun using it 🙌🏻
Excellent video, thanks for sharing
Thanks for the feedback! 🙏🏻
Cool project. Thanks for video.
Thank you, I appreciate your feedback!
The best python tutorial video I've ever watched. Hope I had watched it earlier.
Thank you very much for the kind comment, I appreciate it!
This tutorial was so useful :D !
I'm glad you like it, thanks for the feedback! :)
awesome, thanks!!
Glad you enjoyed it! 🙌
best explanation of class
Thank you, I appreciate it! 🙏🏻
great video, thanks !
Thanks a lot for the feedback, I'm glad you enjoyed it!
as a beginner this was a pain in the ass but i learned a lot and honestly this is amazing because i don't think i've could do this if it wasn't for making a game
I struggled with classes long ago as well, I know the feeling!
Back when I started using Python I created really simple ASCII games, it's a pretty good way of learning in my opinion :)
Well done
Thank you! 🙌🏻
very cool!
Thank you very much! 🙏🏻
I just realized after watching this video that history truly cheated us by denying us the existence of a knight in full armour wielding an RPG.
I definitely forgot about that part - thanks for the good laugh! 😂
Bro what an insanely helpful tutorial tysmmmm
I had a doubt: When defining the methods, what does the "-> None" do at the end?
I'm glad you enjoyed the video! 🙏🏻
When defining functions and methods, you can leave type hints for the arguments and the return value. Let me show examples:
def sum_numbers(n1: int, n2: int) -> int:
return n1 + n2
Here we say both arguments should be integers, just like the returned number. If you use an IDE (code editor) that has a built-in linter (code checker), it will automatically warn you if you
A, define the function/method in a way that the actual returned value is not what you define in the first line (where the arrow points):
def sum_numbers(n1: int, n2: int) -> int:
return str(n1 + n2)
B, you call the function/method with arguments not matching their annotated types:
sum_numbers(n1="string", n2=True)
So, whenever you create a method that returns nothing, you can also emphasize it by putting -> None at the end of the definition, like...
def useless_printer() -> None:
print("I don't return anything")
...and when you call it:
result = useless_printer()
>>> "I don't return anything"
print(result)
>>> None
Whereas you call the other method that has a returned value...
result = sum_numbers(3, 4)
print(result)
>>> 7
I hope it's clear now, let me know if I can help with anything else!
@@orkslayergamedev Ohh gotcha, thanks a lot for such a fast and comprehensive reply!
No problem, glad to be of service!
thanks for the explanation, just wish if it was a little bit slower, but still great way to understand oop more deeper
Thanks a lot for the feedback, I appreciate it! I'm sorry if it turned out to be a little too fast, I always try to set a pace that the tutorial is comprehensible yet fast enough that nobody falls asleep by the end :)
Just watch at 0.5 speed. His voice will change a bit. 😅
I'm still in the beginner phase of learning python, but this was very helpful! Classes and definitions are the bane of my existence, but I understand them a little more now thanks to you. Since the game doesn't end after the health bar reaches "0", what would be a good way to implement that into the code? I've added:
if self.current_value==0:
exit()
Which seems to do the trick, but is there another way to do this?
Thanks a lot for the feedback, I'm glad my video helped you with programming! 🙌🏻
Let me assist you with quitting the game! Here's the original main loop of this video:
# -------------------------------------------
while True:
os.system("cls")
hero.attack(enemy)
enemy.attack(hero)
hero.health_bar.draw()
enemy.health_bar.draw()
input()
# -------------------------------------------
One way of handling the quit event is to break out of the while loop whenever the health of the hero reaches 0:
# -------------------------------------------
if hero.health 0
# -------------------------------------------
We can even wrap all this into a Game class to make it nicer:
# ------------ game class ------------
class Game:
def __init__(self):
self.running = True
def run(self) -> None:
while self.running:
os.system("cls")
hero.attack(enemy)
enemy.attack(hero)
hero.health_bar.draw()
enemy.health_bar.draw()
input()
self.running = hero.health > 0
input("GAME OVER")
exit()
# ------------ game loop ------------
if __name__ == "__main__":
game = Game()
game.run()
# -------------------------------------------
Feel free to copy-paste this into your main.py :)
Drop your questions whenever you need more help!
Its very nice seen all what I learned as a borring way in a fun way, also, I notice the mistakes right away, buts its fine, nice video my boy 1+sub
I'm glad you enjoyed the video even with experience in oop! Thanks for joining! 🙏🏻
Just understood it now
Awesome! Keep up the learning! 🐍
It is very nice to see the progress in the video, but without my own thoughts it is very confusing to follow along :)
Thanks for the feedback!
Don't worry, when I started learning classes years ago, it was very confusing for me too. It's not a simple concept to comprehend especially if you just started learning programming. Although the more and more you use classes, the easier the whole language is gonna be. So keep practicing and one day it will be easy as 1+1 :)
Easy to understand explanation👍🏻
Thanks a lot, bro! I was aiming to make it as beginner-friendly as possible 😁
@@orkslayergamedev will you be doing a mini game tutorial with pygame-ce?
Couldn't say no to a top sub 😎
I think the space shooter tutorial (that comes after I documented my latest game) would go well with the imporved performance of pygame-ce, especially for the transparent displaying and scaling. But if you have any suggestions, I'm open for ideas 👌🏻
@@orkslayergamedev that sounds great, I was like thinking of a complete game starting from a home page (with settings and start button) then the game and the end screen. Showcasing the transition that takes place between these scenes.
There are many tutorials online on how to code game mechanics but there are almost none teaching how to make a complete game.
That's actually a great idea! It won't increase the overall complexity of my tutorial too much, so why not. Let the needs of my people be satisfied 🙌🏻
First some space shooter devlogs, than this complete space shooter game tutorial 👌🏻
First, thanks for this. Second, Which editor is this? I've been using an unregistered copy of Sublime. When I run the code shown at 5:18, I only get one set of values, you seem to get multiples. I tried running it several times in a row and only get the same variables no decrease in their health.
Hey there! I use PyCharm Community Edition but the code should run as expected regardless of the editor you use. The terminal expects an input in each cycle, did you press enter in the console?
@@orkslayergamedev I did and no go.. So I installed pyCharm and worked great. Thanks!
I'm glad that it worked at the end! Have fun using PyCharm, it has lots of cool features that you'll like! 🐍
Damn, your video is so nice and you help me a lot!! Sad youtube recommend late😢
I'm really happy that you find my content helpful, thanks so much for the feedback! 🙏🏻
Thanks a lot! but i didn't get how to do 10:21, which kind a if statement i need?
Hey there! As you can see in the console output, the hero can drop it's default weapon too (Fists) - which is probably a bug we don't want in our games. The simplest way to resolve this issue is to update the drop method as follows:
def drop(self) -> None:
if self.weapon != self.default_weapon:
print(f"{self.name} dropped the {self.weapon.name}!")
self.weapon = self.default_weapon
Thanks man u are really my favorite Python teacher rn! @@orkslayergamedev
I really appreciate your kind words, thank you so much! I hope that you'll enjoy the upcoming content as well 🙏🏻
(ps. sorry for the late reply, youtube sends no notifications of comment answers)
can you explain the: else ' ' :part of the code in the draw method for health bar. self.color if self.is_colored else '' im confused on exactly what this bit of code is doing
Hey! I apologize for the late reply, hope you figured out by now. If not, don't worry, let me explain.
The expression you mentioned decides if the text after that row (the bars of the health bar) should be colored or not. If the self.is_colored is True, then the color code will be applied, coloring the health bar. Otherwise, if the self.is_colored is False, we'll leave an empty string there that does nothing. This way the bar won't be colored.
Let me know if it's clear for you now! 🐍
Nice.
Thanks a lot! 👋🏻
OK good to know thx and after it you need to add it visually if you code in pygame ehat make the code longer
Sure thing! I worked a lot with health bars using Pygame. Including cool visual effects like bubbles in the bar, dynamic decrease/increase instead of instant, so on. I think I even gave some insights in the #8 devlog of Ork Slayer
Question for hp dmg. Why use the max function to prevent it from going below zero, I'm new and my first thought would be a min.
Thanks for the question! It's totally up to your game logic how you want to handle health, although I like to set all negative values to zero. This way whenever I want to display health bars, I don't need to worry about incorrect negative numbers.
If min is confusing to you, take a look at the following:
max(health, 0) means the same as
if health < 0:
health = 0
Let me know if I can help with anything else!
I like to think about it like a container of cookies or something..
You got a container which holds cookies
Each cookie has their own values (shape, size, flavor, etc)
You can inherit it by putting it into another container… and so on.
Now this way of thinking about it falls short when it comes to polymorphism, at least in my example.. but oh well.
Interesting concept!
You can easily incorporate polymorphism in your idea if you define the classes this way:
class Food(ABC):
@abstractmethod
def eat(self):
pass
class Cookie(Food):
def eat(self):
print("You ate a cookie.")
class Container(ABC):
@abstractmethod
def store(self, food):
pass
class CookieJar(Container, list):
def store(self, cookie):
self.append(cookie)
print("You put a cookie in the jar.")
@@orkslayergamedev True, if you include the container itself into the concept and actions performed on it.
It looks nice. I am not familar with high level programming. I use only x86 assembly low level and i can use free memory to build tables for character and weapon.😅
Hey, thanks! Sounds cool to me 😁 Wish I had the time to learn about low-level programming. One of my friends once recreated Celeste for a microcontroller, it's crazy!
Hi there! I just started learning python and using Pycharm IDE. I'm just following the steps as you said but the intellisense is not working when i try to import the Character. Could you please help me with that?
Hey, of course, I'd be happy to help you! PyCharm can be a bit complicated if you just started out whit programming, I also had issues with it when I learned the basics. I'd try the following steps to fix the issue:
First of all, give the computer a restart if you haven't done it already. If the problem persists, try to use:
from .character import Character
instead of
from character import Character
This way you explicitly import Character from the character module that is in the same directory as the file you call the import from.
If the problem persists, it's likely due to improperly configured interpreter and root path.
You can fix this by going to File > Settings > Project: [Your Project Name] > Python Interpreter, and selecting the correct interpreter if it's not already selected.
Then to configure the root path you can right-click on the project root directory in the Project tool window, select "Mark Directory as," and then choose "Sources Root."
Let me know if these steps solved the problem!
Like it..!
Thank you! 🙏🏻
👏👏👏👏👏👏👏👏
Köszönöm a kellemes meglepetést, kolléga! 😁
Szép, igényes munkák ezek a videók, hatalmas gratula🙈😁
@@misterdenko9164 Köszönöm szépen, sokat jelent a visszajelzés! Örülök hogy követed a tartalmat 🙏🏻😁
Great vid Ork, very educational and informative, could you help with one error i got at the very end: self.health_bar = HealthBar(self, color="blue") TypeError: HealthBar() takes no arguments | any help would be appreciated, thanks.
Hey there! Thanks again for the feedback, much appreciated!
I replied to your other comment with the solution, please take a look and tell me if it helped! 🙌
@@orkslayergamedev Hi Thnaks for the reply, and sorry for commenting on the wrong vid, had both open and commented on that one by mistake.
As for my Init(s), i double checked all of them, and all of them are __Init__ (double underscored) no exceptions. still get it.
Here's the relevant code:
CHARACTER CLASS
class Hero(Character):
def __init__(self, name: str, health: int) -> None:
super().__init__(name=name, health=health)
self.default_weapon = self.weapon
self.health_bar = HealthBar(self, color="blue")
HP CLASS
def __init__(self, entity, length: int = 20, is_colored: bool = True, color: str = "") -> None:
self.entity = entity
self.length = length
self.max_value = entity.health_max
self.current_value = entity.health
self.is_colored = is_colored
self.color = self.colors.get(color) or self.colors["default"]
I don't think any typos are causing this, if you have any idea i would appreciate it? Thanks for your time.
EDIT: one very strange thing is that once hover over the color in "HealthBar(self, color="blue")" it says "(function) color: any", but the init in hp class says "(parameter) color: str". This is the only place this happens all other inits. are correctly taking paramaters and all calls are sending paramaters to the class constructor, is it possible there's some inbuilt color function that's colliding with my paramater
No problem buddy, hope we can figure this out. This issue is strange indeed. I copied the snippet you sent me to a fresh file and added minimal extra code to make it exectuable. When I hover over to the color argument of HealthBar in Hero, I get the right and expected hints.
Please copy the following to a new file and try to run it with python in the console.
If all is correct, you should see no messages on the screen. Give it a try.
class HealthBar:
colors: dict = {"red": "\033[91m",
"purple": "\33[95m",
"blue": "\33[34m",
"blue2": "\33[36m",
"blue3": "\33[96m",
"green": "\033[92m",
"green2": "\033[32m",
"brown": "\33[33m",
"yellow": "\33[93m",
"grey": "\33[37m",
"default": "\033[0m"
}
def __init__(self, entity, length: int = 20, is_colored: bool = True, color: str = "") -> None:
self.entity = entity
self.length = length
self.max_value = entity.health_max
self.current_value = entity.health
self.is_colored = is_colored
self.color = self.colors.get(color) or self.colors["default"]
class Character:
health_bar: HealthBar
def __init__(self,
name: str,
health: int,
) -> None:
self.name = name
self.health = health
self.health_max = health
self.weapon = ""
class Hero(Character):
def __init__(self, name: str, health: int) -> None:
super().__init__(name=name, health=health)
self.default_weapon = self.weapon
self.health_bar = HealthBar(self, color="blue")
if __name__ == "__main__":
char = Hero(name="dummy", health=10)
assert char.health_bar
@@orkslayergamedev Done, it does work and show no error messages, only needed to add 2 more underscores to the if _name_ (i assume the youtube commets are deleting some underscores)
As for this ""self.health_bar = HealthBar(self, color="blue")" hovering over color=blue now correctly shows "(parameter) color: str" and not function
Hey, I know it's quite an old video but I have a question. It would be really helpful if you would be able to answer! So, Why did you put 'self' everywhere? What does it do? (I know it's a rookie question but I'm just getting into this stuff)
Hey there! No worries at all; there are no rookie questions here. I'm happy to help!
The keyword self is used in Python class methods to refer to the instance of the object it"self". Whenever you define a method inside a class, you need to include self as the first parameter so you can access the instance's attributes and other methods. When you use self, you're telling Python which object's data to access or modify (again, the data of the object itself).
Furthermore, you could name it anything else, self is just a naming convention. This would work as well...
class Hero:
def __init__(the_object_itself, name):
the_object_itself.name = name
But when you actually create an object, you don't need to pass that self-referencing argument...
hero = Hero("John")
When you want to access the name of the hero object like...
hero.name
...what Python does is it looks into the object and searches for self.name (or the_object_itself.name in this case).
Hope this helps a bit! Let me know if you have further questions, I'll keep an eye out for your comment! 🐍
You made it so much clearer to understand. Thank you so much!
hmm just a quick question... do you know the difference between PascalCase and camelCase ?
Sure thing! Just two naming conventions with the difference of the first letter of the first word being capitalized or not. Although camelCase is not commonly used with Python. Funny thing is that people tend to mistake PascalCase with camelCase thinking it's CamelCase (like camels with two humps, lol), I do it sometimes too, unintentionally of course
Hey there it’s me again! Can you tell me, why there is the None-Value in the def‘s ? Without it, it also works fine.
Thx 🙏
Hi! I'd be happy to explain. Functions/methods have that functionality to return values to the user. The returned value can be anything. It can even be nothing, if we don't put the return statement into them.
Take this for example:
def sum_values(number_1, number_2):
return number_1 + number_2
If you call this method, like:
sum_values(5, 3)
It will return the number 8 to you.
Or you can create other kinds of methods that won't return anything like:
def print_something(text):
print(text)
Another optional thing you can do with python is leavign type hints / annotations of parameters and returned values of functions/methods. The above functions with type hints:
def sum_values(number_1: int, number_2: int) -> int:
return number_1, number_2
def print_something(text: str) -> None:
print(text)
This way you're making it clear what to expect those values to be and your code editor can suggest you type-specific attributes/methods of that value. It's totally not necessary and your code will work just fine without them. Although I like to include them everywhere as it makes your code more clear, especially when you work on a bigger project.
Hope this helps! :)
@@orkslayergamedevwooooo! Thank you. I have had that question for 14 years
@@ZeroSpawn My pleasure, I'm glad if it's clear for you now! Happy coding to you 🐍
At the moment I don’t understand OOP at all. I learn every day and someday I will get there 😅
Don't worry, it took me years of practice to fully understand the concept and learn object-oriented programming. It will get easier and clearer the more you code, so keep up the good work! :)
f"{self.colors['default'] if self.is_colored else ""}" > This crashes the program each time. After messing around with it a bit it seems the issue is the ['default'] area. It says it can't be a string. I've commented it out and the program will run just without correctly working healthbars. Is there another way to write this?
Hey! I see the problem. If you use f strings with double quotes, all strings inside should be single quoted. Vica-versa. Otherwise your code will yield a SyntaxError.
Try this one with 2 single quotes after else:
f"{self.colors['default'] if self.is_colored else ''}"
Swapping all singles and doubles works as well:
f'{self.colors["default"] if self.is_colored else ""}'
@@orkslayergamedev sadly even doing that doesn't seem to help. It just really hates that default portion for some reason and switching from single to double quotes doesn't seem to matter.
I was able to get it work by using your original code but for the life of me I couldn't see where the error on my part was as I copied it line from line but there must have been a wrong character somewhere.
Don't worry, all of us come across anomalies from time to time, where seemingly everything is 100% corrent, yet we still get an unexpected error.
I'm glad you got the code running either way. Let me know if I can help with anything else!
Could you show us guided tutorials for making minigame projects for python? I am a student in uni and i wanna focus on python for data science. But i need to master it first, by making games i will be able to relate to it and understand it much better because i am a gamer too!!. And i can show these projects to employers!
Hey there, welcome here! 👋🏻 I started with small games too and now I'm a hired software engineer, so I was in the same boots :)
I'd be happy to help with minigame tutorials and I'm always open for suggestions!
I planned a space shooter game tutorial - that was postponed from last year unfortunately - with similar design as my almost complete Field Trip.
Feel free to take a look at some of my recent videos, I could make a fairly simplified version of that game for a tutorial. Hope you like the idea!
@@orkslayergamedev yeah! Exactly!! I wanna follow some of your footsteps.
I was thinking about you doing another video for the games that you uploaded. A separate video on the behind the scenes of how you made that game, what are your thought process, the codes that gave solution, functions that were used etc. I would love to watch those and in the end i will also be able to make my own version of your game! ❤️
I'll try to live up to your expectations and continue delivering quality content! 🤞🏻
What I can promise besides whole minigame / feature tutorials is insights from - the close-to-release - Field Trip (eg. I plan to show some reuseable code to implement lots of different powerups quickly); then restarting the development of Ork Slayer and documenting the whole process on the channel!
We will get there soon, thanks for sticking with us 🙌🏻❤️
good video😎
Thanks! Glad you liked it! 🙌
hi. what color sheme do you use?
Hey! It's the One Dark Italic style from the One Dark Theme plugin.
You can find it here: plugins.jetbrains.com/plugin/11938-one-dark-theme
@@orkslayergamedev tks
Hey, I'm very new to Python. I was trying to copy your code word for word. I'm halfway the video but when I try to test I get error. It seems that whenever I type "from weapon import iron_sword" it says "unresesolved reference 'weapon' "
Hey there! We usually get this error when the module we want to import is not in the same directory.
If you're sure that all the files are in the same place, you can also try to use "from .weapon import iron_sword" to explicitly say that the file you're looking for is within that local folder. Let me know if it worked!
not the person who asked the question but I had the same problem.
This helped! thanks
Instant sub mode: ON
Awesome, welcome to the channel! 🙌 Thanks for subscribing! 🐍
- [14:53] I would like if you use: `os.system("cls|clear")`
This way if command: `cls` is not defined -like in my linux machine-, it'll fall back to: `clear`
Also I subscribed from this video and had the bell on so I don't miss any coming uploads ;-)
Hey there! Thanks for the nice addition, I didn't know you can pass "cls|clear" as arguement, cool!
And of course I'm happy to welcome you to the channel! 🙌🏻
@@orkslayergamedev one little correction I need to add use "cls||clear" instead of "cls|clear" as the first ors `cls` with `clear` while the other pipes `cls` to `clear`
Right, thanks for the correction! I'll use this trick later on 👌🏻
I think the health bar take you too much I use for
Can you make the repository for this available again? Thanks.
Oh, my bad! I thought it was ready and set to public, thanks for letting me know.
👇🏻 You can access it from now on :)
github.com/orkslayergamedev/python-classes-text-battle
@@orkslayergamedev Thank you, great tutorial btw, forgot to say. :P
Thank you very much, I appreciate it! 🙌🏻
can u make this video for javascript version please? if u already did it please give me the link
My expertise is limited to Python at the moment, unfortunately. Although if anytime in the future I'll deal with javascript, I'll make such a video, promise! 🙏🏻
How did you open the builtins.py file?
Simply double-tap shift in PyCharm, then type builtins.py 🙌🏻
Alternatively, hold ctrl then click any class/method that redirects you to the file
Thank you!
You lost me with the target.hp. Where is hp defined?
Hey 👋🏻 If you wait a couple of seconds in the video, I fix this error at 5:10.
That "hp" should be "health". Since the target is an already initialized character, it will have its health attribute set in the initializer method.
Sorry for the confusion!
can you make it with c++?
Right now only Python fits into the scope of the channel but in case I dwell into C++ anytime, I'll create such a tutorial! Thanks for the suggestion!
"Hero dropped the fists"
....what?...
Take a look at the video at 10:20 again, as I hint an optional coding challenge for the viewers to implement a safety feature that prevents the hero from dropping the default weapon.
You can give it a try or just use this solution:
def drop(self) -> None:
if self.weapon != self.default_weapon:
print(f"{self.name} dropped the {self.weapon.name}!")
self.weapon = self.default_weapon
@@orkslayergamedevYes, thanks you to the solution! Even tho i wasn't confused about it
Glad to hear it, happy coding to you! 🐍
For those who dont want to type out all of the colors because its a slight pain in the ass, here you go:
colors: dict = {"red": "\033[91m", "purple": "\33[95m","blue": "\33[34m", "blue2": "\33[36m","blue3": "\33[96m", "green": "\033[92m","green2": "\033[32m", "yellow": "\33[93m","grey": "\33[37m", "default": "\033[0m", }
In case anybody wants to copy my code or just needs to double-check everything, I have the git repository linked in the description! But thanks for pointing this out 🙏🏻
@@orkslayergamedevI figured you did it on purpose to have people type this themselves. I just didn’t want anyone to deal with typing the colors since they are a little clunky to type in and Visual Studio Code doesn’t auto complete. 😂
Right! I'm guilty as well for copy-pasting the colors in the video, don't worry 😁
If you need auto-completion with VSCode, I recommend GitHub Copilot which is a damn useful addition! It's not free but it's almost like it reads your mind! I don't use it myself but it's popular amongst my colleagues :)
OOP is great. But the text book example of just Dog Cat and Animals makes it boring.
I was wondering how to make something interesting with it.
And the algorithm read my mind.
Exactly! The well-thought way of presentation can give soul to the topic, making it enjoyable. I'm glad you found my video, thanks for sharing your thoughts :)
I really don't like this tutorial. As a beginner this really glosses over a lot of fundamentals that go way over my head. Would not recommend using this unless you already have a fundamental understanding of coding, python and how to use its modules in general
Thank you for sharing your feedback, even if it leans towards the negative side. Starting your coding journey with OOP without a solid understanding of programming fundamentals is not the most effective approach - I've been there too and had to try again with the topic later. I encourage you to look for beginner-friendly resources and establish a strong foundation before delving into more advanced topics like OOP. Once again, thank you for taking the time to provide feedback. Good luck! 🐍
Lefogadom hogy magyar vagy ..
Ezt bizony a videóimban itt-ott előforduló magyar felületek és a csatornanévjegyem magyar fordítása is rögtön elárulja, úgyhogy jó tipp volt :)
import random
class Soldier:
def __init__(self, name, health, strength):
self.name = name
self.health = health
self.strength = strength
def attack(self):
return random.randint(1, self.strength)
def take_damage(self, damage):
self.health -= damage
if self.health
Hey, thanks a lot for sharing your concept, I love it! 🙏🏻
Please let me show you a revised version. I added the army as an attribute to soldiers. This way whenever a soldier dies, he can be removed from his army and he won't be targeted again. Adding a while loop at the end drives the battle until one of the armies lose all their men.
# ------------ code ------------
import random
class Soldier:
def __init__(self, name, health, strength, army):
self.name = name
self.health = health
self.max_health = health
self.strength = strength
self.army = army
self.army.soldiers.append(self)
def attack(self):
return random.randint(1, self.strength)
def take_damage(self, damage):
self.health -= damage
print(f"{self.name} health: {self.health}/{self.max_health}")
if self.health