Colored Rectangles

This program lets you spawn in a rectangle with a randomly assigned color. This rectangle will then slowly move towards the screen’s edge, eventually fading away.

Controls

  • Left click spawns in a new rectangle at current  mouse position
  • Space takes a screenshot

The first example The second example The third example


# Python 2.7.7 Code
# Pygame 1.9.1 (for Python 2.7.7)
# Jonathan Frech 22nd of January, 2016
#         edited 29th of January, 2016

# importing needed modules
import pygame, sys, time, math, os, random

""" CLASSES """
class FRAME():
	def __init__(self, pos):
		self.positions = [pos[:], pos[:], pos[:], pos[:]]
		self.color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
		self.lifetime = 0

	def render(self, surface):
		pygame.draw.polygon(surface, self.color, self.positions)

	def tick(self):
		self.lifetime += 1
		p = [[0, 0], [G.WIDTH, 0], [G.WIDTH, G.HEIGHT], [0, G.HEIGHT]]
		for i in range(0, len(self.positions)):
			for _ in range(0, 2):
				self.positions[i][_] += (p[i][_] - self.positions[i][_]) / 50.

		# fade towards black
		if self.lifetime > 60*7: # 7 seconds
			for _ in range(0, 3):
				if self.color[_] > 0:
					self.color[_] -= 1

""" FUNCTIONS """
# validates a color integer
def colorValid(_color, _min = 0, _max = 255):
	newColor = math.fabs(_color)
	n = _max - _min
	if newColor > n:
		if int(newColor / n) % 2 == 0:
			newColor = newColor % n
		else:
			newColor = n - (newColor % n)
	
	return int(newColor) + _min

# returns an integer version of given positon
def intpos(_pos):
	return [int(_pos[0]), int(_pos[1])]

# basic vector functions
def vecConvert(p1, p2):
	return [p2[0] - p1[0], p2[1] - p1[1]]
def vecLen(vec):
	return math.sqrt( (vec[0]**2) + (vec[1]**2) )
def vecMultiply(vec, n):
	return [vec[0] * n, vec[1] * n]
def vecGetPoint(vec, point):
	return [point[0] + vec[0], point[1] + vec[1]]

""" GAME """
# game class
class GAME():
	# initialize program
	def __init__(self):
		# variables
		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

		# frame list
		self.FRAMES = []

		# functions
		pygame.display.set_caption("Colored Rectangles")
	
	# tick function
	def tick(self):
		# handle events
		for event in pygame.event.get():
			# quit program
			if event.type == pygame.QUIT:
				self.quit()
			
			# take a screenshot
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_SPACE:
					self.screenshot()
			
			# add a new frame
			if event.type == pygame.MOUSEBUTTONDOWN:
				if event.button == 1:
					self.FRAMES.append(FRAME(list(pygame.mouse.get_pos())))

		# tick frames
		for frame in self.FRAMES:
			frame.tick()
			# remove black frames
			if frame.color == [0, 0, 0]:
				self.FRAMES.remove(frame)

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

		# render frames
		for frame in self.FRAMES:
			frame.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

One thought on “Colored Rectangles

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