<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 = 0
        self.y = 410
        self.vx = 0
        self.vy = 0
        self.jump1 = 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
        # 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

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

        # constantly moving down for experimenting reasons
        self.vy += .001
        self.y += self.vy

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

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

    def ClickOn(self,event):
        self.click = 1
        global cpx
        cpx = event.x
        global cpy
        cpy = event.y
    def jumpOn(self,event):
        self.jump1 = 1
    def jumpOff(self,event):
        self.jump1 = 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, 50, noline, platc)
    def __init__(self, position):
        super().__init__(Platforms.plat, position)
class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        txt_asset= TextAsset(text="A to Move Left, D to Move Right", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset1= TextAsset(text="Left Click to Place Orange Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset2= TextAsset(text="Alt + Left Click to Place Blue Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        resettxt= TextAsset(text="Press R to reset", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        Sprite(wall, (0,0))
        Sprite(goo, (0,650))
        Sprite(exitbig, (800,100))
        Sprite(exitsmall, (800, 100))
        Sprite(doorline, (800, 30))
        Sprite(plat, (0,500))
        Sprite(plat, (650, 150))
        Sprite(goo, (0,650))
        Sprite(txt_asset,(0,0))
        Sprite(txt_asset1, (0,10))
        Sprite(txt_asset2, (0,20))
        Sprite(resettxt,(0,30))
        Platforms((100,100))
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))

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

myapp = PortalGame(1000,750)
myapp.run()<commit_msg>Updated from Brython Server: 5/4/2016 1:49:26 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 = 0
        self.y = 410
        self.vx = 0
        self.vy = 0
        self.jump1 = 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
        # 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

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

        # constantly moving down for expirementing reasons
        self.vy += .001
        self.y += self.vy

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

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

    def ClickOn(self,event):
        self.click = 1
        global cpx
        cpx = event.x
        global cpy
        cpy = event.y
    def jumpOn(self,event):
        self.jump1 = 1
    def jumpOff(self,event):
        self.jump1 = 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, 50, noline, platc)
    def __init__(self, position):
        super().__init__(Platforms.plat, position)
class PortalGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        txt_asset= TextAsset(text="A to Move Left, D to Move Right", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset1= TextAsset(text="Left Click to Place Orange Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        txt_asset2= TextAsset(text="Alt + Left Click to Place Blue Portal", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        resettxt= TextAsset(text="Press R to reset", width=200, align='center',style='10px Arial', fill=Color(0xff2222,1))
        Sprite(wall, (0,0))
        Sprite(goo, (0,650))
        Sprite(exitbig, (800,100))
        Sprite(exitsmall, (800, 100))
        Sprite(doorline, (800, 30))
        Sprite(plat, (0,500))
        Sprite(plat, (650, 150))
        Sprite(goo, (0,650))
        Sprite(txt_asset,(0,0))
        Sprite(txt_asset1, (0,10))
        Sprite(txt_asset2, (0,20))
        Sprite(resettxt,(0,30))
        Platforms((100,100))
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))

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

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


<commit_before>#!/usr/bin/env python
# @lint-avoid-python-3-compatibility-imports
#
# biosnoop  Trace block device I/O and print details including issuing PID.
#           For Linux, uses BCC, eBPF.
#
# This uses in-kernel eBPF maps to cache process details (PID and comm) by I/O
# request, as well as a starting timestamp for calculating I/O latency.
#
# Copyright (c) 2015 Brendan Gregg.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 16-Sep-2015   Brendan Gregg   Created this.
# 11-Feb-2016   Allan McAleavy  updated for BPF_PERF_OUTPUT
# 21-Jun-2022   Rocky Xing      Added disk filter support.

from __future__ import print_function
from bcc import BPF
import argparse
import os

# arguments
examples = """examples:
    ./biosnoop           # trace all block I/O
    ./biosnoop -Q        # include OS queued time
    ./biolatency -d sdc  # trace sdc only
"""
parser = argparse.ArgumentParser(
    description="Trace block I/O",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    epilog=examples)
parser.add_argument("-Q", "--queue", action="store_true",
    help="include OS queued time")
parser.add_argument("-d", "--disk", type=str,
    help="Trace this disk only")
parser.add_argument("--ebpf", action="store_true",
    help=argparse.SUPPRESS)
args = parser.parse_args()
debug = 0

# define BPF program
bpf_text="""
#include <uapi/linux/ptrace.h>
#include <linux/blk-mq.h>

// for saving the timestamp and __data_len of each request
struct start_req_t {
    u64 ts;
    u64 data_len;
};

struct val_t {
    u64 ts;
    u32 pid;
    char name[TASK_COMM_LEN];
};

struct data_t {
    u32 pid;
    u64 rwflag;
    u64 delta;
    u64 qdelta;
    u64 sector;
    u64 len;
    u64 ts;
    char disk_name[DISK_NAME_LEN];
    char name[TASK_COMM_LEN];
};

BPF_HASH(start, struct request *, struct start_req_t);
BPF_HASH(infobyreq, struct request *, struct val_t);
BPF_PERF_OUTPUT(events);

// cache PID and comm by-req
int trace_pid_start(struct pt_regs *ctx, struct request *req)
{
    DISK_FILTER

    struct val_t val = {};
    u64 ts;

    if (bpf_get_current_comm(&val.name, sizeof(val.name)) == 0) {
        val.pid = bpf_get_current_pid_tgid() >> 32;
        if (##QUEUE##) {
            val.ts = bpf_ktime_get_ns();
        }
        infobyreq.update(&req, &val);
    }
    return 0;
}

// time block I/O
int trace_req_start(struct pt_regs *ctx, struct request *req)
{
    DISK_FILTER

    struct start_req_t start_req = {
        .ts = bpf_ktime_get_ns(),
        .data_len = req->__data_len
    };
    start.update(&req, &start_req);
    return 0;
}

// output
int trace_req_completion(struct pt_regs *ctx, struct request *req)
{
    struct start_req_t *startp;
    struct val_t *valp;
    struct data_t data = {};
    u64 ts;

    // fetch timestamp and calculate delta
    startp = start.lookup(&req);
    if (startp == 0) {
        // missed tracing issue
        return 0;
    }
    ts = bpf_ktime_get_ns();
    data.delta = ts - startp->ts;
    data.ts = ts / 1000;
    data.qdelta = 0;

    valp = infobyreq.lookup(&req);
    data.len = startp->data_len;
    if (valp == 0) {
        data.name[0] = '?';
        data.name[1] = 0;
    } else {
        if (##QUEUE##) {
            data.qdelta = startp->ts - valp->ts;
        }
        data.pid = valp->pid;
        data.sector = req->__sector;
        bpf_probe_read_kernel(&data.name, sizeof(data.name), valp->name);
        struct gendisk *rq_disk = req->__RQ_DISK__;
        bpf_probe_read_kernel(&data.disk_name, sizeof(data.disk_name),
                       rq_disk->disk_name);
    }

/*
 * The following deals with a kernel version change (in mainline 4.7, although
 * it may be backported to earlier kernels) with how block request write flags
 * are tested. We handle both pre- and post-change versions here. Please avoid
 * kernel version tests like this as much as possible: they inflate the code,
 * test, and maintenance burden.
 */
#ifdef REQ_WRITE
    data.rwflag = !!(req->cmd_flags & REQ_WRITE);
#elif defined(REQ_OP_SHIFT)
    data.rwflag = !!((req->cmd_flags >> REQ_OP_SHIFT) == REQ_OP_WRITE);
#else
    data.rwflag = !!((req->cmd_flags & REQ_OP_MASK) == REQ_OP_WRITE);
#endif

    events.perf_submit(ctx, &data, sizeof(data));
    start.delete(&req);
    infobyreq.delete(&req);

    return 0;
}
"""
if args.queue:
    bpf_text = bpf_text.replace('##QUEUE##', '1')
else:
    bpf_text = bpf_text.replace('##QUEUE##', '0')
if BPF.kernel_struct_has_field(b'request', b'rq_disk') == 1:
    bpf_text = bpf_text.replace('__RQ_DISK__', 'rq_disk')
else:
    bpf_text = bpf_text.replace('__RQ_DISK__', 'q->disk')

if args.disk is not None:
    disk_path = os.path.join('/dev', args.disk)
    if not os.path.exists(disk_path):
        print("no such disk '%s'" % args.disk)
        exit(1)

    stat_info = os.stat(disk_path)
    major = os.major(stat_info.st_rdev)
    minor = os.minor(stat_info.st_rdev)

    disk_field_str = ""
    if BPF.kernel_struct_has_field(b'request', b'rq_disk') == 1:
        disk_field_str = 'req->rq_disk'
    else:
        disk_field_str = 'req->q->disk'

    disk_filter_str = """
    struct gendisk *disk = %s;
    if (!(disk->major == %d && disk->first_minor == %d)) {
        return 0;
    }
    """ % (disk_field_str, major, minor)

    bpf_text = bpf_text.replace('DISK_FILTER', disk_filter_str)
else:
    bpf_text = bpf_text.replace('DISK_FILTER', '')

if debug or args.ebpf:
    print(bpf_text)
    if args.ebpf:
        exit()

# initialize BPF
b = BPF(text=bpf_text)
if BPF.get_kprobe_functions(b'__blk_account_io_start'):
    b.attach_kprobe(event="__blk_account_io_start", fn_name="trace_pid_start")
else:
    b.attach_kprobe(event="blk_account_io_start", fn_name="trace_pid_start")
if BPF.get_kprobe_functions(b'blk_start_request'):
    b.attach_kprobe(event="blk_start_request", fn_name="trace_req_start")
else:
    b.attach_kprobe(event="blk_mq_start_request", fn_name="trace_req_start")
if BPF.get_kprobe_functions(b'__blk_account_io_done'):
    b.attach_kprobe(event="__blk_account_io_done", fn_name="trace_req_completion")
else:
    b.attach_kprobe(event="blk_account_io_done", fn_name="trace_req_completion")

# header
print("%-11s %-14s %-7s %-9s %-1s %-10s %-7s" % ("TIME(s)", "COMM", "PID",
    "DISK", "T", "SECTOR", "BYTES"), end="")
if args.queue:
    print("%7s " % ("QUE(ms)"), end="")
print("%7s" % "LAT(ms)")

rwflg = ""
start_ts = 0
prev_ts = 0
delta = 0

# process event
def print_event(cpu, data, size):
    event = b["events"].event(data)

    global start_ts
    if start_ts == 0:
        start_ts = event.ts

    if event.rwflag == 1:
        rwflg = "W"
    else:
        rwflg = "R"

    delta = float(event.ts) - start_ts

    disk_name = event.disk_name.decode('utf-8', 'replace')
    if not disk_name:
        disk_name = '<unknown>'

    print("%-11.6f %-14.14s %-7s %-9s %-1s %-10s %-7s" % (
        delta / 1000000, event.name.decode('utf-8', 'replace'), event.pid,
        disk_name, rwflg, event.sector, event.len), end="")
    if args.queue:
        print("%7.2f " % (float(event.qdelta) / 1000000), end="")
    print("%7.2f" % (float(event.delta) / 1000000))

# loop with callback to print_event
b["events"].open_perf_buffer(print_event, page_cnt=64)
while 1:
    try:
        b.perf_buffer_poll()
    except KeyboardInterrupt:
        exit()
<commit_msg>[biosnoop] Revert #4124<commit_after>#!/usr/bin/env python
# @lint-avoid-python-3-compatibility-imports
#
# biosnoop  Trace block device I/O and print details including issuing PID.
#           For Linux, uses BCC, eBPF.
#
# This uses in-kernel eBPF maps to cache process details (PID and comm) by I/O
# request, as well as a starting timestamp for calculating I/O latency.
#
# Copyright (c) 2015 Brendan Gregg.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 16-Sep-2015   Brendan Gregg   Created this.
# 11-Feb-2016   Allan McAleavy  updated for BPF_PERF_OUTPUT
# 21-Jun-2022   Rocky Xing      Added disk filter support.

from __future__ import print_function
from bcc import BPF
import argparse
import os

# arguments
examples = """examples:
    ./biosnoop           # trace all block I/O
    ./biosnoop -Q        # include OS queued time
    ./biolatency -d sdc  # trace sdc only
"""
parser = argparse.ArgumentParser(
    description="Trace block I/O",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    epilog=examples)
parser.add_argument("-Q", "--queue", action="store_true",
    help="include OS queued time")
parser.add_argument("-d", "--disk", type=str,
    help="Trace this disk only")
parser.add_argument("--ebpf", action="store_true",
    help=argparse.SUPPRESS)
args = parser.parse_args()
debug = 0

# define BPF program
bpf_text="""
#include <uapi/linux/ptrace.h>
#include <linux/blk-mq.h>

// for saving the timestamp and __data_len of each request
struct start_req_t {
    u64 ts;
    u64 data_len;
};

struct val_t {
    u64 ts;
    u32 pid;
    char name[TASK_COMM_LEN];
};

struct data_t {
    u32 pid;
    u64 rwflag;
    u64 delta;
    u64 qdelta;
    u64 sector;
    u64 len;
    u64 ts;
    char disk_name[DISK_NAME_LEN];
    char name[TASK_COMM_LEN];
};

BPF_HASH(start, struct request *, struct start_req_t);
BPF_HASH(infobyreq, struct request *, struct val_t);
BPF_PERF_OUTPUT(events);

// cache PID and comm by-req
int trace_pid_start(struct pt_regs *ctx, struct request *req)
{
    DISK_FILTER

    struct val_t val = {};
    u64 ts;

    if (bpf_get_current_comm(&val.name, sizeof(val.name)) == 0) {
        val.pid = bpf_get_current_pid_tgid() >> 32;
        if (##QUEUE##) {
            val.ts = bpf_ktime_get_ns();
        }
        infobyreq.update(&req, &val);
    }
    return 0;
}

// time block I/O
int trace_req_start(struct pt_regs *ctx, struct request *req)
{
    DISK_FILTER

    struct start_req_t start_req = {
        .ts = bpf_ktime_get_ns(),
        .data_len = req->__data_len
    };
    start.update(&req, &start_req);
    return 0;
}

// output
int trace_req_completion(struct pt_regs *ctx, struct request *req)
{
    struct start_req_t *startp;
    struct val_t *valp;
    struct data_t data = {};
    u64 ts;

    // fetch timestamp and calculate delta
    startp = start.lookup(&req);
    if (startp == 0) {
        // missed tracing issue
        return 0;
    }
    ts = bpf_ktime_get_ns();
    data.delta = ts - startp->ts;
    data.ts = ts / 1000;
    data.qdelta = 0;

    valp = infobyreq.lookup(&req);
    data.len = startp->data_len;
    if (valp == 0) {
        data.name[0] = '?';
        data.name[1] = 0;
    } else {
        if (##QUEUE##) {
            data.qdelta = startp->ts - valp->ts;
        }
        data.pid = valp->pid;
        data.sector = req->__sector;
        bpf_probe_read_kernel(&data.name, sizeof(data.name), valp->name);
        struct gendisk *rq_disk = req->__RQ_DISK__;
        bpf_probe_read_kernel(&data.disk_name, sizeof(data.disk_name),
                       rq_disk->disk_name);
    }

/*
 * The following deals with a kernel version change (in mainline 4.7, although
 * it may be backported to earlier kernels) with how block request write flags
 * are tested. We handle both pre- and post-change versions here. Please avoid
 * kernel version tests like this as much as possible: they inflate the code,
 * test, and maintenance burden.
 */
#ifdef REQ_WRITE
    data.rwflag = !!(req->cmd_flags & REQ_WRITE);
#elif defined(REQ_OP_SHIFT)
    data.rwflag = !!((req->cmd_flags >> REQ_OP_SHIFT) == REQ_OP_WRITE);
#else
    data.rwflag = !!((req->cmd_flags & REQ_OP_MASK) == REQ_OP_WRITE);
#endif

    events.perf_submit(ctx, &data, sizeof(data));
    start.delete(&req);
    infobyreq.delete(&req);

    return 0;
}
"""
if args.queue:
    bpf_text = bpf_text.replace('##QUEUE##', '1')
else:
    bpf_text = bpf_text.replace('##QUEUE##', '0')
if BPF.kernel_struct_has_field(b'request', b'rq_disk') == 1:
    bpf_text = bpf_text.replace('__RQ_DISK__', 'rq_disk')
else:
    bpf_text = bpf_text.replace('__RQ_DISK__', 'q->disk')

if args.disk is not None:
    disk_path = os.path.join('/dev', args.disk)
    if not os.path.exists(disk_path):
        print("no such disk '%s'" % args.disk)
        exit(1)

    stat_info = os.stat(disk_path)
    major = os.major(stat_info.st_rdev)
    minor = os.minor(stat_info.st_rdev)

    disk_field_str = ""
    if BPF.kernel_struct_has_field(b'request', b'rq_disk') == 1:
        disk_field_str = 'req->rq_disk'
    else:
        disk_field_str = 'req->q->disk'

    disk_filter_str = """
    struct gendisk *disk = %s;
    if (!(disk->major == %d && disk->first_minor == %d)) {
        return 0;
    }
    """ % (disk_field_str, major, minor)

    bpf_text = bpf_text.replace('DISK_FILTER', disk_filter_str)
else:
    bpf_text = bpf_text.replace('DISK_FILTER', '')

if debug or args.ebpf:
    print(bpf_text)
    if args.ebpf:
        exit()

# initialize BPF
b = BPF(text=bpf_text)
if BPF.get_kprobe_functions(b'__blk_account_io_start'):
    b.attach_kprobe(event="__blk_account_io_start", fn_name="trace_pid_start")
else:
    b.attach_kprobe(event="blk_account_io_start", fn_name="trace_pid_start")
if BPF.get_kprobe_functions(b'blk_start_request'):
    b.attach_kprobe(event="blk_start_request", fn_name="trace_req_start")
b.attach_kprobe(event="blk_mq_start_request", fn_name="trace_req_start")
if BPF.get_kprobe_functions(b'__blk_account_io_done'):
    b.attach_kprobe(event="__blk_account_io_done", fn_name="trace_req_completion")
else:
    b.attach_kprobe(event="blk_account_io_done", fn_name="trace_req_completion")

# header
print("%-11s %-14s %-7s %-9s %-1s %-10s %-7s" % ("TIME(s)", "COMM", "PID",
    "DISK", "T", "SECTOR", "BYTES"), end="")
if args.queue:
    print("%7s " % ("QUE(ms)"), end="")
print("%7s" % "LAT(ms)")

rwflg = ""
start_ts = 0
prev_ts = 0
delta = 0

# process event
def print_event(cpu, data, size):
    event = b["events"].event(data)

    global start_ts
    if start_ts == 0:
        start_ts = event.ts

    if event.rwflag == 1:
        rwflg = "W"
    else:
        rwflg = "R"

    delta = float(event.ts) - start_ts

    disk_name = event.disk_name.decode('utf-8', 'replace')
    if not disk_name:
        disk_name = '<unknown>'

    print("%-11.6f %-14.14s %-7s %-9s %-1s %-10s %-7s" % (
        delta / 1000000, event.name.decode('utf-8', 'replace'), event.pid,
        disk_name, rwflg, event.sector, event.len), end="")
    if args.queue:
        print("%7.2f " % (float(event.qdelta) / 1000000), end="")
    print("%7.2f" % (float(event.delta) / 1000000))

# loop with callback to print_event
b["events"].open_perf_buffer(print_event, page_cnt=64)
while 1:
    try:
        b.perf_buffer_poll()
    except KeyboardInterrupt:
        exit()
<|endoftext|>


<commit_before>import json

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

from crypto import get_public_bytestring
from orderbook import (match_incoming_ask, match_incoming_bid,
        trades, offers, get_offer, remove_offer,
        trade_offer, create_confirm, create_cancel, create_greeting_response)
from utils import print_all_offers

class Trader(DatagramProtocol):
    def __init__(self, name):
        self.name = name
        self.history = {}
        self.peers = {}

    def startProtocol(self):
        self.read_peerlist()

    def stopProtocol(self):
        pass

    def datagramReceived(self, data, (host, port)):
        real_data = json.loads(data)

        if real_data['message-id'] not in self.history:
            self.handle_data(data, host, port)
            self.relay_message(data)
            self.history[real_data['message-id']] = True
            print_all_offers()
        else:
            print "Duplicate message received. ID:%d" % real_data['message-id']

    def relay_message(self, message):
        for address in self.peers:
            self.transport.write(message, (address, int(self.peers[address])))

    def read_peerlist(self):
        peer_dict = {}
        with open("peerlist.txt") as f:
            for line in f:
                (address, port) = line.split(':')
                peer_dict[address] = port
        return peer_dict

    def add_to_peerlist(self, host, port):
        with open("peerlist.txt", "a") as f:
            new_peer = host + ":" + str(port)
            f.write(new_peer)

    def handle_data(self, data, host='127.0.0.1', port=8005):
        try:
            data = json.loads(data)

            responses = {
                'ask': self.handle_ask,
                'bid': self.handle_bid,
                'greeting': self.handle_greeting,
                'greeting_response': self.handle_greeting_response,
                'trade': self.handle_trade,
                'confirm': self.handle_confirm,
                'cancel': self.handle_cancel
            }

            if data['type'] == 'greeting':
                response = self.handle_greeting(host, port)
            else:
                response = responses[data['type']](data)
            return json.dumps(response), data['type']
        except ValueError, e:
            print e.message
            return e.message

    def handle_ask(self, ask):
        bid = match_incoming_ask(ask)
        if bid:
            return trade_offer(ask, bid)
        else:
            offers.append(ask)
            return 'Your ask got processed!'

    def handle_bid(self, bid):
        ask = match_incoming_bid(bid)
        if ask:
            return trade_offer(bid, ask)
        else:
            offers.append(bid)
            return "Your bid got processed!"

    def handle_trade(self, trade):
        id, trade_id = get_public_bytestring(), trade['trade-id']
        offer = get_offer(id=id, message_id=trade_id)
        if offer:
            remove_offer(id=id, message_id=trade_id)
            trades.append(offer)
            return create_confirm(recipient=trade['id'], trade_id=trade_id)
        else:
            return create_cancel(recipient=trade['id'], trade_id=trade_id)

    def handle_confirm(self, confirm):
        offer = remove_offer(id=confirm['id'], message_id=confirm['trade_id'])
        trades.append(offer)
        return 'Trade succesful!'

    def handle_cancel(self, cancel):
        remove_offer(id=cancel['id'], message_id=cancel['trade_id'])
        return 'Trade cancelled'

    def handle_greeting(self, host, port):
        peer_list = self.read_peerlist()
        if host not in peer_list:
            self.add_to_peerlist(host, str(port) + "\n")

        msg = create_greeting_response(peer_list)
        msg = json.dumps(msg)
        self.transport.write(msg, (host, port))
        print "Greeting received from " + host + ":" + str(port)
        return 'Peerlist sent'

    def handle_greeting_response(self, data):
        self.read_peerlist()
        self.peers.update(data['peerlist'])
        for key, value in self.peers.iteritems():
            self.add_to_peerlist(key, value)
        print self.peers
        return 'Peers added'

reactor.listenMulticast(8005, Trader("listener1"), listenMultiple=True)
reactor.run()
<commit_msg>Use list.remove instead of custom remove function.<commit_after>import json

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

from crypto import get_public_bytestring
from orderbook import (match_incoming_ask, match_incoming_bid,
        trades, offers, get_offer, remove_offer,
        trade_offer, create_confirm, create_cancel, create_greeting_response)
from utils import print_all_offers

class Trader(DatagramProtocol):
    def __init__(self, name):
        self.name = name
        self.history = {}
        self.peers = {}

    def startProtocol(self):
        self.read_peerlist()

    def stopProtocol(self):
        pass

    def datagramReceived(self, data, (host, port)):
        real_data = json.loads(data)

        if real_data['message-id'] not in self.history:
            self.handle_data(data, host, port)
            self.relay_message(data)
            self.history[real_data['message-id']] = True
            print_all_offers()
        else:
            print "Duplicate message received. ID:%d" % real_data['message-id']

    def relay_message(self, message):
        for address in self.peers:
            self.transport.write(message, (address, int(self.peers[address])))

    def read_peerlist(self):
        peer_dict = {}
        with open("peerlist.txt") as f:
            for line in f:
                (address, port) = line.split(':')
                peer_dict[address] = port
        return peer_dict

    def add_to_peerlist(self, host, port):
        with open("peerlist.txt", "a") as f:
            new_peer = host + ":" + str(port)
            f.write(new_peer)

    def handle_data(self, data, host='127.0.0.1', port=8005):
        try:
            data = json.loads(data)

            responses = {
                'ask': self.handle_ask,
                'bid': self.handle_bid,
                'greeting': self.handle_greeting,
                'greeting_response': self.handle_greeting_response,
                'trade': self.handle_trade,
                'confirm': self.handle_confirm,
                'cancel': self.handle_cancel
            }

            if data['type'] == 'greeting':
                response = self.handle_greeting(host, port)
            else:
                response = responses[data['type']](data)
            return json.dumps(response), data['type']
        except ValueError, e:
            print e.message
            return e.message

    def handle_ask(self, ask):
        bid = match_incoming_ask(ask)
        if bid:
            return trade_offer(ask, bid)
        else:
            offers.append(ask)
            return 'Your ask got processed!'

    def handle_bid(self, bid):
        ask = match_incoming_bid(bid)
        if ask:
            return trade_offer(bid, ask)
        else:
            offers.append(bid)
            return "Your bid got processed!"

    def handle_trade(self, trade):
        id, trade_id = get_public_bytestring(), trade['trade-id']
        offer = get_offer(id=id, message_id=trade_id)
        if offer:
            offers.remove(offer)
            trades.append(offer)
            return create_confirm(recipient=trade['id'], trade_id=trade_id)
        else:
            return create_cancel(recipient=trade['id'], trade_id=trade_id)

    def handle_confirm(self, confirm):
        offer = remove_offer(id=confirm['id'], message_id=confirm['trade_id'])
        trades.append(offer)
        return 'Trade succesful!'

    def handle_cancel(self, cancel):
        remove_offer(id=cancel['id'], message_id=cancel['trade_id'])
        return 'Trade cancelled'

    def handle_greeting(self, host, port):
        peer_list = self.read_peerlist()
        if host not in peer_list:
            self.add_to_peerlist(host, str(port) + "\n")

        msg = create_greeting_response(peer_list)
        msg = json.dumps(msg)
        self.transport.write(msg, (host, port))
        print "Greeting received from " + host + ":" + str(port)
        return 'Peerlist sent'

    def handle_greeting_response(self, data):
        self.read_peerlist()
        self.peers.update(data['peerlist'])
        for key, value in self.peers.iteritems():
            self.add_to_peerlist(key, value)
        print self.peers
        return 'Peers added'

reactor.listenMulticast(8005, Trader("listener1"), listenMultiple=True)
reactor.run()
<|endoftext|>


<commit_before>#!/usr/bin/python

# Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

"""
Pub buildbot steps.

Runs tests for pub and the pub packages that are hosted in the main Dart repo.
"""

import re
import sys

import bot

PUB_BUILDER = r'pub-(linux|mac|win)(-(russian))?(-(debug))?'

def PubConfig(name, is_buildbot):
  """Returns info for the current buildbot based on the name of the builder.

  Currently, this is just:
  - mode: "debug", "release"
  - system: "linux", "mac", or "win"
  """
  pub_pattern = re.match(PUB_BUILDER, name)
  if not pub_pattern:
    return None

  system = pub_pattern.group(1)
  locale = pub_pattern.group(3)
  mode = pub_pattern.group(5) or 'release'
  if system == 'win': system = 'windows'

  return bot.BuildInfo('none', 'vm', mode, system, checked=True,
                       builder_tag=locale)

def PubSteps(build_info):
  with bot.BuildStep('Build package-root'):
    args = [sys.executable, './tools/build.py', '--mode=' + build_info.mode,
            'packages']
    print 'Building package-root: %s' % (' '.join(args))
    bot.RunProcess(args)

  common_args = ['--write-test-outcome-log']
  if build_info.builder_tag:
    common_args.append('--builder-tag=%s' % build_info.builder_tag)

  # Pub tests currently have a lot of timeouts when run in debug mode.
  # See issue 18479
  if build_info.mode == 'release':
    bot.RunTest('pub', build_info,
                common_args + ['pub', 'pkg', 'docs'])

  pkgbuild_build_info = bot.BuildInfo('none', 'vm', build_info.mode,
      build_info.system, checked=False)
  bot.RunTest('pkgbuild_repo_pkgs', pkgbuild_build_info,
      common_args + ['--append_logs', '--use-repository-packages', 'pkgbuild'])
  bot.RunTest('pkgbuild_public_pkgs', pkgbuild_build_info,
      common_args + ['--append_logs', '--use-public-packages', 'pkgbuild'])

if __name__ == '__main__':
  bot.RunBot(PubConfig, PubSteps)
<commit_msg>Change what we run on pub debug bots<commit_after>#!/usr/bin/python

# Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

"""
Pub buildbot steps.

Runs tests for pub and the pub packages that are hosted in the main Dart repo.
"""

import re
import sys

import bot

PUB_BUILDER = r'pub-(linux|mac|win)(-(russian))?(-(debug))?'

def PubConfig(name, is_buildbot):
  """Returns info for the current buildbot based on the name of the builder.

  Currently, this is just:
  - mode: "debug", "release"
  - system: "linux", "mac", or "win"
  """
  pub_pattern = re.match(PUB_BUILDER, name)
  if not pub_pattern:
    return None

  system = pub_pattern.group(1)
  locale = pub_pattern.group(3)
  mode = pub_pattern.group(5) or 'release'
  if system == 'win': system = 'windows'

  return bot.BuildInfo('none', 'vm', mode, system, checked=True,
                       builder_tag=locale)

def PubSteps(build_info):
  with bot.BuildStep('Build package-root'):
    args = [sys.executable, './tools/build.py', '--mode=' + build_info.mode,
            'packages']
    print 'Building package-root: %s' % (' '.join(args))
    bot.RunProcess(args)

  common_args = ['--write-test-outcome-log']
  if build_info.builder_tag:
    common_args.append('--builder-tag=%s' % build_info.builder_tag)

  # Pub tests currently have a lot of timeouts when run in debug mode.
  # See issue 18479
  if build_info.mode == 'release':
    bot.RunTest('pub', build_info,
                common_args + ['pub', 'pkg', 'docs'])
  else:
    bot.RunTest('pub', build_info,
                common_args + ['pkg', 'docs'])

  if build_info.mode == 'release':
    pkgbuild_build_info = bot.BuildInfo('none', 'vm', build_info.mode,
                                        build_info.system, checked=False)
    bot.RunTest('pkgbuild_repo_pkgs', pkgbuild_build_info,
        common_args + ['--append_logs', '--use-repository-packages',
                       'pkgbuild'])
    bot.RunTest('pkgbuild_public_pkgs', pkgbuild_build_info,
        common_args + ['--append_logs', '--use-public-packages', 'pkgbuild'])

if __name__ == '__main__':
  bot.RunBot(PubConfig, PubSteps)
<|endoftext|>


<commit_before>"""This module contains a prototype implementation of the
TT-cross-based minimization procedure
"""
import numpy as np
import math
import sys
from maxvol import maxvol
from rect_maxvol import rect_maxvol

def reshape(a, sz):
    return np.reshape(a, sz, order = 'F')

def mkron(a, b):
    return np.kron(a, b)

def mysvd(a, full_matrices=False):
    try:
        return np.linalg.svd(a, full_matrices)
    except:
        return np.linalg.svd(a + np.max(np.abs(a).flatten()) * 1e-14 * np.random.randn(a.shape[0], a.shape[1]), full_matrices)

def tt_min(fun, bounds_min, bounds_max, d = None, rmax = 10, tol = 1e-3, n0 = 64, nswp = 10, verb=True, smooth_fun=None):
    if d is None:
        d = len(bounds_min)
        a = np.asanyarray(bounds_min).copy()
        b = np.asanyarray(bounds_max).copy()
    else:
        a = np.ones(d) * bounds_min
        b = np.ones(d) * bounds_max

    if smooth_fun is None:
       smooth_fun = lambda p, lam: (math.pi/2 - np.arctan(p - lam))
    #smooth_fun = lambda p, lam: np.exp(-10*(p - lam))

        #We do not need to store the cores, only the interfaces!
    Rx = [[]] * (d + 1) #Python list for the interfaces
    Rx[0] = np.ones((1, 1))
    Rx[d] = np.ones((1, 1))
    Jy = [np.empty(0)] * (d + 1)
    ry = rmax * np.ones(d + 1, dtype = np.int)
    ry[0] = 1
    ry[d] = 1
    n = n0 * np.ones(d, dtype = np.int)
    fun_evals = 0

    grid = [np.reshape(np.linspace(a[i], b[i], n[i]),(n[i], 1)) for i in xrange(d)]
    for i in xrange(d - 1):
        #cr1 = y[i]
        ry[i + 1] = min(ry[i + 1], n[i] * ry[i])
        cr1 = np.random.randn(ry[i], n[i], ry[i + 1])
        cr1 = reshape(cr1, (ry[i] * n[i], ry[i + 1]))
        q, r = np.linalg.qr(cr1)
        ind = maxvol(q)
        w1 = mkron(np.ones((n[i], 1)), Jy[i])
        w2 = mkron(grid[i], np.ones((ry[i], 1)))
        Jy[i + 1] = np.hstack((w1, w2))
        Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
        Jy[i + 1] = Jy[i + 1][ind, :]

        #Jy{i+1} = [kron(ones(n(i),1), Jy{i}), kron((1:n(i))', ones(ry(i),1))];
        #Jy{i+1} = Jy{i+1}(ind,:);
    swp = 0
    dirn = -1
    i = d - 1
    lm = 999999999999
    while swp < nswp:
        #Right-to-left sweep
        #The idea: compute the current core; compute the function of it;
        #Shift locally or globally? Local shift would be the first try
        #Compute the current core

        if np.size(Jy[i]) == 0:
            w1 = np.zeros((ry[i] * n[i] * ry[i + 1], 0))
        else:
            w1 = mkron(np.ones((n[i] * ry[i + 1], 1)), Jy[i])
        w2 = mkron(mkron(np.ones((ry[i + 1], 1)), grid[i]), np.ones((ry[i], 1)))
        if np.size(Jy[i + 1]) == 0:
            w3 = np.zeros((ry[i] * n[i] * ry[i + 1], 0))
        else:
            w3 = mkron(Jy[i + 1], np.ones((ry[i] * n[i], 1)))

        J = np.hstack((w1, w2, w3))
        #Just add some random indices to J, which is rnr x d, need to make rn (r + r0) x add,
        #i.e., just generate random r, random n and random multiindex

        cry = fun(J)
        fun_evals += cry.size
        cry = reshape(cry, (ry[i], n[i], ry[i + 1]))
        min_cur = np.min(cry.flatten("F"))
        ind_cur = np.argmin(cry.flatten("F"))
        if lm > min_cur:
            lm = min_cur
            x_full = J[ind_cur, :]
            val = fun(x_full)
            if verb:
                print 'New record:', val, 'Point:', x_full, 'fevals:', fun_evals
        cry = smooth_fun(cry, lm)
        if ( dirn < 0 and i > 0):
            cry = reshape(cry, (ry[i], n[i] * ry[i + 1]))
            cry = cry.T
            #q, r = np.linalg.qr(cry)
            u, s, v = mysvd(cry, full_matrices=False)
            ry[i] = min(ry[i], rmax)
            q = u[:, :ry[i]]
            ind = rect_maxvol(q)[0]#maxvol(q)
            ry[i] = ind.size
            w1 = mkron(np.ones((ry[i + 1], 1)), grid[i])
            if np.size(Jy[i + 1]) == 0:
                w2 = np.zeros((n[i] * ry[i + 1], 0))
            else:
                w2 = mkron(Jy[i + 1], np.ones((n[i], 1)))
            Jy[i] = np.hstack((w1, w2))
            Jy[i] = reshape(Jy[i], (n[i] * ry[i + 1], -1))
            Jy[i] = Jy[i][ind, :]

        if ( dirn > 0 and i < d - 1):
            cry = reshape(cry, (ry[i] * n[i], ry[i + 1]))
            q, r = np.linalg.qr(cry)
            #ind = maxvol(q)
            ind = rect_maxvol(q)[0]
            ry[i + 1] = ind.size
            w1 = mkron(np.ones((n[i], 1)), Jy[i])
            w2 = mkron(grid[i], np.ones((ry[i], 1)))
            Jy[i + 1] = np.hstack((w1, w2))
            Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
            Jy[i + 1] = Jy[i + 1][ind, :]

        i += dirn
        if i == d or i == -1:
            dirn = -dirn
            i += dirn
            swp = swp + 1
    return val, x_full

<commit_msg>Add tensor version of the tt_min<commit_after>"""This module contains a prototype implementation of the
TT-cross-based minimization procedure
"""
import numpy as np
import math
import sys
from maxvol import maxvol
from rect_maxvol import rect_maxvol

def reshape(a, sz):
    return np.reshape(a, sz, order = 'F')

def mkron(a, b):
    return np.kron(a, b)

def mysvd(a, full_matrices=False):
    try:
        return np.linalg.svd(a, full_matrices)
    except:
        return np.linalg.svd(a + np.max(np.abs(a).flatten()) * 1e-14 * np.random.randn(a.shape[0], a.shape[1]), full_matrices)

def tt_min(fun, bounds_min, bounds_max, d = None, rmax = 10, tol = 1e-3, n0 = 64, nswp = 10, verb=True, smooth_fun=None):
    if d is None:
        d = len(bounds_min)
        a = np.asanyarray(bounds_min).copy()
        b = np.asanyarray(bounds_max).copy()
    else:
        a = np.ones(d) * bounds_min
        b = np.ones(d) * bounds_max

    if smooth_fun is None:
       smooth_fun = lambda p, lam: (math.pi/2 - np.arctan(p - lam))
    #smooth_fun = lambda p, lam: np.exp(-10*(p - lam))

        #We do not need to store the cores, only the interfaces!
    Rx = [[]] * (d + 1) #Python list for the interfaces
    Rx[0] = np.ones((1, 1))
    Rx[d] = np.ones((1, 1))
    Jy = [np.empty(0)] * (d + 1)
    ry = rmax * np.ones(d + 1, dtype = np.int)
    ry[0] = 1
    ry[d] = 1
    n = n0 * np.ones(d, dtype = np.int)
    fun_evals = 0

    grid = [np.reshape(np.linspace(a[i], b[i], n[i]),(n[i], 1)) for i in xrange(d)]
    for i in xrange(d - 1):
        #cr1 = y[i]
        ry[i + 1] = min(ry[i + 1], n[i] * ry[i])
        cr1 = np.random.randn(ry[i], n[i], ry[i + 1])
        cr1 = reshape(cr1, (ry[i] * n[i], ry[i + 1]))
        q, r = np.linalg.qr(cr1)
        ind = maxvol(q)
        w1 = mkron(np.ones((n[i], 1)), Jy[i])
        w2 = mkron(grid[i], np.ones((ry[i], 1)))
        Jy[i + 1] = np.hstack((w1, w2))
        Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
        Jy[i + 1] = Jy[i + 1][ind, :]

        #Jy{i+1} = [kron(ones(n(i),1), Jy{i}), kron((1:n(i))', ones(ry(i),1))];
        #Jy{i+1} = Jy{i+1}(ind,:);
    swp = 0
    dirn = -1
    i = d - 1
    lm = 999999999999
    while swp < nswp:
        #Right-to-left sweep
        #The idea: compute the current core; compute the function of it;
        #Shift locally or globally? Local shift would be the first try
        #Compute the current core

        if np.size(Jy[i]) == 0:
            w1 = np.zeros((ry[i] * n[i] * ry[i + 1], 0))
        else:
            w1 = mkron(np.ones((n[i] * ry[i + 1], 1)), Jy[i])
        w2 = mkron(mkron(np.ones((ry[i + 1], 1)), grid[i]), np.ones((ry[i], 1)))
        if np.size(Jy[i + 1]) == 0:
            w3 = np.zeros((ry[i] * n[i] * ry[i + 1], 0))
        else:
            w3 = mkron(Jy[i + 1], np.ones((ry[i] * n[i], 1)))

        J = np.hstack((w1, w2, w3))
        #Just add some random indices to J, which is rnr x d, need to make rn (r + r0) x add,
        #i.e., just generate random r, random n and random multiindex

        cry = fun(J)
        fun_evals += cry.size
        cry = reshape(cry, (ry[i], n[i], ry[i + 1]))
        min_cur = np.min(cry.flatten("F"))
        ind_cur = np.argmin(cry.flatten("F"))
        if lm > min_cur:
            lm = min_cur
            x_full = J[ind_cur, :]
            val = fun(x_full)
            if verb:
                print 'New record:', val, 'Point:', x_full, 'fevals:', fun_evals
        cry = smooth_fun(cry, lm)
        if ( dirn < 0 and i > 0):
            cry = reshape(cry, (ry[i], n[i] * ry[i + 1]))
            cry = cry.T
            #q, r = np.linalg.qr(cry)
            u, s, v = mysvd(cry, full_matrices=False)
            ry[i] = min(ry[i], rmax)
            q = u[:, :ry[i]]
            ind = rect_maxvol(q)[0]#maxvol(q)
            ry[i] = ind.size
            w1 = mkron(np.ones((ry[i + 1], 1)), grid[i])
            if np.size(Jy[i + 1]) == 0:
                w2 = np.zeros((n[i] * ry[i + 1], 0))
            else:
                w2 = mkron(Jy[i + 1], np.ones((n[i], 1)))
            Jy[i] = np.hstack((w1, w2))
            Jy[i] = reshape(Jy[i], (n[i] * ry[i + 1], -1))
            Jy[i] = Jy[i][ind, :]

        if ( dirn > 0 and i < d - 1):
            cry = reshape(cry, (ry[i] * n[i], ry[i + 1]))
            q, r = np.linalg.qr(cry)
            #ind = maxvol(q)
            ind = rect_maxvol(q)[0]
            ry[i + 1] = ind.size
            w1 = mkron(np.ones((n[i], 1)), Jy[i])
            w2 = mkron(grid[i], np.ones((ry[i], 1)))
            Jy[i + 1] = np.hstack((w1, w2))
            Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
            Jy[i + 1] = Jy[i + 1][ind, :]

        i += dirn
        if i == d or i == -1:
            dirn = -dirn
            i += dirn
            swp = swp + 1
    return val, x_full

def tt_min_tens(tens, rmax = 10, tol = 1e-3, nswp = 10, verb=True, smooth_fun=None):
    """Find (approximate) minima\l element in a TT-tensor."""
    if smooth_fun is None:
       smooth_fun = lambda p, lam: (math.pi/2 - np.arctan(p - lam))
    d = tens.d
    Rx = [[]] * (d + 1) #Python list for the interfaces
    Rx[0] = np.ones((1, 1))
    Rx[d] = np.ones((1, 1))
    Jy = [np.empty(0)] * (d + 1)
    ry = rmax * np.ones(d + 1, dtype=np.int)
    ry[0] = 1
    ry[d] = 1
    n = tens.n
    fun_evals = 0
    phi_left = [np.empty(0)] * (d + 1)
    phi_left[0] = np.array([1])
    phi_right = [np.empty(0)] * (d + 1)
    phi_right[d] = np.array([1])
    cores = tt.tensor.to_list(tens)

    grid = [np.reshape(range(n[i]), (n[i], 1)) for i in xrange(d)]
    for i in xrange(d - 1):
        ry[i + 1] = min(ry[i + 1], n[i] * ry[i])
        ind = sorted(np.random.permutation(ry[i] * n[i])[0:ry[i + 1]])
        w1 = mkron(np.ones((n[i], 1)), Jy[i])
        w2 = mkron(grid[i], np.ones((ry[i], 1)))
        Jy[i + 1] = np.hstack((w1, w2))
        Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
        Jy[i + 1] = Jy[i + 1][ind, :]
        phi_left[i + 1] = np.tensordot(phi_left[i], cores[i], 1)
        phi_left[i + 1] = reshape(phi_left[i + 1], (ry[i] * n[i], -1))
        phi_left[i + 1] = phi_left[i + 1][ind, :]
    swp = 0
    dirn = -1
    i = d - 1
    lm = 999999999999
    while swp < nswp:
        #Right-to-left sweep
        #The idea: compute the current core; compute the function of it;
        #Shift locally or globally? Local shift would be the first try
        #Compute the current core

        if np.size(Jy[i]) == 0:
            w1 = np.zeros((ry[i] * n[i] * ry[i + 1], 0))
        else:
            w1 = mkron(np.ones((n[i] * ry[i + 1], 1)), Jy[i])
        w2 = mkron(mkron(np.ones((ry[i + 1], 1)), grid[i]), np.ones((ry[i], 1)))
        if np.size(Jy[i + 1]) == 0:
            w3 = np.zeros((ry[i] * n[i] * ry[i + 1], 0))
        else:
            w3 = mkron(Jy[i + 1], np.ones((ry[i] * n[i], 1)))

        phi_right[i] = np.tensordot(cores[i], phi_right[i + 1], 1)
        phi_right[i] = reshape(phi_right[i], (-1, n[i] * ry[i + 1]))

        J = np.hstack((w1, w2, w3))
        #Just add some random indices to J, which is rnr x d, need to make rn (r + r0) x add,
        #i.e., just generate random r, random n and random multiindex

        cry = np.tensordot(phi_left[i], np.tensordot(cores[i], phi_right[i + 1], 1), 1)
        fun_evals += cry.size
        cry = reshape(cry, (ry[i], n[i], ry[i + 1]))
        min_cur = np.min(cry.flatten("F"))
        ind_cur = np.argmin(cry.flatten("F"))
        if lm > min_cur:
            lm = min_cur
            x_full = J[ind_cur, :]
            val = tens[x_full]
            if verb:
                print 'New record:', val, 'Point:', x_full, 'fevals:', fun_evals
        cry = smooth_fun(cry, lm)
        if dirn < 0 and i > 0:
            cry = reshape(cry, (ry[i], n[i] * ry[i + 1]))
            cry = cry.T
            #q, r = np.linalg.qr(cry)
            u, s, v = mysvd(cry, full_matrices=False)
            ry[i] = min(ry[i], rmax)
            q = u[:, :ry[i]]
            ind = rect_maxvol(q)[0]#maxvol(q)
            ry[i] = ind.size
            w1 = mkron(np.ones((ry[i + 1], 1)), grid[i])
            if np.size(Jy[i + 1]) == 0:
                w2 = np.zeros((n[i] * ry[i + 1], 0))
            else:
                w2 = mkron(Jy[i + 1], np.ones((n[i], 1)))
            Jy[i] = np.hstack((w1, w2))
            Jy[i] = reshape(Jy[i], (n[i] * ry[i + 1], -1))
            Jy[i] = Jy[i][ind, :]
            phi_right[i] = np.tensordot(cores[i], phi_right[i + 1], 1)
            phi_right[i] = reshape(phi_right[i], (-1, n[i] * ry[i + 1]))
            phi_right[i] = phi_right[i][:, ind]

        if dirn > 0 and i < d - 1:
            cry = reshape(cry, (ry[i] * n[i], ry[i + 1]))
            q, r = np.linalg.qr(cry)
            #ind = maxvol(q)
            ind = rect_maxvol(q)[0]
            ry[i + 1] = ind.size
            phi_left[i + 1] = np.tensordot(phi_left[i], cores[i], 1)
            phi_left[i + 1] = reshape(phi_left[i + 1], (ry[i] * n[i], -1))
            phi_left[i + 1] = phi_left[i + 1][ind, :]
            w1 = mkron(np.ones((n[i], 1)), Jy[i])
            w2 = mkron(grid[i], np.ones((ry[i], 1)))
            Jy[i + 1] = np.hstack((w1, w2))
            Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
            Jy[i + 1] = Jy[i + 1][ind, :]

        i += dirn
        if i == d or i == -1:
            dirn = -dirn
            i += dirn
            swp = swp + 1
    return val, x_full
<|endoftext|>


<commit_before>from __future__ import division, absolute_import, with_statement, print_function, unicode_literals

TYPE = "Example"
NAME = "include example"
REQUIRES = ["libmagic", "MD5"]
DEFAULTCONF = {
    'ENABLED': True,
    }

def check(conf=DEFAULTCONF):
    # If the config disabled the module don't run
    if not conf['ENABLED']:
        return False
    # If one of the required modules failed, don't run
    if None in REQUIRES:
        return False
    return True

def scan(filelist, conf=DEFAULTCONF):
    # Define our results array
    results = []
    # Pull out the libmagic results and metadata
    libmagicresults, libmagicmeta = REQUIRES[0]

    # Pull out the md5 results and metadata
    md5results, md5meta = REQUIRES[1]
    # Make the md5 results a dictionary
    md5dict = dict(md5results)

    # Run through each value in the libmagic results
    for filename, libmagicresult in libmagicresults:
        if libmagicresult.startswith('PDF document'):
            # If the file's md5 is present we will use that in the results
            if filename in md5dict:
                results.append((filename, md5dict[filename] + " is a pdf"))
            # If we don't know the md5 use the filename instead
            else:
                results.append((filename, "is a pdf"))

    # Create out metadata dictionary
    metadata = {}
    metadata["Name"] = NAME
    metadata["Type"] = TYPE

    # Return our super awesome results
    return (results, metadata)
<commit_msg>Small changes to example module<commit_after>from __future__ import (division, absolute_import, with_statement,
                        print_function, unicode_literals)

TYPE = "Example"
NAME = "include example"
REQUIRES = ["libmagic", "MD5"]
DEFAULTCONF = {
    'ENABLED': True,
}

def check(conf=DEFAULTCONF):
    # If the config disabled the module don't run
    if not conf['ENABLED']:
        return False
    # If one of the required modules failed, don't run
    if None in REQUIRES:
        return False
    return True

def scan(filelist, conf=DEFAULTCONF):
    # Define our results array
    results = []
    # Pull out the libmagic results and metadata
    libmagicresults, libmagicmeta = REQUIRES[0]

    # Pull out the md5 results and metadata
    md5results, md5meta = REQUIRES[1]
    # Make the md5 results a dictionary
    md5dict = dict(md5results)

    # Run through each value in the libmagic results
    for filename, libmagicresult in libmagicresults:
        if libmagicresult.startswith('PDF document'):
            # If the file's md5 is present we will use that in the results
            if filename in md5dict:
                results.append((filename, md5dict[filename] + " is a pdf"))
            # If we don't know the md5 use the filename instead
            else:
                results.append((filename, "is a pdf"))

    # Create out metadata dictionary
    metadata = {}
    metadata["Name"] = NAME
    metadata["Type"] = TYPE

    # Return our super awesome results
    return (results, metadata)
<|endoftext|>


<commit_before>from __future__ import print_function
"""
Tubing sources are defined here. If you want to make your own Source, create a
reader class with a read(amt) function, where amt is the amount of `stuff` to
read. MakeSourceFactory can generate a Source from your Reader. Ex::

    class MyReader(object):
        def read(self, amt):
            return [0] * amt, False

    MySource = MakeSourceFactory(MyReader)

The read(amt) function should return a chunk of data and a boolean indicated if
we've reached EOF. Unlike normal python streams, it's ok to return empty sets
and it won't close the stream. Only returning True as the second parameter
indicates that the stream is closed.
"""
import logging
import socket
import signal
from tubing import compat

logger = logging.getLogger('tubing.sources')

HANDLERS = []

def handle_signals(*signals):
    print("setting up sig handlers")
    def handle(*args, **kwargs):
        print("calling handlers {}".format(HANDLERS))
        for handle in HANDLERS:
            handle()
    for sig in signals:
        print("setting up {}".format(sig))
        signal.signal(sig, handle)

handle_signals(signal.SIGTERM, signal.SIGINT, signal.SIGHUP)

class MakeSourceFactory(object):
    """
    MakeSourceFactory takes a reader object and returns a Source factory.
    """

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

    def __call__(self, *args, **kwargs):
        reader = self.reader_cls(*args, **kwargs)
        src = Source(reader)
        if hasattr(reader, 'interrupt'):
            HANDLERS.append(reader.interrupt)
        print("handlers: %s" % (HANDLERS))
        return src

@compat.python_2_unicode_compatible
class Source(object):
    """
    Source is a wrapper for Readers that allows piping.
    """

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

    def read(self, amt):
        return self.source.read(amt)

    def __or__(self, other):
        return self.pipe(other)

    def pipe(self, other):
        return other.recieve(self)

    def __str__(self):
        return "<tubing.sources.Source(%s)>" % (self.source)

class ObjectReader(object):
    """
    ObjectReader outputs a list of objects.
    """

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

    def read(self, amt=None):
        r, self.objs = self.objs[:amt], self.objs[amt or len(self.objs):]
        return r, len(self.objs) == 0

Objects = MakeSourceFactory(ObjectReader)

class FileReader(object):
    """
    FileReader outputs bytes.
    """

    def __init__(self, filename, mode="rb"):
        self.filename = filename
        self.f = open(self.filename, mode)

    def read(self, amt=None):
        chunk = self.f.read(amt)
        if chunk:
            return chunk, False
        else:
            return '', True

    def __unicode__(self):
        return u"<tubing.sources.File %s>" % (self.filename)

    def __str__(self):
        return unicode(self).encode('utf-8')

File = MakeSourceFactory(FileReader)

class SocketReader(object):
    """
    UDPReader binds and reads from a UDP socket.
    """
    def __init__(self, ip, port, *args):
        self.sock = socket.socket(*args)
        self.sock.bind((ip, port))
        self.sock.settimeout(0.1)
        self.eof = False

    def read(self, amt=None):
        if self.eof:
            return b'', True

        try:
            data, addr = self.sock.recvfrom(amt)
            logger.debug("%s >> %s" % (addr, data))
            return data, False
        except socket.timeout:
            return b'', False
        except socket.error:
            return b'', True

    def interrupt(self):
        print("interrupt called")
        self.eof = True

Socket = MakeSourceFactory(SocketReader)
<commit_msg>Remove print statements<commit_after>from __future__ import print_function
"""
Tubing sources are defined here. If you want to make your own Source, create a
reader class with a read(amt) function, where amt is the amount of `stuff` to
read. MakeSourceFactory can generate a Source from your Reader. Ex::

    class MyReader(object):
        def read(self, amt):
            return [0] * amt, False

    MySource = MakeSourceFactory(MyReader)

The read(amt) function should return a chunk of data and a boolean indicated if
we've reached EOF. Unlike normal python streams, it's ok to return empty sets
and it won't close the stream. Only returning True as the second parameter
indicates that the stream is closed.
"""
import logging
import socket
import signal
from tubing import compat

logger = logging.getLogger('tubing.sources')

HANDLERS = []

def handle_signals(*signals):
    def handle(*args, **kwargs):
        for handle in HANDLERS:
            handle()
    for sig in signals:
        signal.signal(sig, handle)

handle_signals(signal.SIGTERM, signal.SIGINT, signal.SIGHUP)

class MakeSourceFactory(object):
    """
    MakeSourceFactory takes a reader object and returns a Source factory.
    """

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

    def __call__(self, *args, **kwargs):
        reader = self.reader_cls(*args, **kwargs)
        src = Source(reader)
        if hasattr(reader, 'interrupt'):
            HANDLERS.append(reader.interrupt)
        return src

@compat.python_2_unicode_compatible
class Source(object):
    """
    Source is a wrapper for Readers that allows piping.
    """

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

    def read(self, amt):
        return self.source.read(amt)

    def __or__(self, other):
        return self.pipe(other)

    def pipe(self, other):
        return other.recieve(self)

    def __str__(self):
        return "<tubing.sources.Source(%s)>" % (self.source)

class ObjectReader(object):
    """
    ObjectReader outputs a list of objects.
    """

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

    def read(self, amt=None):
        r, self.objs = self.objs[:amt], self.objs[amt or len(self.objs):]
        return r, len(self.objs) == 0

Objects = MakeSourceFactory(ObjectReader)

class FileReader(object):
    """
    FileReader outputs bytes.
    """

    def __init__(self, filename, mode="rb"):
        self.filename = filename
        self.f = open(self.filename, mode)

    def read(self, amt=None):
        chunk = self.f.read(amt)
        if chunk:
            return chunk, False
        else:
            return '', True

    def __unicode__(self):
        return u"<tubing.sources.File %s>" % (self.filename)

    def __str__(self):
        return unicode(self).encode('utf-8')

File = MakeSourceFactory(FileReader)

class SocketReader(object):
    """
    UDPReader binds and reads from a UDP socket.
    """
    def __init__(self, ip, port, *args):
        self.sock = socket.socket(*args)
        self.sock.bind((ip, port))
        self.sock.settimeout(0.1)
        self.eof = False

    def read(self, amt=None):
        if self.eof:
            return b'', True

        try:
            data, addr = self.sock.recvfrom(amt)
            logger.debug("%s >> %s" % (addr, data))
            return data, False
        except socket.timeout:
            return b'', False
        except socket.error:
            return b'', True

    def interrupt(self):
        self.eof = True

Socket = MakeSourceFactory(SocketReader)
<|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: "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"
Scott Bouloutian for the Companion Cube image: "https://lh4.ggpht.com/afyb1Nyo1suLIWpbtEACIY65SHW2Fjr5g1-KN8ONkA3aNSPd7cJKSeIefsngjSaVjtA=w300"
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
import time

# 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
ccx = 0
ccy = 0
hold = 1

class Chell(Sprite):
    asset = ImageAsset("images/ChellSpriteSheet.png", Frame(0,0,205,361), 2, 'horizontal')
    def __init__(self, position):
        super().__init__(Chell.asset, position)
        # assorted variables modified during code
        self.visible = True
        self.x = 50
        self.y = 410
        self.vx = 0
        self.vy = 0
        self.jump = 0
        self.hold = 1
        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.win = 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)
        PortalGame.listenKeyEvent("keydown", "e" , self.holdOn)

    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) and self.win == 0:
            self.thing = YouWin((400,400))
            self.win = 1

        # 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

        # if collliding with platform, go up to counteract the moving down, effectively staying still
        if self.collidingWithSprites(Platforms):
            self.vy -= .1
            self.y += self.vy
            self.vy = 0
            # jump
            if self.jump == 1:
                self.vy = -3
        # constantly moving down for gravity if not colliding with platform
        else:
            self.vy += .1
            self.y += self.vy

        # hold cube
        if self.collidingWithSprites(CompanionCube) and self.hold == -1:
            global ccx
            ccx = self.x
            global ccy
            ccy = self.y
        # death by goo
        if self.y >= 560:
            self.x = 50
            self.y = 410
            self.vy =0
        # 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
            global ccx
            ccx = 10
            global ccy
            ccy = 450
            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 holdOn(self,event):
        self.hold = self.hold * (-1)
        global hold
        hold = hold * (-1)
    def resetOn(self,event):
        self.reset = 1
    def resetOff(self,event):
        self.reset = 0
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

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

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

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

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

class 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 CompanionCube(Sprite):
    cc = ImageAsset("images/companioncube.png", Frame(20,20,260,260), 1, 'horizontal')
    def __init__(self, position):
        super().__init__(CompanionCube.cc, position)
        self.scale = 1/7
        self.x = 10
        self.y = 450
        self.visible = True
        self.vx = 0
        self.vy = 0
        self.held = 1
    def step(self):
        # moving up if colliding with platforms to counteract gravity
        if self.collidingWithSprites(Platforms):
            self.vy -= .1
            self.y += self.vy
            self.vy = 0
        # constantly moving down for gravity if not colliding with platform
        else:
            self.vy += .1
            self.y += self.vy
        # if colliding with Chell and being held, then change to be "held"
        global hold
        self.held = hold
        if self.collidingWithSprites(Chell) and self.held == -1:
            self.vy = 0
            self.x = ccx + 10
            self.y = ccy + 25
        # death by goo
        if self.y >= 620:
            self.x = 10
            self.y = 450
            self.vy =0

class CubeButton(Sprite):
    button = RectangleAsset(100,10,noline,red)
    def __init__(self, position):
        super().__init__(CubeButton.button, position)
        self.x = 100
        self.y = 100
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, E to Interact", 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))
        Platforms((0,500))
        Sprite(plat,(650,150))
        Platforms((650,150))
        Sprite(plat,(600,500))
        Platforms((600,500))
        # button
        CubeButton((0,0))
        # portals, companion cube, and Chell
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))
        CompanionCube((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()
        for cc in self.getSpritesbyClass(CompanionCube):
            cc.step()

myapp = PortalGame(1000,750)
myapp.run()<commit_msg>Updated from Brython Server: 5/10/2016 2:50:40 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: "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"
Scott Bouloutian for the Companion Cube image: "https://lh4.ggpht.com/afyb1Nyo1suLIWpbtEACIY65SHW2Fjr5g1-KN8ONkA3aNSPd7cJKSeIefsngjSaVjtA=w300"
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
import time

# 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
ccx = 0
ccy = 0
hold = 1

class Chell(Sprite):
    asset = ImageAsset("images/ChellSpriteSheet.png", Frame(0,0,205,361), 2, 'horizontal')
    def __init__(self, position):
        super().__init__(Chell.asset, position)
        # assorted variables modified during code
        self.visible = True
        self.x = 50
        self.y = 410
        self.vx = 0
        self.vy = 0
        self.jump = 0
        self.hold = 1
        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.win = 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)
        PortalGame.listenKeyEvent("keydown", "e" , self.holdOn)

    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) and self.win == 0:
            self.thing = YouWin((400,400))
            self.win = 1

        # 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

        # if collliding with platform, go up to counteract the moving down, effectively staying still
        if self.collidingWithSprites(Platforms):
            self.vy -= .1
            self.y += self.vy
            self.vy = 0
            # jump
            if self.jump == 1:
                self.vy = -3
        # constantly moving down for gravity if not colliding with platform
        else:
            self.vy += .1
            self.y += self.vy

        # hold cube
        if self.collidingWithSprites(CompanionCube) and self.hold == -1:
            global ccx
            ccx = self.x
            global ccy
            ccy = self.y
        # death by goo
        if self.y >= 560:
            self.x = 50
            self.y = 410
            self.vy =0
        # 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
            global ccx
            ccx = 10
            global ccy
            ccy = 450
            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 holdOn(self,event):
        self.hold = self.hold * (-1)
        global hold
        hold = hold * (-1)
    def resetOn(self,event):
        self.reset = 1
    def resetOff(self,event):
        self.reset = 0
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

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

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

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

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

class 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 CompanionCube(Sprite):
    cc = ImageAsset("images/companioncube.png", Frame(20,20,260,260), 1, 'horizontal')
    def __init__(self, position):
        super().__init__(CompanionCube.cc, position)
        self.scale = 1/7
        self.x = 10
        self.y = 450
        self.visible = True
        self.vx = 0
        self.vy = 0
        self.held = 1
    def step(self):
        # moving up if colliding with platforms to counteract gravity
        if self.collidingWithSprites(Platforms):
            self.vy -= .1
            self.y += self.vy
            self.vy = 0
        # constantly moving down for gravity if not colliding with platform
        else:
            self.vy += .1
            self.y += self.vy
        # if colliding with Chell and being held, then change to be "held"
        global hold
        self.held = hold
        if self.collidingWithSprites(Chell) and self.held == -1:
            self.vy = 0
            self.x = ccx + 10
            self.y = ccy + 25
        # death by goo
        if self.y >= 620:
            self.x = 10
            self.y = 450
            self.vy =0

class CubeButton(Sprite):
    button = RectangleAsset(100,10,noline,red)
    def __init__(self, position):
        super().__init__(CubeButton.button, position)
        self.x = 600
        self.y = 100
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, E to Interact", 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))
        Platforms((0,500))
        Sprite(plat,(650,150))
        Platforms((650,150))
        Sprite(plat,(600,500))
        Platforms((600,500))
        # button
        CubeButton((0,0))
        # portals, companion cube, and Chell
        BluePortal((0,0))
        OrangePortal((0,0))
        Chell((0,0))
        CompanionCube((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()
        for cc in self.getSpritesbyClass(CompanionCube):
            cc.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.alt == 1:
            print("stuff")
        if self.click == 1 and self.alt != 1:
            OrangePortal((self.cox,self.coy))
            self.click = 0
            self.alt = 0
        else:
            self.click = 0
        if self.click == 1 and self.alt == 1:
            BluePortal((self.cox,self.coy))
            self.click = 0
            self.alt = 0
        else:
            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
        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")
    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/20/2016 1:55:54 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.alt == 1:
            print("stuff")
        if self.click == 1 and self.alt != 1:
            OrangePortal((self.cox,self.coy))
            self.click = 0
            self.alt = 0
        if self.click == 1 and self.alt == 1:
            BluePortal((self.cox,self.coy))
            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
        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")
    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|>