Reputation: 37
I'm making a nice game with the pygame
module, and basically I want to do two things:
Run the game in an endless loop and see if the user wants to close the game, and if he wants to close the game, pop him a MessageBox.
In the second function, I want to add all the features of the game and draw on the screen.
My problem is that when I try to run them both with Thread, the game gets stuck and unresponsive.
Is this a problem with my computer, meaning it's too weak to run the game?
Or is it a problem with my code that keeps the game from running properly?
Code:
import pygame
import ctypes
from threading import Thread
class Game:
def __init__(self):
self.init = pygame.init()
self.screen = pygame.display.set_mode((800, 500))
self.allProcess()
def runGame(self):
self.running = True
while self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
ctypes.windll.user32.MessageBoxW(0, 'Thank you for Playing!', 'Thank You', 0)
self.running = False
def items(self):
self.screen.fill((255, 255, 255))
pygame.draw.circle(self.screen, (0, 0, 255), (250, 250), 75)
def allProcess(self):
Thread(target=self.runGame).start()
Thread(target=self.items).start()
if __name__ == '__main__':
ins = Game()
Upvotes: 1
Views: 589
Reputation: 9746
Pygame is built on SDL2 which has some rules regarding in which threads certain functions can be called. For example, for functions in the event module, ("you can only call this function in the thread that set the video mode.").
You should almost always avoid using threads unless they are absolutely necessary! They make your program non-deterministic, harder to debug, harder to test, harder to maintain and often slower (unless you use them effectively). In your program, there are no reasons to use threads. In your case, they are unnecessary. You should do this instead:
import pygame
import ctypes
class Game:
def __init__(self):
self.init = pygame.init()
self.screen = pygame.display.set_mode((800, 500))
self.runGame()
def runGame(self):
self.running = True
while self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
ctypes.windll.user32.MessageBoxW(0, 'Thank you for Playing!', 'Thank You', 0)
self.running = False
self.screen.fill((255, 255, 255))
pygame.draw.circle(self.screen, (0, 0, 255), (250, 250), 75)
pygame.display.flip() # Don't forget to call this to update the screen!
if __name__ == '__main__':
ins = Game()
Less code, deterministic, and most likely faster and using less memory.
Upvotes: 2