Rand Pix

This program generates a snake of pixels which is randomly moving across the screen. If it leaves the screen, it (as in snakes) gets out the other side. It is also restricted to a length of 1000 pixels. As in ‘Colors V’ there are other ways the snake can look, based on the code used (I may post another color variant in the future).
Green-Orange Snake From The LeftBlue-Red Snake From The TopBlue-White Snake On The Top And Bottom


# Python 2.7.7 Code
# Pygame 1.9.1 (for Python 2.7.7)
# Jonathan Frech 23rd of March, 2015
#         edited  9th of April, 2015

# validates color integer
def getMousePos():
	return [pygame.mouse.get_pos()[0] / main.SCALE, pygame.mouse.get_pos()[1] / main.SCALE]

# 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():
	
	# handle events
	for event in pygame.event.get():
		# quit
		if event.type == pygame.QUIT:
				sys.exit()
		
		# keys
		if event.type == pygame.KEYDOWN:
			# save current display
			if event.key == keys.screenshot:
				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")
				print "SAVED"
	
	# move snake
	for _ in range(0, 20):
		#"""
		if random.randint(0, 1) == 0:
			# x
			if random.randint(0, 1) == 0:
				main.POS[0] += 1
			else:
				main.POS[0] -= 1
		else:
			# y
			if random.randint(0, 1) == 0:
				main.POS[1] += 1
			else:
				main.POS[1] -= 1
		#"""
		
		# other move mechanics
		"""
		moved = False
		dist = 1
		while not moved:
			r = random.randint(0, 3)
			if r == 0:
				if [main.POS[0] + dist, main.POS[1]] not in main.POSLIST:
					main.POS[0] += dist
				else:
					r = 1
			if r == 1:
				if [main.POS[0] - dist, main.POS[1]] not in main.POSLIST:
					main.POS[0] -= dist
				else:
					r = 2
			if r == 2:
				if [main.POS[0], main.POS[1] + dist] not in main.POSLIST:
					main.POS[1] += dist
				else:
					r = 3
			if r == 3:
				if [main.POS[0], main.POS[1] - dist] not in main.POSLIST:
					main.POS[1] -= dist
				else:
					r = 4
			
			if r == 4:
				# cannot move
				dist += 1
			else:
				moved = True
		#"""
		
		"""
		if random.randint(0, 3) == 0:
			if main.DIR in ["right", "left"]:
				dirs = ["up", "down"]
			else:
				dirs = ["right", "left"]
			
			main.DIR = dirs[random.randint(1, len(dirs)) - 1]
		#"""
		
		"""
		main.DIR = ""
		mousePos = getMousePos()
		
		xDif, yDif = math.fabs(mousePos[0] - main.POS[0]), math.fabs(mousePos[1] - main.POS[1])
		if xDif > yDif:
			if main.POS[0]  mousePos[0]:
				main.DIR = "left"
		else:
			if main.POS[1] > mousePos[1]:
				main.DIR = "up"
			elif main.POS[1] < mousePos[1]:
				main.DIR = "down"
		#"""
		
		"""
		if main.DIR == "right":
			main.POS[0] += 1
		elif main.DIR == "left":
			main.POS[0] -= 1
		elif main.DIR == "up":
			main.POS[1] -= 1
		elif main.DIR == "down":
			main.POS[1] += 1
		#"""
		
		# bounds
		if main.POS[0] = main.WIDTH:
			main.POS[0] = 0
		
		if main.POS[1] = main.HEIGHT:
			main.POS[1] = 0
		
		# add position
		main.POSLIST.append(main.POS[:])
	
	# make sure the snake does not get too long
	while len(main.POSLIST) > 1000:
		main.POSLIST.pop(0)

# render function
def render():
	# fill
	main.SCREEN.fill([0, 0, 0])
	main.SURF.fill([
		0,#colorValid(main.TICKS),
		0,#colorValid(main.TICKS),
		0#colorValid(main.TICKS)
		])
	
	# make the array
	array = pygame.PixelArray(main.SURF)
	
	# draw the snake (color code!)
	w = -1
	for _ in main.POSLIST:
		w += 1
		array[_[0]][_[1]] = [
			colorValid(255./len(main.POSLIST)*w),
			#colorValid((255./len(main.POSLIST)*w)**2),
			colorValid(main.TICKS),
			colorValid(main.TICKS+(random.randint(1,2)*40)),
		]	
	
	# delete the array
	del array
	
	# blit and flip
	main.SCREEN.blit(pygame.transform.scale(main.SURF, [int(main.WIDTH * main.SCALE), int(main.HEIGHT * main.SCALE)]), [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

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

# main dummy
main = dummy()
main.TICKS = 0

main.resolution = 10
main.WIDTH = 1080 / main.resolution
main.HEIGHT = 720 / main.resolution
main.SCALE = 1 * main.resolution

main.SIZE = [main.WIDTH, main.HEIGHT]
main.SCALEDSIZE = [int(main.WIDTH * main.SCALE), int(main.HEIGHT * main.SCALE)]

main.SURF = pygame.Surface(main.SIZE)
main.SURF.fill([0, 0, 0])

main.SCREEN = pygame.display.set_mode(main.SCALEDSIZE)
pygame.display.set_caption("Rand Pix")

# snake
main.POS = [main.WIDTH / 2, main.HEIGHT / 2]
main.POSLIST = []
main.POSLIST.append(main.POS[:])
main.DIR = "right"

# key dummy
keys = dummy()
keys.screenshot = pygame.K_s

# start program
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