Rotating Squares

Using the pygame.transform.rotozoom() function, a velocity argument and changing colors, this program rotates squares across the screen.

Controls

  • Left click spawns in a new square 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 27th of November, 2015
#         edited  2nd of January , 2016

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

""" CLASSES """
class entity():
	def __init__(self, _pos):
		self.pos = _pos
		self.size = [20, 20]
		self.color = [255, 0, 0]
		self.img = pygame.Surface(self.size)
		
		self.angle = 0
		self.velocity = [random.randint(-5, 5), random.randint(-5, 5)]

	def render(self, _surface):
		self.img.fill(self.color)
		_surface.blit(pygame.transform.rotozoom(self.img, self.angle, 1), self.pos)

	def tick(self):
		self.color[random.randint(0, 2)] += random.randint(-10, 10)
		for _ in range(0, 3):
			if self.color[_] < 0:
				self.color[_] = 0
			elif self.color[_] > 255:
				self.color[_] = 255
		
		self.angle += 1
		
		for _ in range(0, 2):
			self.pos[_] += self.velocity[_]
			if self.pos[_] < 0:
				self.pos[_] = 0
				self.velocity[_] *= -1
			
			elif self.pos[_] + self.size[_] > GAME.SIZE[_]:
				self.pos[_] = GAME.SIZE[_] - self.size[_] 
				self.velocity[_] *= -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

""" 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

		self.entities = []

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

			if event.type == pygame.MOUSEBUTTONDOWN:
				if event.button == 1:
					self.entities.append(entity(list(pygame.mouse.get_pos())))
		
		# tick entities
		for _ in self.entities:
			_.tick()

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

		for _ in self.entities:
			_.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
GAME = GAME()
GAME.run()
Advertisements

One thought on “Rotating Squares

  1. Pingback: J-Filters IV | 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