pygame

Record time in Pygame


I am new to Python so please explain thoroughly when you respond to me.

I want my code to measure the time the player lasts before his cursor touches the bouncing ball on the screen but the time I'm obtaining is the sum of all the seconds since the first time the command was initialized. I need the program to stop counting seconds when the user ends the game and begin afresh when the play again option is chosen.

I would also like a way to make the player qualify for the next level without using the detection of the position of the mouse since that is making the program code logic incorrect.

here is my code:

import pygame,sys
from pygame.locals import*
from pygame import *
import random

def main():
    # set up sounds
    # import pygame
    #gameOverSound = pygame.mixer.Sound('gameover.wav')
    #pygame.mixer.music.load('background.mid')
    #from pygame import *
    #import random
         
        
        
            
    #pygame.mixer.pre_init(44100, 16, 2, 4096)
        
    #background = image.load('C:\Users\Administrator\Desktop\oearth.png')
            
            
        
            ballpic = image.load('ball1.png')
            ballpic.set_colorkey((0,0,0))
        
            #find a way to include verification of more than one colour key
            # to add more than one shape....pending
        
            numballs = 10
            delay = 5
        
            done = False
        
            balls = []
            stars = []
    #generate an if loop for execution of both the parts
            k = 2
        
            init()
            screen = display.set_mode((640, 480))
            display.set_caption('mouse game by shivangi and ananya')
            event.set_grab(1)
                
        
        
        
    #pygame.time.Clock() Creates a Clock object (assign this to a name), which you can then call the tick() method on
    #to find out how much time has passed since the last time you called tick()
    #pygame.time.delay(milliseconds) Pauses game for time specified
    #pygame.time.get_ticks() Returns the number of milliseconds passed since pygame.init() was #called
        
        
                
        
        
        
            for count in range(numballs):
                balls.append(dict)
                balls[count] = {'x': 0, 'y': 0, 'xmove': random.randint(1, 2), 'ymove': random.randint(1, 2)}
        
            screen = display.set_mode((640, 480))    #####screen = display.set_mode((640,480),FULLSCREEN,32).....check functioning...
        
        
        
    #pygame.display.list_modes()
    #[(800, 600), (1280, 1024), (1280, 960), (1280, 800), (1280, 768), (1280, 720),
    #(1152, 864), (1088, 612), (1024, 768), (960, 600), (848, 480), (800, 600),
    #(720, 576), (720, 480), (640, 480), (640, 400), (512, 384), (480, 360), (400, 300),
    #(320, 240), (320, 200), (640, 480)]
        
        
        
        
            while done == False:
                pygame.time.Clock()
                init()
                screen.fill((0,100,0))
        
                for count in range(numballs):
                    screen.blit(ballpic, (balls[count]['x'], balls[count]['y']))
        
                display.update()
                time.delay(delay)
        
                for count in range(numballs):
                    balls[count]['x'] = balls[count]['x'] + balls[count]['xmove']
                    balls[count]['y'] = balls[count]['y'] + balls[count]['ymove']
        
                for count in range(numballs):
                    if balls[count]['x'] > 620:
                        balls[count]['xmove'] = random.randint(-2, 0)
                    if balls[count]['x'] < -10:
                        balls[count]['xmove'] = random.randint(0, 6)
                    if balls[count]['y'] > 470:
                        balls[count]['ymove'] = random.randint(-9, 0)
                    if balls[count]['y'] < -10:
                        balls[count]['ymove'] = random.randint(0, 5)
        
                for e in event.get():
                    if e.type == KEYUP:
                        if e.key == K_ESCAPE:
                            done = True
        
                if screen.get_at((mouse.get_pos())) == (227,209,43):
                    done = True
                    
                if done == True:
                        #pygame.mixer.init()
                        break
            sec = time.get_ticks()/1000
            quit()
        
        
            while sec < k:
                 print "you lasted for only",sec,"seconds...try again to qualify for the next level..."
                 quit()
                 break
            time_lasted = 0
        
        
        
            while sec >= k:
                 starpic = image.load('star.png')
                 starpic.set_colorkey((0,0,0))
                 #find a way to include verification of more than one colour key...PENDING
        
                 numstars = 30
                 delay = 8
        
                 done = False
                 
                 stars = []
                 for count in range(numstars):
                         stars.append(dict)
                         stars[count] = {'x': 0, 'y': 0, 'xmove': random.randint(1, 2), 'ymove': random.randint(1, 2)}
        
                
                 screen = display.set_mode((640, 480))
                 display.set_caption('mouse game')
                 event.set_grab(1)
        
                 while done == False:
                     init()
                     screen.fill((160,32,240))
        
                     for count in range(numstars):
                         screen.blit(starpic, (stars[count]['x'], stars[count]['y']))
        
                     display.update()
                     time.delay(delay)
        
                     for count in range(numstars):
                         stars[count]['x'] = stars[count]['x'] + stars[count]['xmove']
                         stars[count]['y'] = stars[count]['y'] + stars[count]['ymove']
        
                     for count in range(numstars):
                         if stars[count]['x'] > 620:
                             stars[count]['xmove'] = random.randint(-2, 0)
                         if stars[count]['x'] < -10:
                             stars[count]['xmove'] = random.randint(0, 2)
                         if stars[count]['y'] > 470:
                             stars[count]['ymove'] = random.randint(-2, 0)
                         if stars[count]['y'] < -10:
                             stars[count]['ymove'] = random.randint(0, 2)
        
                     for e in event.get():
                         if e.type == KEYUP:
                             if e.key == K_ESCAPE:
                                 done = True 
        
                     if screen.get_at((mouse.get_pos())) == (255,255,255,255):
                             done = True
                             if done == True:
                                     time_lasted = time.get_ticks()/1000
                                     quit()
                                     break
                 
                 #sec = time.update()
                 #time_lasted = time.update()
                 
                 #correction of time error to be done....pending....
        
                 quit()
                 print "You lasted for", sec, "seconds in the first level!"
                 print "\n"
                 print "you lasted for",time_lasted,"in the second level!"
                 print "\n"
                 print "your total score is :", int(sec) + int(time_lasted)
                 print "\n"
                 print "game over...! Thank you for playing!! :D :P :)"
                 quit()
                 break
                
         
        
        main()
        x = 1
        x = raw_input("Do you want to play again?")
        
        while x.upper() in  ['YES','Y']:
            main()
            x =  raw_input("Do you want to play again?")
            
        while x.upper() in  ['NO','N']:
            break

Solution

  • # when player starts game
    start = time.get_ticks()
    
    # during game 
    current = time.get_ticks()
    
    time_you_played = (current - start)/1000
    

    EDIT:

    Timer to count seconds.

    class Timer():
    
        def __init__(self):
            self._start = 0
    
        def start(self):
            self._start = pygame.time.get_ticks()
    
        def current(self):
            return (pygame.time.get_ticks() - self._start)/1000
    

    Example - how to use:

    import pygame
    
    # add class Timer here 
    
    pygame.init()
    
    t = Timer()
    
    t.start() # start or restart timer
    
    pygame.time.wait(3000) # for test only
    
    print t.current() # print seconds
    
    pygame.time.wait(2000) # for test only
    
    print t.current() # print seconds
    

    You don't have to stop timer because you can use start() to restart timer.