def display(self, dst, corner, radius): white = (255, 255, 255) self.draw_bounds(dst, white, corner, radius) if self.num_items() == 0: return # draw the items item_skip = 3 * radius row = col = 0 num_cols = self.num_cols for (i, item) in enumerate(self.items): center = corner + item_skip * vector(col, row) item.display(dst, center, radius) col += 1 if col >= num_cols: col = 0 row += 1 # draw a box around the currently selected item if not self.selecting: return loc = self.selection center = corner + item_skip * loc skip = item_skip * vector(1, 1) corner = center - 0.5 * item_skip * vector(1, 1) dims = corner.list() + skip.list() pygame.draw.rect(dst, white, dims, 1)
def kbdraw(self, event): if event.type == KEYDOWN: if event.key == K_w: self.hist_key = event.key self.move_vec = vector(0, -5) self.player_sprite = self.player_sprite_up if event.key == K_s: self.hist_key = event.key self.move_vec = vector(0, 5) self.player_sprite = self.player_sprite_down if event.key == K_d: self.hist_key = event.key self.move_vec = vector(5, 0) self.player_sprite = self.player_sprite_right if event.key == K_a: self.hist_key = event.key self.move_vec = vector(-5, 0) self.player_sprite = self.player_sprite_left if event.key == K_ESCAPE: exit() if event.type == KEYUP and event.key == self.hist_key: self.move_vec = vector(0, 0) self.pos += self.move_vec sprite_pos = self.pos.tupleit() sprite_pos = (sprite_pos[0] - self.player_sprite.get_width() / 2, sprite_pos[1] - self.player_sprite.get_height() / 2) screen.blit(background, (sprite_pos[0] - 5, sprite_pos[1] - 5), pygame.Rect(sprite_pos[0] - 5, sprite_pos[1] - 5, 60, 60)) screen.blit(self.player_sprite, sprite_pos)
def normalupdate(self, entities): #if timetodie was specified during initialization, kill the projectile when the frame timer hits 0 if self.timetodie != None: if self.timetodie.update(): self.ondeath(entities) #friendly bullet if self.id == 1: #self.image = bullet image self.image = self.images[0] #when the image is drawn it'll face in the direction it's travelling self.imagerotation = -self.rotation if self.speed != 0: #move using it's constant velocity, change it's position self.velocity = vector(self.speed, 0) self.velocity.rotate_ip(self.rotation) self.pos = vector(self.pos) + self.velocity #enemy bubble if self.id == 2: #loops the animation for the bubble bouncing self.image = self.images[0] #when the timer is up, reset it and cycle the list of images if self.imagetimer.update(): self.imagetimer.reset() self.images.append(self.images.pop(0)) #unless it's stationary, update it's position based on velocity if self.speed != 0: self.velocity = vector(self.speed, 0) self.velocity.rotate_ip(self.rotation) self.pos = vector(self.pos) + self.velocity pass
def key_released(self, key): if not self.selecting: return mapping = { pygame.K_UP: [0, -1], pygame.K_DOWN: [0, 1], pygame.K_LEFT: [-1, 0], pygame.K_RIGHT: [1, 0] } if key in mapping and self.num_items() > 0: vel = vector(mapping[key]) loc = self.selection + vel num_items = self.num_items() num_cols = self.num_cols num_rows = self.num_rows() loc += vector(num_cols, num_rows) loc[0] %= num_cols loc[1] %= num_rows if loc[0] >= num_items % num_cols and \ loc[1] == num_rows - 1: if vel[1] < 0: loc[1] = num_rows - 2 elif vel[0] != 0: if vel[0] < 0 and self.selection[0] == 0: loc[0] = num_items % num_cols - 1 else: loc[0] %= num_items % num_cols else: loc[1] = 0 self.selection = loc
def display(self, dst, center, radius): color = (255, 255, 255) # Compute six different corners for the central hexagon vels = {'N': 90, 'NE': 30, 'SE': -30, 'S': -90, 'SW': -150, 'NW': 150} d2r = math.pi / 180 dir_vel = { k: vector(math.cos(t * d2r), math.sin(t * d2r)) for (k, t) in vels.iteritems() } # Now add in extra points for each outer hexagon. Uses an # ordering to only compute each unique corner point once. dirs = ['N', 'NE', 'SE', 'S', 'SW', 'NW'] points = [[x] for x in range(6)] for x in range(6): points += [[x, x], [x, x, (x + 1) % 6], [(x + 1) % 6, (x + 1) % 6, x]] zero = vector(0, 0) points = [sum([dir_vel[dirs[dir]] for dir in p], zero) for p in points] # Build up the list of edges we want to actually draw between points. # Separated out so we generate each segment via rotational symmetry. segments = [[0, 1, 2, 3, 4, 5, 0]] for x in range(6): y = 3 * x vals = [y, y + 1, y + 2, y + 3] vals = [x] + [6 + v % 18 for v in vals] segments += [vals] # Now actually draw line segments between each point in our hex grid icon. for line in segments: plist = [center + 0.5 * radius * points[p] for p in line] plist = [p.list() for p in plist] pygame.draw.lines(dst, color, False, plist)
def updateLoop(self): TATA = 0xffaaffbb TATA = TATA.to_bytes(4, 'little') while not self.die: try: v = self.serialConnection.read(4) if v != TATA or self.die: continue # read 3 float vectors: gravity, orientation, acceleration # 3 vectors = 9 floats = 36 bytes data = self.serialConnection.read(36) data = struct.unpack('f' * 9, data) self.gravity = vector(*data[0:3]) self.orientation = vector(*data[3:6]) self.acceleration = vector(*data[6:9]) self.lastUpdate = time.time() self.updateCount += 1 except BaseException as e: print(e) self.serialConnection.close() self.serialConnection.open()
def applyForce1(self,point,mag,direction): # create a new zero vector temp = vector((0,0,0),(0,0,0)) # copying the direction vector to the temprary vector temp.x,temp.y,temp.z = direction.x,direction.y,direction.z # multiplying the vector to the magnitude temp.mult(mag) # checking the line execution of the focre k = self.pos.get() r = vector(k,point) rx,ry,rz = makeVector(r.x,r),makeVector(r.y,r),makeVector(r.z,r) # calculating the rotational effect of that force phi = getAngle(r,temp) # get angle b/w r,F torque = r.magCal()*temp.magCal() *math.sin(phi) # T = |r|*|F|*sin(phi)* n^ _dir_ = cross(r,temp) # n^ print r.get(),point _dir_.normalized() v = makeVector(torque,_dir_) self.torque.copy(v) # calculating the angular acc self.updateAngAcc() # calculating the force if temp.isAlong(rx): temp.multS(rx) if temp.isAlong(ry): temp.multS(ry) if temp.isAlong(rz): temp.multS(rz) # copying the temp force to the force self.force.add(temp) # updating the acc self.updateAcc()
def update(self,screen,player,entities,inencounter): if not inencounter and self.cango: location = player.pos self.pos = vector(self.pos).slerp(location,self.slip) else: location = self.spawnpos self.pos = vector(self.pos).slerp(location,0.5) self.previousposlist.append(self.pos) self.previousposlist.pop(0) pygame.draw.lines(screen,(90,90,90),False,self.previousposlist,2) imagerect = COINIMAGE_NOOUT.get_rect() imagerect.center = self.pos screen.blit(COINIMAGE_NOOUT,imagerect) glitterprob = uniform(0,1) if glitterprob < 0.01: randomangle = randint(0,360) inplace = vector(0,randint(0,3)) inplace.rotate_ip(randomangle) glitterpos = self.pos+inplace length = randint(1,2) for angle in range(0,270+1,90): entities.add(e.Dust(glitterpos,3,(0,0),angle,length)) if player.rect.collidepoint(self.pos): self.delete = True self.collected = True if inttuple(self.pos) == inttuple(self.spawnpos): self.cango = True
def __init__(self, baud=115200, port=None, timeout=1): if port == None: ports = serial.tools.list_ports.comports() assert len(ports) > 0, "No ports found, please provide a port" port = str(ports[0]).split(" ")[0] self.port = port self.baud = baud self.timeout = timeout try: self.serialConnection = serial.Serial(self.port, self.baud, timeout=self.timeout) except: raise BaseException("Couldnt open serial port '%s'" % self.port) self.gravity = vector(0, 0, 0) self.orientation = vector(0, 0, 0) self.acceleration = vector(0, 0, 0) self.lastUpdate = 0 self.updateCount = 0 self.die = False self.updateThread = threading.Thread(target=self.updateLoop) self.updateThread.start()
def __init__(self, width, height): self.dims = vector(width, height) self.points = [] # List of where each location is in the world self.edges = [] # List of which pairs of locations are connected # Begin world generation by selecting points in a rectangular region print 'Generating nodes...' #self.uniform(num_points) self.bridson(width / 12) # Now we want to connect up some of the points (add roads between locations) n = len(self.points) print 'Connecting ' + str(n) + ' nodes...' self.edges = self.build_edges(self.euclid) # Place some actual trees and content within each of the locations self.generator = ForestGenerator() level_dims = vector(12, 17) print 'Building levels...' self.levels = [Level(level_dims) for i in range(n)] for i in range(n): self.build_level(i) # Add in connections so that when players reach the edge of a location they # will be taken to the corresponding location print 'Connecting levels...' self.connect_levels() print 'World generation done!'
def getdictfromimage(): spritesheet = pygame.image.load( "sprites/idle_run_jump_AA.png").convert_alpha() dims = vector(13, 26) spritelist = [] for x in range(int(spritesheet.get_width() // dims[0])): newimage = pygame.Surface(dims, pygame.SRCALPHA) newimage.fill((0, 0, 0, 0)) newimage.convert_alpha() newimage.blit(spritesheet, (-(x * dims[0]), 0)) imgoutline = outline(newimage) newimage.convert_alpha() finalimage = pygame.Surface( vector(imgoutline.get_size()) - vector(0, 1), pygame.SRCALPHA) finalimage.fill((0, 0, 0, 0)) finalimage.convert_alpha() finalimage.blit(imgoutline, (0, 0)) finalimage.blit(newimage, (1, 1)) spritelist.append(finalimage) imagedict = {"idle": [], "walk": []} imagedict["idle"] = spritelist[0:4] imagedict["walk"] = spritelist[4:8] imagedict["jumpup"] = [spritelist[8]] imagedict["jumpdown"] = [spritelist[9]] return imagedict
def outline(image): poss = [[0,1],[1,0],[2,1],[1,2],[1,1]] mask = pygame.mask.from_surface(image) #create blank image with alpha 0 (transparent) newimage = pygame.Surface(vector(image.get_size())+vector(2,2),pygame.SRCALPHA) newimage.fill((0,0,0,0)) #use a mask to get the positions for the outline of an image #outlining a mask only gives the inside pixels and gives coordinates, not another mask outlinelist = mask.outline() outlinemask = pygame.Mask(image.get_size()) surf = pygame.Surface(vector(image.get_size()),pygame.SRCALPHA) surf.fill((0,0,0,0)) #create an outline mask out of the outline coordinates for coord in outlinelist: surf.set_at(coord,(0,0,0,255)) #turn the outline mask into a surface #surf = outlinemask.to_surface(unsetcolor=(0,0,0,0),setcolor=(0,0,0,255)) #blits the mask one pixel from the original picture's center for every cardinal direction #this is done because the current outline is only on the inside of the image for pos in poss: newimage.blit(surf,pos) return newimage
def spritesheettolist(spritesheet,framenum,fulloutline=False,dooutline=True): #create blank list to store surfaces imagelist = [] #works out the width of each frame in the spritesheet xtravel = spritesheet.get_width()//framenum #loops through the x positions for the top right of each frame int the spritesheet for x in range(0,spritesheet.get_width()+1-xtravel,xtravel): #create new transparent surface(alpha 0) newsurf = pygame.Surface(vector(xtravel,spritesheet.get_height()),pygame.SRCALPHA) newsurf.fill((0,0,0,0)) #blit the image from the spritesheet onto the transparent image newsurf.blit(spritesheet,(-x,0)) #get the surface for an outline outlinesurf = outline(newsurf) #there is a parameter for if the bottom part of the outline should be cut off #this is because if there is a sprite on the ground,the extra outline on the bottom #will make the sprite look like it is floating one pixel on the ground if not fulloutline: extra = vector(2,1) else: extra = vector(2,2) #apply the outline to the frame that has just been retrieved from the spritesheet newsurf2 = pygame.Surface(vector(xtravel,spritesheet.get_height())+extra,pygame.SRCALPHA) newsurf2.fill((0,0,0,0)) newsurf2.blit(outlinesurf,(0,0)) newsurf2.blit(newsurf,(1,1)) #appends an outlined or non outlined image to the list of images if dooutline: imagelist.append(newsurf2) else: imagelist.append(newsurf) return imagelist
def __init__(self, name, position): self.name = name self.position = position self.mass = knowMass self.radius = knowRadius self.velocity = vector(0,0) self.acceleration = vector(0,0)
def from_yaml(cls, obj) -> 'AreaLight': return cls(corner=point(*obj['corner']), full_uvec=vector(*obj['uvec']), full_vvec=vector(*obj['vvec']), usteps=int(obj['usteps']), vsteps=int(obj['vsteps']), jitter=obj['jitter'], intensity=color(*obj['intensity']))
def draw_bounds(self, dst, color, corner, radius, shrink=0): item_skip = 3 * radius corner = corner - 0.5 * item_skip * vector(1, 1) corner += shrink * vector(1, 1) dims = item_skip * vector(self.num_cols, self.visible_rows()) dims -= 2 * shrink * vector(1, 1) rect = corner.list() + dims.list() pygame.draw.rect(dst, color, rect, 1)
def test_v(self): self.assertEqual(v(), vector()) self.assertEqual(v(1), vector([1])) self.assertEqual(v(1,2), vector([1,2])) with self.assertRaises(TypeError): v(x=1) with self.assertRaises(TypeError): v(1, z=3)
def update(self,specialdict,keys,screen,tree,explored,currentroom,pos=(0,0)): adjacent = m.getunexplored(tree,explored) notinclude = m.getnotincluded(tree,explored) surface = pygame.Surface((100,70)) surfacedims = surface.get_size() surfacemag = max(surfacedims[1],surfacedims[0]) #determines how many times the pure image for the minimap is enlarged by magnification = 2 surfacedims = vector(surfacemag*magnification,surfacemag*magnification) #if tab is pressed, expand the minimap if K_TAB in keys: self.bigmode = True else: self.bigmode = False #if the player moves between rooms if self.currentroom != currentroom or self.previousexplored != explored: #update the surface for the minimap self.surf = pygame.Surface(surfacedims) self.surf = m.generatemapsurface(tree,specialdict,self.surf,adjacent,True,notinclude,currentroom) self.updatebigmap(specialdict,tree,explored,currentroom) self.currentroom = currentroom self.previousexplored = explored.copy() #if the tree changes, change the coordinate dictionary if self.previoustree != tree: self.previoustree = tree self.coordict = m.generatecoorddict(tree) #if the minimap isn't expanded if not self.bigmode: #scroll the camera to the current room aimpos = self.coordict[currentroom] aimpos = vector(aimpos)* m.mapsurfacemultiplier(self.surf) self.actualscroll = lerp(self.actualscroll,aimpos,0.7) if (self.actualscroll-aimpos).magnitude()<=2: self.actualscroll = aimpos #draw the map surface onto minimap surface, applying camera movement self.surfrect = self.surf.get_rect() self.surfrect.center = -self.actualscroll + (vector(surface.get_size())/2) surface.blit(self.surf,self.surfrect) #draw minimap onto the screen self.surfacerect = surface.get_rect() self.surfacerect.topright = screen.get_rect().topright surface.set_alpha(self.transparency) screen.blit(surface,self.surfacerect) else: #darken the screen and draw the enlarged map to the middle of the screen shade = pygame.Surface(screen.get_size()) shade.set_alpha(100) bigrect = self.bigmap.get_rect() bigrect.center = vector(screen.get_size())/2 screen.blit(shade,(0,0)) screen.blit(self.bigmap,bigrect)
def calcForce(self): displacement = self.object2.position.sub(self.object1.position) springDisplacement = displacement.unit().mult(displacement.magnitude() - self.eqLength) force = springDisplacement.mult(self.strength) if self.eqLength == displacement.magnitude(): force1, force2 = vector(0,0), vector(0,0) else: force1, force2 = force, force.mult(-1) return {1: force1, 2: force2}
def __init__(self, file): self.objects = [] self.materials = [] self.textures = [] self.camera = None if (file != ""): self.loadscene(file) else: self.camera = camera(vector(0, 0, 0), vector(0, 0, -1), vector(0, 1, 0), 90, YA.WIDTH / YA.HEIGHT)
def normalupdate(self, screen): #sparks if self.id == 1: #decrease it's speed as it travels self.speed = lerp(self.speed, 0, 0.9) self.velocity = vector(self.speed, 0) self.velocity.rotate_ip(self.rotation) #apply gravity acceleration self.pos = vector(self.pos) + self.velocity + vector( 0, self.gravity) self.gravity = min(self.gravity + (GRAVITY / 5), MAXY) #add positions onto a list, limit the size of that list based on "traillength" self.previouslist.append(self.pos) if len(self.previouslist) > self.traillength: self.previouslist.pop(0) previouspos = self.previouslist[0] #draw a line from previous positions, creating a trail pygame.draw.lines(screen, self.colour, False, self.previouslist, self.linesize) #after the timer ends, decrease it's size and make it's colour darker if self.deletetimer.update(): self.colour = (90, 90, 90) self.deletetimer.reset() self.traillength -= 2 self.linesize -= 1 if self.linesize == 0: self.delete = True if self.id == 2 or self.id == 3: #decrease it's speed as it travels self.velocity = vector(self.speed, 0) self.velocity.rotate_ip(self.rotation) self.pos = vector(self.pos) + self.velocity self.speed = lerp(self.speed, 0, self.slip) #add positions onto a list, limit the size of that list based on "traillength" self.previouslist.append(self.pos) if len(self.previouslist) > self.traillength: self.previouslist.pop(0) previouspos = self.previouslist[0] #draw a line from previous positions, creating a trail pygame.draw.lines(screen, self.colour, False, self.previouslist, self.linesize) #if the dust is stationary if self.speed <= 0.1: #decrease it's size every time the timer is finished if self.deletetimer.update(): self.deletetimer.reset() self.linesize -= 1 if self.linesize <= 0: self.delete = True
def getVertexDistance(self, vertexlist, center, distance): # finds the vertex with longest distance from center vertex = None tol_min = distance - distance * 0.01 tol_max = distance + distance * 0.01 for v in range(len(vertexlist)): length = vlength(vector(vertexlist[v]) - vector(center)) if length >= tol_min and length <= tol_max: vertex = vertexlist[v] return vertex
def test_isub(self): x = vector([1,2]) x -= vector([3,4]) self.assertEqual(x, vector([-2, -2])) x = vector([4,5,6]) x -= (1,2,3) self.assertEqual(x, (3, 3, 3)) with self.assertRaises(TypeError): x = vector([0,-1]) x -= 1
def resizemenu(pixelperfect,screensurf,mousepos2,menu,scale): screenscale = (min(screen.get_width(),screen.get_height())/GAMESIZE[0]) if pixelperfect: screensurf = getscreensurf(screen,scale) mousepos2 = (vector(pygame.mouse.get_pos()))/scale else: screensurf = getscreensurf(screen,scale) mousepos2 = (vector(pygame.mouse.get_pos()))/scale menu.reposition(screensurf) return pixelperfect,screensurf,mousepos2,menu,scale
def random_empty(self): done = False loc = vector(0, 0) while not done: loc = [random.randint(0, self.dims[0] - 1), random.randint(0, self.dims[1] - 1)] loc = vector(loc) if not self.is_blocked(loc): done = True return loc
def getVertexLongest(self, vertexlist, center): # finds the vertex with longest distance from center distance = 0 vertex = None for v in range(len(vertexlist)): length = vlength(vector(vertexlist[v])-vector(center)) if length>distance: distance = length vertex = vertexlist[v] return vertex
def getVertexLongest(self, vertexlist, center): # finds the vertex with longest distance from center distance = 0 vertex = None for v in range(len(vertexlist)): length = vlength(vector(vertexlist[v]) - vector(center)) if length > distance: distance = length vertex = vertexlist[v] return vertex
def getVertexDistance(self, vertexlist, center, distance): # finds the vertex with longest distance from center vertex = None tol_min = distance-distance*0.01 tol_max = distance+distance*0.01 for v in range(len(vertexlist)): length = vlength(vector(vertexlist[v])-vector(center)) if length>=tol_min and length<=tol_max: vertex = vertexlist[v] return vertex
def __init__(self): self.spritesheet = pygame.image.load(TEXTSHEET) self.tiledictsmall = {} self.tilesizesmall = {} self.tiledictbig = {} self.tilesizebig = {} capitalalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" self.bigalpha = list(capitalalpha) ypointer = 0 bigletters = ["M","W"] for x in range(len(capitalalpha)): dimensions = (11,12) char = capitalalpha[x] if char not in bigletters: actualdimensions = (6,12) else: actualdimensions = (10,12) xpointer = x*dimensions[0] charsurf = pygame.Surface(actualdimensions) charsurf.blit(self.spritesheet,-vector(xpointer,ypointer)) charsurf.set_colorkey((255,255,255)) charsurf.convert() self.tiledictbig[char] = charsurf self.tilesizebig[char] = actualdimensions alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-,:+'!?0123456789()/_=\\[]*\"<>" self.smallalpha = list(alpha) ypointer = 12 dimensions = (6,7) small1 = ["!",".","i","'",":"] small2 = [",","j","r"] big = ["m","w","M","W"] for x in range(len(alpha)): char = alpha[x] actualsize = tuple(dimensions) if char not in big+small2+small1: actualsize = (3,8) if char in small2: actualsize = (2,8) if char in small1: actualsize = (1,8) if char in big: actualsize = (5,8) xpointer = x*dimensions[0] charsurf = pygame.Surface(actualsize) charsurf.blit(self.spritesheet,-vector(xpointer,ypointer)) charsurf.set_colorkey((255,255,255)) charsurf.convert() self.tiledictsmall[char] = charsurf self.tilesizesmall[char] = actualsize
def get_output(classid): from pythonrc import * from vector import * # call demo program # specify arguments demofile = "./de1_demo" classidx_int = classid noise_float = 0.1 # convert argument to string classidx = "-class=" + str(classidx_int) noise = "-noise=" + str(noise_float) # put all arguments to a list arglist = [demofile, classidx, noise] # call the arm demo program, comment out when debug # the program may return a value, it's not used now # each time the program is called, it will execute once and create two file in # same folder as the program: 'input_spike_record.txt' and 'output_spike_record.txt' ret = subprocess.call(arglist) # plot the input spike # window size is 100, there are 128 axons inp = rasterplot(100, 128) inp.read_input_spike_file('input_spike_record.txt') # return a well formatted string # inpplot = inp.plot_raster() # plot output spikes # window is 100, 50 neurons outp = rasterplot(100, 50) outp.read_output_spike_file('output_spike_record.txt') # you can specify the symbol which represent the pixel # outplot = outp.plot_raster(pixel_symbol_off = ' ', pixel_symbol_on = '*') # outplot = outp.plot_raster() figure( ) ## uncomment to preserve the raster plot when another class is entered # need to convert neuron index and spike times to 'vector' plot(vector(outp.spiketimes[1]), vector(outp.spiketimes[0]), '.') figure() #draw_now() # print(inpplot) # print(outplot) plot(vector(inp.spiketimes[1]), vector(inp.spiketimes[0]), '.') draw_now() return ret
def random_empty(self): done = False loc = vector(0, 0) while not done: loc = [ random.randint(0, self.dims[0] - 1), random.randint(0, self.dims[1] - 1) ] loc = vector(loc) if not self.is_blocked(loc): done = True return loc
def update(self, surf, player, keys, completed, entities): #some of the parameters will be equal to None, this is because in some cases (such as the tile editor) #where I can't pass in the player or entities objects and just want the image toreturn = False #only draw the door when the room is completed if completed: #check this is the first time the door is drawn if self.washidden and entities != None: #effects for the door appearing for _ in range(randint(5, 10)): angle = randint(0, 360) v1 = vector(15, 0) v1.rotate_ip(angle) entities.add( e.Dust( vector(self.bottomrect.center) + v1, 3, (0, 0), angle, randint(2, 3))) self.washidden = False imagerect = SURFACES[self.image].get_rect() imagerect.bottom = self.bottomrect.bottom imagerect.left = self.bottomrect.left surf.blit(SURFACES[self.image], imagerect) if player != None: #if the player is touching the door if imagerect.colliderect(player.getrect()): #put a text prompt above the player textimage = generatetext("press R to go to the next stage", None, "small", (0, 0), (192, 192, 192)) textback = pygame.Surface(textimage.get_size()) textback.blit(textimage, (0, 0)) textrect = textback.get_rect() textrect.centerx = imagerect.centerx textrect.bottom = imagerect.top + -5 surf.blit(textback, textrect) #if the player presses the key in the prompt if K_r in keys: keys.remove(K_r) toreturn = True else: #if the room isn't completed, use a variable to keep track of this for the effects #that happen when the door first appears self.washidden = True #returns true if the player pressed the key that the prompt was asking for #this is used elsewhere in the code to change stages return toreturn
def changetext(self, text): self.textcolour = (192, 192, 192) self.textimage = generatetext(text) self.textimage = changecolour(self.textimage, (0, 0, 0), self.textcolour) pos = self.rect.topleft centerx = self.rect.centerx self.buttonsurface = pygame.Surface( (vector(self.textimage.get_size()) + vector(1, 1))) self.rect = self.buttonsurface.get_rect() self.rect.topleft = pos if self.center: self.rect.centerx = centerx
class player(object): pos = vector(0, 0) move_vec = vector(0, 0) speed = 5 hist_key = K_1 player_img = "player1.png" player_sprite_right = pygame.image.load(player_img).convert_alpha() player_sprite_up = pygame.transform.rotate(player_sprite_right, 90) player_sprite_down = pygame.transform.rotate(player_sprite_right, -90) player_sprite_left = pygame.transform.rotate(player_sprite_right, 180) player_sprite = player_sprite_right def click_draw(self, destination): direction = destination - self.pos direction.normalize() self.pos += direction * self.speed pos = self.pos.tupleit() screen.blit(self.player_sprite, pos) def kbdraw(self, event): if event.type == KEYDOWN: if event.key == K_w: self.hist_key = event.key self.move_vec = vector(0, -5) self.player_sprite = self.player_sprite_up if event.key == K_s: self.hist_key = event.key self.move_vec = vector(0, 5) self.player_sprite = self.player_sprite_down if event.key == K_d: self.hist_key = event.key self.move_vec = vector(5, 0) self.player_sprite = self.player_sprite_right if event.key == K_a: self.hist_key = event.key self.move_vec = vector(-5, 0) self.player_sprite = self.player_sprite_left if event.key == K_ESCAPE: exit() if event.type == KEYUP and event.key == self.hist_key: self.move_vec = vector(0, 0) self.pos += self.move_vec sprite_pos = self.pos.tupleit() sprite_pos = (sprite_pos[0] - self.player_sprite.get_width() / 2, sprite_pos[1] - self.player_sprite.get_height() / 2) screen.blit(background, (sprite_pos[0] - 5, sprite_pos[1] - 5), pygame.Rect(sprite_pos[0] - 5, sprite_pos[1] - 5, 60, 60)) screen.blit(self.player_sprite, sprite_pos)
def getObjDistanceShortest(self, vertexlist): # finds the shortest distance between two vertices # and returns both vertices distance = vector(vertexlist[0]) vertices = None for v1 in range(len(vertexlist)): for v2 in range(v1+1,len(vertexlist)): #print "From-To", v1, v2 #print "From-To", vertexlist[v1], vertexlist[v2] length = vlength(vector(vertexlist[v2])-vector(vertexlist[v1])) if length<distance: distance = length vertices = [vertexlist[v1], vertexlist[v2]] return vertices
def kepler(self): n_new = int(input('Number of bodies: ')) self.n += n_new cent_mass = float(input('Central body mass: ')) other_mass = float(input('Other masses: ')) mean_r = float(input('Mean radius: ')) self.part.append({ 'pos-1':vector(0,0,0), 'pos':vector(0,0,0), 'mass':cent_mass, 'vel':vector(0,0,0), 'acc':vector(0,0,0), 'num':self.index }) self.index += 1 for i in range(0,n_new - 1): r = vector(1,0,0) * expovariate(1./mean_r) r = rotate(r, uniform(0, 2*pi), vector(0,0,1)) self.part.append({ 'pos-1':r, 'pos':r, 'mass':other_mass, 'vel':cross(r/mag(r),vector(0,0,1))*pow(self.G*(cent_mass + n_new*other_mass*(1-exp(-mag(r)/mean_r)))/mag(r),0.5), 'acc':vector(0,0,0), 'num':self.index }) self.index += 1
def __init__(self,pos,value): self.slip = uniform(0.04,0.05) self.pos = vector(pos) self.previousposlist = [] randomangle = randint(0,360) inplace = vector(0,randint(0,10)) inplace.rotate_ip(randomangle) self.spawnpos = self.pos+inplace for _ in range(4): self.previousposlist.append(self.pos) self.collected = False self.delete = False self.value = value self.cango = False
def getObjDistanceShortest(self, vertexlist): # finds the shortest distance between two vertices # and returns both vertices distance = vector(vertexlist[0]) vertices = None for v1 in range(len(vertexlist)): for v2 in range(v1 + 1, len(vertexlist)): #print "From-To", v1, v2 #print "From-To", vertexlist[v1], vertexlist[v2] length = vlength( vector(vertexlist[v2]) - vector(vertexlist[v1])) if length < distance: distance = length vertices = [vertexlist[v1], vertexlist[v2]] return vertices
def pnt2line(pnt, start, end): line_vec = vector(start, end) pnt_vec = vector(start, pnt) line_len = length(line_vec) line_unitvec = unit(line_vec) pnt_vec_scaled = scale(pnt_vec, 1.0 / line_len) t = dot(line_unitvec, pnt_vec_scaled) if t < 0.0: t = 0.0 elif t > 1.0: t = 1.0 nearest = scale(line_vec, t) dist = distance(nearest, pnt_vec) nearest = add(nearest, start) return dist, int(nearest[0]), int(nearest[1])
def getHelperUp(self, object): # gets the center of the predefined helper object vertices = self.getObjectVertices(object) center = self.getHelperCenter(object) up = vnormal(vector(self.getVertexMedium(vertices, center))-center) #up = vnormal(vector(self.getVertexDistance(vertices, center, distance))-center) return up
def getHelperForward(self, object): # gets the center of the predefined helper object vertices = self.getObjectVertices(object) center = self.getHelperCenter(object) forward = vnormal(vector(self.getVertexLongest(vertices, center))-center) #print "Forward = ", forward return forward
def dir_vel(self, dir, loc): mid = self.size - 1 upper = { HEX_NW: [-1, -1], HEX_NE: [-1, 0], HEX_E: [0, 1], HEX_SE: [1, 1], HEX_SW: [1, 0], HEX_W: [0, -1] } lower = { HEX_NW: [-1, 0], HEX_NE: [-1, 1], HEX_E: [0, 1], HEX_SE: [1, 0], HEX_SW: [1, -1], HEX_W: [0, -1] } middle = { HEX_NW: [-1, -1], HEX_NE: [-1, 0], HEX_E: [0, 1], HEX_SE: [1, 0], HEX_SW: [1, -1], HEX_W: [0, -1] } if loc[0] < mid: ret = upper[dir] elif loc[0] > mid: ret = lower[dir] else: ret = middle[dir] return vector(ret)
def collide(self, other): # Bodies bounce off each other, conserving momentum and energy # Radial unit vector ur = (other.pos - self.pos)/(other.pos - self.pos).mag() # Tangential unit vector ut = vector(-ur.y, ur.x) # Break velocities into radial and tangential components vel_r_self = self.vel.dot(ur) vel_t_self = self.vel.dot(ut) vel_r_other = other.vel.dot(ur) vel_t_other = other.vel.dot(ut) # Tangential components are not affected by collision # New radial velocities are given by new_vel_r_self = (vel_r_self * (self.mass - other.mass) + \ 2 * other.mass * vel_r_other)/ \ (self.mass + other.mass) new_vel_r_other = (vel_r_other * (other.mass - self.mass) + \ 2 * self.mass * vel_r_self)/ \ (self.mass + other.mass) # Combine to get the new total velocities self.vel = ur*new_vel_r_self + ut*vel_t_self other.vel = ur*new_vel_r_other + ut*vel_t_other
def __init__(self, vectors): self.vectors = [] self.n = len(vectors[0]) for v in vectors: if len(v) != self.n: raise Exception("Multiple Dimensions Exception") self.vectors.append(vector(v)) self.centroid = mean(self.vectors)
def calcCenter(self): centerOfMass = vector(0,0) totalMass = 0 for obj in self.objects: centerOfMass = centerOfMass.add(obj.position.mult(obj.mass)) totalMass += obj.mass return centerOfMass.div(totalMass)
def display(self, dst, center, radius): # get rgb tuple for rendering color = self.color.tuple(255) # draw the crystal core num_sides = 8 points = [] for i in range(num_sides): theta = i * 2.0 * math.pi / num_sides t = vector(math.cos(theta), math.sin(theta)) p = center + radius * t points.append(p.list()) pygame.draw.polygon(dst, color, points, 1) # draw corruption if 'Corruption' in self.atts and self.atts['Corruption']: n2 = num_sides / 2 for i in range(num_sides / 2): pygame.draw.line(dst, color, points[i], points[i + n2]) # draw the pipes for (i, pipe) in enumerate(self.pipes): if pipe is None: continue # draw the pipe segment offset = i - 2 theta = offset * 2.0 * math.pi / len(self.pipes) t = vector(math.cos(theta), math.sin(theta)) r = 1.7 * radius p0 = center p1 = center + r * t pygame.draw.line(dst, color, p0.list(), p1.list()) # draw the arrowhead r1 = 0.7 * r r2 = 0.8 * r if pipe == 'Out': r1, r2 = r2, r1 phi = 10 p0 = center + r1 * t p1 = center + (r2 * t).rotate(-phi) p2 = center + (r2 * t).rotate(phi) pygame.draw.line(dst, color, p0.list(), p1.list()) pygame.draw.line(dst, color, p0.list(), p2.list())
def main(): global font black = (0, 0, 0) red = (255, 0, 0) blue = (0, 0, 255) white = (255, 255, 255) size = width, height = 800, 600 screen = init(size) settings = Settings() global_font = pygame.font.Font(pygame.font.get_default_font(), FONT_SIZE) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False screen.fill(black) pygame.draw.line(screen, blue, (0, 0), (width, height)) pygame.draw.line(screen, blue, (0, height), (width, 0)) pos = pygame.mouse.get_pos() vec = vector(pos) - vector(size) / 2 dir = get_dir(size, vec) intersection = get_intersection(size, vec) dims = vector(10, 10) rect = intersection - dims / 2 rect = rect.list() + dims.list() center = (width / 2, height / 2) pygame.draw.rect(screen, red, rect, 1) pygame.draw.line(screen, red, center, intersection.list()) draw_string(screen, dir, (10, 10), white) pygame.display.flip() pygame.quit()
def get_bfs(self, start): grid = self.grid # Make sure there is actually a crystal at start if grid.cells[start[0]][start[1]] is None: return [], False dirs = [HEX_NW, HEX_NE, HEX_E, HEX_SE, HEX_SW, HEX_W] q = [vector(start)] # Our queue of current nodes edges = [] visited = [] cycle = False # Standard BFS loop while len(q) > 0: # Get the next location cur = q.pop(0) row1, col1 = cur.tuple() # Check if we've already visited if cur.list() in visited: cycle = True continue visited.append(cur.list()) # Obtain the actual contents of the cell c1 = grid.cells[row1][col1] # Visit each of the neighboring cells neighbors = [] for dir in dirs: loc = grid.move_loc(dir, cur) # Make sure we're still in bounds if grid.out_of_bounds(loc): continue # Check to see if there is a crystal in the neighboring cell row2, col2 = loc.tuple() c2 = grid.cells[row2][col2] if c2 is None: continue # Make sure colors match up. We use <= as opposed to == since # some crystal can take more than one color as input. Yellow # can take Red or Green, but output would have to be sent to a # crystal which can take both Red and Green. In this case, these # would be Yellow and White crystals. if not c1.color <= c2.color: continue # Make there is an actual pipe going between the two crystals if c1.pipes[dir] == 'Out' and \ c2.pipes[(dir + 3) % 6] == 'In': edges.append((cur, loc)) q.append(loc) return edges, cycle
def get_dir(dims, vec): w, h = map(float, dims) center = vector(w, h) / 2 w2, h2 = center.list() new_vec = vector(vec.x / w2, vec.y / h2).norm() rot_vec = vector(new_vec) rot_vec.rotate(-45) if rot_vec.x < 0: if rot_vec.y < 0: return 'NORTH' else: return 'WEST' else: if rot_vec.y < 0: return 'EAST' else: return 'SOUTH'
def __init__(self, parent, items): parent.add_key_listener(self) self.parent = parent self.items = items self.selecting = True self.selection = vector(0, 0) self.num_cols = 10 self.max_size = None self.max_rows = None self.allowed_types = []
def display(self, dst, corner, dims): grid_viewer = self.grid_viewer grid_viewer.display(dst) row0, col0 = corner.tuple() offset = vector(0, 0) grid = self.level.grid for row in range(dims[0]): for col in range(dims[1]): tile = grid.cells[row + row0][col + col0] tile_bounds = (self.tile_size % tile).list() tile_bounds += self.tile_size.list() pos = offset + self.tile_size % vector(col, row) dst.blit(self.tile_sheet, pos.list(), tile_bounds) for crystal in self.level.items.cells[row][col]: center = grid_viewer.get_center((row - row0, col - col0)) radius = 0.25 * grid_viewer.cell_w crystal.display(dst, center, radius)
def find_components(self): grid = self.component for row in range(grid.num_rows()): for col in range(grid.num_cols()): grid.cells[row][col] = -1 cur_component = 0 for row in range(grid.num_rows()): for col in range(grid.num_cols()): loc = vector(row, col) self.component_dfs(loc, cur_component) cur_component += 1
def display(self, dst, center, radius): color = (255, 255, 255) # Compute six different corners for the central hexagon vels = { 'N': 90, 'NE': 30, 'SE': -30, 'S': -90, 'SW': -150, 'NW': 150 } d2r = math.pi / 180 dir_vel = {k: vector(math.cos(t * d2r), math.sin(t * d2r)) for (k, t) in vels.iteritems()} # Now add in extra points for each outer hexagon. Uses an # ordering to only compute each unique corner point once. dirs = ['N', 'NE', 'SE', 'S', 'SW', 'NW'] points = [[x] for x in range(6)] for x in range(6): points += [[x, x], [x, x, (x + 1) % 6], [(x + 1) % 6, (x + 1) % 6, x]] zero = vector(0, 0) points = [sum([dir_vel[dirs[dir]] for dir in p], zero) for p in points] # Build up the list of edges we want to actually draw between points. # Separated out so we generate each segment via rotational symmetry. segments = [[0, 1, 2, 3, 4, 5, 0]] for x in range(6): y = 3 * x vals = [y, y + 1, y + 2, y + 3] vals = [x] + [6 + v % 18 for v in vals] segments += [vals] # Now actually draw line segments between each point in our hex grid icon. for line in segments: plist = [center + 0.5 * radius * points[p] for p in line] plist = [p.list() for p in plist] pygame.draw.lines(dst, color, False, plist)
def get_intersection(dims, vec): w, h = map(float, dims) center = vector(w, h) / 2 w2, h2 = center.list() new_vec = vector(vec.x / w2, vec.y / h2).norm() dir = get_dir(dims, vec) scale = None if dir == 'NORTH': scale = -1 / new_vec.y elif dir == 'SOUTH': scale = 1 / new_vec.y elif dir == 'WEST': scale = -1 / new_vec.x elif dir == 'EAST': scale = 1 / new_vec.x intersection = scale * new_vec #intersection = vector(new_vec) intersection %= center intersection += center return intersection
def test_iadd(self): x = vector([1,2]) x += vector([3,4]) self.assertEqual(x, vector([4,6])) x = vector([1,2]) x += (3,4) self.assertEqual(x, vector([4,6])) with self.assertRaises(TypeError): x = vector([0,-1]) x += 1
def drawpipe(rs,xx=q,draw=True): assert sum(rs)==840 h=0 prev = None for i,r in enumerate(rs): x = xx-R+r if i%2:x=xx+R-r p = vector(x,q-2*h-r) h+=r while prev: if abs(satisfy(prev[0],p,r+prev[1]))<.000001: break if draw:circle(p,r) prev = (p,r) H = p.y-r line(xx-R,q,xx-R,H) line(xx+R,q,xx+R,H) return H