Example #1
0
 def construct_hierarchy(self):
     jnt_hier = self.get_joints_dictionary()
     self.base = Frame(0)
     self.jnt_objs.append(self.base)
     self.add_items_to_frame(self.base, 0, jnt_hier)
     self.jnt_objs.sort(key=lambda jnt_obj: jnt_obj.index)
     self.jnt_dict = {}
     for i, jnt in enumerate(self.jnt_objs):
         sym = self.robo.get_q(i)
         if sym != 0:
             self.jnt_dict[sym] = jnt
     self.assign_mono_scale()
     self.representation(expanded=True)
Example #2
0
 def construct_hierarchy(self):
     jnt_hier = self.get_joints_dictionary()
     self.base = Frame(0)
     self.jnt_objs.append(self.base)
     self.add_items_to_frame(self.base, 0, jnt_hier)
     self.jnt_objs.sort(key=lambda jnt_obj: jnt_obj.index)
     self.jnt_dict = {}
     for i, jnt in enumerate(self.jnt_objs):
         sym = self.robo.get_q(i)
         if sym != 0:
             self.jnt_dict[sym] = jnt
     self.assign_mono_scale()
     self.representation(expanded=True)
Example #3
0
 def _initialize_game_objects(self):
     self.screen.fill(BLACK)
     self.line = MiddleLine(GREY, self.screen,
                            (int(self.screen_width / 2), 0), 1,
                            self.screen_height)
     pod_player1_position, pod_player2_position = self._compute_player_pods_initial_positions(
     )
     self.pod_player1 = Paddle('seznam_logo.png', self.screen,
                               pod_player1_position, POD_WIDTH, POD_HEIGHT)
     self.pod_player2 = Paddle('seznam_logo.png', self.screen,
                               pod_player2_position, POD_WIDTH, POD_HEIGHT)
     score_player1_position, score_player2_position = self._compute_player_score_positions(
     )
     self.score_player1 = Score(self.state['player1']['score'],
                                DARK_GREY,
                                self.screen,
                                score_player1_position,
                                width=SCORE_WIDTH,
                                heigth=SCORE_HEIGHT)
     self.score_player2 = Score(self.state['player2']['score'],
                                DARK_GREY,
                                self.screen,
                                score_player2_position,
                                width=SCORE_WIDTH,
                                heigth=SCORE_HEIGHT)
     self.frame = Frame(WHITE,
                        self.screen, (0, 0),
                        self.screen_width,
                        self.screen_height,
                        border=1)
     self.ball = Ball([5, 5],
                      'seznam_icon.png',
                      self.screen,
                      width=BALL_WIDTH,
                      height=BALL_HEIGHT)
     pygame.display.flip()
Example #4
0
class myGLCanvas(GLCanvas):
    def __init__(self, parent, robo, params, size=(600, 600)):
        super(myGLCanvas, self).__init__(parent, size=size)
        self.Bind(wx.EVT_PAINT, self.OnPaintAll)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_RIGHT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_MOTION, self.OnMouseMotion)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.size = self.GetClientSize()
        self.hor_angle = self.ver_angle = 0
        self.cen_x = self.cen_y = self.cen_z = 0
        self.robo = robo
        self.q_sym = self.robo.q_vec
        self.q_pas_sym = self.robo.q_passive
        self.q_act_sym = self.robo.q_active
        self.pars_num = params
        self.init = 0
        self.distance = 5.
        self.fov = 40.
        self.jnt_objs = []
        self.construct_hierarchy()
        self.dgms = {}
        self.l_solver = None

    def OnEraseBackground(self, event):
        # Do nothing, to avoid flashing on MSW.
        # This is needed
        pass

    def assign_mono_scale(self):
        """Sets the coefficients used to draw objects

        This function calculates coefficients which are used
        to draw the objects (Joints, links, end-effectors)
        It computes the minimum and maximum r or d different from 0.
        Then uses those sizes to determine the reference
        numbers which are used all over the class.
        """
        minv = inf
        for jnt in self.jnt_objs[1:]:
            dist = max(abs(jnt.r), abs(jnt.d))
            if dist < minv and dist != 0:
                minv = dist
        if minv == inf:
            minv = 1.
        self.length = 0.4 * minv
        #print self.length
        for jnt in self.jnt_objs:
            if isinstance(jnt, PrismaticJoint):
                jnt.r = 3.5 * self.length
            jnt.set_length(self.length)

    def add_items_to_frame(self, frame, index, jnt_hier):
        children = jnt_hier[index]
        for child_i in children:
            params = [child_i]
            for par in ['theta', 'r', 'alpha', 'd', 'gamma', 'b']:
                val = self.robo.get_val(child_i, par)
                try:
                    if isinstance(val, Expr):
                        params.append(float(val.subs(self.pars_num)))
                    else:
                        params.append(float(val))
                except:
                    if val in self.q_sym:
                        params.append(0.)

            if self.robo.sigma[child_i] == 0:
                child_frame = RevoluteJoint(*params)
            elif self.robo.sigma[child_i] == 1:
                child_frame = PrismaticJoint(*params)
            else:
                child_frame = FixedJoint(*params)
            self.jnt_objs.append(child_frame)
            frame.add_child(child_frame)
            self.add_items_to_frame(child_frame, child_i, jnt_hier)

    def get_joints_dictionary(self):
        result = {}
        for jnt_i in range(self.robo.NF):
            result[jnt_i] = [
                i for i, child in enumerate(self.robo.ant) if child == jnt_i
            ]
        return result

    def construct_hierarchy(self):
        jnt_hier = self.get_joints_dictionary()
        self.base = Frame(0)
        self.jnt_objs.append(self.base)
        self.add_items_to_frame(self.base, 0, jnt_hier)
        self.jnt_objs.sort(key=lambda jnt_obj: jnt_obj.index)
        self.jnt_dict = {}
        for i, jnt in enumerate(self.jnt_objs):
            sym = self.robo.get_q(i)
            if sym != 0:
                self.jnt_dict[sym] = jnt
        self.assign_mono_scale()
        self.representation(expanded=True)

    def OnSize(self, event):
        size = self.size = self.GetClientSize()
        if self.GetContext():
            self.SetCurrent()
            gl.glViewport(0, 0, size.width, size.height)
            #gl.glMatrixMode(gl.GL_PROJECTION)
            #gl.glLoadIdentity()
            #gl.gluPerspective(40.0, size.width/size.height, 1.0, 100.0)
            #gl.glMatrixMode(gl.GL_MODELVIEW)
        event.Skip()

    def OnMouseDown(self, evt):
        self.CaptureMouse()
        self.lastx, self.lasty = evt.GetPosition()

    def OnMouseUp(self, _):
        if self.HasCapture():
            self.ReleaseMouse()

    def OnMouseMotion(self, evt):
        if evt.Dragging():
            x, y = evt.GetPosition()
            if evt.LeftIsDown():
                dx, dy = x - self.lastx, y - self.lasty
                self.lastx, self.lasty = x, y
                coef = self.distance / self.length * sin(radians(
                    self.fov / 2.))
                self.hor_angle += dx * coef / self.size.width
                self.ver_angle += dy * coef / self.size.height
                self.ver_angle = max(min(pi / 2, self.ver_angle), -pi / 2)
            elif evt.RightIsDown():
                dy = y - self.lasty
                self.lasty = y
                self.distance *= 1 + 2 * float(dy) / self.size.height
            self.CameraTransformation()
            self.Refresh(False)

    def dgm_for_frame(self, i):
        if i not in self.dgms:
            jnt = self.jnt_objs[i]
            if i > 0 and jnt.r == 0 and jnt.d == 0 and jnt.b == 0:
                self.dgms[i] = self.dgm_for_frame(self.robo.ant[i])
            else:
                symo = symbolmgr.SymbolManager(sydi=self.pars_num)
                T = dgm(self.robo, symo, 0, i, fast_form=True, trig_subs=True)
                self.dgms[i] = symo.gen_func('dgm_generated', T, self.q_sym)
        return self.dgms[i]

    def find_solution(self, qs_act, qs_pas):
        slns = self.l_solver(qs_act)
        min_error = 99999999
        min_sln = None
        for sln in slns:
            if nan in sln:
                continue
            error = 0
            for j, (qp, sigma) in enumerate(qs_pas):
                if sigma == 0:
                    error += atan2(sin(qp - sln[j]), cos(qp - sln[j]))**2
                else:
                    error += (qp - sln[j])**2
            if error < min_error:
                min_sln = sln
                min_error = error
        if min_sln is not None:
            for i, sym in enumerate(self.q_pas_sym):
                self.jnt_dict[sym].q = min_sln[i]

    def solve(self):
        if self.robo.structure != tools.CLOSED_LOOP:
            return
        if self.l_solver is None:
            self.generate_loop_fcn()
        qs_act = []
        qs_pas = []
        for sym in self.q_sym:
            if sym in self.q_act_sym:
                qs_act.append(self.jnt_dict[sym].q)
            elif sym in self.q_pas_sym:
                i = self.jnt_dict[sym].index
                if i < self.robo.NL:
                    qs_pas.append((self.jnt_dict[sym].q, self.robo.sigma[i]))

        self.find_solution(qs_act, qs_pas)

    def generate_loop_fcn(self):
        symo = symbolmgr.SymbolManager(sydi=self.pars_num)
        loop_solve(self.robo, symo)
        self.l_solver = symo.gen_func('IGM_gen',
                                      self.q_pas_sym,
                                      self.q_act_sym,
                                      multival=True)

    def centralize_to_frame(self, index):
        q_vec = [self.jnt_dict[sym].q for sym in self.q_sym]
        T = self.dgm_for_frame(index)(q_vec)
        self.cen_x, self.cen_y, self.cen_z = T[0][3], T[1][3], T[2][3]
        self.CameraTransformation()
        self.Refresh(False)

    def OnPaintAll(self, event):
        self.SetCurrent()
        if not self.init:
            self.InitGL()
            self.init = 1
        self.OnDraw()
        event.Skip()

    def CameraTransformation(self):
        gl.glLoadIdentity()
        glu.gluLookAt(
            self.cen_x -
            self.distance * cos(self.ver_angle) * sin(self.hor_angle),
            self.cen_y -
            self.distance * cos(self.ver_angle) * cos(self.hor_angle),
            self.cen_z + self.distance * sin(self.ver_angle), self.cen_x,
            self.cen_y, self.cen_z, 0.0, 0.0, 1.0)

    # def SetCameraForLabels(self):
    #     gl.glLoadIdentity()
    #     glu.gluLookAt(self.center_x,
    #                   self.center_y - self.distance, self.center_z,
    #                   self.center_x, self.center_y, self.center_z,
    #                   0.0, 0.0, 1.0)

    # def direction(self, jnt):
    #     """Returns 1 if the direction of previous r was positive otherwise 0
    #     It is used to determine the direction of shifts in expanded view.
    #     """
    #     while jnt:
    #         if jnt.r != 0:
    #             return jnt.r/abs(jnt.r)
    #         jnt = jnt.antc
    #     return 1

    @staticmethod
    def get_child_obj(jnt_obj):
        """ Returns a child frame which has the common perpendicular with
            the current frame.
        """
        for child in jnt_obj.children:
            if child.b == 0:
                return child
        if jnt_obj.children:
            return jnt_obj.children[0]
        return

    def representation(self, expanded=True):
        """ This method is used to shift joints that have the same origin
            in a way that is close to the scientific representation.
            Only joints (not frames) are shifted.
        """
        if expanded:
            for jnt in self.jnt_objs[1:]:
                i = jnt.index
                if i > self.robo.nl or self.robo.sigma[i] == 2:
                    # if cut or fixed don't shift
                    continue
                child = self.get_child_obj(jnt)
                if child is None and jnt.r == 0:
                    # The last frame (like Rx-90 6-th frame)
                    jnt.shift = 1
                elif child is not None:
                    if child.alpha != 0:
                        if self.robo.sigma[i] == 1 and child.d == 0:
                            jnt.shift = 1
                        elif jnt.r != 0 and child.d == 0 or i == 1:
                            jnt.shift = -1
                    elif child.d == 0 and child.r == 0:
                        s_child = self.get_child_obj(child)
                        if not s_child or s_child.d != 0:
                            jnt.shift = 1
                        else:
                            # jnt.shift = -2*self.length
                            # shift = -0.7*self.length
                            # jnt.shift = -(4*jnt.r + self.length)/6.
                            # child.shift = -(2*jnt.r - self.length)/6.
                            jnt.shift = 1
                            child.shift = -1

        else:
            for obj in self.jnt_objs[1:]:
                obj.shift = 0.
        self.OnDraw()

    def show_frames(self, lst):
        for jnt in self.jnt_objs:
            jnt.set_show_frame(False)
        for index in lst:
            self.jnt_objs[index].set_show_frame(True)
        self.OnDraw()

    def change_lengths(self, new_length):
        for jnt in self.jnt_objs:
            jnt.set_length(new_length)
        self.length = new_length
        self.OnDraw()

    def OnDraw(self):
        if not self.init:
            return
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
        gl.glEnableClientState(gl.GL_NORMAL_ARRAY)
        self.base.draw()
        gl.glClear(gl.GL_DEPTH_BUFFER_BIT)
        self.base.draw_frames()
        gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
        gl.glDisableClientState(gl.GL_NORMAL_ARRAY)
        gl.glFlush()
        self.SwapBuffers()

    def InitGL(self):
        # set viewing projection
        mat_specular = (1.0, 1.0, 1.0, 1.0)
        light_position = (.3, .3, 0.5, 0.0)
        light_position1 = (-0.3, 0.3, 0.5, 0.0)
        diffuseMaterial = (1., 1., 1., 1.0)
        ambientMaterial = (0.5, .5, .5, 1.0)

        gl.glClearColor(1.0, 1.0, 1.0, 1.0)
        gl.glShadeModel(gl.GL_SMOOTH)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_AMBIENT, ambientMaterial)
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_DIFFUSE, diffuseMaterial)
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_SPECULAR, mat_specular)
        gl.glMaterialf(gl.GL_FRONT, gl.GL_SHININESS, 25.0)
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, light_position)
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_POSITION, light_position1)
        gl.glEnable(gl.GL_LIGHTING)
        gl.glEnable(gl.GL_LIGHT0)
        gl.glEnable(gl.GL_LIGHT1)

        gl.glColorMaterial(gl.GL_FRONT, gl.GL_DIFFUSE)
        gl.glEnable(gl.GL_COLOR_MATERIAL)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        glu.gluPerspective(40.0, 1., 0.2, 200.0)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        self.CameraTransformation()
Example #5
0
class myGLCanvas(GLCanvas):

    def __init__(self, parent, robo, params, size=(600, 600)):
        super(myGLCanvas, self).__init__(parent, size=size)
        self.Bind(wx.EVT_PAINT, self.OnPaintAll)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_RIGHT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_MOTION, self.OnMouseMotion)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.size = self.GetClientSize()
        self.hor_angle = self.ver_angle = 0
        self.cen_x = self.cen_y = self.cen_z = 0
        self.robo = robo
        self.q_sym = self.robo.q_vec
        self.q_pas_sym = self.robo.q_passive
        self.q_act_sym = self.robo.q_active
        self.pars_num = params
        self.init = 0
        self.distance = 5.
        self.fov = 40.
        self.jnt_objs = []
        self.construct_hierarchy()
        self.dgms = {}
        self.l_solver = None

    def OnEraseBackground(self, event):
        # Do nothing, to avoid flashing on MSW.
        # This is needed
        pass

    def assign_mono_scale(self):
        """ This function calculates coefficients which are used
        to draw the objects (Joints, links, end-effectors)
        It computes the minimum and maximum r or d different from 0.
        Then uses those sizes to determine the reference
        numbers which are used all over the class.
        """
        minv = inf
        for jnt in self.jnt_objs[1:]:
            dist = max(abs(jnt.r), abs(jnt.d))
            if dist < minv and dist != 0:
                minv = dist
        if minv == inf:
            minv = 1.
        self.length = 0.4*minv
        print self.length
        for jnt in self.jnt_objs:
            if isinstance(jnt, PrismaticJoint):
                jnt.r = 3.5*self.length
            jnt.set_length(self.length)

    def add_items_to_frame(self, frame, index, jnt_hier):
        children = jnt_hier[index]
        for child_i in children:
            params = [child_i]
            for par in ['theta', 'r', 'alpha', 'd', 'gamma', 'b']:
                val = self.robo.get_val(child_i, par)
                try:
                    if isinstance(val, Expr):
                        params.append(float(val.subs(self.pars_num)))
                    else:
                        params.append(float(val))
                except:
                    if val in self.q_sym:
                        params.append(0.)

            if self.robo.sigma[child_i] == 0:
                child_frame = RevoluteJoint(*params)
            elif self.robo.sigma[child_i] == 1:
                child_frame = PrismaticJoint(*params)
            else:
                child_frame = FixedJoint(*params)
            self.jnt_objs.append(child_frame)
            frame.add_child(child_frame)
            self.add_items_to_frame(child_frame, child_i, jnt_hier)

    def get_joints_dictionary(self):
        result = {}
        for jnt_i in range(self.robo.NF):
            result[jnt_i] = [i for i, child in enumerate(self.robo.ant)
                             if child == jnt_i]
        return result

    def construct_hierarchy(self):
        jnt_hier = self.get_joints_dictionary()
        self.base = Frame(0)
        self.jnt_objs.append(self.base)
        self.add_items_to_frame(self.base, 0, jnt_hier)
        self.jnt_objs.sort(key=lambda jnt_obj: jnt_obj.index)
        self.jnt_dict = {}
        for i, jnt in enumerate(self.jnt_objs):
            sym = self.robo.get_q(i)
            if sym != 0:
                self.jnt_dict[sym] = jnt
        self.assign_mono_scale()
        self.representation(expanded=True)

    def OnSize(self, event):
        size = self.size = self.GetClientSize()
        if self.GetContext():
            self.SetCurrent()
            gl.glViewport(0, 0, size.width, size.height)
            #gl.glMatrixMode(gl.GL_PROJECTION)
            #gl.glLoadIdentity()
            #gl.gluPerspective(40.0, size.width/size.height, 1.0, 100.0)
            #gl.glMatrixMode(gl.GL_MODELVIEW)
        event.Skip()

    def OnMouseDown(self, evt):
        self.CaptureMouse()
        self.lastx, self.lasty = evt.GetPosition()

    def OnMouseUp(self, _):
        if self.HasCapture():
            self.ReleaseMouse()

    def OnMouseMotion(self, evt):
        if evt.Dragging():
            x, y = evt.GetPosition()
            if evt.LeftIsDown():
                dx, dy = x - self.lastx, y - self.lasty
                self.lastx, self.lasty = x, y
                coef = self.distance/self.length*sin(radians(self.fov/2.))
                self.hor_angle += dx*coef/self.size.width
                self.ver_angle += dy*coef/self.size.height
                self.ver_angle = max(min(pi/2, self.ver_angle), -pi/2)
            elif evt.RightIsDown():
                dy = y - self.lasty
                self.lasty = y
                self.distance *= 1 + 2 * float(dy) / self.size.height
            self.CameraTransformation()
            self.Refresh(False)

    def dgm_for_frame(self, i):
        if i not in self.dgms:
            jnt = self.jnt_objs[i]
            if i > 0 and jnt.r == 0 and jnt.d == 0 and jnt.b == 0:
                self.dgms[i] = self.dgm_for_frame(self.robo.ant[i])
            else:
                symo = Symoro(sydi=self.pars_num)
                T = dgm(self.robo, symo, 0, i, fast_form=True, trig_subs=True)
                self.dgms[i] = symo.gen_func('dgm_generated', T, self.q_sym)
        return self.dgms[i]

    def find_solution(self, qs_act, qs_pas):
        slns = self.l_solver(qs_act)
        min_error = 99999999
        min_sln = None
        for sln in slns:
            if nan in sln:
                continue
            error = 0
            for j, (qp, sigma) in enumerate(qs_pas):
                if sigma == 0:
                    error += atan2(sin(qp-sln[j]), cos(qp-sln[j]))**2
                else:
                    error += (qp - sln[j])**2
            if error < min_error:
                min_sln = sln
                min_error = error
        if min_sln is not None:
            for i, sym in enumerate(self.q_pas_sym):
                self.jnt_dict[sym].q = min_sln[i]

    def solve(self):
        if self.robo.structure != CLOSED_LOOP:
            return
        if self.l_solver is None:
            self.generate_loop_fcn()
        qs_act = []
        qs_pas = []
        for sym in self.q_sym:
            if sym in self.q_act_sym:
                qs_act.append(self.jnt_dict[sym].q)
            elif sym in self.q_pas_sym:
                i = self.jnt_dict[sym].index
                if i < self.robo.NL:
                    qs_pas.append((self.jnt_dict[sym].q, self.robo.sigma[i]))

        self.find_solution(qs_act, qs_pas)

    def generate_loop_fcn(self):
        symo = Symoro(sydi=self.pars_num)
        loop_solve(self.robo, symo)
        self.l_solver = symo.gen_func('IGM_gen', self.q_pas_sym,
                                      self.q_act_sym, multival=True)

    def centralize_to_frame(self, index):
        q_vec = [self.jnt_dict[sym].q for sym in self.q_sym]
        T = self.dgm_for_frame(index)(q_vec)
        self.cen_x, self.cen_y, self.cen_z = T[0][3], T[1][3], T[2][3]
        self.CameraTransformation()
        self.Refresh(False)

    def OnPaintAll(self, event):
        self.SetCurrent()
        if not self.init:
            self.InitGL()
            self.init = 1
        self.OnDraw()
        event.Skip()

    def CameraTransformation(self):
        gl.glLoadIdentity()
        glu.gluLookAt(
            self.cen_x-self.distance*cos(self.ver_angle)*sin(self.hor_angle),
            self.cen_y-self.distance*cos(self.ver_angle)*cos(self.hor_angle),
            self.cen_z+self.distance*sin(self.ver_angle),
            self.cen_x, self.cen_y, self.cen_z,
            0.0, 0.0, 1.0)

    # def SetCameraForLabels(self):
    #     gl.glLoadIdentity()
    #     glu.gluLookAt(self.center_x,
    #                   self.center_y - self.distance, self.center_z,
    #                   self.center_x, self.center_y, self.center_z,
    #                   0.0, 0.0, 1.0)

    # def direction(self, jnt):
    #     """Returns 1 if the direction of previous r was positive otherwise 0
    #     It is used to determine the direction of shifts in expanded view.
    #     """
    #     while jnt:
    #         if jnt.r != 0:
    #             return jnt.r/abs(jnt.r)
    #         jnt = jnt.antc
    #     return 1

    @staticmethod
    def get_child_obj(jnt_obj):
        """ Returns a child frame which has the common perpendicular with
            the current frame.
        """
        for child in jnt_obj.children:
            if child.b == 0:
                return child
        if jnt_obj.children:
            return jnt_obj.children[0]
        return

    def representation(self, expanded=True):
        """ This method is used to shift joints that have the same origin
            in a way that is close to the scientific representation.
            Only joints (not frames) are shifted.
        """
        if expanded:
            for jnt in self.jnt_objs[1:]:
                i = jnt.index
                if i > self.robo.nl or self.robo.sigma[i] == 2:
                    # if cut or fixed don't shift
                    continue
                child = self.get_child_obj(jnt)
                if child is None and jnt.r == 0:
                    # The last frame (like Rx-90 6-th frame)
                    jnt.shift = 1
                elif child is not None:
                    if child.alpha != 0:
                        if self.robo.sigma[i] == 1 and child.d == 0:
                            jnt.shift = 1
                        elif jnt.r != 0 and child.d == 0 or i == 1:
                            jnt.shift = -1
                    elif child.d == 0 and child.r == 0:
                        s_child = self.get_child_obj(child)
                        if not s_child or s_child.d != 0:
                            jnt.shift = 1
                        else:
                            # jnt.shift = -2*self.length
                            # shift = -0.7*self.length
                            # jnt.shift = -(4*jnt.r + self.length)/6.
                            # child.shift = -(2*jnt.r - self.length)/6.
                            jnt.shift = 1
                            child.shift = -1

        else:
            for obj in self.jnt_objs[1:]:
                obj.shift = 0.
        self.OnDraw()

    def show_frames(self, lst):
        for jnt in self.jnt_objs:
            jnt.set_show_frame(False)
        for index in lst:
            self.jnt_objs[index].set_show_frame(True)
        self.OnDraw()

    def change_lengths(self, new_length):
        for jnt in self.jnt_objs:
            jnt.set_length(new_length)
        self.length = new_length
        self.OnDraw()

    def OnDraw(self):
        if not self.init:
            return
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
        gl.glEnableClientState(gl.GL_NORMAL_ARRAY)
        self.base.draw()
        gl.glClear(gl.GL_DEPTH_BUFFER_BIT)
        self.base.draw_frames()
        gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
        gl.glDisableClientState(gl.GL_NORMAL_ARRAY)
        self.SwapBuffers()

    def InitGL(self):
        # set viewing projection
        mat_specular = (1.0, 1.0, 1.0, 1.0)
        light_position = (.3, .3, 0.5, 0.0)
        light_position1 = (-0.3, 0.3, 0.5, 0.0)
        diffuseMaterial = (1., 1., 1., 1.0)
        ambientMaterial = (0.5, .5, .5, 1.0)

        gl.glClearColor(1.0, 1.0, 1.0, 1.0)
        gl.glShadeModel(gl.GL_SMOOTH)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_AMBIENT, ambientMaterial)
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_DIFFUSE, diffuseMaterial)
        gl.glMaterialfv(gl.GL_FRONT, gl.GL_SPECULAR, mat_specular)
        gl.glMaterialf(gl.GL_FRONT, gl.GL_SHININESS, 25.0)
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, light_position)
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_POSITION, light_position1)
        gl.glEnable(gl.GL_LIGHTING)
        gl.glEnable(gl.GL_LIGHT0)
        gl.glEnable(gl.GL_LIGHT1)

        gl.glColorMaterial(gl.GL_FRONT, gl.GL_DIFFUSE)
        gl.glEnable(gl.GL_COLOR_MATERIAL)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        glu.gluPerspective(40.0, 1., 0.2, 200.0)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        self.CameraTransformation()
Example #6
0
class Pong(object):
    def __init__(self):
        # Screen settings
        display = pygame.display.Info()
        self.screen_width = int(display.current_w / 2)
        self.screen_height = int(display.current_h / 2)

        # screen = pygame.display.set_mode([screen_width,screen_height], pygame.FULLSCREEN, 32)
        self.screen = pygame.display.set_mode(
            [self.screen_width, self.screen_height])

        # Font and images
        self.sprite = pygame.sprite.Sprite()
        image = pygame.image.load("seznam_icon.png")
        scaled_image = pygame.transform.smoothscale(
            image, (BALL_WIDTH, BALL_HEIGHT))  # or scale
        self.sprite.image = scaled_image
        self.sprite.rect = self.sprite.image.get_rect()
        self.sprite.rect.topleft = (int(self.screen_width / 2) - 32,
                                    random.randint(0, self.screen_height) - 32
                                    )  # Place the ball somewhere in the middle

        # State
        self.state = {
            'player1': {
                'score': 0,
                'moving_up': False,
                'moving_down': False,
                'movement_speed': 6
            },
            'player2': {
                'score': 0,
                'moving_up': False,
                'moving_down': False,
                'movement_speed': 6
            }
        }

        self.clock = pygame.time.Clock()

        # Initialize game objects
        self._initialize_game_objects()

    def _compute_player_pods_initial_positions(self):
        position1 = (POD_OFFSET,
                     int(self.screen.get_height() / 2) - int(POD_HEIGHT / 2))
        position2 = (self.screen.get_width() - (POD_WIDTH + POD_OFFSET),
                     int(self.screen.get_height() / 2) - int(POD_HEIGHT / 2))
        return position1, position2

    def _compute_player_score_positions(self):
        position1 = (int(self.screen.get_width() / 4) - int(SCORE_WIDTH / 2),
                     int(self.screen.get_height() / 2) - int(SCORE_HEIGHT / 2))
        position2 = (int(self.screen.get_width() / 4) * 3 -
                     int(SCORE_WIDTH / 2),
                     int(self.screen.get_height() / 2) - int(SCORE_HEIGHT / 2))
        return position1, position2

    def _initialize_game_objects(self):
        self.screen.fill(BLACK)
        self.line = MiddleLine(GREY, self.screen,
                               (int(self.screen_width / 2), 0), 1,
                               self.screen_height)
        pod_player1_position, pod_player2_position = self._compute_player_pods_initial_positions(
        )
        self.pod_player1 = Paddle('seznam_logo.png', self.screen,
                                  pod_player1_position, POD_WIDTH, POD_HEIGHT)
        self.pod_player2 = Paddle('seznam_logo.png', self.screen,
                                  pod_player2_position, POD_WIDTH, POD_HEIGHT)
        score_player1_position, score_player2_position = self._compute_player_score_positions(
        )
        self.score_player1 = Score(self.state['player1']['score'],
                                   DARK_GREY,
                                   self.screen,
                                   score_player1_position,
                                   width=SCORE_WIDTH,
                                   heigth=SCORE_HEIGHT)
        self.score_player2 = Score(self.state['player2']['score'],
                                   DARK_GREY,
                                   self.screen,
                                   score_player2_position,
                                   width=SCORE_WIDTH,
                                   heigth=SCORE_HEIGHT)
        self.frame = Frame(WHITE,
                           self.screen, (0, 0),
                           self.screen_width,
                           self.screen_height,
                           border=1)
        self.ball = Ball([5, 5],
                         'seznam_icon.png',
                         self.screen,
                         width=BALL_WIDTH,
                         height=BALL_HEIGHT)
        pygame.display.flip()

    def generate_random_color(self):
        return random.randint(0, 255), random.randint(0, 255), random.randint(
            0, 255)

    def run(self):
        running = True
        while running:
            # Reset playground
            self.screen.fill(BLACK)
            self.line.render()
            self.frame.render()
            self.score_player1.render()
            self.score_player2.render()

            # Movement
            #
            # Because we move on the Y axis, we have to have "reversed" movement.
            if self.state['player1']['moving_up']:
                self.pod_player1.move(0,
                                      -self.state['player1']['movement_speed'],
                                      increment=True)
            if self.state['player1']['moving_down']:
                self.pod_player1.move(0,
                                      self.state['player1']['movement_speed'],
                                      increment=True)
            if self.state['player2']['moving_up']:
                self.pod_player2.move(0,
                                      -self.state['player2']['movement_speed'],
                                      increment=True)
            if self.state['player2']['moving_down']:
                self.pod_player2.move(0,
                                      self.state['player2']['movement_speed'],
                                      increment=True)

            # Events
            for event in pygame.event.get():
                # Cant quit on an event or when Escape button is pressed.
                if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN
                                                 and event.key
                                                 == pygame.K_ESCAPE):
                    running = False

                # Actions
                if event.type == pygame.KEYDOWN and event.key == Q_BUTTON:
                    self.state['player1']['moving_up'] = True
                    self.state['player1']['moving_down'] = False
                if event.type == pygame.KEYDOWN and event.key == UP_BUTTON:
                    self.state['player2']['moving_up'] = True
                    self.state['player2']['moving_down'] = False
                if event.type == pygame.KEYDOWN and event.key == A_BUTTON:
                    self.state['player1']['moving_up'] = False
                    self.state['player1']['moving_down'] = True
                if event.type == pygame.KEYDOWN and event.key == DOWN_BUTTON:
                    self.state['player2']['moving_up'] = False
                    self.state['player2']['moving_down'] = True
                if event.type == pygame.KEYUP and event.key in (A_BUTTON,
                                                                Q_BUTTON):
                    self.state['player1']['moving_up'] = False
                    self.state['player1']['moving_down'] = False
                if event.type == pygame.KEYUP and event.key in (UP_BUTTON,
                                                                DOWN_BUTTON):
                    self.state['player2']['moving_up'] = False
                    self.state['player2']['moving_down'] = False

            # Player pads
            self.pod_player1.render()
            self.pod_player2.render()

            # Move the ball
            try:
                self.ball.render([self.pod_player1, self.pod_player2])
            except GameOverException as e:
                # Change the score
                self.state[e.winning_player_info]['score'] += 1

                # Reset the playground
                self._initialize_game_objects()
                continue
            pygame.display.flip()

            self.clock.tick(60)  # 60 FPS

        pygame.quit()