Pascal’s Triangle

Pascal’s triangle is an interesting mathematical sequence. It is often written as a triangle, starting with \{1\}, then \{1, 1\}. To generate the next row, you add the two numbers above to form another one. So the next row in the sequence is \{1, 2, 1\} then \{1, 3, 3, 1\}, \{1, 4, 6, 4, 1\} and so on (sequence A007318 in OEIS).

One interesting property of Pascal’s triangle is the generation of binomials.
To calculate (a + b)^4, you can look at the 4th row (listed above and when starting to count at 0) and determine
(a + b)^4 = (1 \cdot a^4 \cdot b^0) + (4 \cdot a^3 \cdot b^1) + (6 \cdot a^2 \cdot b^2) + (4 \cdot a^1 \cdot b^3) + (1 \cdot a^0 \cdot b^4)
(a + b)^4 = a^4 + 4a^3b + 6a^2b^2 + 4ab^3 + b^4.

This program generates Pascal’s sequence in a rather unusual shape, looking a bit like a crown.

To get more information about Pascal’s triangle, check out this Wikipedia entry.

Controls

  • F1 advances the sequence
  • Space takes a screenshot

Fontsize 50 Fontsize 10 Fontsize 1


# Python 2.7.7 Code
# Pygame 1.9.1 (for Python 2.7.7)
# Jonathan Frech 25th of March, 2016

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

# define the font size
FONTSIZE = 50

""" FUNCTIONS """
# generate the next row in Pascal's triangle
def advance(row):
	# variables
	last = None
	Row = []
	
	# go through row and add
	for r in row:
		if last == None:
			Row.append(1)
		else:
			Row.append(last + r)
		last = r
	Row.append(1)
	
	# return
	return Row

# check if n is prime
def prime(n):
	if n <= 1:
		return False
	for _ in range(2, n):
		if n % _ == 0:
			return False
	return True

""" GAME """
# game class
class GAME():
	# initialize program
	def __init__(self):
		# screen
		self.width, self.height = 1080, 720
		self.size = [self.width, self.height]
		self.surface = pygame.Surface(self.size)
		self.screen = pygame.display.set_mode(self.size)

		# main
		self.ticks = 0
		self.running = True

		# variables
		self.rows = [[1]]
		self.font = pygame.font.SysFont(None, FONTSIZE)

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

		# advance the triangle
		if pygame.key.get_pressed()[pygame.K_F1]:
			self.rows.append(advance(self.rows[-1]))

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

		# draw the triangle's numbers
		yoff = 0
		for row in self.rows:
			x = 0
			for r in row:
				x += 1
				
				# define color
				color = [255, 255, 255]

				# get text and rect
				txt = self.font.render(str(r), True, color)
				rct = txt.get_rect()
				
				# dividing the screen's width into equal pieces and then offsetting by a half of the text's size
				pos = [(2*self.width*x - len(row)*rct.right - self.width)/(2*len(row)), yoff]
				
				# blit
				self.surface.blit(txt, pos)

			yoff += self.font.get_linesize()

		# blit and flip
		self.screen.blit(self.surface, [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))) + " (fontsize " + str(FONTSIZE) + ").png"
			pygame.image.save(self.surface, 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