1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Wir sind dabei - mit Pyra Prototyp!

    Für weitere Informationen hier klicken!
    Dismiss Notice

PyGame - Two issues

Discussion in 'Python / PyGame' started by Silverhawk11011, Jul 27, 2011.

  1. Silverhawk11011

    Silverhawk11011 Still Fresh

    Joined:
    Jul 27, 2011
    Messages:
    11
    I would first like to say hello to everyone in the community, this is my first time here, and I like what ive been reading, there are some very bright people here. I am a programming student and currently taking game programming and working on a game assignment. The assignment is to add sounds to the game (.ogg - done) and play sounds on colission of sprites (done), create an additional sprite to get bonus points (first problem), and randomize the size/scale of the sprtes that come onto the screen. So as of right now I have tried to add a new sprite called Treasure. I have the treasure.gif file saved in the correct location (along with the other .gif files), and I thought I coded properly. However I am getting this error upon starting the game (the game opens to the main intro screen) When I click to start playing I get an error. I hope someone is able to help :p .


    --- File "C:\Users\Steve\workspace\Assignment2\src\mailPilot.py", line 35, in __init__


    self.image = pygame.image.load("I:\School Work\Term 5\Game Programming\Project 2\Images\treasure.gif")



    pygame.error: Couldn't open I:\School Work\Term 5\Game Programming\Project 2\Images reasure.gif



    Below in green are all areas with the new code for the treasure sprite, if I remove all instances of treasure the game runs fine.


    I thought it may have been a typo but I could not find one at all. Here is the code below :


    """



    mail pilot - Project 2






    """






    import pygame, random



    pygame.init()






    screen = pygame.display.set_mode((640, 480))






    class Plane(pygame.sprite.Sprite):



    def __init__(self):



    pygame.sprite.Sprite.__init__(self)



    self.image = pygame.image.load("I:\School Work\Term 5\Game Programming\Project 2\Images\plane.gif")



    self.image = self.image.convert()



    self.rect = self.image.get_rect()






    if not pygame.mixer:



    print "problem with sound"



    else:



    pygame.mixer.init()



    self.sndCoins = pygame.mixer.Sound("I:\School Work\Term 5\Game Programming\Project 2\Sounds\coins.ogg")



    self.sndExplosion = pygame.mixer.Sound("I:\School Work\Term 5\Game Programming\Project 2\Sounds\explosion.ogg")



    self.sndEngine = pygame.mixer.Sound("I:\School Work\Term 5\Game Programming\Project 2\Sounds\engine.ogg")



    self.sndEngine.play(-1)






    def update(self):



    mousex, mousey = pygame.mouse.get_pos()



    self.rect.center = (mousex, 430)






    """This is the new sprite added in"""


    class Treasure(pygame.sprite.Sprite):


    def __init__(self):


    pygame.sprite.Sprite.__init__(self)


    self.image = pygame.image.load("I:\School Work\Term 5\Game Programming\Project 2\Images\treasure.gif")


    self.image = self.image.convert()


    self.rect = self.image.get_rect()


    self.reset()


    self.dy = 5


    def update(self):


    self.rect.centery += self.dy


    if self.rect.top > screen.get_height():


    self.reset()


    def reset(self):


    self.rect.top = 0


    self.rect.centerx = random.randrange(0, screen.get_width())


    class Island(pygame.sprite.Sprite):


    def __init__(self):


    pygame.sprite.Sprite.__init__(self)


    self.image = pygame.image.load("I:\School Work\Term 5\Game Programming\Project 2\Images\island.gif")


    self.image = self.image.convert()


    self.rect = self.image.get_rect()


    self.reset()


    self.dy = 5


    def update(self):


    self.rect.centery += self.dy


    if self.rect.top > screen.get_height():


    self.reset()


    def reset(self):


    self.rect.top = 0


    self.rect.centerx = random.randrange(0, screen.get_width())


    class Cloud(pygame.sprite.Sprite):


    def __init__(self):


    pygame.sprite.Sprite.__init__(self)


    self.image = pygame.image.load("I:\School Work\Term 5\Game Programming\Project 2\Images\Cloud.gif")


    self.image = self.image.convert()


    self.rect = self.image.get_rect()


    self.reset()


    def update(self):


    self.rect.centerx += self.dx


    self.rect.centery += self.dy


    if self.rect.top > screen.get_height():


    self.reset()


    def reset(self):


    self.rect.bottom = 0


    self.rect.centerx = random.randrange(0, screen.get_width())


    self.dy = random.randrange(3, 8)


    self.dx = random.randrange(-2, 2)


    class Ocean(pygame.sprite.Sprite):


    def __init__(self):


    pygame.sprite.Sprite.__init__(self)


    self.image = pygame.image.load("I:\School Work\Term 5\Game Programming\Project 2\Images\ocean.gif")


    self.rect = self.image.get_rect()


    self.dy = 5


    self.reset()


    def update(self):


    self.rect.bottom += self.dy


    if self.rect.bottom >= 1440:


    self.reset()


    def reset(self):


    self.rect.top = -960


    class Scoreboard(pygame.sprite.Sprite):


    def __init__(self):


    pygame.sprite.Sprite.__init__(self)


    self.lives = 5


    self.score = 0


    self.font = pygame.font.SysFont("None", 50)


    def update(self):


    self.text = "planes: %d, score: %d" % (self.lives, self.score)


    self.image = self.font.render(self.text, 1, (255, 255, 0))


    self.rect = self.image.get_rect()


    def game():


    pygame.display.set_caption("Mail Pilot!")


    background = pygame.Surface(screen.get_size())


    background.fill((0, 0, 0))


    screen.blit(background, (0, 0))


    plane = Plane()


    """defining the variable"""


    treasure = Treasure()


    island = Island()


    cloud1 = Cloud()


    cloud2 = Cloud()


    cloud3 = Cloud()


    ocean = Ocean()


    scoreboard = Scoreboard()


    """defining the sprite groups"""


    friendSprites = pygame.sprite.Group(ocean, treasure, island, plane)


    cloudSprites = pygame.sprite.Group(cloud1, cloud2, cloud3)


    scoreSprite = pygame.sprite.Group(scoreboard)


    clock = pygame.time.Clock()


    keepGoing = True


    while keepGoing:


    clock.tick(30)


    pygame.mouse.set_visible(False)


    for event in pygame.event.get():


    if event.type == pygame.QUIT:


    keepGoing = False


    #check collisions


    """defining collision with new sprite"""


    if plane.rect.colliderect(treasure.rect):


    plane.sndCoins.play()


    treasure.reset()


    scoreboard.score += 500


    if plane.rect.colliderect(island.rect):


    plane.sndCoins.play()


    island.reset()


    scoreboard.score += 100


    hitClouds = pygame.sprite.spritecollide(plane, cloudSprites, False)


    if hitClouds:


    plane.sndExplosion.play()


    scoreboard.lives -= 1


    if scoreboard.lives <= 0:


    keepGoing = False


    for theCloud in hitClouds:


    theCloud.reset()


    friendSprites.update()


    cloudSprites.update()


    scoreSprite.update()


    friendSprites.draw(screen)


    cloudSprites.draw(screen)


    scoreSprite.draw(screen)


    pygame.display.flip()


    plane.sndEngine.stop()


    #return mouse cursor


    pygame.mouse.set_visible(True)


    return scoreboard.score


    def instructions(score):


    pygame.display.set_caption("Mail Pilot!")


    plane = Plane()


    ocean = Ocean()


    allSprites = pygame.sprite.Group(ocean, plane)


    insFont = pygame.font.SysFont(None, 50)


    insLabels = []


    instructions = (


    "Mail Pilot. Last score: %d" % score ,


    "Instructions: You are a mail pilot,",


    "delivering mail to the islands.",


    "",


    "Fly over an island to drop the mail,",


    "but be careful not to fly too close",


    "to the clouds. Your plane will fall ",


    "apart if it is hit by lightning too",


    "many times. You can also collect",


    "treasure chest to gain a nice bonus.",


    "Steer with the mouse.",


    "",


    "good luck!",


    "",


    "click to start, escape to quit..."


    )


    for line in instructions:


    tempLabel = insFont.render(line, 1, (255, 255, 0))


    insLabels.append(tempLabel)


    keepGoing = True


    clock = pygame.time.Clock()


    pygame.mouse.set_visible(False)


    while keepGoing:


    clock.tick(30)


    for event in pygame.event.get():


    if event.type == pygame.QUIT:


    keepGoing = False


    donePlaying = True


    if event.type == pygame.MOUSEBUTTONDOWN:


    keepGoing = False


    donePlaying = False


    elif event.type == pygame.KEYDOWN:


    if event.key == pygame.K_ESCAPE:


    keepGoing = False


    donePlaying = True


    allSprites.update()


    allSprites.draw(screen)


    for i in range(len(insLabels)):


    screen.blit(insLabels, (50, 30*i))





    pygame.display.flip()






    plane.sndEngine.stop()



    pygame.mouse.set_visible(True)



    return donePlaying






    def main():



    donePlaying = False



    score = 0



    while not donePlaying:



    donePlaying = instructions(score)



    if not donePlaying:



    score = game()









    if __name__ == "__main__":



    main()









    The second problem is randomizing the size of the sprites, I cant seem to find anything in my text on doing this. The only thing I could think of is creating multiple .gif files with different sizes; However my Prof informed me that this would not count
    :) .





    I really hope someone has come across this problem before and could help. Thank you in advance to anyone who is taking the time to read this.
     
  2. Tempel

    Tempel Active Member

    Joined:
    Dec 30, 2008
    Messages:
    670
    First: Welcome!


    Second: I think you may be in the wrong place. This forum is for the Pandora handheld, and this specific board is about using Python on the Pandora. You should probably look for a community dedicated to Python if you want help with it, but since we're here, I'll try to help you through this problem :) .


    Third: You should put that code inside code tags, so that indentation is preserved. As I'm sure you know, indentation is critical in Python, and it's hard for me to read the code without it.


    Fourth: If you're not familiar with the available documentation, you should become familiar with it. The Python standard library is immense, and very useful. The Pygame documentation will be critical for your assignments.


    As for your actual questions: Your sprite isn't being loaded due to special characters. In an ordinary Python string, the backslash (\) is used to indicate special characters. So '\n' is a newline, '\t' is a tab, and '\\' is a literal backslash. You can see where the problem occurs in your error message: "Images\treasure.gif" is printed as "Images reasure.gif" because the '\t' was replaced with a tab. The easiest way to solve this is to simply put 'r' in front of your string:



    Code:
    self.image = pygame.image.load(r"I:\School Work\Term 5\Game Programming\Project 2\Images\treasure.gif")
    This makes it a "raw string", which causes Python to ignore the special character codes. Another solution would be to replace all backslashes with double backslashes in all of your file paths. But the best solution is probably to use the builtin os.path module to construct your file paths (specifically os.path.join) because this will work on any platform, no matter what file path convention that platform uses.


    To randomize sprite size, you'll have to read that documentation I mentioned ;) . This is an assignment, so I don't want to help you too much, but I will point you to the builtin random module and Pygame's transform module. Good luck!
     
  3. Silverhawk11011

    Silverhawk11011 Still Fresh

    Joined:
    Jul 27, 2011
    Messages:
    11
    I tried both the r and then // neither worked. I will try the os.path.join next :)
     
  4. Caine

    Caine Advanced Member

    Joined:
    Jun 5, 2008
    Messages:
    2,979
    Should work just fine (though for windows you would want \\). Using os.path.join is better as it automatically handles the platform specific path separators.



    Code:
    
    os.path.join('I:', 'School Work', 'Term 5', 'Game Programming', 'Project 2', 'Images', 'treasure.gif')
    
    
    Also you might want to change that to a relative path. So if your main python file resides in I:\School Work\Term 5\Game Programming\Project 2\ you would utilize:



    Code:
    
    os.path.join('Images', treasure.gif')
    
    
    Make sure to properly match the case if you want to be platform independent.
     
    Last edited by a moderator: Jul 27, 2011
  5. Tempel

    Tempel Active Member

    Joined:
    Dec 30, 2008
    Messages:
    670
    Could you clarify on what went wrong? Copy and paste the error messages. Adding r should have worked (remember, the r comes immediately before the quotation mark). I wouldn't suggest relative paths here; they're important for cross-platform programs, but a school assignment only needs to work on one computer. And it looks like the program and images are stored in very different places, so a relative path would have to be more complex. So Caine's first suggestion would work here (just remember to import os.path first!)
     
  6. Caine

    Caine Advanced Member

    Joined:
    Jun 5, 2008
    Messages:
    2,979
    Whoops, missed that part. You are right, with this setup relative paths will be more complicated.


    @Silverhawk11011.


    By the way, when you post code put it between code tags. This preserves indentation and adds some syntax highlighting. I.e.:


    [code]<your code here>[/code]
     
    Last edited by a moderator: Jul 28, 2011
  7. Silverhawk11011

    Silverhawk11011 Still Fresh

    Joined:
    Jul 27, 2011
    Messages:
    11
    os.path.join("Images", "treasure.gif")


    NameError: global name 'os' is not defined


    lol. Where would I define this?
     
  8. Caine

    Caine Advanced Member

    Joined:
    Jun 5, 2008
    Messages:
    2,979
    As Tempel mentioned. Don't forget to import os.path.


    Add the following to the top of your unit:



    Code:
    
    import os.path
    
    
    Also pay attention to his warning about the relative path. It seems like your main unit resides in C:\Users\Steve\workspace\Assignment2\src\ whereas I thought it was I:\School Work\Term 5\Game Programming\Project 2\. So a relative path like that won't work.


    The warning you are receiving is that the name os is not defined. In this particular case, os is a module. You can either import os or just os.path (which is a submodule of os). By convention modules are imported at the start of the unit (just like import pygame in your example). Regardless of which import you use, you refer to the function as os.path.join, which tells python to look in the os module, submodule path and the join function within that submodule.


    If you are unfamiliar with modules, I recommend you to read the Python tutorial, in particular Chapter 6. Modules.
     
    Last edited by a moderator: Jul 28, 2011
  9. Silverhawk11011

    Silverhawk11011 Still Fresh

    Joined:
    Jul 27, 2011
    Messages:
    11
    Gahhh lol.


    self.image = self.image.convert()


    AttributeError: 'Treasure' object has no attribute 'image'


    OMg lol... let me put the files in one place. I forgot that eclipse puts the main unit in its own folder....
     
    Last edited by a moderator: Jul 28, 2011
  10. Silverhawk11011

    Silverhawk11011 Still Fresh

    Joined:
    Jul 27, 2011
    Messages:
    11
    Ok so after moving everything into the c:/.. folder and using "r" it works. lol Now to just make the clouds show up in random sizes, :p
     
  11. Caine

    Caine Advanced Member

    Joined:
    Jun 5, 2008
    Messages:
    2,979
    The documentation that Tempel linked should help you solve this issue. Good luck with your assignment.
     
  12. Silverhawk11011

    Silverhawk11011 Still Fresh

    Joined:
    Jul 27, 2011
    Messages:
    11
    Thank you guys so much for all the help :) .. You guys rock!!
     
  13. Blue Protoman

    Blue Protoman Well-Known Member

    Joined:
    Mar 6, 2010
    Messages:
    4,119
    Come back when you have $500. ;)
     
  14. Silverhawk11011

    Silverhawk11011 Still Fresh

    Joined:
    Jul 27, 2011
    Messages:
    11
    Heh. I wish I had $500, text books and tuition take most of my money, the rest is for frozen pizza and KD. If anyone is still up, I am having some difficulty with this, I have added an ememy plane to the mix, that just goes from the top of the screen to the bottom. However I am trying to set a delay on it so it wont just keep going over and over. I tried pygame.time.delay also wait, but that just freezes the whole game for that time. Any ideas?
     
  15. Caine

    Caine Advanced Member

    Joined:
    Jun 5, 2008
    Messages:
    2,979
    Plenty. But I'm going to let you puzzle on it for a while :)
     
  16. Silverhawk11011

    Silverhawk11011 Still Fresh

    Joined:
    Jul 27, 2011
    Messages:
    11
    So I am still trying to get this working lol. I found a feature called pygame.transform.scale now I figure this would be the best to do the job however, I cant get this to work. I have never used it at all, so I am unsure what needs to be done with it. Think someone could point me in the right direction? :p
     
  17. Caine

    Caine Advanced Member

    Joined:
    Jun 5, 2008
    Messages:
    2,979
    If you feel you are lacking in understanding of python as a language then take an afternoon to work through the entire python language tutorial linked above.


    Next, go to the pygame website. Click documentation. Read all the tutorials, browse the reference manual and look at example programs.


    Google for pygame examples for what you want to do and study examples given.


    To summarize: read, read, and read some more...
     

Share This Page