import simplegui import random import math #http://www.codeskulptor.org/#user43_xK6bwFYD2Mgvyy4_0.py # math helper function def dot(v, w): return v[0] * w[0] + v[1] * w[1] WIDTH = 500 HEIGHT = 500 #The two vectors that are being added vector1 = [0,100] vector2 = [100,0] #vector is drawn from the center of the canvas. class vector: def __init__ (self, xy, color, rot): self.xy = xy self.color = color self.border = 2 #initial x/y coords converted to polar coords (length, theta) self.length = math.sqrt(self.xy[0]*self.xy[0] + self.xy[1]*self.xy[1]) self.theta = math.atan2(self.xy[1], self.xy[0]) self.rot = rot def __str__ (self): print "Vector with coordinates " print self.xy print "Color is " + self.color return "" def update(self): #polar coords updtated by adding 3.14/rot to theta, then x/y coords updated self.theta += math.pi/self.rot self.xy[0] = self.length * math.cos(self.theta) self.xy[1] = self.length * math.sin(self.theta) def draw(self, canvas): canvas.draw_line((WIDTH/2,HEIGHT/2), (WIDTH/2 + self.xy[0], HEIGHT/2 + self.xy[1]), self.border, self.color) class resultant: def __init__(self, vectorA, vectorB, color): self.coords = [vectorA.xy[0] + vectorB.xy[0], vectorA.xy[1] + vectorB.xy[1]] self.color = color self.border = 2 def __str__ (self): print "Vector with coordinates " print self.coords print "Color is " + self.color return "" def update(self, vectorA, vectorB): #update function has to be passed both of the vectors to get most recent values for x/y self.coords = [vectorA.xy[0] + vectorB.xy[0], vectorA.xy[1] + vectorB.xy[1]] def draw(self,canvas): canvas.draw_line((WIDTH/2,HEIGHT/2), (WIDTH/2 + self.coords[0], HEIGHT/2 + self.coords[1]), self.border, self.color) def draw(canvas): v1.update() v2.update() v3.update(v1, v2) v1.draw(canvas) v2.draw(canvas) v3.draw(canvas) v1 = vector(vector1, "Red", 60) v2 = vector(vector2, "White", -600) v3 = resultant(v1, v2, "Green") frame = simplegui.create_frame("Dot Product", WIDTH, HEIGHT) frame.set_draw_handler(draw) frame.start()