<commit_before>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield, Mr. Donnelly,
Marcelo Almaguer for the Chell character model used in his own version of Portal called "Remember the Game"
maxiesnax for the Orange Portal Image:0 "http://orig05.deviantart.net/58ec/f/2012/361/2/5/portal___orange_portal_by_maxiesnax-d5pcfmj.png"
Blue Portal Image "http://vignette4.wikia.nocookie.net/kirby-bulborb/images/1/12/Blue_Portal.png/revision/latest?cb=20151004085207"
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
plat=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickishline= LineStyle(2.5, black)
noline=LineStyle(0, black)
portalline=LineStyle(1, blue)
portalline2=LineStyle(1, orange)

wall=RectangleAsset(1000,500, noline, wall)
blueportal=EllipseAsset(27, 60, noline, blue)
orangeportal=EllipseAsset(27, 60, noline, orange)
innerportal=EllipseAsset(24, 57, noline, white)
exit=CircleAsset(70, thinline, plat)
exit2=CircleAsset(20, thinline, plat)
plat=RectangleAsset(250, 50, noline, plat)
doorline=LineAsset(0, 120, thinline)
goo=PolygonAsset([(0,500),(800,500),(800,600,),(0,600)],noline,gooy)

cpx = 0
cpy = 0
cox = -100
coy = -100
cbx = -100
cby = -100

class Chell(Sprite):
    asset = ImageAsset("images/ChellSpriteSheet.png", Frame(0,0,205,361), 2, 'horizontal')
    def __init__(self, position):
        super().__init__(Chell.asset, position)
        self.visible = True
        self.x = 250
        self.y = 250
        self.click = 0
        self.mright = 0
        self.mleft = 0
        self.alt = 0
        self.image = 0
        self.scale = .25
        self.op = 0
        PortalGame.listenKeyEvent("keydown", "d", self.rightOn)
        PortalGame.listenKeyEvent("keyup", "d", self.rightOff)
        PortalGame.listenKeyEvent("keydown", "a", self.leftOn)
        PortalGame.listenKeyEvent("keyup", "a", self.leftOff)
        PortalGame.listenMouseEvent("click", self.ClickOn)
        PortalGame.listenKeyEvent("keydown", "alt", self.altOn)
        PortalGame.listenKeyEvent("keyup", "alt", self.altOff)

    def step(self):
        if self.click == 1 and self.alt != 1:
            global cox
            cox = cpx
            global coy
            coy = cpy
            self.click = 0

        if self.click == 1 and self.alt == 1:
            global cbx
            cbx = cpx
            global cby
            cby = cpy
            self.click = 0

        if self.x<= cox-20 and self.x>=cox-30 and self.y <= coy-10 and self.y >= coy-40 and cby>=0 and cbx>=0:
            self.x = cbx - 10
            self.y = cby - 40

        if self.x<=cbx-20 and self.x>=cbx-30 and self.y <= cby-10 and self.y >= cby-40 and coy>=0 and cox>=0:
            self.x = cox - 10
            self.y = coy - 40

        if self.mright == 1:
            self.setImage(0)
            self.x += 1
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 1:
            self.setImage(1)
            self.x += -1
            self.y = self.y
        if self.mleft == 0:
            self.x = self.x
            self.y = self.y

    def ClickOn(self,event):
        self.click = 1
        global cpx
        cpx = event.x
        global cpy
        cpy = event.y
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

class BluePortal(Sprite):
    asset = ImageAsset("images/Blue_Portal.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(BluePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = cbx - 50
        self.y = cby - 60

class OrangePortal(Sprite):
    asset = ImageAsset("images/portal___orange_portal_by_maxiesnax-d5pcfmj.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(OrangePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = cox - 50
        self.y = coy - 60

class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        txt_asset= TextAsset(text="WASD to Move", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset1= TextAsset(text="Left Click to Place Orange Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset2= TextAsset(text="Alt + Left Click to Place Blue Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        Sprite(wall, (0,0))
        Sprite(wall, (100,20))
        Sprite(exit, (800,100))
        Sprite(exit2, (800, 100))
        Sprite(doorline, (800, 30))
        Sprite(plat, (100,400))
        Sprite(plat, (650, 150))
        Sprite(goo, (100,0))
        Sprite(txt_asset,(0,0))
        Sprite(txt_asset1, (0,10))
        Sprite(txt_asset2, (0,20))
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))

    def step(self):
        for chell in self.getSpritesbyClass(Chell):
            chell.step()
        for blueportal in self.getSpritesbyClass(BluePortal):
            blueportal.step()
        for orangeportal in self.getSpritesbyClass(OrangePortal):
            orangeportal.step()

myapp = PortalGame(1000,750)
myapp.run()<commit_msg>Updated from Brython Server: 5/2/2016 2:16:43 PM<commit_after>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield, Mr. Donnelly,
Marcelo Almaguer for the Chell character model used in his own version of Portal called "Remember the Game"
maxiesnax for the Orange Portal Image:0 "http://orig05.deviantart.net/58ec/f/2012/361/2/5/portal___orange_portal_by_maxiesnax-d5pcfmj.png"
Blue Portal Image "http://vignette4.wikia.nocookie.net/kirby-bulborb/images/1/12/Blue_Portal.png/revision/latest?cb=20151004085207"
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
plat=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickishline= LineStyle(2.5, black)
noline=LineStyle(0, black)
portalline=LineStyle(1, blue)
portalline2=LineStyle(1, orange)

wall=RectangleAsset(1000,500, noline, wall)
blueportal=EllipseAsset(27, 60, noline, blue)
orangeportal=EllipseAsset(27, 60, noline, orange)
innerportal=EllipseAsset(24, 57, noline, white)
exit=CircleAsset(70, thinline, plat)
exit2=CircleAsset(20, thinline, plat)
plat=RectangleAsset(250, 50, noline, plat)
doorline=LineAsset(0, 120, thinline)
goo=PolygonAsset([(0,500),(800,500),(800,600,),(0,600)],noline,gooy)

cpx = 0
cpy = 0
cox = -100
coy = -100
cbx = -100
cby = -100

class Chell(Sprite):
    asset = ImageAsset("images/ChellSpriteSheet.png", Frame(0,0,205,361), 2, 'horizontal')
    def __init__(self, position):
        super().__init__(Chell.asset, position)
        self.visible = True
        self.x = 250
        self.y = 250
        self.click = 0
        self.mright = 0
        self.mleft = 0
        self.alt = 0
        self.image = 0
        self.scale = .25
        self.op = 0
        PortalGame.listenKeyEvent("keydown", "d", self.rightOn)
        PortalGame.listenKeyEvent("keyup", "d", self.rightOff)
        PortalGame.listenKeyEvent("keydown", "a", self.leftOn)
        PortalGame.listenKeyEvent("keyup", "a", self.leftOff)
        PortalGame.listenMouseEvent("click", self.ClickOn)
        PortalGame.listenKeyEvent("keydown", "alt", self.altOn)
        PortalGame.listenKeyEvent("keyup", "alt", self.altOff)

    def step(self):
        if self.click == 1 and self.alt != 1:
            global cox
            cox = cpx
            global coy
            coy = cpy
            self.click = 0

        if self.click == 1 and self.alt == 1:
            global cbx
            cbx = cpx
            global cby
            cby = cpy
            self.click = 0

        if self.x<= cox-20 and self.x>=cox-30 and self.y <= coy-10 and self.y >= coy-40 and cby>=0 and cbx>=0:
            self.x = cbx - 10
            self.y = cby - 40

        if self.x<=cbx-20 and self.x>=cbx-30 and self.y <= cby-10 and self.y >= cby-40 and coy>=0 and cox>=0:
            self.x = cox - 10
            self.y = coy - 40

        if self.mright == 1:
            self.setImage(0)
            self.x += 1
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 1:
            self.setImage(1)
            self.x += -1
            self.y = self.y
        if self.mleft == 0:
            self.x = self.x
            self.y = self.y

    def ClickOn(self,event):
        self.click = 1
        global cpx
        cpx = event.x
        global cpy
        cpy = event.y
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

class BluePortal(Sprite):
    asset = ImageAsset("images/Blue_Portal.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(BluePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = cbx - 50
        self.y = cby - 60

class OrangePortal(Sprite):
    asset = ImageAsset("images/portal___orange_portal_by_maxiesnax-d5pcfmj.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(OrangePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = cox - 50
        self.y = coy - 60

class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        txt_asset= TextAsset(text="WASD to Move", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset1= TextAsset(text="Left Click to Place Orange Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset2= TextAsset(text="Alt + Left Click to Place Blue Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        Sprite(wall, (0,0))
        Sprite(exit, (800,100))
        Sprite(exit2, (800, 100))
        Sprite(doorline, (800, 30))
        Sprite(plat, (100,400))
        Sprite(plat, (650, 150))
        Sprite(goo, (100,0))
        Sprite(txt_asset,(0,0))
        Sprite(txt_asset1, (0,10))
        Sprite(txt_asset2, (0,20))
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))

    def step(self):
        for chell in self.getSpritesbyClass(Chell):
            chell.step()
        for blueportal in self.getSpritesbyClass(BluePortal):
            blueportal.step()
        for orangeportal in self.getSpritesbyClass(OrangePortal):
            orangeportal.step()

myapp = PortalGame(1000,750)
myapp.run()<|endoftext|>


<commit_before>#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
Types used internally by the rBuild implementation.

As with all internal components, these interfaces are subject to
change.
"""

import inspect
import weakref

def findPropCaller(descr, cls):
    """
    Figure out what attribute a descriptor was accessed as.

    NOTE: When using a descriptor that utilizes this function, never
    use the same instance of the descriptor for multiple attributes,
    or this function will return the wrong name!

    @param descr: Descriptor to find the binding for
    @param cls: Class whose MRO will be searched
    """

    for cls in inspect.getmro(cls):
        for key, value in cls.__dict__.iteritems():
            if value is descr:
                return key

    # Nothing in the object's MRO references this descriptor.
    raise RuntimeError("invalid descriptor call")

class AttributeHook(object):
    """
    A property descriptor that "hooks" all assignments.

    Before an assignment, a method is invoked on the new value (if it
    is not C{None}), with the parent object as the only argument.

    Attribute fetches are passed through. Deletions will assign C{None}.

    This is a data descriptor.

    @param attribute: The attribute to invoke on the new value before
                      the assignment is performed.
    @type  attribute: C{basestring}
    """

    __slots__ = ['attribute']

    def __init__(self, attribute):
        self.attribute = attribute

    def _attr(self, cls):
        """
        Get the called attribute name.

        @param cls: Owner class
        """
        return findPropCaller(self, cls)

    def __get__(self, obj, cls):
        """
        Pass-through; should behave identically to a selfiptorless fetch.
        """
        prop = self._attr(cls)
        if obj:
            return obj.__dict__[prop]
        else:
            return self

    def __set__(self, obj, value):
        """
        If C{value} is not C{None}, invoke a pre-hook on that value.
        """
        if value is not None:
            getattr(value, self.attribute)(obj)

        prop = self._attr(type(obj))
        obj.__dict__[prop] = value

    def __delete__(self, obj):
        """
        Assign C{None}.
        """
        prop = self._attr(type(obj))
        obj.__dict__[prop] = None

class WeakReference(object):
    """
    A property descriptor that transparently weak references its value.

    Upon assignment, a weak reference is created, and further accesses
    dereference it automatically. The default value is always C{None}.

    The generated weak reference can be accessed by appending "_ref" to
    the name this descriptor is assigned to, though only after an
    assignment has been performed. Consequently, if slots are in use
    in the owning class, a slot will need to be added with this name.

    This is a data descriptor.
    """

    __slots__ = []

    def _attr(self, cls):
        """
        Return the name used to stow the reference itself in the
        owner's dictionary.

        @param cls: Owner class
        """
        return findPropCaller(self, cls) + '_ref'

    def __get__(self, obj, cls):
        """
        If the stored reference exists and is not C{None}, de-reference
        it and return that value. Otherwise, return C{None}.
        """
        if obj:
            prop = self._attr(cls)
            ref = obj.__dict__.get(prop, None)
            if ref:
                return ref()
        return None

    def __set__(self, obj, value):
        """
        Store a weak reference to C{value}, or C{None} if C{value} is
        C{None}.
        """
        if value is not None:
            value = weakref.ref(value)
        prop = self._attr(type(obj))
        obj.__dict__[prop] = value

    def __delete__(self, obj):
        """
        Assign C{None}.
        """
        prop = self._attr(type(obj))
        obj.__dict__[prop] = None
<commit_msg>Semantic tweaks to descriptors<commit_after>#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
Types used internally by the rBuild implementation.

As with all internal components, these interfaces are subject to
change.
"""

import inspect
import weakref

def findPropCaller(descr, cls):
    """
    Figure out what attribute a descriptor was accessed as.

    NOTE: When using a descriptor that utilizes this function, never
    use the same instance of the descriptor for multiple attributes,
    or this function will return the wrong name!

    @param descr: Descriptor to find the binding for
    @param cls: Class whose MRO will be searched
    """

    for cls in inspect.getmro(cls):
        for key, value in cls.__dict__.iteritems():
            if value is descr:
                return key

    # Nothing in the object's MRO references this descriptor.
    raise AssertionError("invalid descriptor call")

class AttributeHook(object):
    """
    A property descriptor that "hooks" all assignments.

    Before an assignment, a method is invoked on the new value (if it
    is not C{None}), with the parent object as the only argument.

    Attribute fetches are passed through. Deletions will assign C{None}.

    This is a data descriptor.

    @param attribute: The attribute to invoke on the new value before
                      the assignment is performed.
    @type  attribute: C{basestring}
    """

    __slots__ = ['attribute']

    def __init__(self, attribute):
        self.attribute = attribute

    def _attr(self, cls):
        """
        Get the called attribute name.

        @param cls: Owner class
        """
        return findPropCaller(self, cls)

    def __get__(self, obj, cls):
        """
        Pass-through; should behave identically to a selfiptorless fetch.
        """
        prop = self._attr(cls)
        if obj:
            return obj.__dict__.get(prop, None)
        else:
            return self

    def __set__(self, obj, value):
        """
        If C{value} is not C{None}, invoke a pre-hook on that value.
        """
        if value is not None:
            getattr(value, self.attribute)(obj)

        prop = self._attr(type(obj))
        obj.__dict__[prop] = value

    def __delete__(self, obj):
        """
        Assign C{None}.
        """
        prop = self._attr(type(obj))
        obj.__dict__[prop] = None

class WeakReference(object):
    """
    A property descriptor that transparently weak references its value.

    Upon assignment, a weak reference is created, and further accesses
    dereference it automatically. The default value is always C{None}.

    The generated weak reference can be accessed by appending "_ref" to
    the name this descriptor is assigned to, though only after an
    assignment has been performed. Consequently, if slots are in use
    in the owning class, a slot will need to be added with this name.

    This is a data descriptor.
    """

    __slots__ = []

    def _attr(self, cls):
        """
        Return the name used to stow the reference itself in the
        owner's dictionary.

        @param cls: Owner class
        """
        return findPropCaller(self, cls) + '_ref'

    def __get__(self, obj, cls):
        """
        If the stored reference exists and is not C{None}, de-reference
        it and return that value. Otherwise, return C{None}.
        """
        if obj:
            prop = self._attr(cls)
            ref = obj.__dict__.get(prop, None)
            if ref:
                return ref()
            else:
                return None
        else:
            # Pass-through
            return self

    def __set__(self, obj, value):
        """
        Store a weak reference to C{value}, or C{None} if C{value} is
        C{None}.
        """
        if value is not None:
            value = weakref.ref(value)
        prop = self._attr(type(obj))
        obj.__dict__[prop] = value

    def __delete__(self, obj):
        """
        Assign C{None}.
        """
        prop = self._attr(type(obj))
        obj.__dict__[prop] = None
<|endoftext|>


<commit_before># -*- coding: utf-8  -*-

__version__ = '$Id$'

import family

# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'

class Family(family.Family):
    def __init__(self):
        family.Family.__init__(self)
        self.name = u'wikia'

        self.langs = {
            u'wikia': None,
        }

        self.namespaces[4] = {
            '_default': [u'search', self.namespaces[4]['_default']],
        }
        self.namespaces[5] = {
            '_default': [u'search talk', self.namespaces[5]['_default']],
        }
        self.namespaces[100] = {
            '_default': u'Forum',
        }
        self.namespaces[101] = {
            '_default': u'Forum talk',
        }
        self.namespaces[112] = {
            '_default': u'Mini',
        }
        self.namespaces[113] = {
            '_default': u'Mini talk',
        }

    def hostname(self, code):
        return u'www.wikia.com'

    def version(self, code):
        return "1.15.1"

    def scriptpath(self, code):
        return ''

    def apipath(self, code):
        return '/api.php'
<commit_msg>remove obsolete namespace dict.<commit_after># -*- coding: utf-8  -*-

__version__ = '$Id$'

import family

# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'

class Family(family.Family):
    def __init__(self):
        family.Family.__init__(self)
        self.name = u'wikia'

        self.langs = {
            u'wikia': None,
        }

    def hostname(self, code):
        return u'www.wikia.com'

    def version(self, code):
        return "1.15.1"

    def scriptpath(self, code):
        return ''

    def apipath(self, code):
        return '/api.php'
<|endoftext|>


<commit_before><commit_msg>STY: removed unreachable error catch<commit_after><|endoftext|>


<commit_before>"""
This module provides an abstraction for working with XModuleDescriptors
that are stored in a database an accessible using their Location as an identifier
"""

import re
from .exceptions import InvalidLocationError

URL_RE = re.compile("""
    (?P<tag>[^:]+)://
    (?P<org>[^/]+)/
    (?P<course>[^/]+)/
    (?P<category>[^/]+)/
    (?P<name>[^/]+)
    (/(?P<revision>[^/]+))?
    """, re.VERBOSE)

class Location(object):
    '''
    Encodes a location.

    Locations representations of URLs of the
    form {tag}://{org}/{course}/{category}/{name}[/{revision}]

    However, they can also be represented a dictionaries (specifying each component),
    tuples or list (specified in order), or as strings of the url
    '''
    def __init__(self, location):
        """
        Create a new location that is a clone of the specifed one.

        location - Can be any of the following types:
            string: should be of the form {tag}://{org}/{course}/{category}/{name}[/{revision}]
            list: should be of the form [tag, org, course, category, name, revision]
            dict: should be of the form {
                'tag': tag,
                'org': org,
                'course': course,
                'category': category,
                'name': name,
                'revision': revision,
            }
            Location: another Location object

        None of the components of a location may contain the '/' character
        """
        self.update(location)

    def update(self, location):
        """
        Update this instance with data from another Location object.

        location: can take the same forms as specified by `__init__`
        """
        self.tag = self.org = self.course = self.category = self.name = self.revision = None

        if isinstance(location, basestring):
            match = URL_RE.match(location)
            if match is None:
                raise InvalidLocationError(location)
            else:
                self.update(match.groupdict())
        elif isinstance(location, list):
            if len(location) not in (5, 6):
                raise InvalidLocationError(location)

            (self.tag, self.org, self.course, self.category, self.name) = location[0:5]
            self.revision = location[5] if len(location) == 6 else None
        elif isinstance(location, dict):
            try:
                self.tag = location['tag']
                self.org = location['org']
                self.course = location['course']
                self.category = location['category']
                self.name = location['name']
            except KeyError:
                raise InvalidLocationError(location)
            self.revision = location.get('revision')
        elif isinstance(location, Location):
            self.update(location.list())
        else:
            raise InvalidLocationError(location)

        for val in self.list():
            if val is not None and '/' in val:
                raise InvalidLocationError(location)

    def __str__(self):
        return self.url()

    def url(self):
        """
        Return a string containing the URL for this location
        """
        url = "{tag}://{org}/{course}/{category}/{name}".format(**self.dict())
        if self.revision:
            url += "/" + self.revision
        return url

    def list(self):
        """
        Return a list representing this location
        """
        return [self.tag, self.org, self.course, self.category, self.name, self.revision]

    def dict(self):
        """
        Return a dictionary representing this location
        """
        return {'tag': self.tag,
                'org': self.org,
                'course': self.course,
                'category': self.category,
                'name': self.name,
                'revision': self.revision}

class ModuleStore(object):
    """
    An abstract interface for a database backend that stores XModuleDescriptor instances
    """
    def get_item(self, location):
        """
        Returns an XModuleDescriptor instance for the item at location.
        If location.revision is None, returns the most item with the most
        recent revision

        If any segment of the location is None except revision, raises
            keystore.exceptions.InsufficientSpecificationError
        If no object is found at that location, raises keystore.exceptions.ItemNotFoundError

        location: Something that can be passed to Location
        """
        raise NotImplementedError

    # TODO (cpennington): Replace with clone_item
    def create_item(self, location, editor):
        raise NotImplementedError

    def update_item(self, location, data):
        """
        Set the data in the item specified by the location to
        data

        location: Something that can be passed to Location
        data: A nested dictionary of problem data
        """
        raise NotImplementedError

    def update_children(self, location, children):
        """
        Set the children for the item specified by the location to
        data

        location: Something that can be passed to Location
        children: A list of child item identifiers
        """
        raise NotImplementedError
<commit_msg>Remove extra word in doc string<commit_after>"""
This module provides an abstraction for working with XModuleDescriptors
that are stored in a database an accessible using their Location as an identifier
"""

import re
from .exceptions import InvalidLocationError

URL_RE = re.compile("""
    (?P<tag>[^:]+)://
    (?P<org>[^/]+)/
    (?P<course>[^/]+)/
    (?P<category>[^/]+)/
    (?P<name>[^/]+)
    (/(?P<revision>[^/]+))?
    """, re.VERBOSE)

class Location(object):
    '''
    Encodes a location.

    Locations representations of URLs of the
    form {tag}://{org}/{course}/{category}/{name}[/{revision}]

    However, they can also be represented a dictionaries (specifying each component),
    tuples or list (specified in order), or as strings of the url
    '''
    def __init__(self, location):
        """
        Create a new location that is a clone of the specifed one.

        location - Can be any of the following types:
            string: should be of the form {tag}://{org}/{course}/{category}/{name}[/{revision}]
            list: should be of the form [tag, org, course, category, name, revision]
            dict: should be of the form {
                'tag': tag,
                'org': org,
                'course': course,
                'category': category,
                'name': name,
                'revision': revision,
            }
            Location: another Location object

        None of the components of a location may contain the '/' character
        """
        self.update(location)

    def update(self, location):
        """
        Update this instance with data from another Location object.

        location: can take the same forms as specified by `__init__`
        """
        self.tag = self.org = self.course = self.category = self.name = self.revision = None

        if isinstance(location, basestring):
            match = URL_RE.match(location)
            if match is None:
                raise InvalidLocationError(location)
            else:
                self.update(match.groupdict())
        elif isinstance(location, list):
            if len(location) not in (5, 6):
                raise InvalidLocationError(location)

            (self.tag, self.org, self.course, self.category, self.name) = location[0:5]
            self.revision = location[5] if len(location) == 6 else None
        elif isinstance(location, dict):
            try:
                self.tag = location['tag']
                self.org = location['org']
                self.course = location['course']
                self.category = location['category']
                self.name = location['name']
            except KeyError:
                raise InvalidLocationError(location)
            self.revision = location.get('revision')
        elif isinstance(location, Location):
            self.update(location.list())
        else:
            raise InvalidLocationError(location)

        for val in self.list():
            if val is not None and '/' in val:
                raise InvalidLocationError(location)

    def __str__(self):
        return self.url()

    def url(self):
        """
        Return a string containing the URL for this location
        """
        url = "{tag}://{org}/{course}/{category}/{name}".format(**self.dict())
        if self.revision:
            url += "/" + self.revision
        return url

    def list(self):
        """
        Return a list representing this location
        """
        return [self.tag, self.org, self.course, self.category, self.name, self.revision]

    def dict(self):
        """
        Return a dictionary representing this location
        """
        return {'tag': self.tag,
                'org': self.org,
                'course': self.course,
                'category': self.category,
                'name': self.name,
                'revision': self.revision}

class ModuleStore(object):
    """
    An abstract interface for a database backend that stores XModuleDescriptor instances
    """
    def get_item(self, location):
        """
        Returns an XModuleDescriptor instance for the item at location.
        If location.revision is None, returns the item with the most
        recent revision

        If any segment of the location is None except revision, raises
            keystore.exceptions.InsufficientSpecificationError
        If no object is found at that location, raises keystore.exceptions.ItemNotFoundError

        location: Something that can be passed to Location
        """
        raise NotImplementedError

    # TODO (cpennington): Replace with clone_item
    def create_item(self, location, editor):
        raise NotImplementedError

    def update_item(self, location, data):
        """
        Set the data in the item specified by the location to
        data

        location: Something that can be passed to Location
        data: A nested dictionary of problem data
        """
        raise NotImplementedError

    def update_children(self, location, children):
        """
        Set the children for the item specified by the location to
        data

        location: Something that can be passed to Location
        children: A list of child item identifiers
        """
        raise NotImplementedError
<|endoftext|>


<commit_before>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield, Mr. Donnelly,
Marcelo Almaguer for the Chell character model used in his own version of Portal called "Remember the Game"
maxiesnax for the Orange Portal Image:0 "http://orig05.deviantart.net/58ec/f/2012/361/2/5/portal___orange_portal_by_maxiesnax-d5pcfmj.png"
Blue Portal Image "http://vignette4.wikia.nocookie.net/kirby-bulborb/images/1/12/Blue_Portal.png/revision/latest?cb=20151004085207"
Special thanks to Valve for creating such an awesome game. Hopefully you can count to three.
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
plat=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

wall=RectangleAsset(1000,750, noline, wall)
exitbig=CircleAsset(70, thinline, plat)
exitsmall=CircleAsset(20, thinline, plat)
plat=RectangleAsset(250, 50, noline, plat)
doorline=LineAsset(0, 120, thinline)
goo=RectangleAsset(1000,100,noline,gooy)

cpx = 0
cpy = 0
cox = -100
coy = -100
cbx = -100
cby = -100

class Chell(Sprite):
    asset = ImageAsset("images/ChellSpriteSheet.png", Frame(0,0,205,361), 2, 'horizontal')
    def __init__(self, position):
        super().__init__(Chell.asset, position)
        self.visible = True
        self.x = 0
        self.y = 410
        self.vx = 0
        self.vy = 0
        self.jump1 = 0
        self.thing = 0
        self.click = 0
        self.mright = 0
        self.mleft = 0
        self.alt = 0
        self.image = 0
        self.scale = .25
        self.op = 0
        self.reset = 0
        PortalGame.listenKeyEvent("keydown", "d", self.rightOn)
        PortalGame.listenKeyEvent("keyup", "d", self.rightOff)
        PortalGame.listenKeyEvent("keydown", "a", self.leftOn)
        PortalGame.listenKeyEvent("keyup", "a", self.leftOff)
        PortalGame.listenMouseEvent("click", self.ClickOn)
        PortalGame.listenKeyEvent("keydown", "alt", self.altOn)
        PortalGame.listenKeyEvent("keyup", "alt", self.altOff)
        PortalGame.listenKeyEvent("keydown","r", self.resetOn)
        PortalGame.listenKeyEvent("keyup", "r", self.resetOff)
        PortalGame.listenKeyEvent("keydown", "space", self.jumpOn)
        PortalGame.listenKeyEvent("keyup", "w", self.jumpOff)

    def step(self):
        if self.click == 1 and self.alt != 1:
            global cox
            cox = cpx
            global coy
            coy = cpy
            self.click = 0

        if self.click == 1 and self.alt == 1:
            global cbx
            cbx = cpx
            global cby
            cby = cpy
            self.click = 0

        # player and orange portal detection
        if self.x<= cox-20 and self.x>=cox-30 and self.y <= coy-10 and self.y >= coy-40 and cby>=0 and cbx>=0:
            self.x = cbx - 10
            self.y = cby - 40

        # player and blue portal detection
        if self.x<=cbx-20 and self.x>=cbx-30 and self.y <= cby-10 and self.y >= cby-40 and coy>=0 and cox>=0:
            self.x = cox - 10
            self.y = coy - 40

        # move right and left
        if self.mright == 1:
            self.setImage(0)
            self.x += 1
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 1:
            self.setImage(1)
            self.x += -1
            self.y = self.y
        if self.mleft == 0:
            self.x = self.x
            self.y = self.y

        # basic jump
        if self.jump1 == 1:
            if self.thing == 1 and self.jump1 == 1:
                self.vy += .1
                self.y += self.vy
            else:
                self.thing = 1
                self.vy = -10

        # borders
        if self.y >= 560:
            self.x = 100
            self.y = 410
        if self.x <0:
            self.x = 0
        if self.x > 947:
            self.x = 947

        # reset
        if self.reset == 1:
            self.x = 0
            self.y = 410
            global cox
            cox = -100
            global coy
            coy = -100
            global cbx
            cbx = -100
            global cby
            cby = -100
            self.reset = 0

    def ClickOn(self,event):
        self.click = 1
        global cpx
        cpx = event.x
        global cpy
        cpy = event.y
    def jumpOn(self,event):
        self.jump1 = 1
    def jumpOff(self,event):
        self.jump1 = 1
    def resetOn(self,event):
        self.reset = 1
    def resetOff(self,event):
        self.reset = 0
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

class BluePortal(Sprite):
    asset = ImageAsset("images/Blue_Portal.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(BluePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = cbx - 50
        self.y = cby - 60

class OrangePortal(Sprite):
    asset = ImageAsset("images/portal___orange_portal_by_maxiesnax-d5pcfmj.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(OrangePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = cox - 50
        self.y = coy - 60

class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        txt_asset= TextAsset(text="A to Move Left, D to Move Right", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset1= TextAsset(text="Left Click to Place Orange Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset2= TextAsset(text="Alt + Left Click to Place Blue Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        resettxt= TextAsset(text="Press R to reset", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        Sprite(wall, (0,0))
        Sprite(goo, (0,650))
        Sprite(exitbig, (800,100))
        Sprite(exitsmall, (800, 100))
        Sprite(doorline, (800, 30))
        Sprite(plat, (0,500))
        Sprite(plat, (650, 150))
        Sprite(goo, (0,650))
        Sprite(txt_asset,(0,0))
        Sprite(txt_asset1, (0,10))
        Sprite(txt_asset2, (0,20))
        Sprite(resettxt,(0,30))
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))

    def step(self):
        for chell in self.getSpritesbyClass(Chell):
            chell.step()
        for blueportal in self.getSpritesbyClass(BluePortal):
            blueportal.step()
        for orangeportal in self.getSpritesbyClass(OrangePortal):
            orangeportal.step()

myapp = PortalGame(1000,750)
myapp.run()<commit_msg>Updated from Brython Server: 5/4/2016 1:25:21 PM<commit_after>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield, Mr. Donnelly,
Marcelo Almaguer for the Chell character model used in his own version of Portal called "Remember the Game"
maxiesnax for the Orange Portal Image:0 "http://orig05.deviantart.net/58ec/f/2012/361/2/5/portal___orange_portal_by_maxiesnax-d5pcfmj.png"
Blue Portal Image "http://vignette4.wikia.nocookie.net/kirby-bulborb/images/1/12/Blue_Portal.png/revision/latest?cb=20151004085207"
Special thanks to Valve for creating such an awesome game. Hopefully you can count to three.
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
plat=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

wall=RectangleAsset(1000,750, noline, wall)
exitbig=CircleAsset(70, thinline, plat)
exitsmall=CircleAsset(20, thinline, plat)
plat=RectangleAsset(250, 50, noline, plat)
doorline=LineAsset(0, 120, thinline)
goo=RectangleAsset(1000,100,noline,gooy)

cpx = 0
cpy = 0
cox = -100
coy = -100
cbx = -100
cby = -100

class Chell(Sprite):
    asset = ImageAsset("images/ChellSpriteSheet.png", Frame(0,0,205,361), 2, 'horizontal')
    def __init__(self, position):
        super().__init__(Chell.asset, position)
        self.visible = True
        self.x = 0
        self.y = 410
        self.vx = 0
        self.vy = 0
        self.jump1 = 0
        self.thing = 0
        self.click = 0
        self.mright = 0
        self.mleft = 0
        self.alt = 0
        self.image = 0
        self.scale = .25
        self.op = 0
        self.reset = 0
        PortalGame.listenKeyEvent("keydown", "d", self.rightOn)
        PortalGame.listenKeyEvent("keyup", "d", self.rightOff)
        PortalGame.listenKeyEvent("keydown", "a", self.leftOn)
        PortalGame.listenKeyEvent("keyup", "a", self.leftOff)
        PortalGame.listenMouseEvent("click", self.ClickOn)
        PortalGame.listenKeyEvent("keydown", "alt", self.altOn)
        PortalGame.listenKeyEvent("keyup", "alt", self.altOff)
        PortalGame.listenKeyEvent("keydown","r", self.resetOn)
        PortalGame.listenKeyEvent("keyup", "r", self.resetOff)
        PortalGame.listenKeyEvent("keydown", "space", self.jumpOn)
        PortalGame.listenKeyEvent("keyup", "w", self.jumpOff)

    def step(self):
        if self.click == 1 and self.alt != 1:
            global cox
            cox = cpx
            global coy
            coy = cpy
            self.click = 0

        if self.click == 1 and self.alt == 1:
            global cbx
            cbx = cpx
            global cby
            cby = cpy
            self.click = 0

        # player and orange portal detection
        if self.x<= cox-20 and self.x>=cox-30 and self.y <= coy-10 and self.y >= coy-40 and cby>=0 and cbx>=0:
            self.x = cbx - 10
            self.y = cby - 40

        # player and blue portal detection
        if self.x<=cbx-20 and self.x>=cbx-30 and self.y <= cby-10 and self.y >= cby-40 and coy>=0 and cox>=0:
            self.x = cox - 10
            self.y = coy - 40

        # move right and left
        if self.mright == 1:
            self.setImage(0)
            self.x += 1
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 1:
            self.setImage(1)
            self.x += -1
            self.y = self.y
        if self.mleft == 0:
            self.x = self.x
            self.y = self.y

        # basic jump
        if self.jump1 == 1:
            if self.thing == 1 and self.jump1 == 1:
                self.vy += .1
                self.y += self.vy
                if self.y < self.thing2:
                    self.vy -= .1
                    self.y -= self.vy
            else:
                self.thing2 = self.y
                self.thing = 1
                self.vy = -10

        # borders
        if self.y >= 560:
            self.x = 100
            self.y = 410
        if self.x <0:
            self.x = 0
        if self.x > 947:
            self.x = 947

        # reset
        if self.reset == 1:
            self.x = 0
            self.y = 410
            global cox
            cox = -100
            global coy
            coy = -100
            global cbx
            cbx = -100
            global cby
            cby = -100
            self.reset = 0

    def ClickOn(self,event):
        self.click = 1
        global cpx
        cpx = event.x
        global cpy
        cpy = event.y
    def jumpOn(self,event):
        self.jump1 = 1
    def jumpOff(self,event):
        self.jump1 = 1
    def resetOn(self,event):
        self.reset = 1
    def resetOff(self,event):
        self.reset = 0
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

class BluePortal(Sprite):
    asset = ImageAsset("images/Blue_Portal.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(BluePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = cbx - 50
        self.y = cby - 60

class OrangePortal(Sprite):
    asset = ImageAsset("images/portal___orange_portal_by_maxiesnax-d5pcfmj.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(OrangePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = cox - 50
        self.y = coy - 60

class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        txt_asset= TextAsset(text="A to Move Left, D to Move Right", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset1= TextAsset(text="Left Click to Place Orange Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset2= TextAsset(text="Alt + Left Click to Place Blue Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        resettxt= TextAsset(text="Press R to reset", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        Sprite(wall, (0,0))
        Sprite(goo, (0,650))
        Sprite(exitbig, (800,100))
        Sprite(exitsmall, (800, 100))
        Sprite(doorline, (800, 30))
        Sprite(plat, (0,500))
        Sprite(plat, (650, 150))
        Sprite(goo, (0,650))
        Sprite(txt_asset,(0,0))
        Sprite(txt_asset1, (0,10))
        Sprite(txt_asset2, (0,20))
        Sprite(resettxt,(0,30))
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))

    def step(self):
        for chell in self.getSpritesbyClass(Chell):
            chell.step()
        for blueportal in self.getSpritesbyClass(BluePortal):
            blueportal.step()
        for orangeportal in self.getSpritesbyClass(OrangePortal):
            orangeportal.step()

myapp = PortalGame(1000,750)
myapp.run()<|endoftext|>


<commit_before>"""Constants."""

from . import HDLValue
import math

class HDLConstant(HDLValue):
    """Abstract class from which other constants inherit."""

    def __init__(self, **kwargs):
        """Initialize."""
        # save kwargs
        self.optional_args = kwargs

class HDLStringConstant(HDLConstant):
    """String constant value."""

    def __init__(self, value, **kwargs):
        """Initialize."""
        super().__init__(**kwargs)
        self.value = str(value)

    def dumps(self):
        """Representation."""
        return self.value

class HDLIntegerConstant(HDLConstant):
    """A constant value."""

    def __init__(self, value, size=None, **kwargs):
        """Initialize.

        Args
        ----
        value: int
            A constant value
        """
        super().__init__(**kwargs)

        if size is not None:
            # check size
            if self.value_fits_width(size, value) is True:
                self.size = size
            else:
                raise ValueError("given value does not fit in given size")
        else:
            # attribute size
            self.size = self.minimum_value_size(value)

        self.value = value

    def evaluate(self, **kwargs):
        """Evaluate."""
        return self.value

    def __repr__(self):
        """Get representation."""
        return str(self.value)

    def dumps(self):
        """Alias for __repr__."""
        return self.__repr__()

    def __sub__(self, other):
        """Subtract two constants, return a new one.

        Args
        ----
        other: int or HDLIntegerConstant
           Other value
        """
        if isinstance(other, (int, HDLIntegerConstant)):
            return HDLIntegerConstant(self.value - int(other))
        else:
            raise TypeError(
                "can only subtract int and " "HDLIntegerConstant types"
            )

    def __abs__(self):
        """Return absolute value."""
        if self.value < 0:
            return HDLIntegerConstant(-self.value)
        else:
            return HDLIntegerConstant(self.value)

    def __int__(self):
        """Convert to integer."""
        return self.value

    def __add__(self, other):
        """Add two constants, return a new one.

        Args
        ----
        other: int, HDLIntegerConstant
           Other value to add
        """
        if isinstance(other, (int, HDLIntegerConstant)):
            return HDLIntegerConstant(self.value + int(other))
        else:
            raise TypeError("can only add int and HDLIntegerConstant types")

    def __radd__(self, other):
        """Reverse add. Uses __add__."""
        return self.__add__(other)

    def __rsub__(self, other):
        """Reverse sub."""
        return self.__sub__(other)

    def __mul__(self, other):
        """Multiply two constants."""
        if isinstance(other, (int, HDLIntegerConstant)):
            return HDLIntegerConstant(self.value * int(other))
        else:
            raise TypeError(
                "can only multiply int and" " HDLIntegerConstant types"
            )

    def __rmul__(self, other):
        """Reverse mult."""
        return self.__mul__(other)

    def __eq__(self, other):
        """Equality test.

        Args
        ----
        other: int, HDLIntegerConstant
           Value to compare against
        """
        if isinstance(other, int):
            return bool(self.value == other)
        elif isinstance(other, HDLIntegerConstant):
            return bool(self.value == other.value)
        else:
            return False

    def __lt__(self, other):
        """Les than."""
        if isinstance(other, int):
            return bool(self.value < other)
        elif isinstance(other, HDLIntegerConstant):
            return bool(self.value < other.value)
        else:
            raise TypeError

    def __gt__(self, other):
        """Greater than."""
        if isinstance(other, int):
            return bool(self.value > other)
        elif isinstance(other, HDLIntegerConstant):
            return bool(self.value > other.value)
        else:
            raise TypeError

    @staticmethod
    def value_fits_width(width, value):
        """Check if a value fits in a vector.

        Args
        ----
        width: int
           Bit Vector width
        value: int
           The value
        """
        return bool(value <= (int(math.pow(2, width)) - 1))

    @staticmethod
    def minimum_value_size(value):
        """Get minimum number of bits needed to store value."""
        if value == 0:
            return 1
        else:
            return int(math.ceil(math.log2(float(abs(value))))) + 1

    def __len__(self):
        """Get size."""
        return self.size
<commit_msg>Barf on non integer<commit_after>"""Constants."""

from . import HDLValue
import math

class HDLConstant(HDLValue):
    """Abstract class from which other constants inherit."""

    def __init__(self, **kwargs):
        """Initialize."""
        # save kwargs
        self.optional_args = kwargs

class HDLStringConstant(HDLConstant):
    """String constant value."""

    def __init__(self, value, **kwargs):
        """Initialize."""
        super().__init__(**kwargs)
        self.value = str(value)

    def dumps(self):
        """Representation."""
        return self.value

class HDLIntegerConstant(HDLConstant):
    """A constant value."""

    def __init__(self, value, size=None, **kwargs):
        """Initialize.

        Args
        ----
        value: int
            A constant value
        """
        super().__init__(**kwargs)

        if not isinstance(value, int):
            raise TypeError("value must be an integer")

        if size is not None:
            # check size
            if self.value_fits_width(size, value) is True:
                self.size = size
            else:
                raise ValueError("given value does not fit in given size")
        else:
            # attribute size
            self.size = self.minimum_value_size(value)

        self.value = value

    def evaluate(self, **kwargs):
        """Evaluate."""
        return self.value

    def __repr__(self):
        """Get representation."""
        return str(self.value)

    def dumps(self):
        """Alias for __repr__."""
        return self.__repr__()

    def __sub__(self, other):
        """Subtract two constants, return a new one.

        Args
        ----
        other: int or HDLIntegerConstant
           Other value
        """
        if isinstance(other, (int, HDLIntegerConstant)):
            return HDLIntegerConstant(self.value - int(other))
        else:
            raise TypeError(
                "can only subtract int and " "HDLIntegerConstant types"
            )

    def __abs__(self):
        """Return absolute value."""
        if self.value < 0:
            return HDLIntegerConstant(-self.value)
        else:
            return HDLIntegerConstant(self.value)

    def __int__(self):
        """Convert to integer."""
        return self.value

    def __add__(self, other):
        """Add two constants, return a new one.

        Args
        ----
        other: int, HDLIntegerConstant
           Other value to add
        """
        if isinstance(other, (int, HDLIntegerConstant)):
            return HDLIntegerConstant(self.value + int(other))
        else:
            raise TypeError("can only add int and HDLIntegerConstant types")

    def __radd__(self, other):
        """Reverse add. Uses __add__."""
        return self.__add__(other)

    def __rsub__(self, other):
        """Reverse sub."""
        return self.__sub__(other)

    def __mul__(self, other):
        """Multiply two constants."""
        if isinstance(other, (int, HDLIntegerConstant)):
            return HDLIntegerConstant(self.value * int(other))
        else:
            raise TypeError(
                "can only multiply int and" " HDLIntegerConstant types"
            )

    def __rmul__(self, other):
        """Reverse mult."""
        return self.__mul__(other)

    def __eq__(self, other):
        """Equality test.

        Args
        ----
        other: int, HDLIntegerConstant
           Value to compare against
        """
        if isinstance(other, int):
            return bool(self.value == other)
        elif isinstance(other, HDLIntegerConstant):
            return bool(self.value == other.value)
        else:
            return False

    def __lt__(self, other):
        """Les than."""
        if isinstance(other, int):
            return bool(self.value < other)
        elif isinstance(other, HDLIntegerConstant):
            return bool(self.value < other.value)
        else:
            raise TypeError

    def __gt__(self, other):
        """Greater than."""
        if isinstance(other, int):
            return bool(self.value > other)
        elif isinstance(other, HDLIntegerConstant):
            return bool(self.value > other.value)
        else:
            raise TypeError

    @staticmethod
    def value_fits_width(width, value):
        """Check if a value fits in a vector.

        Args
        ----
        width: int
           Bit Vector width
        value: int
           The value
        """
        return bool(value <= (int(math.pow(2, width)) - 1))

    @staticmethod
    def minimum_value_size(value):
        """Get minimum number of bits needed to store value."""
        if value == 0:
            return 1
        else:
            return int(math.ceil(math.log2(float(abs(value))))) + 1

    def __len__(self):
        """Get size."""
        return self.size
<|endoftext|>


<commit_before># Copyright (C) 2016 Vasily Ryabov
# Copyright (C) 2016 airelil
# Copyright (C) 2010 Mark Mc Mahon
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
Wrap various UIA windows controls
"""
import pywinauto.six as six
import pywinauto.uia_defines as uia_defs
from . import UIAWrapper
from ..uia_defines import IUIA

#====================================================================
class ButtonWrapper(UIAWrapper.UIAWrapper):
    """Wrap a UIA-compatible Button, CheckBox or RadioButton control"""

    control_types = [
        IUIA().UIA_dll.UIA_ButtonControlTypeId,
        IUIA().UIA_dll.UIA_CheckBoxControlTypeId,
        IUIA().UIA_dll.UIA_RadioButtonControlTypeId
        ]

    #-----------------------------------------------------------
    def __init__(self, hwnd):
        """Initialize the control"""
        super(ButtonWrapper, self).__init__(hwnd)

    #-----------------------------------------------------------
    def toggle(self):
        """
        An interface to Toggle method of the Toggle control pattern.

        Control supporting the Toggle pattern cycles through its
        toggle states in the following order:
        ToggleState_On, ToggleState_Off and,
        if supported, ToggleState_Indeterminate

        Usually applied for the check box control.

        The radio button control does not implement IToggleProvider,
        because it is not capable of cycling through its valid states.
        Toggle a state of a check box control. (Use 'select' method instead)
        Notice, a radio button control isn't supported by UIA.
        https://msdn.microsoft.com/en-us/library/windows/desktop/ee671290(v=vs.85).aspx
        """
        elem = self.element_info.element
        iface = uia_defs.get_elem_interface(elem, "Toggle")
        iface.Toggle()

        # Return itself so that action can be chained
        return self

    #-----------------------------------------------------------
    def get_toggle_state(self):
        """
        Get a toggle state of a check box control.

        The toggle state is represented by an integer
        0 - unchecked
        1 - checked
        2 - indeterminate

        The following constants are defined in the uia_defines module
        toggle_state_off = 0
        toggle_state_on = 1
        toggle_state_inderteminate = 2
        """
        elem = self.element_info.element
        iface = uia_defs.get_elem_interface(elem, "Toggle")
        return iface.CurrentToggleState

    #-----------------------------------------------------------
    def is_dialog(self):
        """Buttons are never dialogs so return False"""
        return False

    #-----------------------------------------------------------
    def click(self):
        """Click the Button control by using Invoke pattern"""
        self.invoke()

        # Return itself so that action can be chained
        return self

    #-----------------------------------------------------------
    def select(self):
        """
        An interface to Select method of the SelectionItem control pattern.

        Usually applied for a radio button control
        """

        elem = self.element_info.element
        iface = uia_defs.get_elem_interface(elem, "SelectionItem")
        iface.Select()

        # Return itself so that action can be chained
        return self

    #-----------------------------------------------------------
    def is_selected(self):
        """
        An interface to CurrentIsSelected method of the SelectionItem control pattern.

        Usually applied for a radio button control
        """

        elem = self.element_info.element
        iface = uia_defs.get_elem_interface(elem, "SelectionItem")
        return iface.CurrentIsSelected

#====================================================================
class ComboBoxWrapper(UIAWrapper.UIAWrapper):
    """Wrap a UIA CoboBox control"""

    control_types = [
        IUIA().UIA_dll.UIA_ComboBoxControlTypeId
        ]

    #-----------------------------------------------------------
    def __init__(self, hwnd):
        """Initialize the control"""
        super(ComboBoxWrapper, self).__init__(hwnd)

    #-----------------------------------------------------------
    def texts(self):
        """Return the text of the items in the combobox"""

        texts = []
        # ComboBox has to be expanded to populate a list of its children items
        try:
            self.expand()
            for c in self.children():
                texts.append(c.window_text())
        finally:
            # Make sure we collapse back in any case
            self.collapse()
        return texts

    def select(self, item):
        """
        Select the ComboBox item

        item can be either a 0 based index of the item to select
        or it can be the string that you want to select
        """

        item_index = 0
        item_name = None
        if isinstance(item, six.integer_types):
            item_index = item
        elif isinstance(item, six.string_types):
            item_name = item
        else:
            err_msg = "unsupported {0} for item {1}".format(type(item), item)
            raise ValueError(err_msg)

        # ComboBox has to be expanded to populate a list of its children items
        self.expand()
        try:
            self.select_by_name_or_by_idx(item_name, item_index)
        # TODO: do we need to handle except ValueError for a wrong name/index ?
        #except ValueError:
        #    raise  # re-raise the last exception
        finally:
            # Make sure we collapse back in any case
            self.collapse()
        return self

    #-----------------------------------------------------------
    # TODO: add selected_texts for a combobox with a multi-select support
    def selected_text(self):
        """
        Return the selected text or None

        Notice, that in case of multi-select it will be only the text from
        a first selected item
        """
        selection = self.get_selection()
        if selection:
            return selection[0].name
        else:
            return None

    #-----------------------------------------------------------
    # TODO: add selected_indices for a combobox with multi-select support
    def selected_index(self):
        """Return the selected index"""

        # Go through all children and look for an index
        # of an item with the same text.
        # Maybe there is another and more efficient way to do it
        selection = self.get_selection()
        if selection:
            for i, c in enumerate(self.children()):
                if c.window_text() == selection[0].name:
                    return i
        return None

    #-----------------------------------------------------------
    def item_count(self):
        """
        Return the number of items in the combobox

        The interface is kept mostly for a backward compatibility with
        the native ComboBox interface
        """
        return self.control_count()
<commit_msg>uia_controls: use the relative import instead of absolute<commit_after># Copyright (C) 2016 Vasily Ryabov
# Copyright (C) 2016 airelil
# Copyright (C) 2010 Mark Mc Mahon
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
Wrap various UIA windows controls
"""
import pywinauto.six as six
from .. import uia_defines as uia_defs
from . import UIAWrapper
from ..uia_defines import IUIA

#====================================================================
class ButtonWrapper(UIAWrapper.UIAWrapper):
    """Wrap a UIA-compatible Button, CheckBox or RadioButton control"""

    control_types = [
        IUIA().UIA_dll.UIA_ButtonControlTypeId,
        IUIA().UIA_dll.UIA_CheckBoxControlTypeId,
        IUIA().UIA_dll.UIA_RadioButtonControlTypeId
        ]

    #-----------------------------------------------------------
    def __init__(self, hwnd):
        """Initialize the control"""
        super(ButtonWrapper, self).__init__(hwnd)

    #-----------------------------------------------------------
    def toggle(self):
        """
        An interface to Toggle method of the Toggle control pattern.

        Control supporting the Toggle pattern cycles through its
        toggle states in the following order:
        ToggleState_On, ToggleState_Off and,
        if supported, ToggleState_Indeterminate

        Usually applied for the check box control.

        The radio button control does not implement IToggleProvider,
        because it is not capable of cycling through its valid states.
        Toggle a state of a check box control. (Use 'select' method instead)
        Notice, a radio button control isn't supported by UIA.
        https://msdn.microsoft.com/en-us/library/windows/desktop/ee671290(v=vs.85).aspx
        """
        elem = self.element_info.element
        iface = uia_defs.get_elem_interface(elem, "Toggle")
        iface.Toggle()

        # Return itself so that action can be chained
        return self

    #-----------------------------------------------------------
    def get_toggle_state(self):
        """
        Get a toggle state of a check box control.

        The toggle state is represented by an integer
        0 - unchecked
        1 - checked
        2 - indeterminate

        The following constants are defined in the uia_defines module
        toggle_state_off = 0
        toggle_state_on = 1
        toggle_state_inderteminate = 2
        """
        elem = self.element_info.element
        iface = uia_defs.get_elem_interface(elem, "Toggle")
        return iface.CurrentToggleState

    #-----------------------------------------------------------
    def is_dialog(self):
        """Buttons are never dialogs so return False"""
        return False

    #-----------------------------------------------------------
    def click(self):
        """Click the Button control by using Invoke pattern"""
        self.invoke()

        # Return itself so that action can be chained
        return self

    #-----------------------------------------------------------
    def select(self):
        """
        An interface to Select method of the SelectionItem control pattern.

        Usually applied for a radio button control
        """

        elem = self.element_info.element
        iface = uia_defs.get_elem_interface(elem, "SelectionItem")
        iface.Select()

        # Return itself so that action can be chained
        return self

    #-----------------------------------------------------------
    def is_selected(self):
        """
        An interface to CurrentIsSelected method of the SelectionItem control pattern.

        Usually applied for a radio button control
        """

        elem = self.element_info.element
        iface = uia_defs.get_elem_interface(elem, "SelectionItem")
        return iface.CurrentIsSelected

#====================================================================
class ComboBoxWrapper(UIAWrapper.UIAWrapper):
    """Wrap a UIA CoboBox control"""

    control_types = [
        IUIA().UIA_dll.UIA_ComboBoxControlTypeId
        ]

    #-----------------------------------------------------------
    def __init__(self, hwnd):
        """Initialize the control"""
        super(ComboBoxWrapper, self).__init__(hwnd)

    #-----------------------------------------------------------
    def texts(self):
        """Return the text of the items in the combobox"""

        texts = []
        # ComboBox has to be expanded to populate a list of its children items
        try:
            self.expand()
            for c in self.children():
                texts.append(c.window_text())
        finally:
            # Make sure we collapse back in any case
            self.collapse()
        return texts

    def select(self, item):
        """
        Select the ComboBox item

        item can be either a 0 based index of the item to select
        or it can be the string that you want to select
        """

        item_index = 0
        item_name = None
        if isinstance(item, six.integer_types):
            item_index = item
        elif isinstance(item, six.string_types):
            item_name = item
        else:
            err_msg = "unsupported {0} for item {1}".format(type(item), item)
            raise ValueError(err_msg)

        # ComboBox has to be expanded to populate a list of its children items
        self.expand()
        try:
            self.select_by_name_or_by_idx(item_name, item_index)
        # TODO: do we need to handle except ValueError for a wrong name/index ?
        #except ValueError:
        #    raise  # re-raise the last exception
        finally:
            # Make sure we collapse back in any case
            self.collapse()
        return self

    #-----------------------------------------------------------
    # TODO: add selected_texts for a combobox with a multi-select support
    def selected_text(self):
        """
        Return the selected text or None

        Notice, that in case of multi-select it will be only the text from
        a first selected item
        """
        selection = self.get_selection()
        if selection:
            return selection[0].name
        else:
            return None

    #-----------------------------------------------------------
    # TODO: add selected_indices for a combobox with multi-select support
    def selected_index(self):
        """Return the selected index"""

        # Go through all children and look for an index
        # of an item with the same text.
        # Maybe there is another and more efficient way to do it
        selection = self.get_selection()
        if selection:
            for i, c in enumerate(self.children()):
                if c.window_text() == selection[0].name:
                    return i
        return None

    #-----------------------------------------------------------
    def item_count(self):
        """
        Return the number of items in the combobox

        The interface is kept mostly for a backward compatibility with
        the native ComboBox interface
        """
        return self.control_count()
<|endoftext|>


<commit_before>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield, Mr. Donnelly,
Marcelo Almaguer for the Chell character model used in his own version of Portal called "Remember the Game"
maxiesnax for the Orange Portal Image:0 "http://orig05.deviantart.net/58ec/f/2012/361/2/5/portal___orange_portal_by_maxiesnax-d5pcfmj.png"
Blue Portal Image "http://vignette4.wikia.nocookie.net/kirby-bulborb/images/1/12/Blue_Portal.png/revision/latest?cb=20151004085207"
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
plat=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickishline= LineStyle(2.5, black)
noline=LineStyle(0, black)
portalline=LineStyle(1, blue)
portalline2=LineStyle(1, orange)

wall=RectangleAsset(500,500, noline, wall)
blueportal=EllipseAsset(27, 60, noline, blue)
orangeportal=EllipseAsset(27, 60, noline, orange)
innerportal=EllipseAsset(24, 57, noline, white)
exit=CircleAsset(70, thinline, plat)
exit2=CircleAsset(20, thinline, plat)
plat=RectangleAsset(250, 50, noline, plat)
doorline=LineAsset(0, 120, thinline)
goo=PolygonAsset([(0,500),(800,500),(800,600,),(0,600)],noline,gooy)

global.cpx = 0
global.cpy = 0

class Chell(Sprite):
    asset = ImageAsset("images/ChellSpriteSheet.png", Frame(0,0,205,361), 2, 'horizontal')
    def __init__(self, position):
        super().__init__(Chell.asset, position)
        self.visible = True
        self.x = 250
        self.y = 250
        self.click = 0
        self.mright = 0
        self.mleft = 0
        self.alt = 0
        self.image = 0
        self.scale = .25
        self.op = 0
        PortalGame.listenKeyEvent("keydown", "d", self.rightOn)
        PortalGame.listenKeyEvent("keyup", "d", self.rightOff)
        PortalGame.listenKeyEvent("keydown", "a", self.leftOn)
        PortalGame.listenKeyEvent("keyup", "a", self.leftOff)
        PortalGame.listenMouseEvent("click", self.ClickOn)
        PortalGame.listenKeyEvent("keydown", "alt", self.altOn)
        PortalGame.listenKeyEvent("keyup", "alt", self.altOff)
        self.oportal = None
        self.bportal = None
        self.cox = 0
        self.coy = 0
        self.cbx = 0
        self.cby = 0

    def step(self):
        if self.click == 1 and self.alt != 1:
            if self.oportal:
                self.x1 = self.x
                self.y1 = self.y
                self.oportal.destroy()
                self.oportal = OrangePortal((cpx-50,cpy-70))
                self.cox = cpx
                self.coy = cpy
                self.click = 0
            else:
                self.x1 = self.x
                self.y1 = self.y
                self.oportal = OrangePortal((cpx-50,cpy-70))
                self.cox = cpx
                self.coy = cpy
                self.click = 0

        if self.click == 1 and self.alt == 1:
            if self.bportal:
                self.bportal.destroy()
                self.bportal = BluePortal((cpx-50,cpy-70))
                self.cbx = cpx
                self.cby = cpy
                self.click = 0

            else:
                self.bportal = BluePortal((cpx-50,cpy-70))
                self.cbx = cpx
                self.cby = cpy
                self.click = 0

        if self.x<=self.cox-20 and self.x>=self.cox-30 and self.bportal and self.y <=self.coy-10 and self.y>=self.coy-40:
            self.x = self.cbx - 10
            self.y = self.cby - 40

        if self.x<=self.cbx-20 and self.x>=self.cbx-30 and self.bportal and self.y <=self.cby-10 and self.y>=self.cby-40:
            self.x = self.cox - 10
            self.y = self.coy - 40

        if self.mright == 1:
            self.setImage(0)
            self.x += .75
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 1:
            self.setImage(1)
            self.x += -.75
            self.y = self.y
        if self.mleft == 0:
            self.x = self.x
            self.y = self.y

    def ClickOn(self,event):
        self.click = 1
        cpx = event.x
        cpy = event.y
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

class BluePortal(Sprite):
    asset = ImageAsset("images/Blue_Portal.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(BluePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = self.x
        self.y = self.y

class OrangePortal(Sprite):
    asset = ImageAsset("images/portal___orange_portal_by_maxiesnax-d5pcfmj.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(OrangePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = self.x
        self.y = self.y

class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        Sprite(wall, (400,20))
        Sprite(wall, (100,20))
        Sprite(exit, (800,100))
        Sprite(exit2, (800, 100))
        Sprite(doorline, (800, 30))
        Sprite(plat, (100,400))
        Sprite(plat, (650, 150))
        Sprite(goo, (100,0))
        Chell((0,0))

    def step(self):
        for chell in self.getSpritesbyClass(Chell):
            chell.step()

myapp = PortalGame(1000,750)
myapp.run()<commit_msg>Updated from Brython Server: 4/29/2016 2:23:48 PM<commit_after>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield, Mr. Donnelly,
Marcelo Almaguer for the Chell character model used in his own version of Portal called "Remember the Game"
maxiesnax for the Orange Portal Image:0 "http://orig05.deviantart.net/58ec/f/2012/361/2/5/portal___orange_portal_by_maxiesnax-d5pcfmj.png"
Blue Portal Image "http://vignette4.wikia.nocookie.net/kirby-bulborb/images/1/12/Blue_Portal.png/revision/latest?cb=20151004085207"
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
plat=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickishline= LineStyle(2.5, black)
noline=LineStyle(0, black)
portalline=LineStyle(1, blue)
portalline2=LineStyle(1, orange)

wall=RectangleAsset(500,500, noline, wall)
blueportal=EllipseAsset(27, 60, noline, blue)
orangeportal=EllipseAsset(27, 60, noline, orange)
innerportal=EllipseAsset(24, 57, noline, white)
exit=CircleAsset(70, thinline, plat)
exit2=CircleAsset(20, thinline, plat)
plat=RectangleAsset(250, 50, noline, plat)
doorline=LineAsset(0, 120, thinline)
goo=PolygonAsset([(0,500),(800,500),(800,600,),(0,600)],noline,gooy)

global cpx = 0
global cpy = 0

class Chell(Sprite):
    asset = ImageAsset("images/ChellSpriteSheet.png", Frame(0,0,205,361), 2, 'horizontal')
    def __init__(self, position):
        super().__init__(Chell.asset, position)
        self.visible = True
        self.x = 250
        self.y = 250
        self.click = 0
        self.mright = 0
        self.mleft = 0
        self.alt = 0
        self.image = 0
        self.scale = .25
        self.op = 0
        PortalGame.listenKeyEvent("keydown", "d", self.rightOn)
        PortalGame.listenKeyEvent("keyup", "d", self.rightOff)
        PortalGame.listenKeyEvent("keydown", "a", self.leftOn)
        PortalGame.listenKeyEvent("keyup", "a", self.leftOff)
        PortalGame.listenMouseEvent("click", self.ClickOn)
        PortalGame.listenKeyEvent("keydown", "alt", self.altOn)
        PortalGame.listenKeyEvent("keyup", "alt", self.altOff)
        self.oportal = None
        self.bportal = None
        self.cox = 0
        self.coy = 0
        self.cbx = 0
        self.cby = 0

    def step(self):
        if self.click == 1 and self.alt != 1:
            if self.oportal:
                self.x1 = self.x
                self.y1 = self.y
                self.oportal.destroy()
                self.oportal = OrangePortal((cpx-50,cpy-70))
                self.cox = cpx
                self.coy = cpy
                self.click = 0
            else:
                self.x1 = self.x
                self.y1 = self.y
                self.oportal = OrangePortal((cpx-50,cpy-70))
                self.cox = cpx
                self.coy = cpy
                self.click = 0

        if self.click == 1 and self.alt == 1:
            if self.bportal:
                self.bportal.destroy()
                self.bportal = BluePortal((cpx-50,cpy-70))
                self.cbx = cpx
                self.cby = cpy
                self.click = 0

            else:
                self.bportal = BluePortal((cpx-50,cpy-70))
                self.cbx = cpx
                self.cby = cpy
                self.click = 0

        if self.x<=self.cox-20 and self.x>=self.cox-30 and self.bportal and self.y <=self.coy-10 and self.y>=self.coy-40:
            self.x = self.cbx - 10
            self.y = self.cby - 40

        if self.x<=self.cbx-20 and self.x>=self.cbx-30 and self.bportal and self.y <=self.cby-10 and self.y>=self.cby-40:
            self.x = self.cox - 10
            self.y = self.coy - 40

        if self.mright == 1:
            self.setImage(0)
            self.x += .75
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 1:
            self.setImage(1)
            self.x += -.75
            self.y = self.y
        if self.mleft == 0:
            self.x = self.x
            self.y = self.y

    def ClickOn(self,event):
        self.click = 1
        cpx = event.x
        cpy = event.y
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

class BluePortal(Sprite):
    asset = ImageAsset("images/Blue_Portal.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(BluePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = self.x
        self.y = self.y

class OrangePortal(Sprite):
    asset = ImageAsset("images/portal___orange_portal_by_maxiesnax-d5pcfmj.png", Frame(25,10,350,475), 1, 'vertical')
    def __init__(self, position):
        super().__init__(OrangePortal.asset, position)
        self.scale = .25
        self.center = (0,0)

    def step(self):
        self.x = self.x
        self.y = self.y

class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        Sprite(wall, (400,20))
        Sprite(wall, (100,20))
        Sprite(exit, (800,100))
        Sprite(exit2, (800, 100))
        Sprite(doorline, (800, 30))
        Sprite(plat, (100,400))
        Sprite(plat, (650, 150))
        Sprite(goo, (100,0))
        Chell((0,0))

    def step(self):
        for chell in self.getSpritesbyClass(Chell):
            chell.step()

myapp = PortalGame(1000,750)
myapp.run()<|endoftext|>


<commit_before>import unittest
import numpy
import matplotlib
import axelrod

class TestResultSet(unittest.TestCase):

    def test_init(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        expected_results = [
            [[0, 0, 0, 0], [0, 0, 0, 0]],
            [[0, 0, 0, 0], [0, 0, 0, 0]]
        ]
        self.assertEquals(rs.nplayers, 2)
        self.assertEquals(rs.players, players)
        self.assertEquals(rs.turns, 10)
        self.assertEquals(rs.repetitions, 4)
        self.assertEquals(rs.results, expected_results)
        self.assertFalse(rs.output_initialised)

    def test_generate_scores(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        expected_results = numpy.array([[0, 0, 0, 0], [0, 0, 0, 0]])
        self.assertTrue(numpy.array_equal(rs.generate_scores(), expected_results))

    def test_generate_ranking(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        scores = rs.generate_scores()
        expected_results = [0, 1]
        self.assertEquals(rs.generate_ranking(scores), expected_results)

    def test_generate_ranked_names(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        scores = rs.generate_scores()
        rankings = rs.generate_ranking(scores)
        expected_results = ['Player', 'Player']
        self.assertEquals(rs.generate_ranked_names(rankings), expected_results)

    def test_init_output(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        rs.init_output()
        expected_scores = numpy.array([[0, 0, 0, 0], [0, 0, 0, 0]])
        expected_ranking = [0, 1]
        expected_names = ['Player', 'Player']
        self.assertTrue(numpy.array_equal(rs.scores, expected_scores))
        self.assertEquals(rs.ranking, expected_ranking)
        self.assertEquals(rs.ranked_names, expected_names)

    def test_csv(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        expected_results = 'Player, Player\n0, 0\n0, 0\n0, 0\n0, 0\n'
        self.assertEquals(rs.csv(), expected_results)
<commit_msg>removes matplotlib import statement<commit_after>import unittest
import numpy
import axelrod

class TestResultSet(unittest.TestCase):

    def test_init(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        expected_results = [
            [[0, 0, 0, 0], [0, 0, 0, 0]],
            [[0, 0, 0, 0], [0, 0, 0, 0]]
        ]
        self.assertEquals(rs.nplayers, 2)
        self.assertEquals(rs.players, players)
        self.assertEquals(rs.turns, 10)
        self.assertEquals(rs.repetitions, 4)
        self.assertEquals(rs.results, expected_results)
        self.assertFalse(rs.output_initialised)

    def test_generate_scores(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        expected_results = numpy.array([[0, 0, 0, 0], [0, 0, 0, 0]])
        self.assertTrue(numpy.array_equal(rs.generate_scores(), expected_results))

    def test_generate_ranking(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        scores = rs.generate_scores()
        expected_results = [0, 1]
        self.assertEquals(rs.generate_ranking(scores), expected_results)

    def test_generate_ranked_names(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        scores = rs.generate_scores()
        rankings = rs.generate_ranking(scores)
        expected_results = ['Player', 'Player']
        self.assertEquals(rs.generate_ranked_names(rankings), expected_results)

    def test_init_output(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        rs.init_output()
        expected_scores = numpy.array([[0, 0, 0, 0], [0, 0, 0, 0]])
        expected_ranking = [0, 1]
        expected_names = ['Player', 'Player']
        self.assertTrue(numpy.array_equal(rs.scores, expected_scores))
        self.assertEquals(rs.ranking, expected_ranking)
        self.assertEquals(rs.ranked_names, expected_names)

    def test_csv(self):
        players = (axelrod.Player(), axelrod.Player())
        rs = axelrod.ResultSet(players, 10, 4)
        expected_results = 'Player, Player\n0, 0\n0, 0\n0, 0\n0, 0\n'
        self.assertEquals(rs.csv(), expected_results)
<|endoftext|>


<commit_before># This file is heavily inspired from the django admin autodiscover

__version_info__ = {
    'major': 1,
    'minor': 1,
    'micro': 5,
    'releaselevel': 'final',
    'serial': 0
}

def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present.

    This forces an import on them to register any admin bits they may want.
    """
    import copy
    from django.conf import settings
    from importlib import import_module
    from django.utils.module_loading import module_has_submodule
    from health_check.plugins import plugin_dir

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = copy.copy(plugin_dir._registry)
            import_module('%s.plugin_health_check' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            plugin_dir._registry = before_import_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'plugin_health_check'):
                raise

def get_version(short=False):
    assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
    vers = ["%(major)i.%(minor)i" % __version_info__, ]
    if __version_info__['micro']:
        vers.append(".%(micro)i" % __version_info__)
    if __version_info__['releaselevel'] != 'final' and not short:
        vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
    return ''.join(vers)

__version__ = get_version()
<commit_msg>Bump version number<commit_after># This file is heavily inspired from the django admin autodiscover

__version_info__ = {
    'major': 1,
    'minor': 1,
    'micro': 6,
    'releaselevel': 'final',
    'serial': 0
}

def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present.

    This forces an import on them to register any admin bits they may want.
    """
    import copy
    from django.conf import settings
    from importlib import import_module
    from django.utils.module_loading import module_has_submodule
    from health_check.plugins import plugin_dir

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = copy.copy(plugin_dir._registry)
            import_module('%s.plugin_health_check' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            plugin_dir._registry = before_import_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'plugin_health_check'):
                raise

def get_version(short=False):
    assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
    vers = ["%(major)i.%(minor)i" % __version_info__, ]
    if __version_info__['micro']:
        vers.append(".%(micro)i" % __version_info__)
    if __version_info__['releaselevel'] != 'final' and not short:
        vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
    return ''.join(vers)

__version__ = get_version()
<|endoftext|>