Reduce CPU usage by waiting for event, and make updating the timer an event
This commit is contained in:
		
							parent
							
								
									c7c0c1220d
								
							
						
					
					
						commit
						5845156e15
					
				
							
								
								
									
										10
									
								
								main.py
								
								
								
								
							
							
						
						
									
										10
									
								
								main.py
								
								
								
								
							|  | @ -10,6 +10,7 @@ from board import Board | ||||||
| 
 | 
 | ||||||
| def start_game(rows, cols, mines): | def start_game(rows, cols, mines): | ||||||
|     pygame.init() |     pygame.init() | ||||||
|  | 
 | ||||||
|     # Pygame/ALSA has a bug that results in high CPU usage. This line reduces |     # Pygame/ALSA has a bug that results in high CPU usage. This line reduces | ||||||
|     # the CPU usage |     # the CPU usage | ||||||
|     pygame.mixer.quit() |     pygame.mixer.quit() | ||||||
|  | @ -23,19 +24,24 @@ def start_game(rows, cols, mines): | ||||||
|     # Prevents mouse movement from counting as an event, reducing CPU usage |     # Prevents mouse movement from counting as an event, reducing CPU usage | ||||||
|     pygame.event.set_blocked(MOUSEMOTION) |     pygame.event.set_blocked(MOUSEMOTION) | ||||||
| 
 | 
 | ||||||
|  |     # Creates an event that will cause the board timer to update every 100ms | ||||||
|  |     UPDATETIMER = pygame.USEREVENT + 1 | ||||||
|  |     pygame.time.set_timer(UPDATETIMER, 100) | ||||||
|  | 
 | ||||||
|     while True: |     while True: | ||||||
|         board.update_mine_counter() |         board.update_mine_counter() | ||||||
|         board.update_timer() |  | ||||||
|         board.check_for_win() |         board.check_for_win() | ||||||
|         pygame.display.update() |         pygame.display.update() | ||||||
| 
 | 
 | ||||||
|         if board.game_lost or board.game_won: |         if board.game_lost or board.game_won: | ||||||
|             break |             break | ||||||
| 
 | 
 | ||||||
|         for event in pygame.event.get(): |         event = pygame.event.wait() | ||||||
|         if event.type == QUIT: |         if event.type == QUIT: | ||||||
|             pygame.quit() |             pygame.quit() | ||||||
|             sys.exit() |             sys.exit() | ||||||
|  |         elif event.type == UPDATETIMER: | ||||||
|  |             board.update_timer() | ||||||
|         elif event.type == MOUSEBUTTONUP and event.button == 1: |         elif event.type == MOUSEBUTTONUP and event.button == 1: | ||||||
|             if not board.game_started: |             if not board.game_started: | ||||||
|                 board.place_mines(event.pos) |                 board.place_mines(event.pos) | ||||||
|  |  | ||||||
		Loading…
	
		Reference in New Issue