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

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0

    Question How to display score on Pygame?


    I'm a new programmer working on a memory game for my computer science summative.The game goes like this: the computer displays random boxes at random positions and then the user has to guess where the boxes are and click on it.

    I'm basically done, except right now I'm trying to create like 5 different levels that range in level of difficulty. eg level 1 will display like 2 boxes and level 2 will display like 5, etc. And then if the user gets through all levels they can play again. I know its a lot but I really want to get an A on this.

    But right now I'm stuck because it doesnt really work until I try to close the window, and even then it only goes halfway. Any help would be appreciated.

    Code:
    import pygame , sys
    import random
    import time
    
    size=[500,500]
    pygame.init()
    screen=pygame.display.set_mode(size)
    
    
    # Colours
    LIME = (0,255,0) 
    RED = (255, 0, 0)
    BLACK = (0,0,0)
    PINK = (255,102,178)
    SALMON = (255,192,203)
    WHITE = (255,255,255)
    LIGHT_PINK = (255, 181, 197)
    SKY_BLUE = (176, 226, 255)
    screen.fill(BLACK)
    
    # Width and Height of game box
    width=50
    height=50
    
    
    
    # Margin between each cell
    margin = 5
    
    rows = 20
    columns = 20
    
    
    # Set title of screen
    pygame.display.set_caption("Spatial Recall")
    
    # Used to manage how fast the screen updates
    clock=pygame.time.Clock()
    
    
    coord=[]
    
    # Create a 2 dimensional array. A two dimesional
    # array is simply a list of lists.
    def resetGrid():
        grid = []
        for row in range(rows):
            # Add an empty array that will hold each cell
            # in this row
            grid.append([])
            for column in range(columns):
                grid[row].append(0) # Append a cell  
        return grid
    
    def displayAllPink(pygame):
        for row in range(rows):
            for column in range(columns):
                color = LIGHT_PINK
                pygame.draw.rect(screen,color,[(margin+width)*column + margin,(margin+height)*row+margin,width,height])
                pygame.display.flip()      
    
    def displayOtherColor(pygame,grid):
        coord = []
        for i in range(random.randint(2,5)):
            x = random.randint(2, rows-1)
            y = random.randint(2, columns-1)                
            color = LIME    
            pygame.draw.rect(screen,color,[(margin+width)*y + margin,(margin+height)*x+margin,width,height])
            coord.append((x,y))  
            grid[x][y] = 1
            pygame.display.flip() 
        time.sleep(1)
        return coord
    
    def runGame(gameCount,coord,pygame,grid):
        pygame.event.clear()
        pygame.display.set_caption("Spatial Recall: Level "+ str(gameCount))
        pygame.time.set_timer(pygame.USEREVENT,1000)
        time = 0
        #clock.tick( 
                # -------- Main Program Loop -----------
        #Loop until the user clicks the close button.
        done = False
        while done==False:    
            event = pygame.event.wait() # User did something
            if event.type == pygame.QUIT: # If user clicked close
                done=True # Flag that we are done so we exit this loop
                pygame.event.clear()
                print "Game ",gameCount, "ends"
            elif event.type == pygame.USEREVENT:
                time = time + 1
                pygame.display.set_caption("Spatial Recall: Level "+ str(gameCount) + " Time: "+ str(time))
                if time == 100:
                    done = True
                    pygame.display.set_caption("Time out, moving to next level")
                    pygame.event.clear()
                    return False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # User clicks the mouse. Get the position
                pos = pygame.mouse.get_pos()
                # Change the x/y screen coordinates to grid coordinates
                column=pos[0] // (width+margin)
                row=pos[1] // (height+margin)
                if (row,column) in coord:
                    print coord
                    coord.remove((row,column))
                    print coord
                    color = LIME
                    pygame.draw.rect(screen,color,[(margin+width)*column + margin,(margin+height)*row+margin,width,height])
                    if coord == []:
                        done=True 
                        pygame.display.set_caption("Time out, moving to next level")
                        pygame.event.clear()
                        return True
                else:
                    color = RED
                    pygame.draw.rect(screen,color,[(margin+width)*column + margin,(margin+height)*row+margin,width,height])
                pygame.display.flip() 
    
    
    def startTheGame(gameCount):
        grid = resetGrid()
        displayAllPink(pygame)
        coord = displayOtherColor(pygame,grid)
        displayAllPink(pygame)
        runGame(gameCount,coord,pygame,grid)
    
    for i in range(2):
        startTheGame(i+1)
    pygame.quit ()
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2010
    Posts
    18
    Rep Power
    0
    Put your code inside code tags. It's easier for people to help you.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0
    Originally Posted by RexT
    Put your code inside code tags. It's easier for people to help you.
    Sorry about that. I wasn't sure how to do that, but I've done it now.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,904
    Rep Power
    481
    You have a statement near line 106
    Code:
                      pygame.display.set_caption("Time out, moving to next level")
    However I think the caption should indicate victory. There's a lot of duplicate code. I would encapsulate as
    Code:
    class Draw:
    
        def __init__(self,width,height,margin):
            self.args = (width,height,margin,margin+width,margin+height,)
    
        def draw(self,col,row,color):
            (w,h,m,mw,mh,) = self.args
            pygame.draw.rect(screen, color, [mw * col + m, mh * row + m, w, h])
    
        def find(self,x,y):
            (w,h,m,mw,mh,) = self.args
            return (x // mw, y // mh,)
    
        def board_size(self,rows,columns):
            (w,h,m,mw,mh,) = self.args
            return (mw*rows+m,mh*columns+m)
    You assign values to grid, but never use them. Discard your grid variable. The coord logic works.

    You pass pygame to several functions. pygame is a global module name, so, while not incorrect, why pass it around? If you need to improve the game speed call display flip less often.

    Why "and even then it only goes halfway."? Actually it goes less than a quarter of the way. You told pygame the size is 500x500. Then you tried to use a 20 by 20 grid which takes margin+(margin+width)*cells pixelsWidths across the screen. That's 1105 . Most of the cells don't draw. I decreased to
    rows = 10
    columns = 10
    then computed the size with my Draw.board_size method.

    I'll post my solution sometime in the future if you remind me. The game really is OK.
    I saved it on my computer as ~/devshed/memoryGame.py
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0
    Originally Posted by b49P23TIvg
    You have a statement near line 106
    Code:
                      pygame.display.set_caption("Time out, moving to next level")
    However I think the caption should indicate victory. There's a lot of duplicate code. I would encapsulate as
    Code:
    class Draw:
    
        def __init__(self,width,height,margin):
            self.args = (width,height,margin,margin+width,margin+height,)
    
        def draw(self,col,row,color):
            (w,h,m,mw,mh,) = self.args
            pygame.draw.rect(screen, color, [mw * col + m, mh * row + m, w, h])
    
        def find(self,x,y):
            (w,h,m,mw,mh,) = self.args
            return (x // mw, y // mh,)
    
        def board_size(self,rows,columns):
            (w,h,m,mw,mh,) = self.args
            return (mw*rows+m,mh*columns+m)
    You assign values to grid, but never use them. Discard your grid variable. The coord logic works.

    You pass pygame to several functions. pygame is a global module name, so, while not incorrect, why pass it around? If you need to improve the game speed call display flip less often.

    Why "and even then it only goes halfway."? Actually it goes less than a quarter of the way. You told pygame the size is 500x500. Then you tried to use a 20 by 20 grid which takes margin+(margin+width)*cells pixelsWidths across the screen. That's 1105 . Most of the cells don't draw. I decreased to
    rows = 10
    columns = 10
    then computed the size with my Draw.board_size method.

    I'll post my solution sometime in the future if you remind me. The game really is OK.
    I saved it on my computer as ~/devshed/memoryGame.py
    Hi. Thank you so much for looking at it.
    I made the changes but I'm still a little unsure about what to do. Could you please explain more?
  10. #6
  11. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,904
    Rep Power
    481
    The most significant easy improvement you could make would be to get the size to agree with the size you use.


    # this is the size you tell pygame to use
    size=[500,500]
    pygame.init()
    screen=pygame.display.set_mode(size)



    and you use (considering width)
    columns * (width + margin) + margin
    where


    # Width and Height of game box
    width=50
    height=50

    # Margin between each cell
    margin = 5

    rows = 20
    columns = 20
    [code]Code tags[/code] are essential for python code and Makefiles!
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0
    But would you know how to make a play again button for the user to press after he/she clicks all the green boxes? That's where I'm stuck
  14. #8
  15. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,904
    Rep Power
    481
    Yes.
    [code]Code tags[/code] are essential for python code and Makefiles!
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0
    You do? So could you please explain how I can do that?
  18. #10
  19. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,904
    Rep Power
    481
    pygame's a big package with which I am mostly unfamiliar. I'd go with
    Code:
    >>> import Tkinter as tkinter
    >>> def main(): print('restart')
    ... 
    >>> tkinter.Button(text='Play again?',command=main).pack()
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo