def __init__(self, name="Manager", dt=10e-3, **kwargs): """Create a manager using a context, this methods it to be overloaded.""" self.context = Context(name=name, **kwargs) self.count = self.context.count self.pause = False self.dt = dt # Typing stuff self.typing = False self.alphabet = "abcdefghijklmnopqrstuvwxyz" self.caps_numbers = ")!@#$%^&*(" self.numbers = "0123456789" self.typing = False self.shiftlock = False self.capslock = False self.altlock = False
class SimpleManager: """Manage a program using the context by many having functions that can be overloaded to make simple and fast programs. This process allow the user to think directly about what the program does, instead of focusing on how to display things. The way it works is by making the main class of the program inheriting from this one.""" def __init__(self, name="SimpleManager", **kwargs): """Create a context manager with the optional name.""" self.context = Context(name=name, **kwargs) self.pause = False def __call__(self): """Call the main loop.""" while self.context.open: self.events() if not self.pause: self.update() self.show() def events(self): """Deal with all the events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: self.context.open = False if event.type == KEYDOWN: if event.key == K_ESCAPE: self.context.open = False if event.key == K_SPACE: self.pause = not (self.pause) if event.key == K_f: self.context.switch() # Set or reverse fullscreen if event.type == MOUSEBUTTONDOWN: if event.button == 4: self.context.draw.plane.zoom([1.1, 1.1]) if event.button == 5: self.context.draw.plane.zoom([0.9, 0.9]) def update(self): """Update the context manager.""" def show(self): """Show the context manager.""" self.context.refresh() self.context.control() self.context.flip()
mv = self.velocity v = Vector.createFromPolar(mv.norm, angle) v.color = mv.color v.show(context, point) if len(self) >= 3: angle += math.pi / 2 ma = self.acceleration a = Vector.createFromPolar(ma.norm, angle) a.color = ma.color a.show(context, point) if __name__ == "__main__": from mycontext import Context context = Context(name="Motion Demonstration") motion1 = Motion.random() motion2 = Motion.random() motion = motion1 + motion2 motion = Motion.sum([Motion.random() for i in range(9)] + [motion]) # Summing 10 motions together moment = Moment.random() print(motion, moment) while context.open: context.check() context.control() context.clear() context.show() motion.show(context) moment.show(context) context.flip()
for i in range(len(self.bodies)): self.context.draw.window.print("body: " + str(self.bodies[i]), (x, y)) y += 30 def getFocus(self): """Return the body being focused.""" if self.focus_index is not None: return self.bodies[self.focus_index] else: return None def setFocus(self, body): """Set the focus using a body.""" if body is not None: if not (body in self.bodies): self.bodies.append(body) self.focus_index = self.bodies.index(body) else: self.focus_index = None focus = property(getFocus, setFocus) if __name__ == "__main__": from mycontext import Context context = Context(fullscreen=True) builder = Builder(context) builder()
def show(self): """Show a circle.""" super().show() self.circle.show(self.context) @on.press(pygame.KEYDOWN, pygame.K_LEFT) def left(self): """Go left when left key is pressed.""" self.circle.x -= 1 @on.press(pygame.KEYDOWN, pygame.K_RIGHT) def right(self): """Go right when right key is pressed.""" self.circle.x += 1 @on.press(pygame.KEYDOWN, pygame.K_SPACE) def color_circle(self): """Print the position in the console.""" self.circle.area_color = mycolors.reverse(self.circle.area_color) @on.press(pygame.KEYDOWN, pygame.K_ESCAPE) def escape(self): """Escape the game.""" self.quit() if __name__ == "__main__": context = Context(name='Test Controller') game = Game(context) game()
size = random.uniform(0, size_born) return cls(x, y, size, **kwargs) def __init__(self, x, y, size, **kwargs): super().__init__(x, y, size, size, **kwargs) def __str__(self): return type(self).__name__ + "(x=" + str(self.x) + ",y=" + str( self.y) + ",s=" + str(self.size[0]) + ")" if __name__ == "__main__": from mycontext import Context from myabstract import Point context = Context(name="Rectangle Test") p = Point.random(radius=0.5) r1 = Rectangle(0, 0, 3, 2, side_width=3, side_color=mycolors.BLUE, area_color=mycolors.WHITE, area_show=True) r2 = Square(-1, -1, 2, side_width=3, side_color=mycolors.BLUE, area_color=mycolors.WHITE,
def getCorners(self): return self.context.corners def getWidth(self): return self.size[0] def getHeight(self): return self.size[1] #Properties corners = property(getCorners) height = property(getHeight) width = property(getWidth) if __name__ == "__main__": context_size = [800, 600] mandelbrot_size = [200, 150] corners = [-2, -1, 1, 1] context = Context.createFromSizeAndCorners( context_size, corners, name="Mandelbrot") #width,height=context.size print(context.corners) print(context.position) print([0, 0] in context) #width=800;height=600;maxiter=20 #matrix=getMatrix(width,height,maxiter=maxiter) #showMatrixWithPIL(matrix,width,height,maxiter=maxiter) m = Mandelbrot(context, mandelbrot_size) m()
#Show interpolations being made while moving the points. #Impors from mycontext import Context from myabstract import Point from myinterpolation import PolynomialInterpolation context = Context() l = 10 points = [Point(2 * x, random.randint(-5, 5)) for x in range(l)] n = 0 ncp = 50 #number construction points while context.open: context.check() context.control() context.clear() context.show() Point.turnPoints([1 / 1000 for i in range(l)], points) p = PolynomialInterpolation(points) p.show(context) n = (n + 1) % (ncp + 1) p1 = b(n / ncp) p2 = t(n / ncp) #l1=Line.createFromTwoPoints(p1,p2) p1.show(context, color=mycolors.YELLOW, radius=0.1, fill=True) p2.show(context, color=mycolors.YELLOW, radius=0.1, fill=True)
filename = "FourierObjects/Path" imagename = tm try: path = pickle.load(open(filename, 'rb'))['path'] raise None except: to = time.time() # Sample the picture into an ordered list of points. image = cv2.imread(imagename) canny = cv2.Canny(image, 50, 150) pts = searchPoints(canny) pts = cleanPoints(pts) pts = sampleOnceEveryN(pts, n=10) path = getPath(pts) path = interpolate(path) print(time.time() - to) path = getAllToPlane(path, image.shape) pickle.dump({'path': path}, open(filename, 'wb')) # Use this ordered list of points to make the fourier transform. context = Context(name="Application of the Fourier Transform.", fullscreen=False) fourier = VisualFourier(context, image=imagename) # fourier.load() fourier.drawing = path fourier.updateSample() fourier() fourier.save()
class Circuit: def __init__(self, logic_gates=[]): """Create a circuit object.""" self.logic_gates = logic_gates self.connexions = [] def show(self, surface): """Show the circuit by showing all its logic gates.""" for gate in self.logic_gates: gate.show(surface) if __name__ == "__main__": from mycontext import Context context = Context(name="Logic Gates") g1 = OrGate([1, 1]) g2 = AndGate([2, 1]) gs = [g1, g2] c = Circuit(gs) while context.open: context.check() context.control() context.clear() context.show() c.show(context) context.flip()
"""Draw the vectors from the points.""" for i in range(len(points) - 1): v = Vector.createFromTwoTuples(points[i], points[i + 1], color=color) v.showFromTuple(context, points[i]) def drawCircles(context, color, points): """Draw the circles from the points.""" for i in range(len(points) - 1): radius = distance(points[i], points[i + 1]) c = Circle.createFromPointAndRadius(points[i], radius, color=color) c.show(context) trace = [] context = Context(fullscreen=False) n = 0 mn = 1000 while context.open: context.check() context.control() context.clear() context.show() #Update the variables n = (n + 1) % mn t = n / mn cst = build(cfs, t) trace.append(cst[-1]) #Show the graphical components
class Manager: def __init__(self, name="Manager", dt=10e-3, **kwargs): """Create a manager using a context, this methods it to be overloaded.""" self.context = Context(name=name, **kwargs) self.count = self.context.count self.pause = False self.dt = dt # Typing stuff self.typing = False self.alphabet = "abcdefghijklmnopqrstuvwxyz" self.caps_numbers = ")!@#$%^&*(" self.numbers = "0123456789" self.typing = False self.shiftlock = False self.capslock = False self.altlock = False def __str__(self): """Return the string representation of the manager.""" return type(self).__name__ + "(\n{}\n)".format("\n".join( map(lambda x: ":".join(map(str, x)), self.__dict__.items()))) def __call__(self): """Call the main loop, this method is to be overloaded.""" self.main() def main(self): """Main loop of the simple manager.""" self.setup() # Name choices inspired from processing while self.context.open: self.loop() def setup(self): """Code executed before the loop.""" pass def loop(self): """Code executed during the loop.""" self.eventsLoop() self.updateLoop() self.showLoop() def eventsLoop(self): """Deal with the events in the loop.""" for event in pygame.event.get(): self.react(event) def react(self, event): """React to the pygame events.""" if event.type == QUIT: self.switchQuit() elif event.type == KEYDOWN: self.reactKeyDown(event.key) elif event.type == KEYUP: self.reactKeyUp(event.key) elif event.type == MOUSEBUTTONDOWN: self.reactMouseButtonDown(event.button, event.pos) elif event.type == MOUSEBUTTONUP: self.reactMouseButtonUp(event.button, event.pos) elif event.type == MOUSEMOTION: self.reactMouseMotion(event.pos) def switchQuit(self): """React to a quit event.""" self.context.open = not (self.context.open) def reactKeyDown(self, key): """React to a keydown event.""" self.reactAlways(key) if self.typing: self.reactTyping(key) else: self.reactMain(key) def reactKeyUp(self, key): """React to a keyup event.""" pass def reactAlways(self, key): """React to a key whether or not the typing mode is on.""" # print(key) for debugging the keys if key == K_ESCAPE: self.switchQuit() if key == K_SLASH or key == K_BACKSLASH: if not self.typing: self.context.console("Typing activated.") self.typing = True if key == K_BACKQUOTE: self.switchTyping() def reactLock(self, key): """React to a locking key.""" if key == K_CAPSLOCK: self.capslock = not (self.capslock) elif key == K_LSHIFT or key == K_RSHIFT: self.shiftlock = True elif key == K_LALT or key == K_RALT: self.altlock = True def reactTyping(self, key): """React to a typing event.""" self.reactLock(key) if self.altlock: self.reactAltCase(key) elif self.capslock or self.shiftlock: self.reactUpperCase(key) else: self.reactLowerCase(key) if key == K_SPACE: self.write(" ") elif key == 8: self.delete() if key == K_LCTRL: self.context.console.nextArg() elif key == K_UP: self.context.console.back() elif key == K_DOWN: self.context.console.forward() elif key == K_RETURN: self.eval() self.context.console.nextLine() def eval(self): """Execute a line.""" content = self.context.console.line.content if content[0] == "/": for command in content[1:]: try: self.context.console(str(eval(command))) except: self.context.console("Invalid command.") if content[0] == "\\": for command in content[1:]: try: exec(command) self.context.console("Command " + command + " executed.") except Exception as e: self.context.console(str(e)) self.context.console.eval() def reactAltCase(self, key): """React when typing with alt key pressed.""" if key == K_e: self.write("`") # Stupid elif key == 167: self.write("ยด") def reactLowerCase(self, key): """React when typing in lower case.""" d = { K_COMMA: ",", K_PERIOD: ".", K_SEMICOLON: ";", K_LEFTBRACKET: "[", K_RIGHTBRACKET: "]", 39: "'", 45: "-", K_EQUALS: "=" } if 48 <= key <= 57: self.write(self.numbers[key - 48]) elif 97 <= key <= 122: self.write(self.alphabet[key - 97]) elif key in d: self.write(d[key]) elif key == K_SLASH: if not self.context.console.line.empty: self.context.console.nextLine() self.write("/") self.context.console.nextArg() elif key == K_BACKSLASH: if not self.context.console.line.empty: self.context.console.nextLine() self.write("\\") self.context.console.nextArg() def reactUpperCase(self, key): """React to a key when typing in uppercase.""" d = {59: ":''", 44: "<", 46: ">", 47: "?", 45: "_", 39: "\"", 61: "+"} if 48 <= key <= 57: self.write(self.caps_numbers[key - 48]) elif 97 <= key <= 122: self.write(self.alphabet[key - 97].upper()) elif key in d: self.write(d[key]) def write(self, c): """Write some content.""" self.context.console.lines[-1].content[-1] += c self.context.console.lines[-1].refresh() self.shiftlock = False self.altlock = False def delete(self, n=1): """Delete some content.""" self.context.console.lines[-1].content[ -1] = self.context.console.lines[-1].content[-1][:-n] self.context.console.lines[-1].refresh() def reactMain(self, key): """React as usual when not typing.""" if key == K_f: self.switchFullscreen() if key == K_1: self.switchCapture() if key == K_2: self.switchCaptureWriting() if key == K_3: self.switchScreenWriting() if key == K_LALT: self.switchPause() def switchTyping(self): """Switch the typing mode.""" self.typing = not (self.typing) if self.typing: self.context.console("Typing activated.") self.context.console.nextLine() else: self.context.console("Typing deactivated.") def switchScreenWriting(self): """Switch the screen writing mode.""" if self.context.camera.screen_writing: self.context.camera.screen_writer.release() self.context.camera.switchScreenWriting() if self.context.camera.screen_writing: self.context.console('The screen is being written.') else: self.context.console('The screen video has been released') self.context.console('and is not being written anymore.') def switchCaptureWriting(self): """Switch the capture writing mode.""" if self.context.camera.capture_writing: self.context.camera.capture_writer.release() self.context.camera.switchCaptureWriting() if self.context.camera.capture_writing: self.context.console('The capture is being written.') else: self.context.console('The capture video has been released') self.context.console('and is not being written anymore.') def switchPause(self): """React to a pause event.""" self.pause = not self.pause if self.pause: self.context.console('The system is paused.') else: self.context.console('The system is unpaused.') def switchCapture(self): """React to a capture event.""" self.context.camera.switchCapture() if self.context.camera.capturing: self.context.console('The camera capture is turned on.') else: self.context.console('The camera capture is turned off.') def switchFullscreen(self): """React to a fullscreen event.""" self.context.switch() if self.context.fullscreen: self.context.console("The fullscreen mode is set.") else: self.context.console("The fullscreen mode is unset.") def reactMouseButtonDown(self, button, position): """React to a mouse button down event.""" if button == 4: self.context.draw.plane.zoom([1.1, 1.1]) if button == 5: self.context.draw.plane.zoom([0.9, 0.9]) def reactMouseButtonUp(self, button, position): """React to a mouse button up event.""" pass def reactMouseMotion(self, position): """React to a mouse motion event.""" pass def updateLoop(self): """Update the manager while in the loop.""" if not self.pause: self.update() self.count() self.context.camera.write( ) # Write on the camera writers if they are on def update(self): """Update the components of the manager of the loop. This method is to be overloaded.""" pass def showLoop(self): """Show the graphical components and deal with the context in the loop.""" if not self.typing: # Ugly fix for easier pratical use self.context.control() self.context.clear() self.context.show() self.show() self.showCamera() self.context.console.show() self.context.flip() def show(self): """Show the graphical components on the context. This method is to be overloaded.""" pass def showCamera(self): """Show the camera if active.""" if self.context.camera.capturing: self.context.camera.show() def counter(): doc = "The Counter property." def fget(self): """Bind the counter of the manager to the one of the context.""" return self.context.counter def fset(self, counter): """Set the counter of the context.""" self.context.counter = counter return locals() counter = property(**counter())
def __init__(self, name="SimpleManager", **kwargs): """Create a context manager with the optional name.""" self.context = Context(name=name, **kwargs) self.pause = False
class Manager: def __init__(self,title="Unnamed"): """Create a manager using a context, this methods it to be overloaded.""" self.context=Context(name=title) def __call__(self): """Call the main loop, this method is to be overloaded.""" self.main() def main(self): """Main loop of the simple manager.""" self.setup() #Name choices inspired from processing while self.context.open: self.loop() def setup(self): """Code executed before the loop.""" pass def loop(self): """Code executed during the loop.""" self.eventsLoop() self.updateLoop() self.showLoop() def eventsLoop(self): """Deal with the events in the loop.""" for event in pygame.event.get(): if event.type == pygame.QUIT: self.reactQuit() if event.type == KEYDOWN: self.reactKeyDown(event.key) if event.type == pygame.MOUSEBUTTONDOWN: self.reactMouseButtonDown(event.button) def reactQuit(self,event): """React to a quit event.""" self.context.open=False def reactKeyDown(self,key): """React to a keydown event.""" if key == K_ESCAPE: self.context.open=False def reactMouseButtonDown(self,button): """React to a mouse button down event.""" if button == 4: self.context.draw.plane.zoom([1.1,1.1]) if button == 5: self.context.draw.plane.zoom([0.9,0.9]) def updateLoop(self): """Update the manager while in the loop.""" self.update() def update(self): """Update the components of the manager of the loop. This method is to be overloaded.""" pass def showLoop(self): """Show the graphical components and deal with the context in the loop.""" self.context.control() self.context.clear() self.context.show() self.show() self.context.showConsole() self.context.flip() def show(self): """Show the graphical components on the context. This method is to be overloaded.""" pass
self.context = context def setPlayer(self, player): """Set the player of the expanse level.""" self.player = player def main(self): """Main loop of the level.""" while self.context.open: self.context.check() self.show() self.update() def update(self): """Update the level.""" pass def show(self): """Show the level.""" self.context.control() self.context.clear() self.context.show() self.map.show(self.context) self.context.flip() if __name__ == "__main__": context = Context(fullscreen=True, size=[1440, 900]) expanse = Expanse(context) expanse.main()
def __init__(self,title="Unnamed"): """Create a manager using a context, this methods it to be overloaded.""" self.context=Context(name=title)
def update(self): """Update the spaceship.""" pass def control(self): """Control the spaceship.""" pass def shoot(self, vector): """Return a missile that follow the vector.""" motion = self.getMotion() return Missile(motion) class Missile(MaterialForm): def __init__(self, motion): """Create a missile.""" super().__init__(*args, **kwargs) class Player: def __init__(self): """Create a player.""" if __name__ == "__main__": from mycontext import Context context = Context() game = Game(context)
def showBar(self, context, t, l): """Show the bar.""" v = self.getVector() v *= l p = self(t) v.rotate(math.pi / 2) p1 = v(p) v.rotate(math.pi) p2 = v(p) s = Segment(p1, p2) s.color = self.color s.show(context) if __name__ == "__main__": from mycontext import Context surface = Context() o = Point.origin() s = Step.random() print(s) while surface.open: surface.check() surface.control() surface.clear() surface.show() s.rotate(0.001, o) o.show(surface) s.show(surface) surface.flip()
from myabstract import Form,Point from mybody import Body from mycontext import Context import copy import mycolors ps=[Point(10,2),Point(12,5),Point(15,-2)] f=Form(ps) b=Body.createFromAbsolute(f) context=Context() while context.open: context.check() context.control() context.clear() context.show() p=Point(*context.point()) nb=copy.deepcopy(b) nba=copy.deepcopy(nb.absolute) nba.points.append(p) for point in nba.points: point.show(context,color=mycolors.BLUE) nb.absolute=nba nb.show(context) nb.absolute.center.show(context,color=mycolors.RED) context.flip()
self.intruding_points[i], self.points[i + 1], ] b = BezierCurve(bezier_points) bezier_curves.append(b) if __name__ == "__main__": # To show the points from mycontext import Context import colors # To create the points import random context = Context(name="Interpolation Demonstration") # Parameters h = 1 w = 1 xmin, xmax, ymin, ymax = [-w, w, -h, h] # corners l = 5 # number of points n = 0 # number of steps m = 100 # max number of steps # Final version # pts=[Point.random() for i in range(10)] pts = [Point(2 * x, random.randint(-5, 5)) for x in range(l)] interpolation = PolynomialInterpolation([p.components for p in pts]) interpolation.color npts = interpolation.sample(200)
new_rays=[] for ray in self.entity.getRays(): for form in self.forms: new_rays.append(ray.crossForm(form)) break return new_rays if __name__=="__main__": from myzone import Zone from mycontext import Context s=20 size=[s,s] zone=Zone([2*s,2*s]) context=Context(name="Maze",fullscreen=True) matrix=np.array(Maze.conversion(Maze.convert(Maze.eller(Maze.make_empty_grid(*size))),['X',' '],[1,0])) maze=Maze(matrix,fill=True) entity=BasicEntity(1,1,color=mycolors.RED,vector_color=mycolors.GREEN,vector_width=3) solver=Solver(maze,entity) n=0 while context.open: context.check() context.control() context.clear() context.show() n=(n+1)%1 if n==0: solver.update() solver.show(context) context.flip()
o = Point.origin() random_force = Force.random() # print(random_force) random_force += gravity # print(random_force) result = Force.sum([gravity, propulsion, random_force]) # print("Force.sum:",result) x, y = result # print(x,y) #Unpacking is compatible for vectors f = gravity print(result) from mycontext import Context context = Context() position = (0, 0) while context.open: context.check() context.control() context.clear() context.show() position = context.point() f.components = list(position) f.show(context, o) context.flip() # context.wait(0.1)
point.show(self.context) def showGraphs(self, graphs): """Show the graphs on the screen.""" for (i, graph) in enumerate(graphs): color = self.colors[i] print(color) self.showGraph(graph, color) def showGraph(self, graph, color=mycolors.WHITE): """Show a graph on the screen.""" self.context.draw.lines(self.context.screen, color, graph, connected=False) if __name__ == "__main__": from mycontext import Context from polynomial import Polynomial from myabstract import Point context = Context(name="Grapher Demonstration") xs, ys = [1, 2, -4, -6, 4], [1, -3, -2, 5, -2] ps = [Point(x, y, radius=2, conversion=False) for (x, y) in zip(xs, ys)] p = Polynomial.createFromInterpolation(xs, ys) fs = [math.sin, math.cos, math.tan, p] grapher = Grapher(context, fs) grapher.points = ps grapher()