<commit_before>import os

from pulsar import Setting

import lux
from lux.core.commands import CommandError

class Command(lux.Command):
    help = 'Alembic commands for migrating database.'

    commands = ['auto', 'branches', 'current', 'downgrade', 'heads', 'history',
                'init', 'merge', 'revision', 'show', 'stamp', 'upgrade']

    option_list = (
        Setting('command', nargs='*', default=None, desc='Alembic command'),
        Setting('branch', ('-b', '--branch'), default=None, nargs='?',
                desc='Branch label for auto, revision and merge command',
                meta='LABEL'),
        Setting('list', ('-l', '--list'), default=None, action='store_true',
                desc='List available Alembic commands'),
        Setting('msg', ('-m', '--message'), nargs='?', default=None,
                desc='Message for auto, revision and merge command'),
    )

    def run(self, opt):
        '''
        Run obvious commands and validate more complex.
        '''
        # alembic package is required to run any migration related command
        try:
            import alembic  # noqa
        except ImportError:  # pragma nocover
            raise CommandError('Alembic package is not installed')

        list_msg = 'Put [-l] for available commands'

        if opt.list:
            availabe = 'Available commands:\n%s' % ', '.join(self.commands)
            self.write(availabe)
            return availabe
        if opt.command:
            cmd = opt.command[0]
            if cmd not in self.commands:
                raise CommandError('Unrecognized command: %s\n'
                                   % opt.command[0] + list_msg)
            if cmd in ('auto', 'revision', 'merge') and not opt.msg:
                raise CommandError('Missing [-m] parameter for: %s' % cmd)
            self.run_alembic_cmd(opt)
            return True
        raise CommandError(list_msg)

    def get_lux_template_directory(self):
        return os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            'template')

    def get_config(self):
        '''
        Programmatically create Alembic config. To determine databases,
        DATASTORE from project's config file is used. To customize Alembic
        use MIGRATIONS in you config file.

        Example:
        MIGRATIONS = {
            'alembic': {
                'script_location': '<path>',
                'databases': '<db_name1>,<db_name2>',
            },
            '<db_name1>': {
                'sqlalchemy.url': 'driver://user:pass@localhost/dbname',
            },
            '<bd_name2>': {
                'sqlalchemy.url': 'driver://user:pass@localhost/dbname',
            },
            'logging': {
                'path': '<path_to_logging_config>',
            }
        }

        For more information about possible options, please visit Alembic
        documentation:
        https://alembic.readthedocs.org/en/latest/index.html
        '''
        from alembic.config import Config
        # Because we are using custom template, we need to change default
        # implementation of get_template_directory() to make it pointing
        # to template stored in lux, we need to do this hack
        Config.get_template_directory = self.get_lux_template_directory

        # put migrations in main project dir
        migration_dir = os.path.join(self.app.meta.path, 'migrations')
        # set default settings in case where MIGRATIONS is not set
        alembic_cfg = Config()
        # where to place alembic env
        alembic_cfg.set_main_option('script_location', migration_dir)
        # get database(s) name(s) and location(s)
        odm = self.app.odm()
        databases = []
        # set section for each found database
        for name, engine in odm.keys_engines():
            if not name:
                name = 'default'
            databases.append(name)
            alembic_cfg.set_section_option(name, 'sqlalchemy.url',
                                           str(engine.url))
        # put databases in main options
        alembic_cfg.set_main_option("databases", ','.join(databases))
        # create empty logging section to avoid raising errors in env.py
        alembic_cfg.set_section_option('logging', 'path', '')
        # obtain the metadata required for `auto` command
        self.get_metadata(alembic_cfg)

        # get rest of settings from project config. This may overwrite
        # already existing options (especially if different migration dir
        # is provided)
        cfg = self.app.config.get('MIGRATIONS')
        if cfg:
            for section in cfg.keys():
                for key, value in cfg[section].items():
                    if section == 'alembic':
                        alembic_cfg.set_main_option(key, value)
                    else:
                        alembic_cfg.set_section_option(section, key, value)

        return alembic_cfg

    def run_alembic_cmd(self, opt):
        '''
        Logic for running different Alembic commands.
        '''
        from alembic import command as alembic_cmd

        config = self.get_config()
        # command consume any number of parameters but first is command name
        cmd = opt.command.pop(0)
        # init command needs to point to lux template, not alembic default
        if cmd == 'init':
            dirname = config.get_main_option('script_location')
            # line 63 will be executed in:
            # https://github.com/zzzeek/alembic/blob/master/alembic/command.py
            # since we do not use any *.ini file, we simply silence error
            # about referenced before assignment as it have no negative impact.
            try:
                alembic_cmd.init(config, dirname, template='lux')
            except UnboundLocalError:  # pragma nocover
                pass
        # merge required two revision name
        elif cmd == 'merge':
            if len(opt.command) != 2:
                raise CommandError('Command: %s required revisions id.' % cmd)
            alembic_cmd.merge(config, opt.command, message=opt.msg,
                              branch_label=opt.branch)
        elif cmd == 'revision':
            alembic_cmd.revision(config, message=opt.msg,
                                 branch_label=opt.branch)
        # auto command is a shortcut for `revision --autogenerate`
        elif cmd == 'auto':
            alembic_cmd.revision(config, autogenerate=True, message=opt.msg,
                                 branch_label=opt.branch)
        # this commands required revision name, but do not take any message or
        # branch labels
        elif cmd in ('show', 'stamp', 'upgrade', 'downgrade'):
            if len(opt.command) != 1:
                raise CommandError('Command: %s required revision id' % cmd)
            getattr(alembic_cmd, cmd)(config, *opt.command)
        else:
            # execute commands without any additional params
            getattr(alembic_cmd, cmd)(config)

    def get_metadata(self, config):
        '''
        MetaData object stored in odm extension contains aggregated data
        from all databases defined in project. This function splits the data
        to correspond with related database only.
        '''
        from sqlalchemy import MetaData
        odm = self.app.odm()
        metadata = {}

        for key, db_engine in odm.keys_engines():
            if not key:
                key = 'default'
            metadata[key] = meta = MetaData()
            for table, engine in odm.binds.items():
                if engine == db_engine:
                    table.tometadata(meta)

        config.metadata = metadata
<commit_msg>alembic<commit_after>import os

from pulsar import Setting

import lux
from lux.core.commands import CommandError

class Command(lux.Command):
    help = 'Alembic commands for migrating database.'

    commands = ['auto', 'branches', 'current', 'downgrade', 'heads', 'history',
                'init', 'merge', 'revision', 'show', 'stamp', 'upgrade']

    option_list = (
        Setting('command', nargs='*', default=None, desc='Alembic command'),
        Setting('branch', ('-b', '--branch'), default=None, nargs='?',
                desc='Branch label for auto, revision and merge command',
                meta='LABEL'),
        Setting('list', ('-l', '--list'), default=None, action='store_true',
                desc='List available Alembic commands'),
        Setting('msg', ('-m', '--message'), nargs='?', default=None,
                desc='Message for auto, revision and merge command'),
    )

    def run(self, opt):
        '''
        Run obvious commands and validate more complex.
        '''
        # alembic package is required to run any migration related command
        try:
            import alembic  # noqa
        except ImportError:  # pragma nocover
            raise CommandError('Alembic package is not installed')

        list_msg = 'Put [-l] for available commands'

        if opt.list:
            available = 'Available commands:\n%s' % ', '.join(self.commands)
            self.write(available)
            return available
        if opt.command:
            cmd = opt.command[0]
            if cmd not in self.commands:
                raise CommandError('Unrecognized command: %s\n'
                                   % opt.command[0] + list_msg)
            if cmd in ('auto', 'revision', 'merge') and not opt.msg:
                raise CommandError('Missing [-m] parameter for: %s' % cmd)
            self.run_alembic_cmd(opt)
            return True
        raise CommandError(list_msg)

    def get_lux_template_directory(self):
        return os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            'template')

    def get_config(self):
        '''
        Programmatically create Alembic config. To determine databases,
        DATASTORE from project's config file is used. To customize Alembic
        use MIGRATIONS in you config file.

        Example:
        MIGRATIONS = {
            'alembic': {
                'script_location': '<path>',
                'databases': '<db_name1>,<db_name2>',
            },
            '<db_name1>': {
                'sqlalchemy.url': 'driver://user:pass@localhost/dbname',
            },
            '<bd_name2>': {
                'sqlalchemy.url': 'driver://user:pass@localhost/dbname',
            },
            'logging': {
                'path': '<path_to_logging_config>',
            }
        }

        For more information about possible options, please visit Alembic
        documentation:
        https://alembic.readthedocs.org/en/latest/index.html
        '''
        from alembic.config import Config
        # Because we are using custom template, we need to change default
        # implementation of get_template_directory() to make it pointing
        # to template stored in lux, we need to do this hack
        Config.get_template_directory = self.get_lux_template_directory

        # put migrations in main project dir
        migration_dir = os.path.join(self.app.meta.path, 'migrations')
        # set default settings in case where MIGRATIONS is not set
        alembic_cfg = Config()
        # where to place alembic env
        alembic_cfg.set_main_option('script_location', migration_dir)
        # get database(s) name(s) and location(s)
        odm = self.app.odm()
        databases = []
        # set section for each found database
        for name, engine in odm.keys_engines():
            if not name:
                name = 'default'
            databases.append(name)
            # url = str(engine.url).replace('+green', '')
            url = str(engine.url)
            alembic_cfg.set_section_option(name, 'sqlalchemy.url', url)
        # put databases in main options
        alembic_cfg.set_main_option("databases", ','.join(databases))
        # create empty logging section to avoid raising errors in env.py
        alembic_cfg.set_section_option('logging', 'path', '')
        # obtain the metadata required for `auto` command
        self.get_metadata(alembic_cfg)

        # get rest of settings from project config. This may overwrite
        # already existing options (especially if different migration dir
        # is provided)
        cfg = self.app.config.get('MIGRATIONS')
        if cfg:
            for section in cfg.keys():
                for key, value in cfg[section].items():
                    if section == 'alembic':
                        alembic_cfg.set_main_option(key, value)
                    else:
                        alembic_cfg.set_section_option(section, key, value)

        return alembic_cfg

    def run_alembic_cmd(self, opt):
        '''
        Logic for running different Alembic commands.
        '''
        from alembic import command as alembic_cmd

        config = self.get_config()
        # command consume any number of parameters but first is command name
        cmd = opt.command.pop(0)
        # init command needs to point to lux template, not alembic default
        if cmd == 'init':
            dirname = config.get_main_option('script_location')
            # line 63 will be executed in:
            # https://github.com/zzzeek/alembic/blob/master/alembic/command.py
            # since we do not use any *.ini file, we simply silence error
            # about referenced before assignment as it have no negative impact.
            try:
                alembic_cmd.init(config, dirname, template='lux')
            except UnboundLocalError:  # pragma nocover
                pass
        # merge required two revision name
        elif cmd == 'merge':
            if len(opt.command) != 2:
                raise CommandError('Command: %s required revisions id.' % cmd)
            alembic_cmd.merge(config, opt.command, message=opt.msg,
                              branch_label=opt.branch)
        elif cmd == 'revision':
            alembic_cmd.revision(config, message=opt.msg,
                                 branch_label=opt.branch)
        # auto command is a shortcut for `revision --autogenerate`
        elif cmd == 'auto':
            alembic_cmd.revision(config, autogenerate=True, message=opt.msg,
                                 branch_label=opt.branch)
        # this commands required revision name, but do not take any message or
        # branch labels
        elif cmd in ('show', 'stamp', 'upgrade', 'downgrade'):
            if len(opt.command) != 1:
                raise CommandError('Command: %s required revision id' % cmd)
            getattr(alembic_cmd, cmd)(config, *opt.command)
        else:
            # execute commands without any additional params
            getattr(alembic_cmd, cmd)(config)

    def get_metadata(self, config):
        '''
        MetaData object stored in odm extension contains aggregated data
        from all databases defined in project. This function splits the data
        to correspond with related database only.
        '''
        from sqlalchemy import MetaData
        odm = self.app.odm()
        metadata = {}

        for key, db_engine in odm.keys_engines():
            if not key:
                key = 'default'
            metadata[key] = meta = MetaData()
            for table, engine in odm.binds.items():
                if engine == db_engine:
                    table.tometadata(meta)

        config.metadata = metadata
<|endoftext|>


<commit_before># Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import shlex
import subprocess

import six

class CommandException(Exception):

  def __init__(self, exitcode, message):
    self._exitcode = exitcode
    super(Exception, self).__init__(message)

  @property
  def exitcode(self):
    return self._exitcode

class Command:
  """Wrapper around subprocess for simpler syntax in python code for calling other programs"""

  def __init__(self, cmd, print_call=False, print_result=False):
    if print_call:
      print(cmd)

    parsedCmd = shlex.split(cmd)
    self._process = subprocess.Popen(
        parsedCmd, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    self._exitcode = None
    self._output = None
    self._print_call = print_call
    self._print_result = print_result
    self._run()

  def _run(self):
    self._output, error_message = self._process.communicate()
    self._output = six.ensure_str(self._output, 'utf-8')
    error_message = six.ensure_str(error_message, 'utf-8')
    self._exitcode = self._process.returncode
    if self._print_result:
      print("result: " + str((self._exitcode, self._output, error_message)))

    if self._exitcode > 0:
      raise CommandException(self._exitcode, error_message)

  def json(self):
    return json.loads(self._output)

  @property
  def exitcode(self):
    return self._exitcode

  @property
  def output(self):
    return self._output
<commit_msg>Fixed test result output formatting (#582)<commit_after># Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import shlex
import subprocess

import six

class CommandException(Exception):

  def __init__(self, exitcode, message):
    self._exitcode = exitcode
    super(Exception, self).__init__(message)

  @property
  def exitcode(self):
    return self._exitcode

class Command:
  """Wrapper around subprocess for simpler syntax in python code for calling other programs"""

  def __init__(self, cmd, print_call=False, print_result=False):
    if print_call:
      print(cmd)

    parsedCmd = shlex.split(cmd)
    self._process = subprocess.Popen(
        parsedCmd, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    self._exitcode = None
    self._output = None
    self._print_call = print_call
    self._print_result = print_result
    self._run()

  def _run(self):
    self._output, error_message = self._process.communicate()
    self._output = six.ensure_str(self._output, 'utf-8')
    error_message = six.ensure_str(error_message, 'utf-8')
    self._exitcode = self._process.returncode
    if self._print_result:
      result = (f"result: {self._exitcode}\n"
                f"{self._output}\n"
                f"{error_message}\n")

      print(result)

    if self._exitcode > 0:
      raise CommandException(self._exitcode, error_message)

  def json(self):
    return json.loads(self._output)

  @property
  def exitcode(self):
    return self._exitcode

  @property
  def output(self):
    return self._output
<|endoftext|>


<commit_before>"""
2/25/16
Coursera, An Introduction to Interactive Programming in Python (Part 2), Rice University
Mini-project # 5 - "Memory"
"""

import simplegui
import random

def new_game():
    global cards, exposed, state, turn, card1, card2, click1, click2
    cards = [1,2,3,4,5,6,7,8]+[1,2,3,4,5,6,7,8]
    random.shuffle(cards)
    exposed = [False for i in range(16)]
    state, turn, card1, card2, click1, click2 = 0, 0, 0, 0, 0, 0

def mouseclick(pos):
    global exposed, state, card1, card2, click1, click2, turn
    if state == 0:
        card1 = cards[pos[0]/50]
        exposed[pos[0]/50] = True
        click1 = pos[0]/50
        state = 1
    elif state == 1:
        if not exposed[pos[0]/50]:
            card2 = cards[pos[0]/50]
            exposed[pos[0]/50] = True
            click2 = pos[0]/50
            state = 2
            turn += 1
    else:
        if not exposed[pos[0]/50]:
            if card1 == card2:
                pass
            else:
                exposed[click1] = False
                exposed[click2] = False
                exposed[pos[0]/50] = True
            card1 = cards[pos[0]/50]
            exposed[pos[0]/50] = True
            click1 = pos[0]/50
            state = 1

def draw(canvas):
    global cards, exposed
    for i in range(16):
        canvas.draw_polyline([[50*i, 0], [50*i, 100], [50*i + 50, 100], [50*i + 50, 0]], 1, 'Black')
        if exposed[i]:
            canvas.draw_text(str(cards[i]), (50*i+10, 65), 40, 'Black')
        else:
            canvas.draw_polygon([[50*i, 0], [50*i, 100], [50*i + 50, 100], [50*i + 50, 0]], 2, 'Black', 'Grey')
            canvas.draw_polygon([[50*i+5, 50], [50*i+25, 90], [50*i + 45, 50], [50*i +25, 10]], 1, 'Black', 'Red')
            canvas.draw_text('M', (50*i+12, 60), 30, 'Black')
    label.set_text("Turn: " + str(turn))

frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = 0")

frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
frame.set_canvas_background('White')

new_game()
frame.start()<commit_msg>Delete RiceU.Memory.py<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env python
"""Chainer example: train a multi-layer perceptron on MNIST

This is a minimal example to write a feed-forward net.

"""
import numpy as np
import chainer
from chainer import cuda
from chainer import optimizers
import chainer.links as L
import six

import net  # from chaner MNIST example

class MNIST(object):

    @staticmethod
    def create(n_in=784, n_units=1000, n_out=10, gpu=-1):
        self = MNIST()

        mlp = net.MnistMLP(n_in, n_units, n_out)
        self.mlp = mlp
        model = L.Classifier(mlp)
        if gpu >= 0:
            cuda.get_device(gpu).use()
            model.to_gpu()
        self.model = model

        self.gpu = gpu
        self.xp = np if gpu < 0 else cuda.cupy

        optimizer = optimizers.Adam()
        optimizer.setup(model)
        self.optimizer = optimizer

        return self

    @staticmethod
    def load(filepath, *args, **kwargs):
        self = MNIST()
        with open(filepath, 'r') as f:
            self = six.moves.cPickle.load(f)
        if self.gpu >= 0:
            cuda.get_device(self.gpu).use()
            self.model.to_gpu()
        self.xp = np if self.gpu < 0 else cuda.cupy

        return self

    def fit(self, xys):
        x_train = []
        y_train = []
        for d in xys:
            x_train.append(d['data'])
            y_train.append(d['label'])

        nx = np.array(x_train, dtype=np.float32)
        ny = np.array(y_train, dtype=np.int32)
        x = chainer.Variable(self.xp.asarray(nx))
        t = chainer.Variable(self.xp.asarray(ny))

        # Pass the loss function (Classifier defines it) and its arguments
        self.optimizer.update(self.model, x, t)

        sum_loss = float(self.model.loss.data) * len(t.data)
        sum_accuracy = float(self.model.accuracy.data) * len(t.data)

        return sum_loss, sum_accuracy

    def predict(self, x):
        x_test = []
        x_test.append(x)
        nx = np.array(x_test, dtype=np.float32)
        x = chainer.Variable(self.xp.asarray(nx), volatile='on')
        pred = self.mlp(x)
        y = pred.data.reshape(
            pred.data.shape[0], pred.data.size / pred.data.shape[0])
        pred_y = y.argmax(axis=1)

        return int(pred_y[0])

    def save(self, filepath, *args, **kwargs):
        self.xp = None
        self.model.to_cpu()
        with open(filepath, 'w') as f:
            six.moves.cPickle.dump(self, f)
<commit_msg>fix typo<commit_after>#!/usr/bin/env python
"""Chainer example: train a multi-layer perceptron on MNIST

This is a minimal example to write a feed-forward net.

"""
import numpy as np
import chainer
from chainer import cuda
from chainer import optimizers
import chainer.links as L
import six

import net  # from chainer MNIST example

class MNIST(object):

    @staticmethod
    def create(n_in=784, n_units=1000, n_out=10, gpu=-1):
        self = MNIST()

        mlp = net.MnistMLP(n_in, n_units, n_out)
        self.mlp = mlp
        model = L.Classifier(mlp)
        if gpu >= 0:
            cuda.get_device(gpu).use()
            model.to_gpu()
        self.model = model

        self.gpu = gpu
        self.xp = np if gpu < 0 else cuda.cupy

        optimizer = optimizers.Adam()
        optimizer.setup(model)
        self.optimizer = optimizer

        return self

    @staticmethod
    def load(filepath, *args, **kwargs):
        self = MNIST()
        with open(filepath, 'r') as f:
            self = six.moves.cPickle.load(f)
        if self.gpu >= 0:
            cuda.get_device(self.gpu).use()
            self.model.to_gpu()
        self.xp = np if self.gpu < 0 else cuda.cupy

        return self

    def fit(self, xys):
        x_train = []
        y_train = []
        for d in xys:
            x_train.append(d['data'])
            y_train.append(d['label'])

        nx = np.array(x_train, dtype=np.float32)
        ny = np.array(y_train, dtype=np.int32)
        x = chainer.Variable(self.xp.asarray(nx))
        t = chainer.Variable(self.xp.asarray(ny))

        # Pass the loss function (Classifier defines it) and its arguments
        self.optimizer.update(self.model, x, t)

        sum_loss = float(self.model.loss.data) * len(t.data)
        sum_accuracy = float(self.model.accuracy.data) * len(t.data)

        return sum_loss, sum_accuracy

    def predict(self, x):
        x_test = []
        x_test.append(x)
        nx = np.array(x_test, dtype=np.float32)
        x = chainer.Variable(self.xp.asarray(nx), volatile='on')
        pred = self.mlp(x)
        y = pred.data.reshape(
            pred.data.shape[0], pred.data.size / pred.data.shape[0])
        pred_y = y.argmax(axis=1)

        return int(pred_y[0])

    def save(self, filepath, *args, **kwargs):
        self.xp = None
        self.model.to_cpu()
        with open(filepath, 'w') as f:
            six.moves.cPickle.dump(self, f)
<|endoftext|>


<commit_before>import os
import sys
import time
import inspect

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import featureFunction

class FeatureSpace:
    """
    This Class is a wrapper class, to allow user select the
    features based on the available time series vectors (magnitude, time,
    error, second magnitude, etc.) or specify a list of features.

    __init__ will take in the list of the available data and featureList.

    User could only specify the available time series vectors, which will
    output all the features that need this data to be calculated.

    User could only specify featureList, which will output
    all the features in the list.

    User could specify a list of the available time series vectors and
    featureList, which will output all the features in the List that
    use the available data.

    Additional parameters are used for individual features.
    Format is featurename = [parameters]

    usage:
    data = np.random.randint(0,10000, 100000000)
    # automean is the featurename and [0,0] is the parameter for the feature
    a = FeatureSpace(category='all', automean=[0,0])
    print a.featureList
    a=a.calculateFeature(data)
    print a.result(method='array')
    print a.result(method='dict')

    """
    def __init__(self, Data=None, featureList=None, excludeList=[], **kwargs):
        self.featureFunc = []
        self.featureList = []
        self.featureOrder = []
        self.featureList = []

        self.sort = False

        if Data is not None:
            self.Data = Data

            if self.Data == 'all':
                if featureList == None:

                    if excludeList == None:
                        for name, obj in inspect.getmembers(featureFunction):
                            if inspect.isclass(obj) and name != 'Base':
                                # if set(obj().Data).issubset(self.Data):
                                self.featureOrder.append((inspect.getsourcelines(obj)[-1:])[0])
                                self.featureList.append(name)
                    else:
                        for name, obj in inspect.getmembers(featureFunction):
                            if inspect.isclass(obj) and name != 'Base' and not name in excludeList:
                                # if set(obj().Data).issubset(self.Data):
                                self.featureOrder.append((inspect.getsourcelines(obj)[-1:])[0])
                                self.featureList.append(name)

                else:
                    for feature in featureList:
                        for name, obj in inspect.getmembers(featureFunction):
                            if name != 'Base':
                                if inspect.isclass(obj) and feature == name:
                                    self.featureList.append(name)

            else:

                if featureList is None:
                    for name, obj in inspect.getmembers(featureFunction):
                        if inspect.isclass(obj) and name != 'Base' and not name in excludeList:
                            if name in kwargs.keys():
                                if set(obj(kwargs[name]).Data).issubset(self.Data):
                                    self.featureOrder.append((inspect.getsourcelines(obj)[-1:])[0])
                                    self.featureList.append(name)

                            else:
                                if set(obj().Data).issubset(self.Data):
                                    self.featureOrder.append((inspect.getsourcelines(obj)[-1:])[0])
                                    self.featureList.append(name)
                                else:
                                    print "Warning: the feature", name, "could not be calculated because", obj().Data, "are needed."
                else:

                    for feature in featureList:
                        for name, obj in inspect.getmembers(featureFunction):
                            if name != 'Base':
                                if inspect.isclass(obj) and feature == name:
                                    if set(obj().Data).issubset(self.Data):
                                        self.featureList.append(name)
                                    else:
                                        print "Warning: the feature", name, "could not be calculated because", obj().Data, "are needed."

            if self.featureOrder != []:
                self.sort = True
                self.featureOrder = np.argsort(self.featureOrder)
                self.featureList = [self.featureList[i] for i in self.featureOrder]
                self.idx = np.argsort(self.featureList)

        else:
            self.featureList = featureList

        m = featureFunction

        for item in self.featureList:
            if item in kwargs.keys():
                try:
                    a = getattr(m, item)(kwargs[item])
                except:
                    print "error in feature " + item
                    sys.exit(1)
            else:
                try:
                    a = getattr(m, item)()
                except:
                    print " could not find feature " + item
                    # discuss -- should we exit?
                    sys.exit(1)
            try:
                self.featureFunc.append(a.fit)
            except:
                print "could not initilize " + item

    def calculateFeature(self, data):
        self._X = np.asarray(data)
        self.__result = []
        for f in self.featureFunc:
            self.__result.append(f(self._X))
        return self

    def result(self, method='array'):
        if method == 'array':
            if self.sort == True:
                return [np.asarray(self.__result)[i] for i in self.idx]
            else:
                return np.asarray(self.__result)
        elif method == 'dict':
            if self.sort == True:
                return dict(zip([self.featureList[i] for i in self.idx], [np.asarray(self.__result)[i] for i in self.idx]))
            else:
                return dict(zip(self.featureList, np.asarray(self.__result)))
        elif method == 'features':
            if self.sort == True:
                return [self.featureList[i] for i in self.idx]
            else:
                return self.featureList
        else:
            return self.__result

<commit_msg>Extra check for Data argument<commit_after>import os
import sys
import time
import inspect

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import featureFunction

class FeatureSpace:
    """
    This Class is a wrapper class, to allow user select the
    features based on the available time series vectors (magnitude, time,
    error, second magnitude, etc.) or specify a list of features.

    __init__ will take in the list of the available data and featureList.

    User could only specify the available time series vectors, which will
    output all the features that need this data to be calculated.

    User could only specify featureList, which will output
    all the features in the list.

    User could specify a list of the available time series vectors and
    featureList, which will output all the features in the List that
    use the available data.

    Additional parameters are used for individual features.
    Format is featurename = [parameters]

    usage:
    data = np.random.randint(0,10000, 100000000)
    # automean is the featurename and [0,0] is the parameter for the feature
    a = FeatureSpace(category='all', automean=[0,0])
    print a.featureList
    a=a.calculateFeature(data)
    print a.result(method='array')
    print a.result(method='dict')

    """
    def __init__(self, Data=None, featureList=None, excludeList=[], **kwargs):
        self.featureFunc = []
        self.featureList = []
        self.featureOrder = []
        self.featureList = []

        self.sort = False

        if Data is not None:
            self.Data = Data

            if self.Data == 'all':
                if featureList == None:

                    if excludeList == None:
                        for name, obj in inspect.getmembers(featureFunction):
                            if inspect.isclass(obj) and name != 'Base':
                                if obj.__module__.endswith('FeatureFunctionLib'):
                                    # if set(obj().Data).issubset(self.Data):
                                    self.featureOrder.append((inspect.getsourcelines(obj)[-1:])[0])
                                    self.featureList.append(name)
                    else:
                        for name, obj in inspect.getmembers(featureFunction):
                            if inspect.isclass(obj) and name != 'Base' and not name in excludeList:
                                if obj.__module__.endswith('FeatureFunctionLib'):
                                    # if set(obj().Data).issubset(self.Data):
                                    self.featureOrder.append((inspect.getsourcelines(obj)[-1:])[0])
                                    self.featureList.append(name)

                else:
                    for feature in featureList:
                        for name, obj in inspect.getmembers(featureFunction):
                            if name != 'Base':
                                if inspect.isclass(obj) and feature == name:
                                    self.featureList.append(name)

            else:

                if featureList is None:
                    for name, obj in inspect.getmembers(featureFunction):
                        if inspect.isclass(obj) and name != 'Base' and not name in excludeList:
                            if obj.__module__.endswith('FeatureFunctionLib'):
                                if name in kwargs.keys():
                                    if set(obj(kwargs[name]).Data).issubset(self.Data):
                                        self.featureOrder.append((inspect.getsourcelines(obj)[-1:])[0])
                                        self.featureList.append(name)

                                else:
                                    if set(obj().Data).issubset(self.Data):
                                        self.featureOrder.append((inspect.getsourcelines(obj)[-1:])[0])
                                        self.featureList.append(name)
                                    else:
                                        print "Warning: the feature", name, "could not be calculated because", obj().Data, "are needed."
                else:

                    for feature in featureList:
                        for name, obj in inspect.getmembers(featureFunction):
                            if name != 'Base':
                                if inspect.isclass(obj) and feature == name:
                                    if set(obj().Data).issubset(self.Data):
                                        self.featureList.append(name)
                                    else:
                                        print "Warning: the feature", name, "could not be calculated because", obj().Data, "are needed."

            if self.featureOrder != []:
                self.sort = True
                self.featureOrder = np.argsort(self.featureOrder)
                self.featureList = [self.featureList[i] for i in self.featureOrder]
                self.idx = np.argsort(self.featureList)

        else:
            self.featureList = featureList

        m = featureFunction

        for item in self.featureList:
            if item in kwargs.keys():
                try:
                    a = getattr(m, item)(kwargs[item])
                except:
                    print "error in feature " + item
                    sys.exit(1)
            else:
                try:
                    a = getattr(m, item)()
                except:
                    print " could not find feature " + item
                    # discuss -- should we exit?
                    sys.exit(1)
            try:
                self.featureFunc.append(a.fit)
            except:
                print "could not initilize " + item

    def calculateFeature(self, data):
        self._X = np.asarray(data)
        self.__result = []
        for f in self.featureFunc:
            self.__result.append(f(self._X))
        return self

    def result(self, method='array'):
        if method == 'array':
            if self.sort == True:
                return [np.asarray(self.__result)[i] for i in self.idx]
            else:
                return np.asarray(self.__result)
        elif method == 'dict':
            if self.sort == True:
                return dict(zip([self.featureList[i] for i in self.idx], [np.asarray(self.__result)[i] for i in self.idx]))
            else:
                return dict(zip(self.featureList, np.asarray(self.__result)))
        elif method == 'features':
            if self.sort == True:
                return [self.featureList[i] for i in self.idx]
            else:
                return self.featureList
        else:
            return self.__result

<|endoftext|>


<commit_before>"""
FinalProject.py
Author: Liam S
Credit:
"""
from ggame import App, Sprite, ImageAsset, TextAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

class Background(Sprite):

    asset = ImageAsset("images/grass_with_blue_sky_by_devrez-d35pm8j.png")
    width = 1032
    height = 774

    def __init__(self, position):
        super().__init__(Background.asset, position)
        self.scale = 1.4

class WinnerScreen(Sprite):
    asset = TextAsset("You Win", style='400px Arial')

    def __init__(self, position):
        super().__init__(WinnerScreen.asset, position)
        self.visible = False
        self.Trucks = 6

    def step(self):
        self.Trucks = len(PlaneGame.getSpritesbyClass(Truck))
        if self.Trucks == 0:
            self.visible = True

class LoserScreen(Sprite):
    asset = TextAsset("You Lose", style='400px Arial')

    def __init__(self, position, ship):
        super().__init__(LoserScreen.asset, position)
        self.visible = False
        self.ship = ship

    def step(self):
        if self.ship.planeDead == True:
            self.visible = True

class EvilPlane(Sprite):
    asset = ImageAsset("images/EvilPlane.png")
    width = 10
    height = 10

    def __init__(self, position, ship):
        super().__init__(EvilPlane.asset, position)
        self.scale = 0.9
        self.rectangularCollisionModel()
        self.visible = True
        self.ship = ship
        self.newY = 0

    def step(self):
        self.x -= 3
        if self.x <= -10:
            self.x = 1999
        if self.ship.y > self.y:
            self.newY = 0.5
        if self.ship.y < self.y:
            self.newY = -0.5
        if self.ship.y == self.y:
            self.newY = 0
        self.y += self.newY
        if self.collidingWithSprites(Ship):
            self.visible = False
            ExplosionBig(self.position)
            self.destroy

class Truck(Sprite):

    asset = ImageAsset("images/Newtruck.png")
    width = 10
    height = 10

    def __init__(self, position):
        super().__init__(Truck.asset, position)
        self.scale = 1
        self.circularCollisionModel()
        self.visible = True
    def step(self):
        self.x -= 2
        if self.x <= -10:
            self.x = 1999
        if self.collidingWithSprites(Bomb):
            self.visible = False
            ExplosionBig(self.position)
            self.destroy()

class Ship(Sprite):

    asset = ImageAsset("images/il2m3-bp-fl-am-3view-mongolian.png")

    def __init__(self, position):
        super().__init__(Ship.asset, position)
        self.vx = 1
        self.vy = 1
        self.vAddedx = 0
        self.vAddedy = 0
        self.vAddedr = 0
        self.vertThrust = 0
        self.RotThrust = 0
        self.thrustframe = 1
        self.scale = 0.25
        self.planeDead = False
        self.circularCollisionModel()
        PlaneGame.listenKeyEvent("keydown", "up arrow", self.thrustUp)
        PlaneGame.listenKeyEvent("keyup", "down arrow", self.thrustDownoff)
        PlaneGame.listenKeyEvent("keyup", "up arrow", self.thrustUpoff)
        PlaneGame.listenKeyEvent("keydown", "down arrow", self.thrustDown)

        self.fxcenter = self.fycenter = 0.5
    def step(self):
        if self.vertThrust == 1:
            self.vAddedy = 3
        if self.vertThrust == -1:
            self.vAddedy = -3
        if self.vertThrust == 0:
            self.vAddedy = 0
        if self.RotThrust == 1:
            self.vAddedr = -0.3
        if self.RotThrust == -1:
            self.vAddedr = 0.3
        if self.RotThrust == 0:
            self.vAddedr = 0
        if self.x >= 2000:
            self.x = 10
        if self.x <= 0:
            self.x = 1999
        if self.y <=10:
            self.y = 11
        self.x += 5
        self.y += self.vAddedy
        self.rotation = self.vAddedr
        if self.y >= 740:
            self.visible = False
            self.planeDead = True
            self.destroy
        if self.collidingWithSprites(EvilPlane):
            self.visible = False
            self.planeDead = True
            ExplosionBig(self.position)
            self.destroy
        if self.collidingWithSprites(Truck):
            self.visible = False
            self.planeDead = True
            ExplosionBig(self.position)
            self.destroy
    def thrustUp(self, event):
        self.vertThrust = -1
        self.RotThrust = -1

    def thrustDown(self, event):
        self.vertThrust = 1
        self.RotThrust = 1

    def thrustDownoff(self, event):
        self.vertThrust = 0
        self.RotThrust = 0

    def thrustUpoff(self, event):
        self.vertThrust = 0
        self.RotThrust = 0

class Bomb(Sprite):

    asset = ImageAsset("images/bomb2.png")
    width = 200
    height = 100

    def __init__(self, position, ship):
        super().__init__(Bomb.asset, position)
        self.scale = 0.4
        self.ship = ship
        self.visible = False
        self.dropped = False
        self.counter = 0
        PlaneGame.listenKeyEvent("keydown", "space", self.dropBomb)
        self.circularCollisionModel()

    def dropBomb(self, event):
        self.dropped = True

    def nodropBomb(self, event):
        self.dropped = False

    def step(self):
        if self.dropped == False:
            self.x = self.ship.x
            self.y = self.ship.y+15
        if self.dropped == True:
            self.visible = True
            if self.visible == True:
                self.counter += 0.2
                self.x += 5
                self.y += self.counter
        if self.collidingWithSprites(Truck):
            self.visible = False
            self.dropped = False
            self.counter = 0
        if self.y >= 765:
            self.visible = False
            self.dropped = False
            self.counter = 0
            if self.ship.planeDead == True:
                self.destroy()
            if self.ship.planeDead == False:
                ExplosionBig(self.position)
        if self.x >= 2000:
            self.x = 10
        if self.x <= 0:
            self.x = 1999

class ExplosionBig(Sprite):

    asset = ImageAsset("images/explosion2.png", Frame(0,0,4800/25,195), 25)

    def __init__(self, position):
        super().__init__(ExplosionBig.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.scale = 0.7

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image = self.image + 1
        if self.image == 50:
            self.destroy()

class PlaneGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        Background((0, 0))
        Background((1300, 0))
        Background((2000, 0))
        s = Ship((400,200))
        Bomb((400,600),s)
        WinnerScreen((500,0))
        Truck((200,740))
        Truck((500,740))
        Truck((800,740))
        Truck((1100,740))
        Truck((1400,740))
        Truck((1700,740))
        EvilPlane((1200,400),s)
        LoserScreen((500,0),s)

    def step(self):
        for ship in self.getSpritesbyClass(Ship):
            ship.step()
        for ship in self.getSpritesbyClass(Bomb):
            ship.step()
        for ship in self.getSpritesbyClass(ExplosionBig):
            ship.step()
        for ship in self.getSpritesbyClass(Truck):
            ship.step()
        for ship in self.getSpritesbyClass(EvilPlane):
            ship.step()
        for ship in self.getSpritesbyClass(LoserScreen):
            ship.step()
        for ship in self.getSpritesbyClass(WinnerScreen):
            ship.step()

app = PlaneGame(0,0)
app.run()

<commit_msg>Updated from Brython Server: 1/6/2017 1:43:25 PM<commit_after>"""
FinalProject.py
Author: Liam S
Credit:
"""
from ggame import App, Sprite, ImageAsset, TextAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

class Background(Sprite):

    asset = ImageAsset("images/grass_with_blue_sky_by_devrez-d35pm8j.png")
    width = 1032
    height = 774

    def __init__(self, position):
        super().__init__(Background.asset, position)
        self.scale = 1.4

class WinnerScreen(Sprite):
    asset = TextAsset("You Win", style='400px Arial')

    def __init__(self, position, Loserscreen):
        super().__init__(WinnerScreen.asset, position)
        self.visible = False
        self.Trucks = 6
        self.LoserScreen = LoserScreen

    def step(self):
        self.Trucks = len(PlaneGame.getSpritesbyClass(Truck))
        if self.Trucks == 0 and self.LoserScreen.visible == False:
            self.visible = True

class LoserScreen(Sprite):
    asset = TextAsset("You Lose", style='400px Arial')

    def __init__(self, position, ship):
        super().__init__(LoserScreen.asset, position)
        self.visible = False
        self.ship = ship

    def step(self):
        if self.ship.planeDead == True:
            self.visible = True

class EvilPlane(Sprite):
    asset = ImageAsset("images/EvilPlane.png")
    width = 10
    height = 10

    def __init__(self, position, ship):
        super().__init__(EvilPlane.asset, position)
        self.scale = 0.9
        self.rectangularCollisionModel()
        self.visible = True
        self.ship = ship
        self.newY = 0

    def step(self):
        self.x -= 3
        if self.x <= -10:
            self.x = 1999
        if self.ship.y > self.y:
            self.newY = 0.5
        if self.ship.y < self.y:
            self.newY = -0.5
        if self.ship.y == self.y:
            self.newY = 0
        self.y += self.newY
        if self.collidingWithSprites(Ship):
            self.visible = False
            ExplosionBig(self.position)
            self.destroy

class Truck(Sprite):

    asset = ImageAsset("images/Newtruck.png")
    width = 10
    height = 10

    def __init__(self, position):
        super().__init__(Truck.asset, position)
        self.scale = 1
        self.circularCollisionModel()
        self.visible = True
    def step(self):
        self.x -= 2
        if self.x <= -10:
            self.x = 1999
        if self.collidingWithSprites(Bomb):
            self.visible = False
            ExplosionBig(self.position)
            self.destroy()

class Ship(Sprite):

    asset = ImageAsset("images/il2m3-bp-fl-am-3view-mongolian.png")

    def __init__(self, position):
        super().__init__(Ship.asset, position)
        self.vx = 1
        self.vy = 1
        self.vAddedx = 0
        self.vAddedy = 0
        self.vAddedr = 0
        self.vertThrust = 0
        self.RotThrust = 0
        self.thrustframe = 1
        self.scale = 0.25
        self.planeDead = False
        self.circularCollisionModel()
        PlaneGame.listenKeyEvent("keydown", "up arrow", self.thrustUp)
        PlaneGame.listenKeyEvent("keyup", "down arrow", self.thrustDownoff)
        PlaneGame.listenKeyEvent("keyup", "up arrow", self.thrustUpoff)
        PlaneGame.listenKeyEvent("keydown", "down arrow", self.thrustDown)

        self.fxcenter = self.fycenter = 0.5
    def step(self):
        if self.vertThrust == 1:
            self.vAddedy = 3
        if self.vertThrust == -1:
            self.vAddedy = -3
        if self.vertThrust == 0:
            self.vAddedy = 0
        if self.RotThrust == 1:
            self.vAddedr = -0.3
        if self.RotThrust == -1:
            self.vAddedr = 0.3
        if self.RotThrust == 0:
            self.vAddedr = 0
        if self.x >= 2000:
            self.x = 10
        if self.x <= 0:
            self.x = 1999
        if self.y <=10:
            self.y = 11
        self.x += 5
        self.y += self.vAddedy
        self.rotation = self.vAddedr
        if self.y >= 740:
            self.visible = False
            self.planeDead = True
            self.destroy
        if self.collidingWithSprites(EvilPlane):
            self.visible = False
            self.planeDead = True
            ExplosionBig(self.position)
            self.destroy
        if self.collidingWithSprites(Truck):
            self.visible = False
            self.planeDead = True
            ExplosionBig(self.position)
            self.destroy
    def thrustUp(self, event):
        self.vertThrust = -1
        self.RotThrust = -1

    def thrustDown(self, event):
        self.vertThrust = 1
        self.RotThrust = 1

    def thrustDownoff(self, event):
        self.vertThrust = 0
        self.RotThrust = 0

    def thrustUpoff(self, event):
        self.vertThrust = 0
        self.RotThrust = 0

class Bomb(Sprite):

    asset = ImageAsset("images/bomb2.png")
    width = 200
    height = 100

    def __init__(self, position, ship):
        super().__init__(Bomb.asset, position)
        self.scale = 0.4
        self.ship = ship
        self.visible = False
        self.dropped = False
        self.counter = 0
        PlaneGame.listenKeyEvent("keydown", "space", self.dropBomb)
        self.circularCollisionModel()

    def dropBomb(self, event):
        self.dropped = True

    def nodropBomb(self, event):
        self.dropped = False

    def step(self):
        if self.dropped == False:
            self.x = self.ship.x
            self.y = self.ship.y+15
        if self.dropped == True:
            self.visible = True
            if self.visible == True:
                self.counter += 0.2
                self.x += 5
                self.y += self.counter
        if self.collidingWithSprites(Truck):
            self.visible = False
            self.dropped = False
            self.counter = 0
        if self.y >= 765:
            self.visible = False
            self.dropped = False
            self.counter = 0
            if self.ship.planeDead == True:
                self.destroy()
            if self.ship.planeDead == False:
                ExplosionBig(self.position)
        if self.x >= 2000:
            self.x = 10
        if self.x <= 0:
            self.x = 1999

class ExplosionBig(Sprite):

    asset = ImageAsset("images/explosion2.png", Frame(0,0,4800/25,195), 25)

    def __init__(self, position):
        super().__init__(ExplosionBig.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.scale = 0.7

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image = self.image + 1
        if self.image == 50:
            self.destroy()

class PlaneGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        Background((0, 0))
        Background((1300, 0))
        Background((2000, 0))
        s = Ship((400,200))
        Bomb((400,600),s)
        Truck((200,740))
        Truck((500,740))
        Truck((800,740))
        Truck((1100,740))
        Truck((1400,740))
        Truck((1700,740))
        EvilPlane((1200,400),s)
        l = LoserScreen((500,0),s)
        WinnerScreen((500,0),l)

    def step(self):
        for ship in self.getSpritesbyClass(Ship):
            ship.step()
        for ship in self.getSpritesbyClass(Bomb):
            ship.step()
        for ship in self.getSpritesbyClass(ExplosionBig):
            ship.step()
        for ship in self.getSpritesbyClass(Truck):
            ship.step()
        for ship in self.getSpritesbyClass(EvilPlane):
            ship.step()
        for ship in self.getSpritesbyClass(LoserScreen):
            ship.step()
        for ship in self.getSpritesbyClass(WinnerScreen):
            ship.step()

app = PlaneGame(0,0)
app.run()

<|endoftext|>


<commit_before>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield,

"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset

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)

class Chell(Sprite):
    asset = ImageAsset("images/Chell1.png")
    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
        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:
            OrangePortal((self.cox-60,self.coy-70))
            self.click = 0
            self.alt = 0
        if self.click == 1 and self.alt == 1:
            BluePortal((self.cox-60,self.coy-70))
            self.click = 0
            self.alt = 0

        if self.mright == 1:
            self.x += .75
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 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
        self.cox = event.x
        self.coy = 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")
    def __init__(self, position):
        super().__init__(BluePortal.asset, position)
        self.visible = True
        self.scale = .25

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

class OrangePortal(Sprite):
    asset = ImageAsset("images/portal___orange_portal_by_maxiesnax-d5pcfmj.png")
    def __init__(self, position):
        super().__init__(OrangePortal.asset, position)
        self.scale = .25
        self.center = (0,0)
        self.image = 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/21/2016 2:08:33 PM<commit_after>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield,

"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset

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)

class Chell(Sprite):
    asset = ImageAsset("images/Chell1.png")
    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
        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:
            OrangePortal((self.cox-60,self.coy-70))
            self.click = 0
            self.alt = 0
        if self.click == 1 and self.alt == 1:

            BluePortal((self.cox-60,self.coy-70))
            self.click = 0
            self.alt = 0

        if self.mright == 1:
            self.x += .75
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 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
        self.cox = event.x
        self.coy = 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")
    def __init__(self, position):
        super().__init__(BluePortal.asset, position)
        self.visible = True
        self.scale = .25

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

class OrangePortal(Sprite):
    asset = ImageAsset("images/portal___orange_portal_by_maxiesnax-d5pcfmj.png")
    def __init__(self, position):
        super().__init__(OrangePortal.asset, position)
        self.scale = .25
        self.center = (0,0)
        self.image = 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 numpy as np
from scipy import sparse, diag
from scipy import interpolate

import matplotlib.pyplot as plt

class BuckleyLeverett():
    """ Solves the two-phase flow problem using the Buckley-Leverett
    solution. The code provides three methods for providing the
    specifying the fractional flow:
    1) df_ds (highest priority): Directly provide the derivative of the fractional flow \
    function with respect to saturation.
    2) fractional_flow: Provide the fractinal flow function.
    3) k_ro, k_rw, oil_viscosity, water_viscosity: Provide the variables and functions
    that make up the fractional flow function.

    The code first looks for a df_ds function, finding none is looks for fractional_flow,
    and finally it will construct fractional_flow from the relative permeability and
    fluid viscosities.

    :ivar float height: Domain height (m).
    :ivar float length: Domain length (m).
    :ivar float injection_rate: Well water injection rate (kg/s).
    :ivar float residual_water: Residual water saturation.
    :ivar float residual_oil: Residual oil saturation.
    :ivar function fractional_flow: Fractional flow as a function \
    of water satuation (optional).
    :ivar function df_ds_function: Derivative of fractional flow with \
    respect to saturation (optional). If not specified, the program \
    will compute a numerical derivative of fractional_flow.
    """

    def __init__(self):

        ## Domain height (m).
        self.height = 1.

        ## Domain length (m)
        self.length = 1.

        ## Rock porosity.
        self.porosity = 1.

        ## Injection rate (kg/s).
        self.injection_rate = 1.

        ## Minimum water residual.
        self.residual_water = 0.

        ## Minimum oil residual.
        self.residual_oil = 0.

        ## Oil relative permeability
        self.k_ro = None

        ## Water relative permeability
        self.k_rw = None

        ## Oil viscosity
        self.oil_viscosity = 1.e-3

        ## Water viscosity
        self.water_viscosity = 1.e-3

        ## Fractional flow as a function of water satuation ('function' type).
        self.fractional_flow = None

        ## Derivative of fractional flow with respect to saturation ('function' type).
        self.df_ds_function = None

    def plot_water_saturation_at_t(self, time):

        x = np.linspace(0., self.length, 50)
        y = [self.water_saturation_solution(time)(x_i) for x_i in x]

        plt.plot(x, y, 'k')
        plt.show()

    def water_saturation_solution(self, time):
        """ Returns a function based on the  Buckley-Leverett solution
        problem for two-phase problems. The functions gives the water saturation
        at the time (s) specified in the input.
        :param float time: Time (s) after injection.
        :return: A function representing the water saturation at x (distance from injector in meters).
        """
        if self.df_ds_function is None:
            if self.fractional_flow is None:
                def fractional_flow(sw):
                    return 1./(1.+self.k_ro(sw)/self.k_rw(sw)*self.oil_viscosity/self.water_viscosity)
                self.fractional_flow = fractional_flow
            def fractional_flow_prime(water_saturation):
                fw_prime = self.fractional_flow(water_saturation+.0001)
                fw_prime -=self.fractional_flow(water_saturation)
                fw_prime /= .0001
                return fw_prime
        else:
            fractional_flow_prime = self.df_ds_function

        (_, sw_max) = min(map(lambda sw:(abs(fractional_flow_prime(sw)-self.fractional_flow(sw)/sw), sw),
                              np.arange(.01, 1.-.2, .0001)))

        f_prime_max = fractional_flow_prime(sw_max)

        v = time*self.injection_rate/(self.porosity*self.height)
        x_front = v*fractional_flow_prime(sw_max)

        # Compute sw as a function of x. This is done by
        # interpolating over sw, and finding f_prime,
        # then scaling f_prime properly to cover x.
        inter_y = [1.-self.residual_oil]+list(np.arange(1.-self.residual_oil, sw_max, -.001))+[sw_max]
        inter_x = [0.]
        inter_x += map(lambda sw: fractional_flow_prime(sw),
                      np.arange(1.-self.residual_oil, sw_max, -.001))
        inter_x += [fractional_flow_prime(sw_max)]
        inter_x = map(lambda x:x/f_prime_max*x_front, inter_x)

        saturation_before_front = interpolate.interp1d(inter_x, inter_y)

        def bl_solution(point):
            if point<x_front:
                return saturation_before_front(point)
            else:
                return 0.

        return bl_solution

<commit_msg>fixed units for injection rate and cross sectional area<commit_after>
import numpy as np
from scipy import sparse, diag
from scipy import interpolate

import matplotlib.pyplot as plt

class BuckleyLeverett():
    """ Solves the two-phase flow problem using the Buckley-Leverett
    solution. The code provides three methods for providing the
    specifying the fractional flow:
    1) df_ds (highest priority): Directly provide the derivative of the fractional flow \
    function with respect to saturation.
    2) fractional_flow: Provide the fractinal flow function.
    3) k_ro, k_rw, oil_viscosity, water_viscosity: Provide the variables and functions
    that make up the fractional flow function.

    The code first looks for a df_ds function, finding none is looks for fractional_flow,
    and finally it will construct fractional_flow from the relative permeability and
    fluid viscosities.

    :ivar float cross_section: Domain cross sectional area (m^2).
    :ivar float length: Domain length (m).
    :ivar float injection_rate: Well water injection rate (m^3/s).
    :ivar float residual_water: Residual water saturation.
    :ivar float residual_oil: Residual oil saturation.
    :ivar function fractional_flow: Fractional flow as a function \
    of water satuation (optional).
    :ivar function df_ds_function: Derivative of fractional flow with \
    respect to saturation (optional). If not specified, the program \
    will compute a numerical derivative of fractional_flow.
    """

    def __init__(self):

        ## Domain cross sectional area (m^2).
        self.cross_section = 1.

        ## Domain length (m)
        self.length = 1.

        ## Rock porosity.
        self.porosity = 1.

        ## Injection rate (m^3/s).
        self.injection_rate = 1.

        ## Minimum water residual.
        self.residual_water = 0.

        ## Minimum oil residual.
        self.residual_oil = 0.

        ## Oil relative permeability
        self.k_ro = None

        ## Water relative permeability
        self.k_rw = None

        ## Oil viscosity
        self.oil_viscosity = 1.e-3

        ## Water viscosity
        self.water_viscosity = 1.e-3

        ## Fractional flow as a function of water satuation ('function' type).
        self.fractional_flow = None

        ## Derivative of fractional flow with respect to saturation ('function' type).
        self.df_ds_function = None

    def plot_water_saturation_at_t(self, time):

        x = np.linspace(0., self.length, 50)
        y = [self.water_saturation_solution(time)(x_i) for x_i in x]

        plt.plot(x, y, 'k')
        plt.show()

    def water_saturation_solution(self, time):
        """ Returns a function based on the  Buckley-Leverett solution
        problem for two-phase problems. The functions gives the water saturation
        at the time (s) specified in the input.
        :param float time: Time (s) after injection.
        :return: A function representing the water saturation at x (distance from injector in meters).
        """
        if self.df_ds_function is None:
            if self.fractional_flow is None:
                def fractional_flow(sw):
                    return 1./(1.+self.k_ro(sw)/self.k_rw(sw)*self.oil_viscosity/self.water_viscosity)
                self.fractional_flow = fractional_flow
            def fractional_flow_prime(water_saturation):
                fw_prime = self.fractional_flow(water_saturation+.0001)
                fw_prime -=self.fractional_flow(water_saturation)
                fw_prime /= .0001
                return fw_prime
        else:
            fractional_flow_prime = self.df_ds_function

        (_, sw_max) = min(map(lambda sw:(abs(fractional_flow_prime(sw)-self.fractional_flow(sw)/sw), sw),
                              np.arange(.01, 1.-.2, .0001)))

        f_prime_max = fractional_flow_prime(sw_max)

        v = time*self.injection_rate/(self.porosity*self.cross_section)
        x_front = v*fractional_flow_prime(sw_max)

        # Compute sw as a function of x. This is done by
        # interpolating over sw, and finding f_prime,
        # then scaling f_prime properly to cover x.
        inter_y = [1.-self.residual_oil]+list(np.arange(1.-self.residual_oil, sw_max, -.001))+[sw_max]
        inter_x = [0.]
        inter_x += map(lambda sw: fractional_flow_prime(sw),
                      np.arange(1.-self.residual_oil, sw_max, -.001))
        inter_x += [fractional_flow_prime(sw_max)]
        inter_x = map(lambda x:x/f_prime_max*x_front, inter_x)

        saturation_before_front = interpolate.interp1d(inter_x, inter_y)

        def bl_solution(point):
            if point<x_front:
                return saturation_before_front(point)
            else:
                return 0.

        return bl_solution

<|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
# colors
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)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

# lines
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)

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

# global variables changed with the classes
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 = 50
        self.y = 410
        self.vx = 0
        self.vy = 0
        self.jump = 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
        self.jumpup = 0
        # all key inputs
        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", "space", self.jumpOff)

    def step(self):
        # move orange portal
        if self.click == 1 and self.alt != 1:
            global cox
            cox = cpx
            global coy
            coy = cpy
            self.click = 0
        # move blue portal
        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

        # win
        if self.collidingWithSprites(WinDoor):
            self.thing = YouWin((400,400))

        # move right and left
        if self.mright == 1:
            self.setImage(0)
            self.x += 2
            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 += -2
            self.y = self.y
        if self.mleft == 0:
            self.x = self.x
            self.y = self.y

        # constantly moving down for gravity
        self.vy += 6
        self.y += self.vy
        self.vy = 0
        # if collliding with platform, go up to counteract the moving down, effectively staying still
        if self.collidingWithSprites(Platforms):
            self.y -= 6
            self.vy = 0
            # jump
            if self.jump == 1:
                self.vy = 0
                for x in range(1,10):
                    self.vy = -100
                    self.vy += 1
                    self.y -= 10 + self.vy

        # death by goo
        if self.y >= 560:
            self.x = 50
            self.y = 410
        # borders
        if self.x <0:
            self.x = 0
        if self.x > 947:
            self.x = 947

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

    def ClickOn(self,event):
        self.click = 1
        global cpx
        cpx = event.x
        global cpy
        cpy = event.y
    def jumpOn(self,event):
        self.jump = 1
    def jumpOff(self,event):
        self.jump = 0
    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 Platforms(Sprite):
    platc=Color(0xB9BDBB,1.0)
    plat=RectangleAsset(250, 1, noline, platc)
    def __init__(self, position):
        super().__init__(Platforms.plat, position)

class WinDoor(Sprite):
    exitsmall=CircleAsset(20, thinline, platc)
    def __init__(self, position):
        super().__init__(WinDoor.exitsmall, position)
        self.x = 800
        self.y = 100

class YouWin(Sprite):
    youwintxt = TextAsset(text="YOU WIN!!", width=200, align='center',style='100px Arial', fill=Color(0xff2222,1))
    def __init__(self, position):
        super().__init__(YouWin.youwintxt, position)

class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        # defining of text on screen
        movetxt = TextAsset(text="A to Move Left, D to Move Right", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        jumptxt = TextAsset(text="Space to Jump", width=200, align='center',style='10px Arua==ial',fill=Color(0xff2222,1))
        optxt = TextAsset(text="Left Click to Place Orange Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        bptxt = 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))
        #background
        Sprite(wall, (0,0))
        #entrance sprites
        Sprite(exitbig, (75,450))
        Sprite(exitsmall, (75,450))
        Sprite(doorline, (75,380))
        #goo
        Sprite(goo, (0,650))
        # creation of text
        Sprite(movetxt,(0,0))
        Sprite(jumptxt,(0,10))
        Sprite(optxt, (0,20))
        Sprite(bptxt, (0,30))
        Sprite(resettxt,(0,40))
        # exit sprites
        Sprite(exitbig, (800,100))
        # win door
        WinDoor((0,0))
        Sprite(doorline, (800, 30))
        # assorted platforms
        Sprite(plat,(0,500))
        Sprite(plat,(650,150))
        Platforms((0,500))
        Platforms((650,150))
        # portals and Chell
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))
        # win text
        YouWin((-1000,-1000))

    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/6/2016 2:12:53 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
# colors
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)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

# lines
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)

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

# global variables changed with the classes
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 = 50
        self.y = 410
        self.vx = 0
        self.vy = 0
        self.jump = 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
        self.jumpup = 0
        # all key inputs
        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", "space", self.jumpOff)

    def step(self):
        # move orange portal
        if self.click == 1 and self.alt != 1:
            global cox
            cox = cpx
            global coy
            coy = cpy
            self.click = 0
        # move blue portal
        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

        # win
        if self.collidingWithSprites(WinDoor):
            self.thing = YouWin((400,400))

        # move right and left
        if self.mright == 1:
            self.setImage(0)
            self.x += 2
            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 += -2
            self.y = self.y
        if self.mleft == 0:
            self.x = self.x
            self.y = self.y

        # constantly moving down for gravity
        self.vy += 6
        self.y += self.vy
        self.vy = 0
        # if collliding with platform, go up to counteract the moving down, effectively staying still
        if self.collidingWithSprites(Platforms):
            self.y -= 6
            self.vy = 0
            # jump
            if self.jump == 1:
                self.vy = 0
                for x in range(1,100):
                    self.vy = -100
                    self.vy += 1
                    self.y -= 10 + self.vy

        # death by goo
        if self.y >= 560:
            self.x = 50
            self.y = 410
        # borders
        if self.x <0:
            self.x = 0
        if self.x > 947:
            self.x = 947

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

    def ClickOn(self,event):
        self.click = 1
        global cpx
        cpx = event.x
        global cpy
        cpy = event.y
    def jumpOn(self,event):
        self.jump = 1
    def jumpOff(self,event):
        self.jump = 0
    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 Platforms(Sprite):
    platc=Color(0xB9BDBB,1.0)
    plat=RectangleAsset(250, 1, noline, platc)
    def __init__(self, position):
        super().__init__(Platforms.plat, position)

class WinDoor(Sprite):
    exitsmall=CircleAsset(20, thinline, platc)
    def __init__(self, position):
        super().__init__(WinDoor.exitsmall, position)
        self.x = 800
        self.y = 100

class YouWin(Sprite):
    youwintxt = TextAsset(text="YOU WIN!!", width=200, align='center',style='100px Arial', fill=Color(0xff2222,1))
    def __init__(self, position):
        super().__init__(YouWin.youwintxt, position)

class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        # defining of text on screen
        movetxt = TextAsset(text="A to Move Left, D to Move Right", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        jumptxt = TextAsset(text="Space to Jump", width=200, align='center',style='10px Arua==ial',fill=Color(0xff2222,1))
        optxt = TextAsset(text="Left Click to Place Orange Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        bptxt = 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))
        #background
        Sprite(wall, (0,0))
        #entrance sprites
        Sprite(exitbig, (75,450))
        Sprite(exitsmall, (75,450))
        Sprite(doorline, (75,380))
        #goo
        Sprite(goo, (0,650))
        # creation of text
        Sprite(movetxt,(0,0))
        Sprite(jumptxt,(0,10))
        Sprite(optxt, (0,20))
        Sprite(bptxt, (0,30))
        Sprite(resettxt,(0,40))
        # exit sprites
        Sprite(exitbig, (800,100))
        # win door
        WinDoor((0,0))
        Sprite(doorline, (800, 30))
        # assorted platforms
        Sprite(plat,(0,500))
        Sprite(plat,(650,150))
        Platforms((0,500))
        Platforms((650,150))
        # portals and Chell
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))
        # win text
        YouWin((-1000,-1000))

    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>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield

"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset

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)

class Chell(Sprite):
    asset = ImageAsset("images/Chell1.png")
    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
        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:
            self.x = 500
            self.y = 500
        if self.click == 1 and self.alt ==1:
            self.x = 700
            self.y = 700
        if self.mright == 1:
            self.x += .75
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 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
    def ClickOff(self,event):
        self.click = 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")
    def __init__(self, position):
        super().__init__(self.asset, position)
        self.visible = True
        self.scale = .25
        self.x = 250
        self.y = 250

    def step(self):
        self.x = 500
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))
        BluePortal((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/19/2016 2:48:20 PM<commit_after>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield

"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset

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)

class Chell(Sprite):
    asset = ImageAsset("images/Chell1.png")
    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
        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:
            self.x = 500
            self.y = 500
        if self.click == 1 and self.alt ==1:
            self.x = 700
            self.y = 700
        if self.mright == 1:
            self.x += .75
            self.y = self.y
        if self.mright == 0:
            self.x =self.x
            self.y=self.y
        if self.mleft == 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
    def ClickOff(self,event):
        self.click = 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")
    def __init__(self, position):
        super().__init__(BluePortal.asset, position)
        self.visible = True
        self.scale = .25
        self.x = 250
        self.y = 250

    def step(self):
        self.x = 500

class OrangePortal(Sprite):
    asset = ImageAsset("images/portal___orange_portal_by_maxiesnax-d5pcfmj.png")

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))
        BluePortal((0,0))

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

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