Classes confusion

Classes confusion

Postby dboxall123 » Wed Aug 07, 2013 5:48 pm

Hi everyone! Does anyone know where I can find a decent tutorial on using classes in Pygame? I've been learning to program with Python 3 and Pygame for just over a month now, and so far I've succeeded in maing only one game (it was Hangman, and the coding was a mess). I found some example code so I tried to copy the style that it was written in, and I'm stuck at the first hurdle. I'm trying to make a 'Snake' game and I can't even get the damn thing to move with an update function(i'm trying to remove the last segment and insert a new one at the front,which I can do if I don't bother with an update function and just write the lines for this inside the while loop.But what's the point in doing someting if you're not doing it properly, right? ) So I think that I need to properly learn about classes, but I can't find anywhere decent to. Most Pygame tutorials don't even go into classes. Anyone now where to learn this and how best to pratice it? It's starting to look like peerhaps I'm not smart enough for all this, but I really would like to prove myself wrong. It's doing my head in!!!
dboxall123
 
Posts: 108
Joined: Fri Jul 12, 2013 5:28 pm

Re: Classes confusion

Postby dboxall123 » Wed Aug 07, 2013 6:17 pm

Here's an example. I'm just trying to get a screen to show up, and I can't evn do that! I decided to control the snake from inside the main loop, but It won't even display the screen!

Code: Select all
import pygame as pg
import random
import os

CELL_SIZE=20
SCREEN_WIDTH=640
SCREEN_HEIGHT=480
CELL_WIDTH=SCREEN_WIDTH//CELL_SIZE
CELL_HEIGHT=SCREEN_HEIGHT//CELL_SIZE

WHITE=(255,255,255)
BLACK=(0,0,0)
RED=(255,0,0)
GREEN=(0,255,0)
DARK_GREEN=(0,155,0)



class Snake(object):
    pass


class Food(object):
    pass


class Control(object):

    def __init__(self):
        os.eviron['SDL_VIDEO_CENTERED'] = 1
        pg.init()
        self.screen=pg.sisplay.set_mode((640,480))
        self.clock=pg.time.Clock()
        self.fps=10
        self.done=False

    def main_loop(self):
        while not self.done:
            self.screen.fill(-1)
            pg.display.flip()


if __name__ == '__main__':
    run_it=Control
    run_it.main_loop()


When I run this, it says that main loop is missing 1 required positional arguments 'self'. WTF? Any help would be much appreciated
Thanks
Dan
dboxall123
 
Posts: 108
Joined: Fri Jul 12, 2013 5:28 pm

Re: Classes confusion

Postby Yoriz » Wed Aug 07, 2013 6:39 pm

I dont know much about pygame, but you should probably learn classes without pygame first.

Code: Select all
run_it=Control
In this line you has asigned run_it to the class Control, it has not made an instance of control because the () call is missing.

Code: Select all
run_it=Control()
is what is needed to make an instance of Control.
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 568
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Classes confusion

Postby dboxall123 » Wed Aug 07, 2013 7:32 pm

Oh yeh, I missed out the (). What a tit I am! Thanks mate!
dboxall123
 
Posts: 108
Joined: Fri Jul 12, 2013 5:28 pm

Re: Classes confusion

Postby Mekire » Wed Aug 07, 2013 11:28 pm

The problems stopping that from running were very tiny. You misspelled display and you mispelled environ. You also set the environment variable to 1 when you actually need to set it to '1'.
Code: Select all
os.environ['SDL_VIDEO_CENTERED'] = '1'

The biggest thing I want to mention here is you didn't add an event loop. No matter how simple the program; even if all it does is show a screen; it needs an event loop. If you don't have one the game locks up.

I have a repo of a set of Pygame examples all written with classes. You could give them a look. They range from very basic to slightly advanced.
https://github.com/Mekire/meks-pygame-samples
They are examples rather than tutorials, but maybe they will get you headed in the right direction.

As Yoriz said though, if you don't already understand how classes work, you should learn that first and then come back to applying them to Pygame.

Here is your previous code functioning:
Code: Select all
import os
import sys
import random
import pygame as pg


CELL_SIZE =20
SCREEN_SIZE = (SCREEN_WIDTH,SCREEN_HEIGHT) = (640,480)
CELL_WIDTH = SCREEN_WIDTH//CELL_SIZE
CELL_HEIGHT = SCREEN_HEIGHT//CELL_SIZE

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
DARK_GREEN = (0,155,0)



class Snake(object):
    pass


class Food(object):
    pass


class Control(object):
    def __init__(self):
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        pg.init()
        self.screen = pg.display.set_mode(SCREEN_SIZE)
        self.clock = pg.time.Clock()
        self.fps = 60
        self.done = False

    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True

    def main_loop(self):
        while not self.done:
            self.event_loop()
            self.screen.fill(-1)
            pg.display.flip()
            self.clock.tick(self.fps)


if __name__ == '__main__':
    run_it = Control()
    run_it.main_loop()
    pg.quit()
    sys.exit()

-Mek
User avatar
Mekire
 
Posts: 823
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Classes confusion

Postby dboxall123 » Wed Aug 07, 2013 11:57 pm

Wow, cheers Mek! I have been looking into classes quite a bit recently, although I'm still not really 100% sure about how to use them. And thanks for them examples, they will be really helpful. I have another question if you don't mind. I've already got a little further with my snake game, but I am having a bit of bother moving my snake. Here is code:

Code: Select all
import pygame as pg
import random
import os

segment_pic=pg.image.load('snake_segment.png')

CELL_SIZE=20
SCREEN_WIDTH=640
SCREEN_HEIGHT=480
CELL_WIDTH=SCREEN_WIDTH//CELL_SIZE
CELL_HEIGHT=SCREEN_HEIGHT//CELL_SIZE

WHITE=(255,255,255)
BLACK=(0,0,0)
RED=(255,0,0)
GREEN=(0,255,0)
DARK_GREEN=(0,155,0)



class SnakeSegment(pg.sprite.Sprite):
    #Create seperate snake segments
    def __init__(self,x,y):
        pg.sprite.Sprite.__init__(self)
        self.image = segment_pic
        self.rect=self.image.get_rect()
        self.rect.x=x
        self.rect.y=y
       

class Food(object):
    pass


class Control(object):

    def __init__(self):
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        pg.init()
        self.screen=pg.display.set_mode((640,480))
        self.screen.fill(BLACK)
        self.clock=pg.time.Clock()
        self.fps=2
        self.done=False

        self.segments_list = []
        self.segments=pg.sprite.Group()
        for i in range(15):
            self.segment=SnakeSegment(300-(CELL_SIZE*i),100)
            self.segments.add(self.segment)
            self.segments_list.append(self.segment)

    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True

    def main_loop(self):
        while not self.done:
            self.event_loop()
            self.update_snake()
            self.segments.draw(self.screen)
           
            pg.display.flip()
           
            self.clock.tick(self.fps)

    def update_snake(self):
        #Remove last item from segment list and insert new
        #one at the front
        self.x_change = CELL_SIZE
        self.y_change = 0

        #this is the problem.For some reason in the first frame
        #it removes the last segment, but for every othee frame
        #afterwards it doesn't remove any segments, so my snake
        #just keeps growing
        self.old_segment = self.segments_list.pop()
        self.segments.remove(self.old_segment)

        self.x = self.segments_list[0].rect.x + self.x_change
        self.y = self.segments_list[0].rect.y + self.y_change

        self.segment = SnakeSegment(self.x,self.y)
        self.segments_list.insert(0,self.segment)
        self.segments.add(self.segment)
       
       
       
       

if __name__ == '__main__':
    run_it=Control()
    run_it.main_loop()
    pg.quit()


The weird thing with this code is that I've done the exact same thing in a seperate file, but without putting it into a function or class and it works perfectly, ie removes the last segment, creates a new segment and inserts it at the front. What am i doing wrong here?
dboxall123
 
Posts: 108
Joined: Fri Jul 12, 2013 5:28 pm

Re: Classes confusion

Postby Mekire » Thu Aug 08, 2013 1:02 am

You are just forgetting to clear the screen every frame. Add a self.screen.fill(0) in your main loop. Other than that, the snake (update method and all) should really be a completely separate class. In more complex projects Control is just what it sounds like; it manages control flow, and does nothing but tell the game what part is currently updating. Don't get to used to putting logic directly inside it as this will not scale well.

-Mek
User avatar
Mekire
 
Posts: 823
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Classes confusion

Postby dboxall123 » Thu Aug 08, 2013 1:45 am

Oh yeh. Of course. What a fool! As for the game logic, I will be moving it now. I started off trying to do this in a seperate class, and when it wouldn't work I moved it down to the main loop, just to see if it was actually a problem with the class or not. It always seems to be someting really silly and very simple to fix lol. Thanks Mek!

Dan
dboxall123
 
Posts: 108
Joined: Fri Jul 12, 2013 5:28 pm

Re: Classes confusion

Postby micseydel » Thu Aug 08, 2013 2:23 am

It took me about 4 years of programming before I started to understand classes (object oriented programming) myself, and then it didn't really click until I learned about it in a university course specifically dedicated to OOP. In fact, it's one of the few classes I think was useful.
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 929
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to Game Development

Who is online

Users browsing this forum: No registered users and 2 guests