Advertisement

Code review for Object Orientation

Started by June 06, 2014 04:16 AM
4 comments, last by DavitosanX 10 years, 7 months ago

I have never truly grasped the concept of object orientation. I tend to make classes that don't make much sense, or I fail to encapsulate correctly. I think I'm getting better at it, but I'm open to suggestions. In the following code, do you think I'm being correctly object oriented? I really appreciate any help.


import pygame
from pygame.locals import *



class Ball:

    def __init__(self,imageFile,position_arg):
        self.image = pygame.image.load(imageFile)
        self.position = (position_arg)



class AssetManager:

    def load_ball(self,imageFile,position):
        return Ball(imageFile,position)



class Game:

    def __init__(self,resolution,caption):

        self.screen = pygame.display.set_mode(resolution)
        pygame.display.set_caption(caption)
        self.clock = pygame.time.Clock()
        self.running = True
        self.gray = (220,220,220)

    def check_events(self):

        for event in pygame.event.get():
            if event.type == QUIT:
                self.running = False

    def draw_screen(self,ball):
        self.screen.fill(self.gray)
        self.screen.blit(ball.image,ball.position)
        pygame.display.flip()

    def main_loop(self,framerate,assets):

        ball = assets.load_ball('ball.png',(350,250))

        while self.running:

            self.clock.tick(framerate)
            self.check_events()

            self.draw_screen(ball)

        pygame.quit()



assets = AssetManager()
game = Game((800,600),"Game")
game.main_loop(60,assets)

Starting out in game programming? Me too! Check out my blog, written by a newbie, for the newbies. http://myowngamejourney.blogspot.mx/

Also, if you don't mind a 5 seconds ad, here's a great free ebook for beginners on the subject of pygame: http://bit.ly/19Bem2q

It's pretty hard to say from such a small program. You are hardly going to run into any of the pitfalls (or benefits, for that matter) of object orientation in 50 lines of source code...

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Advertisement
It's always best to really understand a concept before trying to use it in a complex scenario. Then you have a solid foundation to build on, and can be as complex as you want by manipulating the basic building blocks of that understanding.

An apple is an object. An apple is also a type of fruit. So an apple belongs to the class of Fruit.

class Fruit:

All fruit have some common attributes like color and taste and climate they grow well in. These are member variables (variables inside of a class).

self.color = color
self.taste = taste
self.climate= climate

Now, functions are actions, so what actions can fruit perform, or what actions can be performed on fruit?

def beEaten():

def grow():

When you initialize the object with def __init__ you are just assigning default attributes to your object. By default fruit have a specific color and taste.

Sometimes objects can inherit attributes from other objects.

If you have a human class and an alien class

class Human:
class Alien:

You can make aliens inherit certain attributes from the human class by extending the human class. This gives the alien class all of the variables and functions of the human class, with the ability to add more attributes to the alien objects themselves.


Your ball is being initialized to have a default image and a default position.

Your asset manager class manages your assets.

To make it short and simple, game stuff goes in a game class, fruit stuff goes in a fruit class, GUI stuff goes in a GUI class, math stuff goes in a math class etc.

I have a rule for myself to name variables like nouns, functions like verbs, and classes like nouns also. In some special cases I might change it up.

I would do:

ball.asset.load_ball()

Since a ball is one asset. Just try to name things in a way that reads like a real sentence.

redApple = Fruit("red","sweet")
greenApple = Fruit("green","sour")

redApple.Grow(1,"inches")
greenApple.Grow(.25,"inches)

redApple.beEaten().quickly (or however)

Hope this helps.

note: ball.load() sounds better

They call me the Tutorial Doctor.

It's always best to really understand a concept before trying to use it in a complex scenario. Then you have a solid foundation to build on, and can be as complex as you want by manipulating the basic building blocks of that understanding.

Good advice, but I'm not so sure that the rest of your post really follows through on this promising start.

Object orientation is a modelling technique aimed at producing code of rich, active "objects" rather than dumb, passive data structures. As swiftcoder mentions, this program is probably too small to really start demonstrating what this is about.

An apple is an object. An apple is also a type of fruit. So an apple belongs to the class of Fruit.

That really depends on the program. For a platformer game where different fruit give you different points but are otherwise interchangeable, that is fine. For a simulation program that is designed to predict crop yields or diseases in orchards, this might not be appropriate.

You can make aliens inherit certain attributes from the human class by extending the human class. This gives the alien class all of the variables and functions of the human class, with the ability to add more attributes to the alien objects themselves.

That would be a surprising use of inheritance. Something like a Humanoid base class would make more sense, if inheritance is appropriate at all.

To make it short and simple, game stuff goes in a game class, fruit stuff goes in a fruit class, GUI stuff goes in a GUI class, math stuff goes in a math class etc.

Again, quite a simplification, and I don't know what exactly counts as "game stuff" or "GUI stuff". Math generally consists of functions and simple data structures (vectors, matrices), so I don't see the value of a "Math class". This might be suitable for a small game, but for a medium sized game I'd be wary of trying to pack too much things into general classes like that.

Yeah, it is a very simplified example. Humanoid would be best (just went with the first example that came to me.

Being that the original post was short, I tried to keep it general for understanding purposes (it worked for me). Not trying to be too in-depth, and I doubt I could get as in-depth as you perhaps could.

But I have written some object oriented code with this understanding (that works well) after struggling myself to simplify for myself how object orientation works.

Indeed, general classes can get messy.

They call me the Tutorial Doctor.

I appreciate your responses. Yes, the program is very short, but I hope you understand that I wanted first to know if I wasn't making any terrible mistakes at the very beginning, since I'm going to build upon this. I will make a more thorough example and post it, or maybe a link to it. If you like reviewing code, you might want to take a look :D

Starting out in game programming? Me too! Check out my blog, written by a newbie, for the newbies. http://myowngamejourney.blogspot.mx/

Also, if you don't mind a 5 seconds ad, here's a great free ebook for beginners on the subject of pygame: http://bit.ly/19Bem2q

This topic is closed to new replies.

Advertisement