Skip to content

Instantly share code, notes, and snippets.

@cowdinosaur
Last active March 13, 2017 00:23
Show Gist options
  • Save cowdinosaur/b3f84aafba560acd0c04 to your computer and use it in GitHub Desktop.
Save cowdinosaur/b3f84aafba560acd0c04 to your computer and use it in GitHub Desktop.
Pygame barebones template
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
@finnbear
Copy link

finnbear commented Mar 12, 2017

This will crash some computers (including mine)! You must limit the frame rate as such:

import time
import datetime

fps_target = 30 # Frames per second  
spf_target = float(1) / fps_target # Seconds per frame  

while (True):  
	global spf_target	
  
	# Log initial time  
	t0 = datetime.datetime.now()

	# Check for events
	for event in pygame.event.get():
	     if event.type == pygame.QUIT:
	          sys.exit()

	# All update logic goes here	 
 
	# Log time after update logic
	t1 = datetime.datetime.now()

	# Calculate elapsed (delta) time
	tDelta = t1 - t0

	# Delay if necessary to meet target fps
	if (spf_target > tDelta.total_seconds()):
	     time.sleep(spf_target - tDelta.total_seconds())
 
	# All draw logic goes here

	pygame.display.flip()

Alternatively, just sleep for about 15 milliseconds each frame.
time.sleep(float(15) / 1000)

@finnbear
Copy link

finnbear commented Mar 12, 2017

Also, you could replace
pygame.display.update()
with
pygame.display.flip()
unless you don't plan to update the whole screen.

http://stackoverflow.com/questions/29314987/difference-between-pygame-display-update-and-pygame-display-flip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment