1

I have a timer in a game I'm programming in python/pygame.

The timer works fine when I have everything in the main class:

time=50

seconds_passed = clock.tick()/1000.0
time-=seconds
draw_time=math.tranc(time)
print(draw_time)

However when I move this into a new class player

class player():
   .
   .
   .
   set_time(self, draw_time):
        seconds_passed = clock.tick()/1000.0
        time-=seconds_passed
        draw_time=math.tranc(time)
        print(draw_time)

When I call this function in the main class:

class main():
    . 
    .
    .
    draw_time=20
    player = Player()
    print player.set_time(draw_time)

My time is not decrementing however stays the same!

Any suggestions?

Pro-grammer
  • 862
  • 3
  • 15
  • 41
  • possible duplicate of [Why can functions in Python print variables in enclosing scope but cannot use them in assignment?](http://stackoverflow.com/questions/18864041/why-can-functions-in-python-print-variables-in-enclosing-scope-but-cannot-use-th) – fjarri Oct 29 '13 at 13:28
  • What is `seconds` and what is its relationship to `seconds_passed`? – tripleee Oct 29 '13 at 13:30
  • sorry typo, fixed -edit – Pro-grammer Oct 29 '13 at 13:31
  • Classes should begin with uppercase, and you don't need the parens, e.g. 'class Main:`, etc. – Wayne Werner Oct 29 '13 at 19:04

1 Answers1

0

When you are decrementing time in your method, you are only modifying a copy of the value. To be able to modify it you can pass a reference to an object instead. You can use for example a timedelta.

from datetime import timedelta

class player():
   set_time(self, draw_time):
        seconds_passed = clock.tick()/1000.0
        time -= timedelta(seconds=seconds_passed)
        draw_time=math.tranc(time.seconds)
        print(draw_time)

class main():
    draw_time = timedelta(seconds=20)
    player = Player()
    print player.set_time(draw_time)
  • sorry, i dont want a time, i meant a timer which decrements – Pro-grammer Oct 29 '13 at 14:11
  • Sure, you can create yourself a Timer class instead which you can use for keeping track of time. The timedelta was just one way of solving it. –  Oct 29 '13 at 14:20