Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Pygame Graphics
Index -> Programming, Python -> Python Help
Goto page 1, 2  Next
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Aange10




PostPosted: Thu May 31, 2012 1:13 pm   Post subject: Pygame Graphics

Is anybody here familiar with the pygame library? http://www.pygame.org/docs/

If so, I need a bit of help with my program. I tried making my program based off a program they used in one of their tutorials, but I seem to still have a problem moving/drawing things.
Sponsor
Sponsor
Sponsor
sponsor
Aange10




PostPosted: Fri Jun 01, 2012 12:06 pm   Post subject: RE:Pygame Graphics

Anyways, if anybody does happen to know about pygame, or would like to learn it, the link is ^. And here is where I'm having problems:
Python:

'''
Created on May 30, 2012

@author: David
'
''
import os, pygame
from pygame.locals import *

#function to create our resources
def loadImage(name, colorkey=None):
    fullname = os.path.join(name)
    try:
        image = pygame.image.load(fullname).convert()
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()



# Class for paddle,
class Paddle (pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
        self.image, self.rect = loadImage ("paddle.jpg",-1)
        self.acceleration = 10 # X acceleration
        self.rect.midtop = [0,height]
       
    def update(self):
        "move the fist based on input"
        pos = 0
        # Go through the events pygame has
        for event in pygame.event.get():
            # If the event is a keydown and is value is == (x):
            if event.type == KEYDOWN and event.key == K_LEFT:
                pos = self.acceleration * -1
                return
            elif event.type == KEYDOWN and event.key == K_RIGHT:
                pos = self.acceleration
                return
            # Move the rectangle
            self.rect.move ([pos,0])

class Ball (pygame.sprite.Sprite):
    def __init__ (self):
        pygame.sprite.Sprite.__init__(self) # call Sprite initalizer
        self.image, self.rect = loadImage ("ball.jpg",-1)
        self.acceleration = [10,10] # X, Y accelerations
        self.velocity = [self.acceleration[0],self.acceleration[1]]
   
    def update (self):
        # Make sure it doesn't go off walls
        for i in range (2):
            if self.velocity [i] + self.rect [i] > screen.get_size() [i] or self.velocity [i] + self.rect [i] < i:
                self.velocity [i] *= -1
               
        # Check for collision with bricks or paddle
        didColide = 0
        for i in pygame.sprite.spritecollide(self, brickGroup, 1):
             # Could play brick break sound
            didColide = 1
            # Let bricks drop things
            i.die ()
           
        if didColide:
            self.colide()
        if pygame.sprite.spritecollide(self, paddleGroup, 0):
            # Bounce sound off paddle
            self.colide()
               
        self.rect.move (self.velocity)
       
    def colide (self):
        # Handles collision
        self.velocity [1] *= -1
       
class Brick (pygame.sprite.Sprite):
    def __init__ (self):
        pygame.sprite.Sprite.__init__(self) # Initalize
        self.image, self.rect = loadImage ("brick.jpg",-1)
   
    def die (self):pass # Drop loot if decided
   

# Global variable
screenSize = width, height = [500,600]
screen = pygame.display.set_mode(screenSize)
# Create groups
brickGroup = pygame.sprite.Group ()
ballGroup = pygame.sprite.Group ()
paddleGroup = pygame.sprite.Group ()   

def main ():
    # initalize the game
    pygame.init()
    clock = pygame.time.Clock()
    paddle = Paddle()
    ball = Ball ()
    ballGroup.add (ball)
    paddleGroup.add (paddle)
   
    # Make a grid of bricks
    brick = [[0,0,0,0,0],
             [0,0,0,0,0],
             [0,0,0,0,0],
             [0,0,0,0,0],
             [0,0,0,0,0] ]
    for y in range (4):
        for x in range (4):
            brick [y] [x]= Brick ()
            brickGroup.add (brick [y] [x])
           
    pygame.display.set_caption('Brick Breaker')
    pygame.mouse.set_visible(0)
           
   

    # Create background
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((255, 250, 250))

    #Display The Background
    screen.blit(background, (0, 0))
    pygame.display.flip()
   
    # main loop
    while 1:
        clock.tick(60) # keeps us from going faster than 60 fps
       
        # update objects
        paddleGroup.update()
        ballGroup.update()
        # draw objects
        brickGroup.draw (background)
        paddleGroup.draw(background)
        ballGroup.draw (background)
        screen.blit(background, (0,0))
        pygame.display.flip() # View.Update
        # handle exit
        for event in pygame.event.get():
            if event.type == QUIT:
                return
       
#this calls the 'main' function when this script is executed
if __name__ == '__main__': main()


There are no errors, I'm just not quite sure what's wrong with it. Pygame didn't have a place for me to ask =/ (And I know it's me, not the library, lol)
mirhagk




PostPosted: Fri Jun 01, 2012 12:45 pm   Post subject: RE:Pygame Graphics

I used python for the course I just finished up, so I might actually learn python, so maybe I'll take a look at this for you.
Aange10




PostPosted: Fri Jun 01, 2012 12:54 pm   Post subject: RE:Pygame Graphics

Why thankyou Mirhagk. And by chance, was any of your courses from www.udacity.com?
mirhagk




PostPosted: Fri Jun 01, 2012 1:26 pm   Post subject: RE:Pygame Graphics

Heck yes it was. Programming Languages (and cryptography, but I didn't have time to finish that and write the exam). The exam is still open for learning to program, or whatever that one course is, so I might take that exam because it looks pretty trivial. I might even try them all lol so I can learn python, and maybe get some certificates.
Aange10




PostPosted: Fri Jun 01, 2012 1:34 pm   Post subject: RE:Pygame Graphics

I have one certificate xD. I completed a course last hexamester. This hexamester I took Programming Languages, Web application Engineering, Cryptography, and Design Of Computer Programs. But I blew off Web app eng, I don't think I watched a single unit.

I was keeping up with Cryptography, but I stopped it. I focused on Design of Computer Programs, which is amazing. I learned a ton, but I didn't properly go through the course like I should have; I just skimmed the units. So I won't be recieving any certificates because I couldn't pass the finals for Design of Comp. Programs. It's hard! But I learned a lot.

Into pygame, however, i just found it 2 days ago. I went to their tutorial section and read through it, but I'm having problems with the 'Sprite module' atm (at leas that's my guess). A lot of the base for my code I took from 'Chimp Tutorial, line by line'. I understand what most of it does, the only part I don't understand is the color scheme thing on the image loading function.

But if you decide to learn Python graphics, and pick up on pygame, try making a paddleball or something. Then we could collaborate and figure out what is wrong with my code.
Senecide




PostPosted: Fri Jun 01, 2012 9:12 pm   Post subject: Re: Pygame Graphics

I just took a quick look, and it seems to me that you aren't specifying the coordinates for each sprite's rect. I suggest adding x and y parameters in your init methods and assign them to the sprite's rect, this can be helpful, especially with your bricks. Something like self.rect.center = (x, y) should work. I also noticed you used self.rect.move, and for that to work you need to assign that back to your rect. Something like self.rect = self.rect.move(x, y).
Aange10




PostPosted: Sat Jun 02, 2012 12:56 pm   Post subject: Re: Pygame Graphics

Thankyou Sene, I've got most of it working. But I can't seem to find out why the paddle wont draw. It has a picture, and a defined .rect. The group its in is being .draw to the screen.

Also, can you see why it also isn't looking at my input?



Brick Breaker.rar
 Description:

Download
 Filename:  Brick Breaker.rar
 Filesize:  13.36 KB
 Downloaded:  294 Time(s)

Sponsor
Sponsor
Sponsor
sponsor
Senecide




PostPosted: Sat Jun 02, 2012 2:02 pm   Post subject: Re: Pygame Graphics

The paddle sprite doesn't appear because it's colorkey is being set as the same colour of the image you are trying to display. When a certain colour is assigned to an image's colorkey, pygame ignores that certain colour. In your case, you seem to have a loadImage function that handles colorkey. When loading the paddle's image, set your colorkey parameter to None or 0 instead of -1, which disables setting colorkey.

Another note is that in your paddle's update method, the pos variable always resets to 0 because you're calling return whenever the user presses left or right. That basically exits the update method before it has a chance to adjust the rect. So I suggest removing the return calls.
Aange10




PostPosted: Sat Jun 02, 2012 2:24 pm   Post subject: RE:Pygame Graphics

ahh, that was suppose to be break! Thankyou.

Everything seems to be working. Thanks for the help! This code will be of good reference until I memorize everything.

I was looking at the http://www.pygame.org/docs/ref/event.html page for events, but I couldn't find one that would read a button 'held' event. How would I detect that? And also my event.type == QUIT: statement at the end of my main loop doesn't seem to work. So I can't close the window, why is that?


Thanks for the help Sene
Senecide




PostPosted: Sat Jun 02, 2012 3:21 pm   Post subject: Re: Pygame Graphics

You can use the method pygame.key.get_pressed(), which returns a huge list of all the buttons pressed. You can assign the list in a variable, and then then have if statements to check if a key in the list is True. The list is conveniently stored in the order of pygame's keys. For example, keys = pygame.key.get_pressed() ... if keys[ pygame.K_LEFT]: then ...

With the exiting problem, I think pygame can sometimes be glitchy. But I suggest adding pygame.quit() after your while loop, which should close the window. Also I think the event.get() in your paddle's update method might interfere with the event.get() in your main loop. But thats only my suspicion.
QuantumPhysics




PostPosted: Tue Jun 05, 2012 1:57 pm   Post subject: RE:Pygame Graphics

Aange, so you made brick breaker in turing... now your moving on to python? even though it is easy to read it is more of a scripting language than a programming language so anyways good luck
Aange10




PostPosted: Tue Jun 05, 2012 4:37 pm   Post subject: RE:Pygame Graphics

@Quantum. No, I'm not remaking brick breaker. Well, I am, but not for the purpose you might have in mind. I just want to explore the pygame library.

Can you elaborate on why it is a scripting language and not much of a programming language?


And I have done more things than just brick breaker in Turing. I didn't just create it, then jump and do it in Python. I believe there was about 8 months, an RPG in Turing, and many smaller projects inbetween.
QuantumPhysics




PostPosted: Wed Jun 06, 2012 10:56 am   Post subject: RE:Pygame Graphics

Because you can load html script into it and create bots for running and creating accounts on websites. Its very accessible to the CursorPosition command, im sorry if you didn't understand what i meant by this but i know what im talking about i just dont know how to put it properly in words.
mirhagk




PostPosted: Wed Jun 06, 2012 11:06 am   Post subject: RE:Pygame Graphics

Python is interpreted, and the syntax is easy to use for smaller projects, I assume that's why he called it a scripting language?

Python really should be a replacement for Turing, not the next step. The syntax is similar, and it's used for a similar purpose (to learn). After experimenting with this I'd suggest going to C# and XNA if you're interested in making games (you can run said games on your xbox360 if you like)
Display posts from previous:   
   Index -> Programming, Python -> Python Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 2  [ 25 Posts ]
Goto page 1, 2  Next
Jump to:   


Style:  
Search: