Moving Fonts

Experimenting with pygame’s font functions, I wanted to list every font pygame could reach with its built-in font.get_fonts() function. This program does so by letting you spawn in the wonderful sentence ‘Hello world.’ and assigns it a font based on the previously mentioned function.

Controls

  • Left click spawns in a new sentence at current mouse position
  • Space saves a screenshot

The first example The third example The second example


# Python 2.7.7 Code
# Pygame 1.9.1 (for Python 2.7.7)
# Jonathan Frech  9th of January, 2016
# Jonathan Frech 13th of January, 2016
# Jonathan Frech 15th of January, 2016

# importing needed modules
import pygame, sys, time, math, os, random
pygame.font.init()

""" CLASSES """
class entity():
	def __init__(self, fnt, pos):
		self.fnt = pygame.font.Font(fnt, 30)
		self.pos = pos
		
		self.clr = [255, 0, 0]
		self.txt = self.fnt.render("Hello world.", 1, self.clr)
		self.rct = self.txt.get_rect()
		self.sze = [self.rct.right, self.rct.bottom]
		self.vel = [random.randint(-10, 10)/10., random.randint(-10, 10)/10.]

	def tick(self):
		for _ in range(0, 2):
			self.pos[_] += self.vel[_]
			if self.pos[_] < 0:
				self.pos[_] = 0
				self.vel[_] *= -1
			if self.pos[_] > G.SIZE[_] - self.sze[_]:
				self.pos[_] = G.SIZE[_] - self.sze[_]
				self.vel[_] *= -1

	def render(self, surface):
		surface.blit(self.txt, self.pos)

""" GAME """
# game class
class GAME():
	# initialize program
	def __init__(self):
		self.WIDTH, self.HEIGHT = 1080, 720
		self.SIZE = [self.WIDTH, self.HEIGHT]
		self.SURF = pygame.Surface(self.SIZE)
		self.SCREEN = pygame.display.set_mode(self.SIZE)

		self.TICKS = 0
		self.RUNNING = True

		# disabled
		"""self.offset = 0"""

		# get font names
		self.fonts = pygame.font.get_fonts()
		
		# variables
		self.f = 0
		self.entities = []

		# functions
		pygame.display.set_caption("Moving Fonts")
	
	# tick function
	def tick(self):
		# handle events
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				self.quit()
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_SPACE:
					self.screenshot()

				# disabled
				"""if event.key == pygame.K_q:
					print self.FONTS[self.FONTNUMBER]
					self.FONT = pygame.font.Font(pygame.font.match_font(self.FONTS[self.FONTNUMBER]), 50)
					self.FONTNUMBER += 1
					if self.FONTNUMBER > len(self.FONTS) - 1:
						self.FONTNUMBER = 0"""
			
			# spawn in a new entity
			if event.type == pygame.MOUSEBUTTONDOWN:
				if event.button == 1:
					if self.f >= len(self.fonts):
						self.f = 0
					self.entities.append(entity(pygame.font.match_font(self.fonts[self.f]), list(pygame.mouse.get_pos())))
					self.f += 1

		# tick all entities
		for e in self.entities:
			e.tick()

	# render function
	def render(self):
		# fill
		self.SURF.fill([0, 0, 0])

		# disabled
		"""self.offset += (self.TICKS*1)
		sze = 30
		hgt = -self.offset
		for _ in pygame.font.get_fonts():
			fnt = pygame.font.Font(pygame.font.match_font(_), sze)
			txt = fnt.render("Hello world.", 1, [255, 0, 0])
			rct = txt.get_rect()
			pos = [(self.WIDTH-rct.right)/2, hgt]
			hgt += rct.bottom
			self.SURF.blit(txt, pos)

		if self.offset > hgt:
			self.offset = 0"""

		# render entities
		for e in self.entities:
			e.render(self.SURF)

		# blit and flip
		self.SCREEN.blit(self.SURF, [0, 0])
		pygame.display.flip()
	
	# quits
	def quit(self):
		self.RUNNING = False

	# takes a screenshot
	def screenshot(self):
		path = os.getcwd() + "/out/"
		
		try:
			if not os.path.isdir(path):
				os.mkdir(path)
			
			name = "img" + str(len(os.listdir(path))) + ".png"
			pygame.image.save(self.SURF, path + name)
		except:
			pass

	# run function (uses tick() and render())
	def run(self):
		ticksPerSecond = 60
		lastTime = time.time() * 1000000000
		nsPerTick =  1000000000.0 / float(ticksPerSecond)
	
		ticks = 0
		frames = 0
	
		lastTimer = time.time() * 1000
		delta = 0.0
		
		while self.RUNNING:
			now = time.time() * 1000000000
			delta += float(now - lastTime) / float(nsPerTick)
			lastTime = now
			shouldRender = False
					
			while delta >= 1:
				ticks += 1
				self.TICKS += 1
				self.tick()
				delta -= 1
				shouldRender = True
			
			if shouldRender:
				frames += 1
				self.render()
			
			if time.time() * 1000 - lastTimer >= 1000:
				lastTimer += 1000
				
				# debug
				# print("Frames: " + str(frames) + ", ticks: " + str(ticks))
			
				frames = 0
				ticks = 0

# start game
G = GAME()
G.run()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s