Create a gist now

Instantly share code, notes, and snippets.

@wkta /day_8.py
Last active Aug 29, 2015

What would you like to do?
#MonthOfCode day 8 - mathematics
import random
import sys # for exit function
import time
import pygame
from pygame import Rect
# DEFINITIONS
################################################
DISP_COLOR=(230, 190, 230) #gray with a violet touch
PREDEF_RADIUS = 8
PREDEF_L_WIDTH = 2
NB_MAX_NODES = 12
CELL_PX_SIZE = 32
NB_CELLS_ROW = 16
def displayNode( matr_x, matr_y ):
nx,ny = ( matr_x*CELL_PX_SIZE, matr_y*CELL_PX_SIZE )
pygame.draw.circle(window, DISP_COLOR,
(nx,ny), PREDEF_RADIUS, PREDEF_L_WIDTH)
# MAIN PART
################################################
# init. pygame libr; create the screen and diplays a help message in the console
pygame.init()
window = pygame.display.set_mode((CELL_PX_SIZE*NB_CELLS_ROW, CELL_PX_SIZE*NB_CELLS_ROW))
# init. a boolean matrix; this aims at representing nodes of a random graph
cnt_nodes = 0
bool_matr = list()
coord_nodes = list()
for i in xrange(NB_CELLS_ROW ):
line = list()
for j in xrange( NB_CELLS_ROW):
if( cnt_nodes > NB_MAX_NODES or j<2 or j>(NB_CELLS_ROW-2) or i<2 or i>(NB_CELLS_ROW-2) ):
line.append( False )
continue
if( random.choice( range(16))==0 ):
line.append( True)
coord_nodes.append( (i,j) )
cnt_nodes +=1
else:
line.append( False)
bool_matr.append(line)
# random edges
assoc_matr = dict()
for i in xrange( cnt_nodes):
for j in xrange(cnt_nodes):
if j>=i:
continue
assoc_matr[ (i,j) ] = True if (random.choice(range(4))==0 ) else False
# diplays nodes
for i in xrange(NB_CELLS_ROW ):
for j in xrange( NB_CELLS_ROW):
if( bool_matr[j][i] ):
displayNode(j, i)
# diplays edges
for nodes_pair in assoc_matr:
if( assoc_matr[ nodes_pair ] ): # the two nodes are linked
x1,y1 = coord_nodes[ nodes_pair[0] ]
x2,y2 = coord_nodes[ nodes_pair[1] ]
pygame.draw.line(window, DISP_COLOR,
(x1*CELL_PX_SIZE,y1*CELL_PX_SIZE),
(x2*CELL_PX_SIZE,y2*CELL_PX_SIZE) )
#draw it to the screen
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
time.sleep(0.1)
Owner

wkta commented Mar 10, 2014

generates and displays random graphs, screenshot available on twitter @spartangeek

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment