Computer Science Canada

Pygame Graphics

Author:  Aange10 [ 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.

Author:  Aange10 [ 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)

Author:  mirhagk [ 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.

Author:  Aange10 [ 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?

Author:  mirhagk [ 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.

Author:  Aange10 [ 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.

Author:  Senecide [ 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).

Author:  Aange10 [ 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?

Author:  Senecide [ 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.

Author:  Aange10 [ 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

Author:  Senecide [ 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.

Author:  QuantumPhysics [ 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

Author:  Aange10 [ 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.

Author:  QuantumPhysics [ 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.

Author:  mirhagk [ 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)

Author:  Aange10 [ Wed Jun 06, 2012 3:01 pm ]
Post subject:  RE:Pygame Graphics

Haha I honestly don't have a desire to make games. Right now I'm just exploring a lot of concepts. Mainly the things I'm discovering in Udacity, problems on Project Euler, etc.

A game is much too involved. I've written enough of an rpg to know that I don't want to make a game. Maybe later, with a team of friends and with me having more knowledge on what is actually happening, and hopefully some grasp of 3d engines.

I really have a lot of concepts I want to learn. Games seem like something I'd do with a group of people later on in my life.

Author:  mirhagk [ Thu Jun 07, 2012 8:15 am ]
Post subject:  RE:Pygame Graphics

Games provide an interesting way to show off some cool algorithms, and I've learned that you can design a game such that no artwork or time consuming data entry is needed, you can design it to all be algorithmic based, which is pretty cool. (for instance throw in some types of weapons, and adjectives and have the computer through those together to create weapons, with the power being equal to points on a function).

But yeah I'm kinda getting in the same spot, there are a lot of concepts I want to learn, and that's why I'm working on a kind of game engine that provides things like scripting, artificial intelligence, parallel programming, and all those goodies that are fun to write.

I'd suggest looking into some of the things C# has to offer (lambdas, LINQ, cryptography, reflection etc)

Author:  Aange10 [ Thu Jun 07, 2012 8:21 am ]
Post subject:  RE:Pygame Graphics

I have been thinking about picking up on C# (btw, Python has lambdas!). And that actually sounds rather interesting, the algorithm games.

Author:  Amarylis [ Thu Jun 07, 2012 9:19 am ]
Post subject:  RE:Pygame Graphics

I'm very happy that Udacity has a class on algorithms- that's one thing among many that my school is seriously lacking in, and I find that it's something quite crucial...

Author:  mirhagk [ Thu Jun 07, 2012 9:36 am ]
Post subject:  RE:Pygame Graphics

Actually algorithms are not as useful as you'd think. The majority of programming jobs are creating applications or maintaining software, both of which you use built in tools (you should never be implementing your not sorting, cryptography or pretty much any other algorithm on your own in a production setting, too much risk). It is a really fun thing to learn though, and really sets you apart from people who merely know how to write code.

@Aagne10 if you wanted you could actually join the project and add whatever algorithms you think would be useful in a video game library. The general idea of it for me was to have fun implementing algorithms, but also create a game library that can be used alongside another engine (or an in-house one) that implements all the tools and concepts that aren't normally in games, but would be awesome to have (scripting, modding, good artificial intelligence, I even want to experiment with creating people from values, like in skyrim, or the sims)

clarification: I'm not saying learning algorithms isn't useful, just saying they are less used that one would think, since most of programming is maintaining rather than creating new products from scratch. The good jobs are creating though, so definitely learn it

Author:  Amarylis [ Thu Jun 07, 2012 9:50 am ]
Post subject:  RE:Pygame Graphics

I'd love to learn a thing or two from you about the process of algorithm development, if you'd be willing to teach

Author:  mirhagk [ Thu Jun 07, 2012 11:13 am ]
Post subject:  RE:Pygame Graphics

I'd be willing to teach, but I'm by no means an expert. If you want to learn something I can probably put together a tutorial or something and post it here. What would you like to learn?

Author:  Amarylis [ Thu Jun 07, 2012 2:10 pm ]
Post subject:  RE:Pygame Graphics

Everything you're willing to teach. Literally.

Author:  Aange10 [ Thu Jun 07, 2012 2:14 pm ]
Post subject:  RE:Pygame Graphics

Haha I too will read and provide feed back Wink

Author:  mirhagk [ Sun Jun 10, 2012 3:58 pm ]
Post subject:  RE:Pygame Graphics

Alright I'm currently working on a project that both of you guys will probably like.Once I go public with it I will write a tutorial explaining how it all works.


: