Timer issue in Python/Pygame game
<p>I am relatively new to Python. I have been modifying this game code and included a start screen etc. The problem I'm having is that when the game ends I am trying to have it start again when a user inputs y at 12. I have got the key press down but there seems to be an issue with the timer. In 6.4 it is using get.ticks() but I can't seem to reinitialize this timer when the game restarts. 6.4 is used to draw and count down the clock. Then further down in 10 it does a comparison for a win/loose check which then leads onto 11 which determines whether a win/loose display is shown. The game is meant to only have a 90 second time limit and then restart when the game re-initializes (ie player selects y at 12). (I have set it to 9 seconds for debugging). The health side of the game works but again the timer is effected when the game restarts. Please help if you can. See code below.</p>

<pre><code># 1 - Import library
import pygame
from pygame.locals import *
import math
import random
import time
import sys


# 2 - Initialize the game
width, height = 640, 480
keys = [False, False, False, False]
fps = 15

# 2.0.1 - Initialises colours R G B
white     = (255, 255, 255)
black     = (  0,   0,   0)
red       = (255,   0,   0)
green     = (  0, 255,   0)
darkgreen = (  0, 155,   0)
darkgrey  = ( 40,  40,  40)
bgcolor = black

def main():
    print "1"
    global screen, basicfont, fpsclock
    pygame.init()
    fpsclock = pygame.time.Clock()
    screen = pygame.display.set_mode((width, height))
    # 2.0.2 - Sets font and size for press any key on start screen ---
    basicfont = pygame.font.Font('freesansbold.ttf', 15)
    # 2.0.3 - Sets Game name in window much like Title tag in HTML -
    pygame.display.set_caption('Developed by: xxxx')
    #-------------------------------------------------------------

    # 2.0.4 - Puts a game icon next to your caption ----------------
    gameIcon = pygame.image.load("resources/images/plane.png")
    pygame.display.set_icon(gameIcon)
    #-------------------------------------------------------
    startScreen()

def restart():
    pygame.quit()
    main()

def drawPressKeyMsg():
    pressKeySurf = basicfont.render('Press any key to play.', True, white)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (width - 200, height - 30)
    screen.blit(pressKeySurf, pressKeyRect)

def terminate():
     pygame.quit()
     sys.exit()

def checkForKeyPress():
    if len(pygame.event.get(QUIT)) &gt; 0:
        terminate()
    keyUpEvents = pygame.event.get(KEYUP)
    if len(keyUpEvents) == 0:
         return None

    if keyUpEvents[0].key == K_ESCAPE:
         terminate()
    return keyUpEvents[0].key


def startScreen():
    # 2.0. - Change start screen attributes between hashes --------------
    titleFont = pygame.font.Font('freesansbold.ttf', 60)
    titleSurf1 = titleFont.render('Naval Warfare', True, red)
    titleSurf2 = titleFont.render('Naval Warfare', True, green)
    #---------------------------------------------------------------------
    degrees1 = 0
    degrees2 = 0
    while True:
         background = pygame.image.load("resources/images/falcons.png")
         screen.blit(background, (0,0))
         rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
         rotatedRect1 = rotatedSurf1.get_rect()
         rotatedRect1.center = (width/2, height/2)
         screen.blit(rotatedSurf1, rotatedRect1)
         rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
         rotatedRect2 = rotatedSurf2.get_rect()
         rotatedRect2.center = (width/2, height/2)
         screen.blit(rotatedSurf2, rotatedRect2)
         drawPressKeyMsg()
         if checkForKeyPress():
             pygame.event.get() # clear event queue
             runGame()
             return
         pygame.display.update()
         fpsclock.tick(fps)
         degrees1 -= 7 # rotate by -7 degrees each frame
         degrees2 += 7 # rotate by 7 degrees each frame



def runGame():
    print"2"
    # 2.1 - Changes initial player position --
    playerpos=[100,240]
    # ----------------------------------------

    acc=[0,0]
    arrows=[]
    badtimer=100
    badtimer1=0
    badguys=[[640,100]]
    healthvalue=194
    pygame.mixer.init()



    # 3 - Load image
    # 3.0.1 - Remember when using own images change file names below ----------
    player = pygame.image.load("resources/images/plane.png")
    grass = pygame.image.load("resources/images/wave.png")
    castle = pygame.image.load("resources/images/carrier.png")
    arrow = pygame.image.load("resources/images/missile.png")
    badguyimg1 = pygame.image.load("resources/images/helo.png")
    badguyimg=badguyimg1
    healthbar = pygame.image.load("resources/images/healthbar.png")
    health = pygame.image.load("resources/images/health.png")
    gameover = pygame.image.load("resources/images/gameover.png")
    youwin = pygame.image.load("resources/images/youwin.png")

    # 3.1 - Load audio
    hit = pygame.mixer.Sound("resources/audio/explode.wav")
    enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
    shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
    hit.set_volume(0.05)
    enemy.set_volume(0.05)
    shoot.set_volume(0.05)
    pygame.mixer.music.load('resources/audio/moonlight.wav')
    pygame.mixer.music.play(-1, 0.0)
    pygame.mixer.music.set_volume(0.25)

    # 4 - keep looping through
    running = 1
    exitcode = 0
    print "exitcode before if: ",  exitcode
    while running:
        print running, " running"
        badtimer-=1
        # 5 - clear the screen before drawing it again
        screen.fill(0)

        # 6 - draw the castles and the background
        # ------------------------------------------------------------------------
        # 6.0.1 - If using a 640 x 480 image remove code between hashes
        # for x in range(width/grass.get_width()+1):
        #    for y in range(height/grass.get_height()+1):
        #        screen.blit(grass,(x*100,y*100))
        # ------------------------------------------------------------------------        

        # 6.0.2- Replace code below with: screen.blit(grass,(0,0)) and remove indent
        screen.blit(grass,(0,0))
        # ------------------------------------------------------------------------

        screen.blit(castle,(0,30))
        screen.blit(castle,(0,135))
        screen.blit(castle,(0,240))
        screen.blit(castle,(0,345 ))

        # 6.1 - Set player position and rotation
        position = pygame.mouse.get_pos()
        angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
        playerrot = pygame.transform.rotate(player, 360-angle*57.29)
        playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
        screen.blit(playerrot, playerpos1) 

        # 6.2 - Draw arrows
        for bullet in arrows:
            index=0
        # 6.2.1 - Changing the multiplier value changes the speed at which bullets travel ie 10 -&gt; 5    
            velx=math.cos(bullet[0])*5
            vely=math.sin(bullet[0])*5
        # ----------------------------------------------------------------------------
            bullet[1]+=velx
            bullet[2]+=vely
            if bullet[1]&lt;-64 or bullet[1]&gt;640 or bullet[2]&lt;-64 or bullet[2]&gt;480:
                arrows.pop(index)
            index+=1
            for projectile in arrows:
                arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
                screen.blit(arrow1, (projectile[1], projectile[2]))

        # 6.3 - Draw badgers
        if  badtimer==0:
            badguys.append([640, random.randint(50,430)])
            badtimer=100-(badtimer1*2)
            if badtimer1&gt;=35:
                badtimer1=35
            else:
                badtimer1+=5
        index=0
        for badguy in badguys:
            if badguy[0]&lt;-64:
                badguys.pop(index)
            # 6.3.0 - Initial x position value is 640. The more we subtract the faster the x position reduces.
            # Hence the faster the badger moves across the screen when it updates the x position in the loop.     
            badguy[0]-=2 # ie 7 -&gt; 2
            # ----------------------------------------------------------------------------

            # 6.3.1 - Attack castle
            badrect=pygame.Rect(badguyimg.get_rect())
            badrect.top=badguy[1]
            badrect.left=badguy[0]
            if badrect.left&lt;64:
                hit.play()
                healthvalue -= random.randint(5,20)
                badguys.pop(index)

            # 6.3.2 - Check for collisions
            index1=0
            for bullet in arrows:
                bullrect=pygame.Rect(arrow.get_rect())
                bullrect.left=bullet[1]
                bullrect.top=bullet[2]
                if badrect.colliderect(bullrect):
                    enemy.play()
                    acc[0]+=1
                    badguys.pop(index)
                    arrows.pop(index1)
                index1+=1

            # 6.3.3 - Next bad guy
            index+=1
        for badguy in badguys:
            screen.blit(badguyimg, badguy)

        # 6.4 - Draw clock
        time = pygame.time.get_ticks()
        font = pygame.font.Font(None, 24)
        survivedtext = font.render(str((90000-time)/60000)+":"+str((90000-time)/1000%60).zfill(2), True, (0,0,0))
        textRect = survivedtext.get_rect()
        textRect.topright=[635,5]
        screen.blit(survivedtext, textRect)

        # 6.5 - Draw health bar
        screen.blit(healthbar, (5,5))
        for health1 in range(healthvalue):
            screen.blit(health, (health1+8,8))

        # 7 - update the screen
        pygame.display.flip()

        # 8 - loop through the events
        for event in pygame.event.get():
            # check if the event is the X button 
            if event.type==pygame.QUIT:
                # if it is quit the game
                terminate()

            if event.type == pygame.KEYDOWN:
                if event.key==K_w:
                    keys[0]=True
                elif event.key==K_a:
                    keys[1]=True
                elif event.key==K_s:
                    keys[2]=True
                elif event.key==K_d:
                    keys[3]=True
            if event.type == pygame.KEYUP:
                if event.key==pygame.K_w:
                    keys[0]=False
                elif event.key==pygame.K_a:
                    keys[1]=False
                elif event.key==pygame.K_s:
                    keys[2]=False
                elif event.key==pygame.K_d:
                    keys[3]=False
            if event.type==pygame.MOUSEBUTTONDOWN:
                shoot.play()
                position=pygame.mouse.get_pos()
                acc[1]+=1
                arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])

        # 9 - Move player
        if keys[0]:
            playerpos[1]-=5
        elif keys[2]:
            playerpos[1]+=5
        if keys[1]:
            playerpos[0]-=5
        elif keys[3]:
            playerpos[0]+=5
        print running , "before win lose check"

        #10 - Win/Lose check
        if time &gt;=9000:
            running=0
            print running, "time check"
            exitcode=1
        if healthvalue&lt;=0:
            running=0
            print running, "health check"
            exitcode=0
        if acc[1]!=0:
            accuracy=acc[0]*1.0/acc[1]*100
        else:
            accuracy=0
        print running , "after win lose check"

   # 11 - Win/lose display        
    if exitcode==0:
        pygame.font.init()
        font = pygame.font.Font(None, 24)
        text = font.render("Accuracy: "+str(accuracy)+"%", True, white)
        textRect = text.get_rect()
        textRect.centerx = screen.get_rect().centerx
        textRect.centery = screen.get_rect().centery+24
        screen.blit(gameover, (0,0))
        screen.blit(text, textRect)
        pygame.display.flip()

    else:
        pygame.font.init()
        font = pygame.font.Font(None, 24)
        text = font.render("Accuracy: "+str(accuracy)+"%.", True, white)
        textRect = text.get_rect()
        textRect.centerx = screen.get_rect().centerx
        textRect.centery = screen.get_rect().centery+24
        screen.blit(youwin, (0,0))
        screen.blit(text, textRect)
        pygame.display.flip()
        print time
        print "3"
        print "exitcode in win/lose display: ", exitcode
        print "running" , running

    #12 player selections at end of game    
    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_y:
                    print "y pressed down."
                    restart()
                    break

                elif event.key == pygame.K_n:
                    print "n pressed down."
                    terminate()
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_y:
                    print "y released."

                elif event.key == pygame.K_n:
                        print "n released."
                        terminate()



if __name__ == '__main__':
    main()
</code></pre>

<p>I can unfortunately not test my suggestion, but the logic here will help.  If there is somewhere to download the code it would help - there are resources missing that prevent me from running the code.</p>

<p>Your #12 isn't restarting the game because it's taking place inside the <code>rungame()</code> def.  Try moving it out of <code>rungame</code>, possibly wrapping it around the code that starts <code>rungame()</code> in #2.  If that doesn't work, have it called from main, or any other exit point.</p>

<p><strong>EDIT 1:</strong> </p>

<p>Try moving the code to the section below 2.0.4, as shown in the example below.  The code below is intended to replace <code>startScreen()</code> completely.   </p>

<p><sub><sup><strong>NOTE:</strong> That <code>restart()</code> function is likely to cause problems because of the <code>pygame.quit()</code> code...</sup></sub></p>

<pre><code>#-------------------------------------------------------

start_game = True

while 1:
    if start_game:
        startScreen()
        start_game = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            terminate()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_y:
                print "y pressed down."
                ##########
                start_game = True
                ##########

                #restart()
                #break

            elif event.key == pygame.K_n:
                print "n pressed down."
                terminate()

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_y:
                print "y released."
                ##########
                start_game = True
                ##########

            elif event.key == pygame.K_n:
                    print "n released."
                    terminate()
</code></pre>

python