Rectangles

Playing around with Pygame I tried to create programs which are pleasant to look at. ‘Rectangles’ generates – as it may sound like – rectangles with different size, color and position. They can appear from the four corners of the screen and have a gradient effect.

Usage

  • ‘s’ to take a screenshot
  • ‘Space’ generates a new set of rectangles

The First ExampleThe Second ExampleThe Third Example


# Python 2.7.7 Code
# Pygame 1.9.1 (for Python 2.7.7)
# Jonathan Frech  7th of March, 2015
#         edited 29th of March, 2015

# validates color integer
# extra feature: _min and _max implementation
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

# tick function
def tick():
	# handles events
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
				sys.exit()
		
		if event.type == pygame.KEYDOWN:
			# screenshot
			# (saved in cwd/screenshots/n.png)
			# ...cwd: current working directory
			# ...n  : screenshot's number
			if event.key == pygame.K_s:
				if not os.path.exists(os.getcwd() + "/screenshots/"):
					os.mkdir(os.getcwd() + "/screenshots")
				n = 1
				while os.path.exists(os.getcwd() + "/screenshots/" + str(n) + ".png"):
					n += 1
				pygame.image.save(main.SCREEN, os.getcwd() + "/screenshots/" + str(n) + ".png")
			
			# generate new rectangles
			if event.key == pygame.K_SPACE:
				# fill surface black (DISABLED)
				# main.SURF.fill([0, 0, 0])
				
				# maxium ('maxX' for x and 'maxY' for y) defines how large rectangles can be
				maxX, maxY = int(main.WIDTH / 1.5), int(main.HEIGHT / 1.5)
				
				for _ in range(0, 100):
					# defines variables
					
					# rectangles will randomly appear from any of the four corners ('corner')
					corner = ["topLeft", "topRight", "bottomLeft", "bottomRight"][random.randint(0, 3)]
					# 'p' as the pygame.draw.rect() argument
					p = [0, 0, 0, 0]
					# 'change' is used for gradient later
					change = [0, 0]
					# color is randomly assigned ('col')
					col = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
					
					# generates variables
					if corner == "topLeft":
						p = [0, 0, random.randint(0, maxX), random.randint(0, maxY)]
						change = [-1, -1]
					elif corner == "topRight":
						p = [main.WIDTH - random.randint(0, maxX), 0, main.WIDTH, random.randint(0, maxY)]
						change = [1, -1]
					elif corner == "bottomLeft":
						p = [0, main.HEIGHT - random.randint(0, maxY), random.randint(0, maxY), main.HEIGHT]
						change = [-1, 1]
					elif corner == "bottomRight":
						p = [main.WIDTH - random.randint(0, maxX), main.HEIGHT - random.randint(0, maxY), main.WIDTH, main.HEIGHT]
						change = [1, 1]
					
					# 'resolution' defines how fine the gradient is
					resolution = 20
					# 'colorChange' defines the color steps
					colorChange = 20
					
					# draw the rectangle and its gradient
					# (by drawing smaller rectangles with another color)
					w = -1
					for _ in range(0, (p[2] + p[3]) / 2 / resolution):
						w += 1
						pygame.draw.rect(
							main.SURF,
							[
								colorValid(col[0] + (w * colorChange)),
								colorValid(col[1]),
								colorValid(col[2])
							],
							[
								p[0] + change[0] * resolution * w,
								p[1] + change[1] * resolution * w,
								p[2],
								p[3]
							],
							0
						)

# render function
def render():
	main.SCREEN.fill([0, 0, 0])
	
	main.SCREEN.blit(pygame.transform.scale(main.SURF, main.SCALEDSIZE), [0, 0])
	pygame.display.flip()

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

# dummy class for global variables
class dummy():
	pass

# init
import pygame, sys, time, math, os, random

main = dummy()
main.TICKS = 0

main.WIDTH, main.HEIGHT = 1080, 720
main.SIZE = [main.WIDTH, main.HEIGHT]
main.SURF = pygame.Surface(main.SIZE)
main.SURF.fill([0, 0, 0])

main.SCALE = 1
main.SCALEDSIZE = [int(main.WIDTH * main.SCALE), int(main.HEIGHT * main.SCALE)]
main.SCREEN = pygame.display.set_mode(main.SCALEDSIZE)
pygame.display.set_caption("Rectangles")

# start program
run()
Advertisements

One thought on “Rectangles

  1. Pingback: Second Anniversary – J-Blog

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