I'm trying to make a game sort of like cookie-clicker, but the problem I'm having is that I want to change the "money" variable once every second while keeping the rest of the program running at normal speed. (i.e. when you click a button to bring up a menu, it doesn't take a second to refresh.
Asked
Active
Viewed 1,642 times
2
-
See this one: http://stackoverflow.com/questions/2846653/python-multithreading-for-dummies – Selcuk Feb 10 '15 at 23:26
-
2But you're using Pygame. Why not stick it right in your gameloop? – Malik Brahimi Feb 11 '15 at 00:25
2 Answers
4
Make a thread which allows you to simultaneously run tasks:
from threading import *
import time
class CookieThread(Thread):
def __init__(self, rate):
self.money = 0
self.rate = rate
self.running = False
super(Thread, self).__init__()
def start(self):
self.running = True
super(Thread, self).start()
def run(self):
while self.running:
self.money += self.rate
time.sleep(1) # wait a second
Now create a thread and start it:
cookie = CookieThread(10)
cookie.start()

Malik Brahimi
- 16,341
- 7
- 39
- 70
3
You have two main choices (for Python, or for any language):
Create a thread (which executes in an infinite loop, and wakes up ever n seconds to do work asynchronously), or
Create a timer (which asynchronously jumps to your "interrupt handler" every N seconds).
Here is a good threads tutorial:
This is a simple "alarm" handler:
https://docs.python.org/3/library/signal.html
import signal, os
def handler(signum, frame):
print('Signal handler called with signal', _)
# Set the alarm to fire every second
signal.signal(signal.SIGALRM, handler)
signal.alarm(1)
# ... Do stuff - the alarm will keep firing ...
# Done: clear alarm
signal.alarm(0)

FoggyDay
- 11,962
- 4
- 34
- 48
-
Does an alarm interrupt a pygame game loop though? Or is it in a separate thread? – Spooky Oct 11 '15 at 21:59