Beispiel #1
0
    def __init__(self, x=0, y=0, z=0):
        self._vec = JSConstructor(glowscript.vec)(x, y, z)

        self.add = self.__add__
        self.sub = self.__sub__
        self.multiply = self.__mul__
        self.divide = self.__truediv__ = self.__div__
Beispiel #2
0
def createRobotExtender(part, length, material):
    cylindergeometryC = JSConstructor(THREE.CylinderGeometry)
    cylindergeometry = cylindergeometryC(22, 22, 6, 32)
    meshC = JSConstructor(THREE.Mesh)
    cylinder = meshC(cylindergeometry, material)
    part.add(cylinder)
    for i in range(4):
        cubegeometryC = JSConstructor(THREE.CubeGeometry)
        cubegeometry = cubegeometryC(4, length, 4)
        meshC = JSConstructor(THREE.Mesh)
        box = meshC(cubegeometry, material)
        if i <2:
            box.position.x = -8
        else:
            box.position.x = 8
        box.position.y = length/2
        if i%2:
            box.position.z = -8
        else:
            box.position.z = 8
        part.add( box )

    cylindergeometry = cylindergeometryC(15, 15, 40, 32)
    meshC = JSConstructor(THREE.Mesh)
    cylinder = meshC(cylindergeometry, material)
    cylinder.rotation.x = 90 * math.pi/180
    cylinder.position.y = length
    part.add(cylinder)
Beispiel #3
0
def createRobotExtender(part, length, material):
    cylindergeometryC = JSConstructor(THREE.CylinderGeometry)
    #CylinderGeometry(radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded)
    cylindergeometry = cylindergeometryC(22, 22, 6, 32)
    meshC = JSConstructor(THREE.Mesh)
    cylinder = meshC(cylindergeometry, material)
    part.add(cylinder)
    for i in range(4):
        cubegeometryC = JSConstructor(THREE.CubeGeometry)
        #CubeGeometry(width, height, depth, widthSegments, heightSegments, depthSegments)
        cubegeometry = cubegeometryC(4, length, 4)
        meshC = JSConstructor(THREE.Mesh)
        box = meshC(cubegeometry, material)
        if i < 2:
            box.position.x = -8
        else:
            box.position.x = 8
        box.position.y = length / 2
        if i % 2:
            box.position.z = -8
        else:
            box.position.z = 8
        part.add(box)

    cylindergeometry = cylindergeometryC(15, 15, 40, 32)
    meshC = JSConstructor(THREE.Mesh)
    cylinder = meshC(cylindergeometry, material)
    cylinder.rotation.x = 90 * math.pi / 180
    cylinder.position.y = length
    part.add(cylinder)
Beispiel #4
0
 def __init__(self, width, height, onclose):
     self._w = window.open("", "")
     self._stage = JSConstructor(GFX.Container)()
     self.width = width if width != 0 else int(window.innerWidth * 0.9)
     self.height = height if height != 0 else int(window.innerHeight *
                                                  0.9)
     self._renderer = GFX.autoDetectRenderer(self.width, self.height,
                                             {'transparent': True})
     self._w.document.body.appendChild(self._renderer.view)
     consoleArea = self._w.document.createElement('DIV')
     self.consoleText = self._w.document.createElement('TEXTAREA')
     self.consoleText.id = "textarea"
     consoleArea.id = "consoleArea"
     self.consoleText.readonly = True
     consoleArea.appendChild(self.consoleText)
     style = self._w.document.createElement('STYLE')
     css = '#consoleArea {width: 70px; height: 100%; background-color: black; position: fixed; right: 0; top: 0;} #textarea {color: white; opacity: 0; background-color: rgba(0,0,0,0); width: 260px; height: 810px; position: absolute; top: 50px; margin: 0px; left: 20px; resize: none; border: none; outline: none;} .switch {position: relative; display: inline-block; width: 30px; height: 17px; top: 15px; margin-left: 20px;} .switch input {display:none;} .slider {position: absolute;cursor: pointer;top: 0;left: 0;right: 0;bottom: 0;background-color: #ccc;-webkit-transition: .4s;transition: .4s;} .slider:before {position: absolute;content: "";height: 13px;width: 13px;left: 2px;bottom: 2px;background-color: white;-webkit-transition: .4s;transition: .4s;} input:checked + .slider {background-color: #2196F3;} input:focus + .slider {box-shadow: 0 0 1px #2196F3;} input:checked + .slider:before {-webkit-transform: translateX(13px);-ms-transform: translateX(13px);transform: translateX(13px);} .slider.round {border-radius: 17px;} .slider.round:before {border-radius: 50%;} body{-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;}'
     style.type = 'text/css'
     style.appendChild(document.createTextNode(css))
     self._w.document.head.appendChild(style)
     script = self._w.document.createElement('SCRIPT')
     js = 'function animateIt(dir, max, min) {var elem = document.getElementById("consoleArea"); var elem2 = document.getElementById("textarea"); var pos = max;var target = min;var id = setInterval(frame, 3);function frame() {var opa = Math.round((Math.abs(pos - target) / Math.abs(max - min)) * 100)/100;if (dir > 0) {opa = 1 - opa;} if (pos == target) {clearInterval(id);} else {pos = pos + dir; elem.style.width = pos + "px"; elem2.style.opacity = opa; }}}sessionStorage.switch = sessionStorage.switch ? sessionStorage.switch : "off";function switched() {if (sessionStorage.switch == "on") {sessionStorage.switch = "off";animateIt(-5, 300, 70);} else {sessionStorage.switch = "on";animateIt(5, 70, 300);}}'
     script.type = 'text/javascript'
     script.appendChild(document.createTextNode(js))
     self._w.document.body.appendChild(script)
     self._w.onunload = onclose
     #if didLoadPyinput:
     #   winput_init()
     consoleArea.insertAdjacentHTML(
         'afterbegin',
         '<label class="switch"><input type="checkbox" onclick = "switched();"><div class="slider round"></div></label>'
     )
     #self._w.document.body.innerHTML += '<div id = "inputScreen" style = "display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.2); z-index: 50;"><div style = "position: fixed; left: calc(50% - 150px); top: calc(50% - 75px); background-color: white;"><p id = "toPrompt"></p><input type = "text" id = "toInput"><input type = "submit" id = "toSubmit"></div></div>'
     self._w.document.body.appendChild(consoleArea)
 def __init__(self, width, height, onclose):
     self._w = window.open("", "")
     self._stage = JSConstructor(GFX.Container)()
     self._renderer = GFX.autoDetectRenderer(width, height,
                                             {'transparent': True})
     self._w.document.body.appendChild(self._renderer.view)
     self._w.onunload = onclose
Beispiel #6
0
 def __init__(self, width, height, onclose):
     self._w = window.open("", "")
     self._stage = JSConstructor(GFX.Container)()
     self.width = width if width != 0 else int(window.innerWidth * 0.9)
     self.height = height if height != 0 else int(window.innerHeight *
                                                  0.9)
     self._renderer = GFX.autoDetectRenderer(self.width, self.height,
                                             {'transparent': True})
     self._w.document.body.appendChild(self._renderer.view)
     self._w.onunload = onclose
Beispiel #7
0
def createRobotCrane(part, length, material):
    cubegeometryC = JSConstructor(THREE.CubeGeometry)
    cubegeometry = cubegeometryC(18, length, 18)
    meshC = JSConstructor(THREE.Mesh)
    box = meshC(cubegeometry, material)
    box.position.y = length/2
    part.add(box)
    spheregeometryC = JSConstructor(THREE.SphereGeometry)
    spheregeometry = spheregeometryC(20, 32, 16)
    meshC = JSConstructor(THREE.Mesh)
    sphere = meshC(spheregeometry, material)
    # place sphere at end of arm
    sphere.position.y = length
    part.add(sphere)
Beispiel #8
0
def createRobotCrane(part, length, material):
    cubegeometryC = JSConstructor(THREE.CubeGeometry)
    cubegeometry = cubegeometryC(18, length, 18)
    meshC = JSConstructor(THREE.Mesh)
    box = meshC(cubegeometry, material)
    box.position.y = length / 2
    part.add(box)
    spheregeometryC = JSConstructor(THREE.SphereGeometry)
    #SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength)
    spheregeometry = spheregeometryC(20, 32, 16)
    meshC = JSConstructor(THREE.Mesh)
    sphere = meshC(spheregeometry, material)
    # place sphere at end of arm
    sphere.position.y = length
    part.add(sphere)
Beispiel #9
0
class JsPhaser(object):
    """
    Brython wrapper for Phaser.

    :return: Instance of JsPhaser.
    """
    _instance = None
    PHASER = window.Phaser
    JSC = JSConstructor
    BraserGame = JSConstructor(PHASER.Game)

    def __new__(cls):

        if not cls._instance:
            cls._instance = super(JsPhaser, cls).__new__(cls)
        print("JsPhaser__new__")
        return cls._instance

    def phaser(self):
        """
        Javascript Phaser.

        :return: A Python reference for js Phaser.
        """
        return JsPhaser.PHASER

    def construct(self, constructor):
        """
        Construct a Python version of a js Constructor.

        :param constructor: Js Constructor to be called.
        :return: The Python wrapper for the given js Constructor.
        """
        return JsPhaser.JSC(constructor)
  def __init__(self, x=0, y=0, z=0):
      self._vec=JSConstructor(window.glowscript.vec)(x,y,z)

      self.add=self.__add__
      self.sub=self.__sub__
      self.multiply=self.__mul__
      self.divide=self.__truediv__=self.__div__
Beispiel #11
0
 def __init__(self, width, height, onclose):
   self._w = window.open("", "")
   self._stage = JSConstructor(GFX.Container)()
   self.width = width if width != 0 else int(window.innerWidth * 0.9)
   self.height = height if height != 0 else int(window.innerHeight * 0.9)
   self._renderer = GFX.autoDetectRenderer(self.width, self.height, {'transparent':True})
   self._w.document.body.appendChild(self._renderer.view)
   self._w.onunload = onclose
    def __init__(self, **kwargs):
        #size of a sphere in glowscript corresponds to diameter of a sphere in vPython
        if (('radius' in kwargs) and ('size' not in kwargs)
                and (isinstance(kwargs['radius'], int)
                     or isinstance(kwargs['radius'], float))):
            kwargs['size'] = kwargs['radius'] * vec(2, 2, 2)

        primitive.__init__(self, JSConstructor(window.glowscript.sphere),
                           **kwargs)
Beispiel #13
0
def load_basic(file, namehint=''):
    '''Load BMP image from a file.

    :see: `load`

    :Parameters:
        `file` : str or file-like object
            Image file or filename to load.
        `namehint` : str
            Ignored, for compatibility.

    :rtype: `Surface`
    '''
    #if not hasattr(file, 'read'):
    #    surf = SDL_LoadBMP(file)
    #else:
    #    rw = SDL_RWFromObject(file)
    #    # XXX Differ from pygame: don't freesrc when we didn't allocate it
    #    surf = SDL_LoadBMP_RW(rw, 0)

    _img = JSConstructor(window.Image)()
    _img.src = file

    _img.canvas = html.CANVAS()

    def img_onload(*args):
        #http://www.jaypan.com/tutorial/javascript-passing-arguments-anonymous-functions-without-firing-function
        #the onload files very slow so variables get messed up so we have
        #to use args[0].path[0] to figure out the correct image
        console.log(args)
        if hasattr(args[0], 'target'):  # Firefox
            this = args[0].target
        else:  #chrome
            this = args[0].path[0]

        this.canvas.width = this.width
        this.canvas.height = this.height
        this.canvas.getContext('2d').drawImage(this, 0, 0)
        #this.loaded=True

    _img.onload = img_onload
    return _pygame_surface.Surface(surf=_img.canvas)
Beispiel #14
0
def load_basic(file, namehint=''):
    '''Load BMP image from a file.

    :see: `load`

    :Parameters:
        `file` : str or file-like object
            Image file or filename to load.
        `namehint` : str
            Ignored, for compatibility.

    :rtype: `Surface`
    '''
    #if not hasattr(file, 'read'):
    #    surf = SDL_LoadBMP(file)
    #else:
    #    rw = SDL_RWFromObject(file)
    #    # XXX Differ from pygame: don't freesrc when we didn't allocate it
    #    surf = SDL_LoadBMP_RW(rw, 0)


    _img=JSConstructor(window.Image)()
    _img.src=file

    _img.canvas=html.CANVAS()
    def img_onload(*args):
        #http://www.jaypan.com/tutorial/javascript-passing-arguments-anonymous-functions-without-firing-function
        #the onload files very slow so variables get messed up so we have
        #to use args[0].path[0] to figure out the correct image
        console.log(args)
        if hasattr(args[0], 'target'):   # Firefox
           this=args[0].target
        else:                            #chrome
           this=args[0].path[0]

        this.canvas.width=this.width
        this.canvas.height=this.height
        this.canvas.getContext('2d').drawImage(this,0,0)
        #this.loaded=True

    _img.onload=img_onload
    return _pygame_surface.Surface(surf=_img.canvas)
 class GFX_Window(object):
   
   def __init__(self, width, height, onclose):
     self._w = window.open("", "")
     self._stage = JSConstructor(GFX.Container)()
     self._renderer = GFX.autoDetectRenderer(width, height, {'transparent':True})
     self._w.document.body.appendChild(self._renderer.view)
     self._w.onunload = onclose
 
   def bind(self, evtspec, callback):
     self._w.document.body.bind(evtspec, callback)
     
   def add(self, obj):
     self._stage.addChild(obj)
     
   def remove(self, obj):
     self._stage.removeChild(obj)
     
   def animate(self, stepcallback):
     self._renderer.render(self._stage)
     self._w.requestAnimationFrame(stepcallback)
     
   def destroy(self):
     SND.all().stop()
     self._stage.destroy()
    class GFX_Window(object):
        def __init__(self, width, height, onclose):
            self._w = window.open("", "")
            self._stage = JSConstructor(GFX.Container)()
            self._renderer = GFX.autoDetectRenderer(width, height,
                                                    {'transparent': True})
            self._w.document.body.appendChild(self._renderer.view)
            self._w.onunload = onclose

        def bind(self, evtspec, callback):
            self._w.document.body.bind(evtspec, callback)

        def add(self, obj):
            self._stage.addChild(obj)

        def remove(self, obj):
            self._stage.removeChild(obj)

        def animate(self, stepcallback):
            self._renderer.render(self._stage)
            self._w.requestAnimationFrame(stepcallback)

        def destroy(self):
            SND.all().stop()
            self._stage.destroy()
Beispiel #17
0
def setupGui():
    global effectController
    effectController = {
        "newGridX": gridX,
        "newGridY": gridY,
        "newGridZ": gridZ,
        "newGround": ground,
        "newAxes": axes,
        "uy": 70.0,
        "uz": -15.0,
        "fy": 10.0,
        "fz": 60.0
    }
    guiC = JSConstructor(dat.GUI)
    gui = guiC()
    h = gui.addFolder("Grid display")
    h.add(effectController, "newGridX").name("Show XZ grid")
    h.add(effectController, "newGridY").name("Show YZ grid")
    h.add(effectController, "newGridZ").name("Show XY grid")
    h.add(effectController, "newGround").name("Show ground")
    h.add(effectController, "newAxes").name("Show axes")
    '''
Beispiel #18
0
 def __init__(self, width, height, onclose):
    self._w = window.open("", "")
    self._stage = JSConstructor(GFX.Container)()
    self.width = width if width != 0 else int(window.innerWidth * 0.9)
    self.height = height if height != 0 else int(window.innerHeight * 0.9)
    self._renderer = GFX.autoDetectRenderer(self.width, self.height, {'transparent':True})
    self._w.document.body.appendChild(self._renderer.view)
    consoleArea = self._w.document.createElement('DIV')
    self.consoleText = self._w.document.createElement('TEXTAREA')
    self.consoleText.id = "textarea"
    self.consoleText.readonly = True
    consoleArea.appendChild(self.consoleText)
    style = self._w.document.createElement('STYLE')
    css = 'div {width: 300px; height: 100%; background-color: black; position: fixed; right: 0; top: 0;} #textarea {color: white; background-color: rgba(0,0,0,0); width: 260px; height: 810px; position: fixed; top: 20px; right: 20px; margin: 0px; resize: none; border: none; outline: none;}'
    style.type = 'text/css'
    style.appendChild(document.createTextNode(css))
    self._w.document.head.appendChild(style)
    self._w.document.body.appendChild(consoleArea)
    self._w.onunload = onclose
    #if didLoadPyinput:
    #   winput_init()
    self._w.document.body.insertAdjacentHTML('beforeend', '<div id = "inputScreen" style = "display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.2); z-index: 50;"><div style = "position: fixed; left: calc(50% - 150px); top: calc(50% - 75px); background-color: white;"><p id = "toPrompt"></p><input type = "text" id = "toInput"><input type = "submit" id = "toSubmit"></div></div>')
Beispiel #19
0
    h.add(effectController, "newGridX").name("Show XZ grid")
    h.add(effectController, "newGridY").name("Show YZ grid")
    h.add(effectController, "newGridZ").name("Show XY grid")
    h.add(effectController, "newGround").name("Show ground")
    h.add(effectController, "newAxes").name("Show axes")
    '''
    h = gui.addFolder("Arm angles")
    h.add(effectController, "uy", list(range(-180, 180, 1))).name("Upper arm y")
    h.add(effectController, "uz", -45.0, 45.0, 0.025).name("Upper arm z")
    h.add(effectController, "fy", -180.0, 180.0, 0.025).name("Forearm y")
    h.add(effectController, "fz", -120.0, 120.0, 0.025).name("Forearm z")
    '''


# camera
cameraC = JSConstructor(THREE.PerspectiveCamera)
camera = cameraC(30, canvasRatio, 1, 10000)
camera.position.z = 500
#camera.position.set( -510, 240, 1000 )

sceneC = JSConstructor(THREE.Scene)
scene = sceneC()

# LIGHTS
ambientlightC = JSConstructor(THREE.AmbientLight)
ambientLight = ambientlightC(0x222222)
lightC = JSConstructor(THREE.DirectionalLight)
light = lightC(0xffffff, 1.0)
light.position.set(200, 400, 500)

light2C = JSConstructor(THREE.DirectionalLight)
Beispiel #20
0
from javascript import JSConstructor
from javascript import JSObject
import math
 
cango = JSConstructor(Cango2D)
shapes2d = JSObject(shapes2D)
#tweener = JSConstructor(Tweener)
#drag2d = JSConstructor(Drag2D)
#svgtocgo2d = JSConstructor(svgToCgo2D)
#involutebezcoeffs = JSConstructor(involuteBezCoeffs)
creategeartooth = JSConstructor(createGearTooth)
#createintgeartooth= JSConstructor(createIntGearTooth)

cgo = cango("plotarea")

module = 3
teeth = 180
pressureAngle = 25

######################################
# 畫正齒輪輪廓
#####################################
'''
Rpitch = module*teeth/2
# base circle radius
Rb = Rpitch * math.cos(pressureAngle*math.pi/180)
print("基圓半徑:", Rb)
#generate Higuchi involute approximation
fs = 0.01  # start 1% off the base circle
fm = 0.25  # break 25% along involute
fe = 1     #end at 100%
Beispiel #21
0
from browser import window
from javascript import JSConstructor

assert window.empty_list() == []
assert window.list1() == [1, 2, 'a', ['b']]
assert window.jsobj().to_dict() == {'a':1}

c = window.subscriptable('abracadabra')
assert len(c) == 11
assert c[2] == 'r'

Foo = JSConstructor(window.get_constructor())
assert Foo().foo == 'hi'

# test dynamic constructor creation
Constructor = JSConstructor(window.base_class.extend())
assert Constructor().name == 'base'
assert Constructor().extra == 'extra'

 def __init__(self, width, height, onclose):
   self._w = window.open("", "")
   self._stage = JSConstructor(GFX.Container)()
   self._renderer = GFX.autoDetectRenderer(width, height, {'transparent':True})
   self._w.document.body.appendChild(self._renderer.view)
   self._w.onunload = onclose
Beispiel #23
0
    gui = guiC()
    h = gui.addFolder("Grid display")
    h.add(effectController, "newGridX").name("Show XZ grid")
    h.add(effectController, "newGridY" ).name("Show YZ grid")
    h.add(effectController, "newGridZ" ).name("Show XY grid")
    h.add(effectController, "newGround" ).name("Show ground")
    h.add(effectController, "newAxes" ).name("Show axes")
    '''
    h = gui.addFolder("Arm angles")
    h.add(effectController, "uy", list(range(-180, 180, 1))).name("Upper arm y")
    h.add(effectController, "uz", -45.0, 45.0, 0.025).name("Upper arm z")
    h.add(effectController, "fy", -180.0, 180.0, 0.025).name("Forearm y")
    h.add(effectController, "fz", -120.0, 120.0, 0.025).name("Forearm z")
    '''

cameraC = JSConstructor( THREE.PerspectiveCamera )
camera = cameraC( 75, 1, 1, 10000 )
camera.position.z = 1000;

sceneC = JSConstructor( THREE.Scene );
scene = sceneC();

geometryC = JSConstructor(THREE.CubeGeometry)
geometry = geometryC(200, 200, 200)
materialC = JSConstructor( THREE.MeshBasicMaterial )

material = materialC( { "color": "#ff0000", "wireframe": True } )

meshC = JSConstructor(THREE.Mesh)
mesh = meshC(geometry, material)
scene.add(mesh);
Beispiel #24
0
 def __init__(self, **kwargs):
     primitive.__init__(self, JSConstructor(glowscript.pyramid), **kwargs)
Beispiel #25
0
from browser import document, window
from javascript import JSConstructor
scene = JSConstructor(window.THREE.Scene)()
camera = JSConstructor(window.THREE.PerspectiveCamera)(
    75, window.innerWidth / window.innerHeight, 0.1, 1000)
renderer = JSConstructor(window.THREE.WebGLRenderer)()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
geometry = JSConstructor(window.THREE.BoxGeometry)(1, 1, 1)
material = JSConstructor(window.THREE.MeshBasicMaterial)({'color': 0x00ff00})
cube = JSConstructor(window.THREE.Mesh)(geometry, material)
scene.add(cube)
camera.position.z = 5


def move():
    cube.rotation.y += 0.1
prev_pos = None
is_down = False
def go_down():
    cube.rotation.x += 0.1
    document['bla'].bind('mousemove',  move)

def go_up():
    document['bla'].unbind('mousemove')

renderer.domElement.id = "bla"
document['bla'].bind('mousedown',  go_down)
document['bla'].bind('mouseup',  go_up)

direction = 0.01
Beispiel #26
0
 def __init__(self, **kwargs):
     self._draw = JSConstructor(glowscript.draw)(kwargs)
def module_exists(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return False
    else:
        return True


if module_exists('browser') and module_exists('javascript'):

    from browser import window, document
    from javascript import JSObject, JSConstructor

    GFX = JSObject(window.PIXI)
    GFX_Rectangle = JSConstructor(GFX.Rectangle)
    GFX_Texture = JSConstructor(GFX.Texture)
    GFX_Texture_fromImage = JSConstructor(GFX.Texture.fromImage)
    GFX_Sprite = JSConstructor(GFX.Sprite)
    GFX_Graphics = JSConstructor(GFX.Graphics)()
    GFX_Text = JSConstructor(GFX.Text)
    GFX_DetectRenderer = GFX.autoDetectRenderer
    SND = JSObject(window.buzz)
    SND_Sound = JSConstructor(SND.sound)

    class GFX_Window(object):
        def __init__(self, width, height, onclose):
            self._w = window.open("", "")
            self._stage = JSConstructor(GFX.Container)()
            self._renderer = GFX.autoDetectRenderer(width, height,
                                                    {'transparent': True})
Beispiel #28
0
 def match_search(text, regex):
     jstext = JSConstructor(window.String)(text)
     return jstext.search(regex)
Beispiel #29
0
 def match(text, regex):
     jstext = JSConstructor(window.String)(text)
     m = jstext.match(regex)
     if m is None:
         return []
     return m
class vec:
  def __init__(self, x=0, y=0, z=0):
      self._vec=JSConstructor(window.glowscript.vec)(x,y,z)

      self.add=self.__add__
      self.sub=self.__sub__
      self.multiply=self.__mul__
      self.divide=self.__truediv__=self.__div__

  #vec should be a glowscript vec, not an instance of this class
  def _set_vec(self, vec):
      self._vec=vec

  @property
  def x(self):
      return self._vec.x

  @x.setter
  def x(self, value):
      self._vec.x=value

  @property
  def y(self):
      return self._vec.y

  @y.setter
  def y(self, value):
      self._vec.y=value

  @property
  def z(self):
      return self._vec.z

  @z.setter
  def z(self, value):
      self._vec.z=value

  def __add__(self, other):
      if isinstance(other, vec):
         _v=vec()
         _v._set_vec(self._vec.add(other._vec))
         return _v

      raise ImplementationError("addition of vec and %s not implemented yet"  % type(other))

  def __sub__(self, other):
      if isinstance(other, vec):
         _v=vec()
         _v._set_vec(self._vec.sub(other._vec))
         return _v

      raise ImplementationError("subtraction of vec and %s not is implemented yet"  % type(other))


  def __mul__(self, other):
      if isinstance(other, (int, float)):
         _v=vec()
         _v._set_vec(self._vec.multiply(other))
         return _v

      raise ImplementationError("multiplication of vec and %s is not implemented yet"  % type(other))

  def __div__(self, other):
      if isinstance(other, (int, float)):
         _v=vec()
         _v._set_vec(self._vec.divide(other))
         return _v

      raise ImplementationError("division of vec and %s is not implemented yet"  % type(other))

  def __eq__(self, other):
      return self._vec.equals(other._vec)

  def __repr__(self):
      return self._vec.toString()

  def __str__(self):
      return self._vec.toString()

  def comp(self, other):
      return self._vec.comp(other._vec)

  def cross(self, other):
      return self._vec.cross(other._vec)

  def diff_angle(self, other):
      return self._vec.diff_angle(other._vec)

  def dot(self):
      return self._vec.dot()

  def mag(self):
      return self._vec.mag()

  def mag2(self):
      return self._vec.mag2()

  def norm(self):
      _v=vec()
      _v._set_vec(self._vec.norm())
      return _v

  def proj(self, other):
      _v=vec()
      _v._set_vec(self._vec.proj(other._vec))
      return _v

  def random(self):
      _v = vec()
      _v._set_vec(self._vec.random())
      return _v

  def rotate(self, **kwargs):
      _v = vec()
      _v._set_vec(self._vec.rotate(kwargs))
      return _v

  def to_glowscript(self):
      return self._vec
Beispiel #31
0
 def __init__(self, **kwargs):
     self._dl = JSConstructor(glowscript.distant_light)(kwargs)
Beispiel #32
0
 def __init__(self, **kwargs):
     primitive.__init__(self, JSConstructor(glowscript.cylinder), **kwargs)
Beispiel #33
0
def MainPlayer(texture, player_name, c_stage):
    mainPlayer = JSConstructor(PIXI.sprite)(texture)

    mainPlayer.anchor.x = 0.5
    mainPlayer.anchor.y = 0.5
    mainPlayer.direction = "right"
    mainPlayer.speed = 4
    mainPlayer.r_speed = 0.09
    mainPlayer.r_limit = 0.3
    mainPlayer.position.x = WIDTH / 2
    mainPlayer.position.y = HEIGHT / 2
    mainPlayer.add_title()
    mainPlayer.text.position.y = @position.y - 40
    mainPlayer.text.position.x = @position.x - 25
    mainPlayer.looking = "right"

    # font = {font:"13.5px Tahoma", fill:"white"}
    mainPlayer.text = JSConstructor(PIXI.Text)(player_name)
    c_stage.addChild(mainPlayer.text)

    mainPlayer.text.setText(player_name)

    if mainPlayer.rotation > mainPlayer.r_limit:
        mainPlayer.direction = "right"
    elif mainPlayer.rotation < -mainPlayer.r_limit:
        mainPlayer.direction = "left"

    mainPlayer.text.position.y = mainPlayer.position.y - 40
    mainPlayer.text.position.x = mainPlayer.position.x - 25

    if mainPlayer.direction == "right":
        mainPlayer.rotation -= mainPlayer.r_speed
    elif mainPlayer.direction == "left":
        mainPlayer.rotation += mainPlayer.r_speed


# sprite.anchor.x = sprite.anchor.y = 0.5
# sprite.position.x = sprite.position.y = 200
# sprite.scale.x = sprite.scale.y = 0.5
#
# stage.addChild(sprite)

# def animate(i):
#     # sprite.position.x -= 0.128
#     sprite.rotation += 0.1
#
#     global id
#     id = raf(animate)
#     renderer.render(stage)
#
# animate(0)
Beispiel #34
0
 def __init__(self, **kwargs):
     primitive.__init__(self, JSConstructor(glowscript.sphere), **kwargs)
Beispiel #35
0
 def match_replace(text, regex, replace):
     jstext = JSConstructor(window.String)(text)
     return jstext.replace(regex, replace)
Beispiel #36
0
 def __init__(self, **kwargs):
     self._ll = JSConstructor(glowscript.local_light)(kwargs)
Beispiel #37
0
 
<script type="text/python">
# 將 導入的 document 設為 doc 主要原因在於與舊程式碼相容
from browser import document as doc
# 由於 Python3 與 Javascript 程式碼已經不再混用, 因此來自 Javascript 的變數, 必須居中透過 window 物件轉換
from browser import window
# 針對 Javascript 既有的物件, 則必須透過 JSConstructor 轉換
from javascript import JSConstructor
import math
 
# 主要用來取得畫布大小
canvas = doc["gear1"]
# 此程式採用 Cango Javascript 程式庫繪圖, 因此無需 ctx
#ctx = canvas.getContext("2d")
# 針對類別的轉換, 將 Cango.js 中的 Cango 物件轉為 Python cango 物件
cango = JSConstructor(window.Cango)
# 針對變數的轉換, shapeDefs 在 Cango 中資料型別為變數, 可以透過 window 轉換
shapedefs = window.shapeDefs
# 目前 Cango 結合 Animation 在 Brython 尚無法運作, 此刻只能繪製靜態圖形
# in CangoAnimation.js
#interpolate1 = window.interpolate
# Cobi 與 createGearTooth 都是 Cango Javascript 程式庫中的物件
cobj = JSConstructor(window.Cobj)
creategeartooth = JSConstructor(window.createGearTooth)
 
# 經由 Cango 轉換成 Brython 的 cango, 指定將圖畫在 id="plotarea" 的 canvas 上
cgo = cango("gear1")
 
######################################
# 畫正齒輪輪廓
#####################################
Beispiel #38
0
 def __init__(self, **kwargs):
     self._label = JSConstructor(glowscript.label)(kwargs)
Beispiel #39
0
from browser import window
from javascript import JSConstructor

b_highchart = JSConstructor(window.Highcharts.Chart)

b_highchart({
    'chart': {
        'type': 'bar',
        'renderTo': 'container'
    },
    'title': {
        'text': 'Stacked bar chart'
    },
    'xAxis': {
        'categories': ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    'yAxis': {
        'min': 0,
        'title': {
            'text': 'Total fruit consumption'
        }
    },
    'legend': {
        'reversed': True
    },
    'plotOptions': {
        'series': {
            'stacking': 'normal'
        }
    },
    'series': [{
Beispiel #40
0
from browser import window
from javascript import JSConstructor

assert window.empty_list() == []
assert window.list1() == [1, 2, 'a', ['b']]
assert window.jsobj().to_dict() == {'a': 1}

c = window.subscriptable('abracadabra')
assert len(c) == 11
assert c[2] == 'r'

Foo = JSConstructor(window.get_constructor())
assert Foo().foo == 'hi'
Beispiel #41
0
from browser import document
from javascript import JSConstructor

b_highchart = JSConstructor(Highcharts.Chart)

chart = b_highchart({
    'chart': {
        'renderTo': 'container',
        'type': 'column',
        'margin': 75,
        'options3d': {
            'enabled': True,
            'alpha': 15,
            'beta': 15,
            'depth': 50,
            'viewDistance': 25
        }
    },
    'title': {
        'text': 'Chart rotation demo'
    },
    'subtitle': {
        'text': 'Test options by dragging the sliders below'
    },
    'plotOptions': {
        'column': {
            'depth': 25
        }
    },
    'series': [{
        'data': [
Beispiel #42
0
class vec:
    def __init__(self, x=0, y=0, z=0):
        self._vec = JSConstructor(glowscript.vec)(x, y, z)

        self.add = self.__add__
        self.sub = self.__sub__
        self.multiply = self.__mul__
        self.divide = self.__truediv__ = self.__div__

    #vec should be a glowscript vec, not an instance of this class
    def _set_vec(self, vec):
        self._vec = vec

    @property
    def x(self):
        return self._vec.x

    @x.setter
    def x(self, value):
        self._vec.x = value

    @property
    def y(self):
        return self._vec.y

    @y.setter
    def y(self, value):
        self._vec.y = value

    @property
    def z(self):
        return self._vec.z

    @z.setter
    def z(self, value):
        self._vec.z = value

    def __add__(self, other):
        if isinstance(other, vec):
            _v = vec()
            _v._set_vec(self._vec.add(other._vec))
            return _v

        raise ImplementationError(
            "addition of vec and %s not implemented yet" % type(other))

    def __sub__(self, other):
        if isinstance(other, vec):
            _v = vec()
            _v._set_vec(self._vec.sub(other._vec))
            return _v

        raise ImplementationError(
            "subtraction of vec and %s not is implemented yet" % type(other))

    def __mul__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            _v = vec()
            _v._set_vec(self._vec.multiply(other))
            return _v

        raise ImplementationError(
            "multiplication of vec and %s is not implemented yet" %
            type(other))

    def __div__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            _v = vec()
            _v._set_vec(self._vec.divide(other))
            return _v

        raise ImplementationError(
            "division of vec and %s is not implemented yet" % type(other))

    def __eq__(self, other):
        return self._vec.equals(other._vec)

    def __repr__(self):
        return self._vec.toString()

    def __str__(self):
        return self._vec.toString()

    def comp(self, other):
        return self._vec.comp(other._vec)

    def cross(self, other):
        return self._vec.cross(other._vec)

    def diff_angle(self, other):
        return self._vec.diff_angle(other._vec)

    def dot(self):
        return self._vec.dot()

    def mag(self):
        return self._vec.mag()

    def mag2(self):
        return self._vec.mag2()

    def norm(self):
        _v = vec()
        _v._set_vec(self._vec.norm())
        return _v

    def proj(self, other):
        _v = vec()
        _v._set_vec(self._vec.proj(other._vec))
        return _v

    def random(self):
        _v = vec()
        _v._set_vec(self._vec.random())
        return _v

    def rotate(self, **kwargs):
        _v = vec()
        _v._set_vec(self._vec.rotate(kwargs))
        return _v

    def to_glowscript(self):
        return self._vec
Beispiel #43
0
__author__ = 'chul'

from javascript import JSConstructor
from browser import document
from browser import websocket

WIDTH = 800
HEIGHT = 600

stage = JSConstructor(PIXI.Stage)(0xFFFFAA)
renderer = JSConstructor(PIXI.autoDetectRenderer)(WIDTH, HEIGHT)
# renderer = JSConstructor(PIXI.autoDetectRenderer)(400, 400, doc['myStage'])
document.body.addpendChild(renderer.view)

texture = JSConstructor(PIXI.Texture.fromImage)('img/bunny.png')
background = JSConstructor(PIXI.Texture.fromImage)('img/grass.png')
bullet_texture = JSConstructor(PIXI.Texture.fromImage)('img/bullet.png')

other_players = {}
bullets = {}

namespace = "/game"
my_name = "undefined :) "
socket = JSConstructor(io.connect)('http://' + document.domain + ':5000'  + namespace)
JSConstructor(console.log)('http://' + document.domain + ':5000'  + namespace)

background_sprite = JSConstructor(PIXI.Sprite)(background);
stage.addChild(background_sprite)

main_player = undefined