How to use the pygame.time.Clock function in pygame

To help you get started, we’ve selected a few pygame examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github horstjens / ThePythonGameBook / pygame / 024_pygamemenu.py View on Github external
def main():

    #Set up pygame
    pygame.init()
    Config.reslist = pygame.display.list_modes()
    pygame.display.set_caption("EzMenu Example")
    screen, background = repaint()
    makemenu(0)
    FPS = 30
    clock = pygame.time.Clock()
    cooldown = 0
    
    # ask for playername
    playername = ask(screen, "Please type in your name and press ENTER")
    print( playername )
    
    while Config.menuloop:
        pygame.display.set_caption("last game result: %s" % Config.result)
        #Get all the events called
        seconds = clock.tick(FPS) / 1000.0 # do not go faster than this frame rate
        if cooldown < 0:
            cooldown = 0
        if cooldown > 0:
            cooldown -= seconds
        events = pygame.event.get()
github CharlesPikachu / AIGames / AIPacman / Algorithm_1 / Algorithm_1_v2 / gameAPI / game.py View on Github external
def __showText(self, msg, position):
		clock = pygame.time.Clock()
		text = self.font.render(msg, True, self.config.WHITE)
		while True:
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					sys.exit()
					pygame.quit()
			self.screen.fill(self.config.BLACK)
			self.screen.blit(text, position)
			pygame.display.flip()
			clock.tick(10)
	def __createGameMap(self):
github filipeabperes / Py3ODE / examples / tutorial2.py View on Github external
def simulate(world, body1, body2):
    # Initialize pygame
    pygame.init()
    
    # Open a display
    srf = pygame.display.set_mode((640,480))

    clk = pygame.time.Clock()

    # Keep the window open and wait for a key
    fps = 50
    dt = 1.0/fps
    loopFlag = True
    while loopFlag:
        events = pygame.event.get()
        for e in events:
            if e.type==QUIT:
                loopFlag=False
                
        # Clear the screen
        srf.fill((255,255,255))

        x1,y1,z1 = body1.getPosition()
        x2,y2,z2 = body2.getPosition()
github ternus / pygame-examples / snake.py View on Github external
import sys
import time
import random

from pygame.locals import *

FPS = 5
pygame.init()
fpsClock=pygame.time.Clock()

SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
surface = pygame.Surface(screen.get_size())
surface = surface.convert()
surface.fill((255,255,255))
clock = pygame.time.Clock()

pygame.key.set_repeat(1, 40)

GRIDSIZE=10
GRID_WIDTH = SCREEN_WIDTH / GRIDSIZE
GRID_HEIGHT = SCREEN_HEIGHT / GRIDSIZE
UP    = (0, -1)
DOWN  = (0, 1)
LEFT  = (-1, 0)
RIGHT = (1, 0)
    
screen.blit(surface, (0,0))

def draw_box(surf, color, pos):
    r = pygame.Rect((pos[0], pos[1]), (GRIDSIZE, GRIDSIZE))
    pygame.draw.rect(surf, color, r)
github koduj-z-klasa / python101 / games / life.py View on Github external
def __init__(self, width, height, cell_size=10):
        """
        Przygotowanie ustawień gry
        :param width: szerokość planszy mierzona liczbą komórek
        :param height: wysokość planszy mierzona liczbą komórek
        :param cell_size: bok komórki w pikselach
        """
        pygame.init()
        self.board = Board(width * cell_size, height * cell_size)
        # zegar którego użyjemy do kontrolowania szybkości rysowania
        # kolejnych klatek gry
        self.fps_clock = pygame.time.Clock()
        self.population = Population(width, height, cell_size)
github kidscancode / gamedev / shmup / shmup-10.py View on Github external
self.rect.bottom = y
        self.rect.centerx = x
        self.speedy = -10

    def update(self):
        self.rect.y += self.speedy
        # kill if off top of screen
        if self.rect.bottom < 0:
            self.kill()

# initialize pygame
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()

# load graphics and sounds
pew_sound = pygame.mixer.Sound(path.join(sound_dir, 'pew.wav'))
expl_sounds = []
for snd in ['expl3.wav', 'expl6.wav']:
    expl_sounds.append(pygame.mixer.Sound(path.join(sound_dir, snd)))
pygame.mixer.music.load(path.join(sound_dir, 'tgfcoder-FrozenJam-SeamlessLoop.ogg'))
pygame.mixer.music.set_volume(0.4)
background = pygame.image.load(path.join(img_dir, "starfield.png")).convert()
background_rect = background.get_rect()
player_image = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')).convert()
bullet_image = pygame.image.load(path.join(img_dir, 'laserRed16.png')).convert()
meteor_list = ['meteorBrown_med3.png', 'meteorBrown_med1.png',
               'meteorBrown_small2.png', 'meteorBrown_tiny1.png']
meteor_images = []
for img in meteor_list:
github hypatia-software-org / hypatia-engine / hypatia / render.py View on Github external
def __init__(self, filters=None):
        """Will init pygame.

        Args:
          filters (list): list of functions which takes and
            returns a surface.

        """

        pygame.init()
        pygame.mouse.set_visible(False)
        self.clock = pygame.time.Clock()
        self.time_elapsed_milliseconds = 0
        display_info = pygame.display.Info()
        self.screen_size = (display_info.current_w, display_info.current_h)
        self.screen = pygame.display.set_mode(self.screen_size,
                                              FULLSCREEN | DOUBLEBUF)
        self.filters = filters
github CharlesPikachu / Games / Game3 / Game3.py View on Github external
def main():
	# 初始化
	pygame.init()
	clock = pygame.time.Clock()
	# 加载图片
	game_img_used = pygame.image.load(GetImagePath('./pictures'))
	game_img_used_rect = game_img_used.get_rect()
	# 设置窗口
	screen = pygame.display.set_mode((game_img_used_rect.width, game_img_used_rect.height))
	pygame.display.set_caption('拼图游戏')
	# 开始界面
	size = ShowStartInterface(screen, game_img_used_rect.width, game_img_used_rect.height)
	if isinstance(size, int):
		num_rows, num_cols = size, size
		num_cells = size * size
	elif len(size) == 2:
		num_rows, num_cols = size[0], size[1]
		num_cells = size[0] * size[1]
	else:
		raise ValueError('cell size error')
github VerifiableRobotics / LTLMoP / src / lib / handlers / drive / CKBotRun.py View on Github external
def run(self):
        """
        Start the demo. This method will block until the demo exits.
        This method is used if the simulator is run stand-alone.
        """

        self.clock = pygame.time.Clock()
        self._running = True
        self.doEvents()

        # Receive Locomotion commands for all the hinges from LTLMoP.
        # Use these commands as reference angles for simple P-controlled servos.	
        while self._running:

		self.doEvents()

	    	# Servo Behavior with Gaits [ YAY CONTROLS ! ]
		counter = self.counter
		
		self.rungait()
	
	        # Simulation Step
	        self.space.collide((), self._nearcb)
github spiffomatic64 / SpiffBot / twitch_bot_utils.py View on Github external
def notify(self):
        elapsed = time.time() - self.notified
        if elapsed >= self.throttle:
            logging.log(logging.INFO,"Playing notification sound to grab attention %s" % elapsed)
            sound_scare = pygame.mixer.Sound(self.sound)
            channel = sound_scare.play()
            channel.set_volume(1,1) #set volume to full

            clock = pygame.time.Clock()
            # check if playback has finished
            while channel.get_busy():
               clock.tick(30)
            self.notified = time.time()
            return False
        else:
            return round(elapsed)