#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    3
    Rep Power
    0

    Some help? Random Image program.


    Hello, everyone, I'm fairly new to python programming (or programming in general), and I'd like to ask for some help on programming a program that randomly displays an image, then with the press of the right arrow key, changes the image to another random image. And finally, when pressing the left arrow key, it changes the current image to the previous image.

    I've been learning some python programming at codecademy, but I think this program that I tried to code is currently beyond my coding know how. So yeah, let me post up what I've coded and if anyone would like to sort of 'guide' me or lend me a helping hand, I would really appreciate it.

    Heheh, looking at the code and how little or bad I understood coding, this code probably makes no sense at all.
    Yeah, so from what I understand, pygame only works on python 3.2.x and I think I was learning the python 3.3.x syntax, so that's probably why I'm getting a bunch of errors.

    Code:
    import pygame
    from pygame import *
    
    pygame.init()
    
    window = pygame.display.set_mode((500,500))
    
    pygame.display.set_caption("Random Imager")
    
    """imports images?... I think. I watched a youtube tutorial and
    this is what the person put to load images."""
    image0 = pygame.image.load("RandomImager/image0.jpg")
    image1 = pygame.image.load("RandomImager/image1.jpg")
    image2 = pygame.image.load("RandomImager/image2.jpg")
    image3 = pygame.image.load("RandomImager/image3.jpg")
    image4 = pygame.image.load("RandomImager/image4.jpg")
    image5 = pygame.image.load("RandomImager/image5.jpg")
    image6 = pygame.image.load("RandomImager/image6.jpg")
    image7 = pygame.image.load("RandomImager/image7.jpg")
    image8 = pygame.image.load("RandomImager/image8.jpg")
    image9 = pygame.image.load("RandomImager/image9.jpg")
    
    """Gives the \"Images\" a value, creates a 
    dictionary into variable \"Image_Val\""""
    Image_Val = {image0 : 0, image1 : 1, image2 : 2,\
                  image3 : 3, image4 : 4, image5 : 5,\
                  image6 : 6, image7 : 7, image8 : 8,\
                  image9 : 9}
    
    """Learned these bits of code from the youtube tutorial"""
    gameLoop = True
    while gameLoop:
         for event in pygame.event.get():
             if (event.type == pygame.QUIT):
                 gameLoop = False
             if (event.type == pygame.KEYRIGHT):
                 if (event.type == pygame.K_RIGHT):
    
              window.fill((255,255,255))
    
              window.blit(Image_Val, (0,0))
    
              pygame.display.flip()
    
    pygame.quit()
    Thanks for any help or advise. =]
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    28
    Rep Power
    0
    I'm also new to Python and did some tutorials from codeacademy. Maybe importing the random module will help out some.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    138
    Rep Power
    2
    As Guitarman2010, you need the random module to get random values.

    I suggest that you keep your images in a list, then you can pick random values from that list like this:

    Code:
    >>> import random
    >>> number_list = [0,2,3,4,5,6,7,8,9]
    >>> random.choice(number_list)
    2
    >>> random.choice(number_list)
    0
    >>> random.choice(number_list)
    4
    The pygame doc says that pygame.K_RIGHT is the correct variable for right arrow, so you'll want to remove the first if-statement below.

    Code:
     if (event.type == pygame.KEYRIGHT):
                 if (event.type == pygame.K_RIGHT):
    http://www.catb.org/esr/faqs/smart-questions.html#code
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    3
    Rep Power
    0
    Thanks Guitarman2010 and partoj for the help/suggestions.

    I've been tinkering with the code a little with the suggestions you've made, and I've taken a few step forwards. Right now, the program starts but with no initial 'random' image, I'd like it to start up displaying a random image. Second, when I press the right arrow key, I get one random image to display, but when I press the arrow key again, it stays on the same image. And last, when I press the left arrow key, I get a random image as well, but the event that I want it to do is to change the current image to the previous image.

    Here is the code with the small changes I've made. =p

    Code:
    import pygame
    from pygame import *
    import random
    
    pygame.init()
    
    #Creates the window and displays window name
    window = pygame.display.set_mode((500,500))
    pygame.display.set_caption("Random Imager")
    
    #imports images
    image0 = pygame.image.load("RandomImagerImages/image0.jpg")
    image1 = pygame.image.load("RandomImagerImages/image1.jpg")
    image2 = pygame.image.load("RandomImagerImages/image2.jpg")
    image3 = pygame.image.load("RandomImagerImages/image3.jpg")
    image4 = pygame.image.load("RandomImagerImages/image4.jpg")
    image5 = pygame.image.load("RandomImagerImages/image5.jpg")
    image6 = pygame.image.load("RandomImagerImages/image6.jpg")
    image7 = pygame.image.load("RandomImagerImages/image7.jpg")
    image8 = pygame.image.load("RandomImagerImages/image8.jpg")
    image9 = pygame.image.load("RandomImagerImages/image9.jpg")
    
    #Creates a list of images and stores the list in variable 'imageList'
    imageList = [image0, image1, image2, image3, image4,\
                 image5, image6, image7, image8, image9]
    
    #Creates two variables, one holds current image/value, other holds previous image/value
    imageHolder1 = random.choice(imageList[0:]) #Holds random image/value
    imageHolder2 = [] #Holds the previous image/value
    
    def imageValue(): #This function places the image/value on 'imageHolder2'
        for n in imageHolder1:
            imageHolder2 = n
    
    gameLoop = True
    while gameLoop:
        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                gameLoop = False
            if (event.type == pygame.KEYDOWN):
                if (event.type == pygame.K_RIGHT):
                    imageValue()
                    window.blit(imageHolder1, (0,0))
                if (event.type == pygame.K_LEFT):
                    window.blit(imageHolder2, (0,0))
                    
                window.fill((255,255,255))
                window.blit(imageHolder1, (0,0))
                pygame.display.flip()
            
    pygame.quit()
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    2
    Load your images with a loop not individually.
    Here is an example (I would normally use classes for anything like this but here it is with just functions). This just shuffles the list once on loading; after that the order is set; but what you want isn't much harder.

    You will either have to pass the correct directory path to the image loader function or place this in the folder with your images.
    python Code:
    import pygame as pg
    import os,sys,random
     
    def load_all_images(directory):
        images = []
        for name in os.listdir(directory):
            if name[-3:] in ["jpg","png","bmp"]:
                images.append(pg.image.load(name).convert())
        random.shuffle(images)
        return images
     
    def main():
        index = 0
        clock = pg.time.Clock()
        done = False
        while not done:
            keys = pg.key.get_pressed()
            for event in pg.event.get():
                if event.type == pg.QUIT or keys[pg.K_ESCAPE]:
                    done = True
                elif event.type == pg.KEYDOWN:
                    if event.key == pg.K_RIGHT:
                        index = (index+1)%len(MYIMAGES)
                    elif event.key == pg.K_LEFT:
                        index = (index-1)%len(MYIMAGES)
            update(index)
            clock.tick(60)
     
    def update(index):
        SCREEN.fill(0)
        SCREEN.blit(MYIMAGES[index],(0,0))
        pg.display.flip()
     
    if __name__ == "__main__":
        pg.init()
        SCREEN = pg.display.set_mode((500,500))
        MYIMAGES = load_all_images(".")
        main()
        pg.quit();sys.exit()

    -Mek

    Comments on this post

    • Samm702 agrees
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    3
    Rep Power
    0

    Thumbs up


    Originally Posted by Mekire
    Load your images with a loop not individually.
    Here is an example (I would normally use classes for anything like this but here it is with just functions). This just shuffles the list once on loading; after that the order is set; but what you want isn't much harder.

    You will either have to pass the correct directory path to the image loader function or place this in the folder with your images.
    python Code:
    import pygame as pg
    import os,sys,random
     
    def load_all_images(directory):
        images = []
        for name in os.listdir(directory):
            if name[-3:] in ["jpg","png","bmp"]:
                images.append(pg.image.load(name).convert())
        random.shuffle(images)
        return images
     
    def main():
        index = 0
        clock = pg.time.Clock()
        done = False
        while not done:
            keys = pg.key.get_pressed()
            for event in pg.event.get():
                if event.type == pg.QUIT or keys[pg.K_ESCAPE]:
                    done = True
                elif event.type == pg.KEYDOWN:
                    if event.key == pg.K_RIGHT:
                        index = (index+1)%len(MYIMAGES)
                    elif event.key == pg.K_LEFT:
                        index = (index-1)%len(MYIMAGES)
            update(index)
            clock.tick(60)
     
    def update(index):
        SCREEN.fill(0)
        SCREEN.blit(MYIMAGES[index],(0,0))
        pg.display.flip()
     
    if __name__ == "__main__":
        pg.init()
        SCREEN = pg.display.set_mode((500,500))
        MYIMAGES = load_all_images(".")
        main()
        pg.quit();sys.exit()

    -Mek
    Hey, thanks a lot Mekire, I was sure there was a way to load the images without having to do them individually, but when it comes to programming, ugh, I'm the worst of the worst. =P I really like how you coded the "load_all_images" function, specially line 7 and 8 (Cool! ). Also, I added this bit of code right under line 22 rNum = random.randint(0,10), and modified line 25 to this index = (index-rNum)%len(MYIMAGES), do you think that is okay? or would you have modified it differently?

    Hey, also, can I ask what website or book you learned to code python? Codecademy just doesn't give much explanation as to the 'why' and the 'what' specific parts of the code do.
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    2
    I started with the rat book:
    Learning Python
    After that I started looking at other peoples' Pygame projects (and unfortunately picked up a ton of bad programming habits this way). Then I started making my own games with pygame and again the first few were really badly written. Eventually I found my own style and refined my habits to the point I'm at now.

    My biggest advice is to start using classes as soon as you can. Lots of new programmers seem to run from them and try to write there first game using only functions (and sometimes not even that). The thing is classes make life easier, not harder.

    The quest continues,
    -Mek

IMN logo majestic logo threadwatch logo seochat tools logo