<commit_before>rint("Welcome to the Text-based The Long Night Recreation.")
print("A strange electromagnetic storm has crashed your plane in Northern Canada. How long can you survive?")
Time = 0
Freeze = 10

def Wait():
    print("The snow whistles, and the wind whips up your hair as you sit and wait. Sound of the forest can be heard. Howls echo through the trees, and chirps of birds are a rare occurance.")

def SeeWolf
print("You fin yourself in a clearing 200 meters in diameter. It is surrounded by snow-laden conifers, and no buildings are in sight.")
print("You are standing in the middle of the clearing, next to your downed plane, flames still licking across the chasis, and a rut in the snow lead about 40 meters to the right.")
first_choice = input(" You check your compass, and you are facing North. What will you do? (a) Go North (b) Go East (c) Go South (d) Go West (e) Search the Plane (f) Wait an hour")
<commit_msg>Updated from Brython Server: December 15, 2015 2:22:51 PM EST<commit_after>print("Welcome to the Text-based The Long Night Recreation.")
print("A strange electromagnetic storm has crashed your plane in Northern Canada. How long can you survive?")
Time = 0
Freeze = 10

def Wait():
    print("The snow whistles, and the wind whips up your hair as you sit and wait. Sound of the forest can be heard. Howls echo through the trees, and chirps of birds are a rare occurance.")

def SeeWolf():
    print("You notice a lupine shape run past a few meters from you. It does not give you a second thought, and quickly leaves your sight.")

def WolfAttack():
    print(

print("You fin yourself in a clearing 200 meters in diameter. It is surrounded by snow-laden conifers, and no buildings are in sight.")
print("You are standing in the middle of the clearing, next to your downed plane, flames still licking across the chasis, and a rut in the snow lead about 40 meters to the right.")
first_choice = input(" You check your compass, and you are facing North. What will you do? (a) Go North (b) Go East (c) Go South (d) Go West (e) Search the Plane (f) Wait an hour")
<|endoftext|>


<commit_before>from django.conf import settings
from hashlib import sha1
from mediagenerator.base import Generator
from mediagenerator.utils import get_media_dirs, find_file, prepare_patterns
from mimetypes import guess_type
import os

COPY_MEDIA_FILETYPES = getattr(settings, 'COPY_MEDIA_FILETYPES',
    ('gif', 'jpg', 'jpeg', 'png', 'svg', 'svgz', 'ico', 'swf', 'ttf', 'otf',
     'eot', 'woff'))

IGNORE_PATTERN = prepare_patterns(getattr(settings,
   'IGNORE_MEDIA_COPY_PATTERNS', ()), 'IGNORE_MEDIA_COPY_PATTERNS')

class CopyFiles(Generator):
    def get_dev_output(self, name):
        path = find_file(name)
        fp = open(path, 'rb')
        content = fp.read()
        fp.close()
        mimetype = guess_type(path)[0]
        return content, mimetype

    def get_dev_output_names(self):
        media_files = {}
        for root in get_media_dirs():
            self.collect_copyable_files(media_files, root)

        for name, source in media_files.items():
            fp = open(source, 'rb')
            hash = sha1(fp.read()).hexdigest()
            fp.close()
            yield name, name, hash

    def collect_copyable_files(self, media_files, root):
        for root_path, dirs, files in os.walk(root, followlinks=True):
            for file in files:
                ext = os.path.splitext(file)[1].lstrip('.')
                path = os.path.join(root_path, file)
                media_path = path[len(root) + 1:].replace(os.sep, '/')
                if ext in COPY_MEDIA_FILETYPES and \
                        not IGNORE_PATTERN.match(media_path):
                    media_files[media_path] = path
<commit_msg>Fixed python 2.5 does not having the followlinks option for os.walk.<commit_after>from django.conf import settings
from hashlib import sha1
from mediagenerator.base import Generator
from mediagenerator.utils import get_media_dirs, find_file, prepare_patterns
from mimetypes import guess_type
import os

COPY_MEDIA_FILETYPES = getattr(settings, 'COPY_MEDIA_FILETYPES',
    ('gif', 'jpg', 'jpeg', 'png', 'svg', 'svgz', 'ico', 'swf', 'ttf', 'otf',
     'eot', 'woff'))

IGNORE_PATTERN = prepare_patterns(getattr(settings,
   'IGNORE_MEDIA_COPY_PATTERNS', ()), 'IGNORE_MEDIA_COPY_PATTERNS')

class CopyFiles(Generator):
    def get_dev_output(self, name):
        path = find_file(name)
        fp = open(path, 'rb')
        content = fp.read()
        fp.close()
        mimetype = guess_type(path)[0]
        return content, mimetype

    def get_dev_output_names(self):
        media_files = {}
        for root in get_media_dirs():
            self.collect_copyable_files(media_files, root)

        for name, source in media_files.items():
            fp = open(source, 'rb')
            hash = sha1(fp.read()).hexdigest()
            fp.close()
            yield name, name, hash

    def collect_copyable_files(self, media_files, root):
        for root_path, dirs, files in os.walk(root):
            for file in files:
                ext = os.path.splitext(file)[1].lstrip('.')
                path = os.path.abspath(os.path.join(root_path, file))
                media_path = path[len(root) + 1:].replace(os.sep, '/')
                if ext in COPY_MEDIA_FILETYPES and \
                        not IGNORE_PATTERN.match(media_path):
                    media_files[media_path] = path
<|endoftext|>


<commit_before>'''
Final Project
'''
from collections import Counter
from math import floor
from ggame import App, Color, LineStyle, Sprite, RectangleAsset
from ggame import CircleAsset, EllipseAsset, PolygonAsset, ImageAsset, MouseEvent, Frame

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
black = Color(0x000000, 1.0)
white=Color(0xffffff,1.0)
yellow=Color(0xffff00,1.0)

thinline = LineStyle(1, black)
noline=LineStyle(0,white)

class pacman(Sprite):
    pacmanSprite=CircleAsset(10,noline,yellow)
    #pacman=RectangleAsset(20,10,noline,yellow)
    def __init__(self,position):
        super().__init__(pacman.pacmanSprite,position)
        self.position=position
        self.vx=0
        self.vy=0
        self.vr=0
        self.moving=0
        self.movingframe=1

        '''
        When keys are pressed
        '''

        pacmanGame.listenKeyEvent("keydown","right arrow", self.rightmoving)
        pacmanGame.listenKeyEvent("keydown","left arrow",self.leftmoving)
        pacmanGame.listenKeyEvent("keydown","down arrow",self.downmoving)
        pacmanGame.listenKeyEvent("keydown","up arrow",self.upmoving)
        '''
        When keys are released
        '''

    '''
    When keys are pressed they do these things
    '''

    def rightmoving(self,event):
            self.vx=1
            self.vy=0

    def leftmoving(self,event):
            self.vx=-1
            self.vy=0

    def downmoving(self,event):
            self.vy=1
            self.vx=0

    def upmoving(self,event):
            self.vy=-1
            self.vx=0

    '''
    When keys are released they do these things
    '''

    def step(self):
        self.x+=self.vx
        self.y+=self.vy
        self.rotation+=self.vr

    #def collision(self,position):
     #   if position==(200,y):
      #      rightmoving.vx=0
       #     leftmoving.vx=0
        #    downmoving.vy=0
         #   upmoving.vy=0

class ghost(pacman):
    ghostRed=RectangleAsset(20,10,noline,red)
    def __init__(self,position):
        super().__init__(ghost.ghostRed,position)
        #self.position=position
        #self.vx=0
        #self.vy=0
        #self.vr=0
        #self.moving=0
        #self.movingframe=1

class pacmanGame(App):
    def __init__(self,width,height):
        super().__init__(width,height)
        background=RectangleAsset(width, height, noline, black)
        bg=Sprite(background, (0,0))

    def step(self):
        for pman in self.getSpritesbyClass(pacman):
            pman.step()

        for rghost in self.getSpritesbyClass(ghost):
            rghost.step()

class maze():
    def __init__(self):
        pass #Will put stuff here later

    def open(x,y):
        return True

class OtherSprites(Sprite):
    def __init__(self):
        wall=RectangleAsset(10,200,noline,black)
        wallsprite=Sprite(wall, (200,25))

myapp=pacmanGame(0,0) #Needs to go first so other sprites show on top of it

pacman((100,25))
ghost((200,200))
OtherSprites()
myapp.run()

<commit_msg>Updated from Brython Server: 12/30/2016 3:26:55 PM<commit_after>'''
Final Project
'''
from collections import Counter
from math import floor
from ggame import App, Color, LineStyle, Sprite, RectangleAsset
from ggame import CircleAsset, EllipseAsset, PolygonAsset, ImageAsset, MouseEvent, Frame

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
black = Color(0x000000, 1.0)
white=Color(0xffffff,1.0)
yellow=Color(0xffff00,1.0)

thinline = LineStyle(1, black)
noline=LineStyle(0,white)

class pacman(Sprite):
    pacmanSprite=CircleAsset(10,noline,yellow)
    #pacman=RectangleAsset(20,10,noline,yellow)
    def __init__(self,position):
        super().__init__(pacman.pacmanSprite,position)
        self.position=position
        self.vx=0
        self.vy=0
        self.vr=0
        self.moving=0
        self.movingframe=1

        '''
        When keys are pressed
        '''

        pacmanGame.listenKeyEvent("keydown","right arrow", self.rightmoving)
        pacmanGame.listenKeyEvent("keydown","left arrow",self.leftmoving)
        pacmanGame.listenKeyEvent("keydown","down arrow",self.downmoving)
        pacmanGame.listenKeyEvent("keydown","up arrow",self.upmoving)
        '''
        When keys are released
        '''

    '''
    When keys are pressed they do these things
    '''

    def rightmoving(self,event):
            self.vx=1
            self.vy=0

    def leftmoving(self,event):
            self.vx=-1
            self.vy=0

    def downmoving(self,event):
            self.vy=1
            self.vx=0

    def upmoving(self,event):
            self.vy=-1
            self.vx=0

    '''
    When keys are released they do these things
    '''

    def step(self):
        self.x+=self.vx
        self.y+=self.vy
        self.rotation+=self.vr

    #def collision(self,position):
     #   if position==(200,y):
      #      rightmoving.vx=0
       #     leftmoving.vx=0
        #    downmoving.vy=0
         #   upmoving.vy=0

class ghost(Sprite):
    ghostRed=RectangleAsset(20,10,noline,red)
    def __init__(self,position):
        super().__init__(ghost.ghostRed,position)
        self.position=position
        self.vx=0
        self.vy=0
        self.vr=0
        self.moving=0
        self.movingframe=1

class pacmanGame(App):
    def __init__(self,width,height):
        super().__init__(width,height)
        background=RectangleAsset(width, height, noline, black)
        bg=Sprite(background, (0,0))

    def step(self):
        for pman in self.getSpritesbyClass(pacman):
            pman.step()

        for rghost in self.getSpritesbyClass(ghost):
            rghost.step()

class maze():
    def __init__(self):
        pass #Will put stuff here later

    def open(x,y):
        return True

class OtherSprites(Sprite):
    def __init__(self):
        wall=RectangleAsset(10,200,noline,black)
        wallsprite=Sprite(wall, (200,25))

myapp=pacmanGame(0,0) #Needs to go first so other sprites show on top of it

pacman((100,25))
ghost((200,200))
OtherSprites()
myapp.run()

<|endoftext|>


<commit_before>
one = input("Welcome to the Text-based The Long Night Recreation.\n(Press Enter)")
two = input("A strange electromagnetic storm has crashed your plane in Northern Canada. How long can you survive? \n(Press Enter)")

Freeze = 8
def FirstChoice():
    first_choice = input("You check your compass, and you are facing North. What will you do? \n(a) Go North \n(b) Go East \n(c) Go South \n(d) Go West \n(e) Search the Plane \n(f) Wait an hour \nChoice: ")
    if first_choice.lower() == "a":
        Freezing()
        North()
    elif first_choice.lower() == "b":
        Freezing()
        East()

    elif first_choice.lower() == "c":
        Freezing()
        South()

    elif first_choice.lower() == "d":
        Freezing()
        West()

    elif first_choice.lower() == "e":
        SearchPlane()

    elif first_choice.lower() == "f":
        Freezing()
        Wait()

def Freezing():
    Freeze -= 1
    if Freeze == 0:
        printz = input("The cold overcomes you, and you fall. Your vision darkens as the snow rushes up to meet you. You have died by frostbite.")

    else:
        print("The cold is starting to get to you. Find some shelter fast.")
def Wait():
    print("The snow whistles, and the wind whips up your hair as you sit and wait. Sound of the forest can be heard. Howls echo through the trees, and chirps of birds are a rare occurance.")
    Freezing()
    first_choice = input("You check your compass, and you are facing North. What will you do? \n(a) Go North \n(b) Go East \n(c) Go South \n(d) Go West \n(e) Search the Plane \n(f) Wait an hour \nChoice: ")

    if first_choice.lower() == "a":
        North()
    elif first_choice.lower() == "b":
        East()
        Freezing()
    elif first_choice.lower() == "c":
        South()
        Freezing()
    elif first_choice.lower() == "d":
        West()
        Freezing()
    elif first_choice.lower() == "e":
        SearchPlane()
    elif first_choice.lower() == "f":
        Wait()
        Freezing()

    else:
        print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")

def Nothing():
    print("As you trudge through the woods, nothing seems out of the ordinary.")
    Freezing()
    CardinalChoice2()
def CardinalChoice2():
    print("You sense of direction has been lost form walking through the woods. Which direction would you like to try to go?\n(a) North\n(b) East\n(c) South\n(d) West")
    if CardinalChoice2 == "a":
        Freezing()
        SeeWolf()
    elif CardinalChoice2 == "b" or CardinalChoice2 == "c" or CardinalChoice2== "c":
        Freezing()
        CardinalChoice2()
    else:
        print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")
def PossibleWolf2():
    choiceW = input("After seeing the wolf you come to a clearing. Which direction would you like to go?\n(a) North\n(b) East\n(c) South\n(d) West")
    if choiceW.lower == "a":
        print("You trudge through the snow past trees and small snow-mounds towards North.")
        Freezing()
        WolfAttack()
    elif choiceW == "b":
        print("You trudge through the snow past trees and small snow-mounds towards East.")
        House()
    elif choiceW == "c":
        print("You trudge through the snow past trees and small snow-mounds towards South.")
        Freezing()
        WolfAttack()
    elif choiceW == "d":
        print("You trudge through the snow past trees and small snow-mounds towards West.")
        Freezing()
        WolfAttack()
    else:
        print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")
def PossibleWolf():
    choiceW = input("After seeing the wolf you come to a clearing. Which direction would you like to go?\n(a) North\n(b) East\n(c) South\n(d) West")
    if choiceW.lower == "a":
        print("You trudge through the snow past trees and small snow-mounds towards North.")
        Freezing()
        WolfAttack()
    elif choiceW == "b":
        print("You trudge through the snow past trees and small snow-mounds towards East.")
        Freezing()
        WolfAttack()
    elif choiceW == "c":
        print("You trudge through the snow past trees and small snow-mounds towards South.")
        Freezing()
        WolfAttack()
    elif choiceW == "d":
        print("You trudge through the snow past trees and small snow-mounds towards West.")
        Freezing()
        PossibleWolf2()
    else:
        print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")
def SeeWolf():
    print("You notice a lupine shape run past a few meters from you. It does not give you a second thought, and quickly leaves your sight.")
    Freezing()
    PossibleWolf()
def WolfAttack():
    print("You trudge through the snow, and all of a sudden a noise break the silence. You hear howling, as the crunches of multiple paws racing through the snow surround you completely. The eyes of the wolves all around you spell certain death.")

def House():
    print("As you crest the hill, a small lodge comes into your vision. You race towards the warmth and your only way of survival.")
    WIN = input("You have completed the Text-Based The Long Night Recreation Game. Congratulations! Don't tell your friends how to win though   ;D")
def North():
    print("You trudge through the snow past trees and small snow-mounds towards North.")
    Freezing()
    Nothing()
def South():
    print("You trudge through the snow past trees and small snow-mounds towards South.")
    Freezing()
    SeeWolf()
def East():
    print("You trudge through the snow past trees and small snow-mounds towards East.")
    Freezing()
    Nothing()
def West():
    print("You trudge through the snow past trees and small snow-mounds towards West.")
    Freezing()
    SeeWolf()
def SearchPlane():
    print("You trudge through the snow to the plane, only to find that the fire does not allow you to access the plane. However, it does seem warmer here.")
    FirstChoice()
def CardinalChoice():
    Cardinal_Direction = input("You check your compass, and you are facing North. What will you do? \n(a) Go North \n(b) Go East \n(c) Go South \n(d) Go West")
    if Cardinal_Direction.lower() == "a":
        Freezing()
        North()

    if Cardinal_Direction.lower() == "b":
        Freezing()
        East()

    if Cardinal_Direction.lower() == "c":
        Freezing()
        South()

    elif Cardnial_Direction.lower() == "d":
        Freezing()
        West()

three = input("You find yourself in a clearing 200 meters in diameter. It is surrounded by snow-laden conifers, with no buildings in sight.\n(Press Enter)")
four = input("You are standing in the middle next to your downed plane, flames still licking across the chasis, and a rut in the snow leads from the plane to about 40 meters to the right.\n(Press Enter)")
first_choice = input("You check your compass, and you are facing North. What will you do? \n(a) Go North \n(b) Go East \n(c) Go South \n(d) Go West \n(e) Search the Plane \n(f) Wait an hour \nChoice: ")
if first_choice.lower() == "a":
    Freezing()
    North()
elif first_choice.lower() == "b":
    Freezing()
    East()

elif first_choice.lower() == "c":
    Freezing()
    South()

elif first_choice.lower() == "d":
    Freezing()
    West()

elif first_choice.lower() == "e":
    SearchPlane()

elif first_choice.lower() == "f":
    Freezing()
    Wait()

else:
    print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")
<commit_msg>Updated from Brython Server: 1/8/2016 2:50:18 PM<commit_after>
one = input("Welcome to the Text-based The Long Night Recreation.\n(Press Enter)")
two = input("A strange electromagnetic storm has crashed your plane in Northern Canada. How long can you survive? \n(Press Enter)")

Freeze = 8
def FirstChoice():
    first_choice = input("You check your compass, and you are facing North. What will you do? \n(a) Go North \n(b) Go East \n(c) Go South \n(d) Go West \n(e) Search the Plane \n(f) Wait an hour \nChoice: ")
    if first_choice.lower() == "a":
        Freezing()
        North()
    elif first_choice.lower() == "b":
        Freezing()
        East()

    elif first_choice.lower() == "c":
        Freezing()
        South()

    elif first_choice.lower() == "d":
        Freezing()
        West()

    elif first_choice.lower() == "e":
        SearchPlane()

    elif first_choice.lower() == "f":
        Freezing()
        Wait()

def Freezing():
    Freeze -= 1
    if Freeze == 0:
        printz = input("The cold overcomes you, and you fall. Your vision darkens as the snow rushes up to meet you. You have died by frostbite.")

    else:
        print("The cold is starting to get to you. Find some shelter fast.")
def Wait():
    print("The snow whistles, and the wind whips up your hair as you sit and wait. Sound of the forest can be heard. Howls echo through the trees, and chirps of birds are a rare occurance.")
    Freezing()
    first_choice = input("You check your compass, and you are facing North. What will you do? \n(a) Go North \n(b) Go East \n(c) Go South \n(d) Go West \n(e) Search the Plane \n(f) Wait an hour \nChoice: ")

    if first_choice.lower() == "a":
        North()
    elif first_choice.lower() == "b":
        East()
        Freezing()
    elif first_choice.lower() == "c":
        South()
        Freezing()
    elif first_choice.lower() == "d":
        West()
        Freezing()
    elif first_choice.lower() == "e":
        SearchPlane()
    elif first_choice.lower() == "f":
        Wait()
        Freezing()

    else:
        print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")

def Nothing():
    print("As you trudge through the woods, nothing seems out of the ordinary.")
    Freezing()
    CardinalChoice2()
def CardinalChoice2():
    print("You sense of direction has been lost form walking through the woods. Which direction would you like to try to go?\n(a) North\n(b) East\n(c) South\n(d) West")
    if CardinalChoice2 == "a":
        Freezing()
        SeeWolf()
    elif CardinalChoice2 == "b" or CardinalChoice2 == "c" or CardinalChoice2== "c":
        Freezing()
        CardinalChoice2()
    else:
        print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")
def PossibleWolf2():
    choiceW = input("After seeing the wolf you come to a clearing. Which direction would you like to go?\n(a) North\n(b) East\n(c) South\n(d) West")
    if choiceW.lower == "a":
        print("You trudge through the snow past trees and small snow-mounds towards North.")
        Freezing()
        WolfAttack()
    elif choiceW == "b":
        print("You trudge through the snow past trees and small snow-mounds towards East.")
        House()
    elif choiceW == "c":
        print("You trudge through the snow past trees and small snow-mounds towards South.")
        Freezing()
        WolfAttack()
    elif choiceW == "d":
        print("You trudge through the snow past trees and small snow-mounds towards West.")
        Freezing()
        WolfAttack()
    else:
        print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")
def PossibleWolf():
    choiceW = input("After seeing the wolf you come to a clearing. Which direction would you like to go?\n(a) North\n(b) East\n(c) South\n(d) West")
    if choiceW.lower == "a":
        print("You trudge through the snow past trees and small snow-mounds towards North.")
        Freezing()
        WolfAttack()
    elif choiceW == "b":
        print("You trudge through the snow past trees and small snow-mounds towards East.")
        Freezing()
        WolfAttack()
    elif choiceW == "c":
        print("You trudge through the snow past trees and small snow-mounds towards South.")
        Freezing()
        WolfAttack()
    elif choiceW == "d":
        print("You trudge through the snow past trees and small snow-mounds towards West.")
        Freezing()
        PossibleWolf2()
    else:
        print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")
def SeeWolf():
    print("You notice a lupine shape run past a few meters from you. It does not give you a second thought, and quickly leaves your sight.")
    Freezing()
    PossibleWolf()
def WolfAttack():
    print("You trudge through the snow, and all of a sudden a noise break the silence. You hear howling, as the crunches of multiple paws racing through the snow surround you completely. The eyes of the wolves all around you spell certain death.")

def House():
    print("As you crest the hill, a small lodge comes into your vision. You race towards the warmth and your only way of survival.")
    WIN = input("You have completed the Text-Based The Long Night Recreation Game. Congratulations! Don't tell your friends how to win though   ;D")
def North():
    print("You trudge through the snow past trees and small snow-mounds towards North.")
    Freezing()
    Nothing()
def South():
    print("You trudge through the snow past trees and small snow-mounds towards South.")
    Freezing()
    SeeWolf()
def East():
    print("You trudge through the snow past trees and small snow-mounds towards East.")
    Freezing()
    Nothing()
def West():
    print("You trudge through the snow past trees and small snow-mounds towards West.")
    Freezing()
    SeeWolf()
def SearchPlane():
    print("You trudge through the snow to the plane, only to find that the fire does not allow you to access the plane. However, it does seem warmer here.")
    FirstChoice()
def CardinalChoice():
    Cardinal_Direction = input("You check your compass, and you are facing North. What will you do? \n(a) Go North \n(b) Go East \n(c) Go South \n(d) Go West")
    if Cardinal_Direction.lower() == "a":
        Freezing()
        North()

    elif Cardinal_Direction.lower() == "b":
        Freezing()
        East()

    elif Cardinal_Direction.lower() == "c":
        Freezing()
        South()

    elif Cardinal_Direction.lower() == "d":
        Freezing()
        West()
    else:
        print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")
three = input("You find yourself in a clearing 200 meters in diameter. It is surrounded by snow-laden conifers, with no buildings in sight.\n(Press Enter)")
four = input("You are standing in the middle next to your downed plane, flames still licking across the chasis, and a rut in the snow leads from the plane to about 40 meters to the right.\n(Press Enter)")
first_choice = input("You check your compass, and you are facing North. What will you do? \n(a) Go North \n(b) Go East \n(c) Go South \n(d) Go West \n(e) Search the Plane \n(f) Wait an hour \nChoice: ")
if first_choice.lower() == "a":
    Freezing()
    North()
elif first_choice.lower() == "b":
    Freezing()
    East()

elif first_choice.lower() == "c":
    Freezing()
    South()

elif first_choice.lower() == "d":
    Freezing()
    West()

elif first_choice.lower() == "e":
    SearchPlane()

elif first_choice.lower() == "f":
    Freezing()
    Wait()

else:
    print("That is not a valid choice. Please resart the program, and make sure not to include anything other than the letter of the choice in the input box.")
<|endoftext|>


<commit_before>"""
FinalProject.py
Author: Avery Wallis
Sources: Hayden Hatfield, Mr. Donnelly,
Marcelo Almaguer for the Chell character model used in his own version of Portal called "Remember the Game"
maxiesnax for the Orange Portal Image:0 "http://orig05.deviantart.net/58ec/f/2012/361/2/5/portal___orange_portal_by_maxiesnax-d5pcfmj.png"
Blue Portal Image "http://vignette4.wikia.nocookie.net/kirby-bulborb/images/1/12/Blue_Portal.png/revision/latest?cb=20151004085207"
Special thanks to Valve for creating such an awesome game. Hopefully you can count to three.
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
# colors
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)
# lines
thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)
# assorted environmental sprites
wall=RectangleAsset(1000,750, noline, wall)
exitbig=CircleAsset(70, thinline, platc)
exitsmall=CircleAsset(20, thinline, platc)
plat=RectangleAsset(250, 50, noline, platc)
doorline=LineAsset(0, 120, thinline)
goo=RectangleAsset(1000,100,noline,gooy)

# global variables changed with the classes
cpx = 0
cpy = 0
cox = -100
coy = -100
cbx = -100
cby = -100

class Chell(Sprite):
    asset = ImageAsset("images/ChellSpriteSheet.png", Frame(0,0,205,361), 2, 'horizontal')
    def __init__(self, position):
        super().__init__(Chell.asset, position)
        self.visible = True
        self.x = 0
        self.y = 410
        self.vx = 0
        self.vy = 0
        self.jump = 0
        self.click = 0
        self.mright = 0
        self.mleft = 0
        self.alt = 0
        self.image = 0
        self.scale = .25
        self.op = 0
        self.reset = 0
        # 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 gravity
        self.vy += 5
        self.y += self.vy
        self.vy = 0
        # if collliding with platform, go up to counteract the moving down, effectively staying still
        if self.collidingWithSprites(Platforms):
            self.y -= 5
            # jump
            if self.jump == 1:
                self.vy = -100
                self.jump = 0

        # 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.jump = 1
    def jumpOff(self,event):
        self.jump = 0
    def resetOn(self,event):
        self.reset = 1
    def resetOff(self,event):
        self.reset = 0
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

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

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

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

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

class Platforms(Sprite):
    platc=Color(0xB9BDBB,1.0)
    plat=RectangleAsset(250, 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(goo, (0,650))
        Sprite(txt_asset,(0,0))
        Sprite(txt_asset1, (0,10))
        Sprite(txt_asset2, (0,20))
        Sprite(resettxt,(0,30))
        Platforms((0,500))
        Platforms((650,150))
        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/5/2016 2:14:27 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.jump = 0
        self.click = 0
        self.mright = 0
        self.mleft = 0
        self.alt = 0
        self.image = 0
        self.scale = .25
        self.op = 0
        self.reset = 0
        # 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 gravity
        self.vy += 5
        self.y += self.vy
        self.vy = 0
        # if collliding with platform, go up to counteract the moving down, effectively staying still
        if self.collidingWithSprites(Platforms):
            self.y -= 5
            self.vy = 0
            # jump
            if self.jump == 1:
                self.vy = -100
                self.jump = 0

        # 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.jump = 1
    def jumpOff(self,event):
        self.jump = 0
    def resetOn(self,event):
        self.reset = 1
    def resetOff(self,event):
        self.reset = 0
    def rightOn(self,event):
        self.mright = 1
    def rightOff(self,event):
        self.mright = 0
    def leftOn(self,event):
        self.mleft = 1
    def leftOff(self,event):
        self.mleft = 0
    def altOn(self,event):
        self.alt = 1
    def altOff(self,event):
        self.alt = 0

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

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

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

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

class Platforms(Sprite):
    platc=Color(0xB9BDBB,1.0)
    plat=RectangleAsset(250, 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(goo, (0,650))
        Sprite(txt_asset,(0,0))
        Sprite(txt_asset1, (0,10))
        Sprite(txt_asset2, (0,20))
        Sprite(resettxt,(0,30))
        Platforms((0,500))
        Platforms((650,150))
        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>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import properties
import numpy as np
import warnings

from . import Maps
from . import Utils

class Array(properties.Array):

    class_info = 'a numpy, Zero or Identity array'

    def validate(self, instance, value):
        if isinstance(value, (Utils.Zero, Utils.Identity)):
            return value
        return super(Array, self).validate(instance, value)

class Float(properties.Float):

    class_info = 'a float, Zero or Identity'

    def validate(self, instance, value):
        if isinstance(value, (Utils.Zero, Utils.Identity)):
            return value
        return super(Float, self).validate(instance, value)

class Integer(properties.Integer):

    class_info = 'an Integer or *'

    def validate(self, instance, value):
        if isinstance(value, str):
            assert value == '*', 'value must be an integer or *, not {}'.format(
                value
            )
            return value
        return super(Integer, self).validate(instance, value)

class Model(properties.Array):

    class_info = 'a numpy array'
    _required = False

class Mapping(properties.Property):

    class_info = 'a SimPEG Map'
    _required = False

    @property
    def prop(self):
        return getattr(self, '_prop', None)

    @prop.setter
    def prop(self, value):
        assert isinstance(value, PhysicalProperty)
        value._mapping = self  # Skip the setter
        self._prop = value

    @property
    def reciprocal(self):
        if self.prop and self.prop.reciprocal:
            return self.prop.reciprocal.mapping

    @property
    def reciprocal_prop(self):
        if self.prop and self.prop.reciprocal:
            return self.prop.reciprocal

    def clear_props(self, instance):
        for prop in (self.prop, self.reciprocal_prop, self.reciprocal):
            if prop is not None:
                if prop.name in instance._props:
                    delattr(instance, prop.name)
                else:
                    setattr(instance, prop.name, None)

    def validate(self, instance, value):
        if not isinstance(value, Maps.IdentityMap):
            self.error(instance, value)
        return value

    def get_property(self):

        scope = self

        def fget(self):
            value = self._get(scope.name)
            if value is not None:
                return value
            if scope.reciprocal is None:
                return None
            reciprocal = self._get(scope.reciprocal.name)
            if reciprocal is None:
                return None
            return Maps.ReciprocalMap() * reciprocal

        def fset(self, value):
            if value is not properties.utils.undefined:
                value = scope.validate(self, value)
            self._set(scope.name, value)
            if value is not properties.utils.undefined:
                scope.clear_props(self)

        def fdel(self):
            self._set(scope.name, properties.utils.undefined)

        return property(fget=fget, fset=fset, fdel=fdel, doc=scope.doc)

    def as_pickle(self, instance):
        return instance._get(self.name)

class PhysicalProperty(properties.Property):

    class_info = 'a physical property'
    reciprocal = None
    _required = False

    @property
    def mapping(self):
        return getattr(self, '_mapping', None)

    @mapping.setter
    def mapping(self, value):
        assert isinstance(value, Mapping)
        value._prop = self  # Skip the setter
        self._mapping = value

    def clear_mappings(self, instance):
        if self.mapping is not None:
            if self.mapping.name in instance._props:
                delattr(instance, self.mapping.name)
            else:
                setattr(instance, self.mapping.name, None)
        if self.reciprocal is not None:
            if self.reciprocal.mapping is not None:
                if self.reciprocal.mapping.name in instance._props:
                    delattr(instance, self.reciprocal.mapping.name)
                else:
                    setattr(instance, self.reciprocal.mapping.name, None)

    def validate(self, instance, value):
        assert isinstance(value, (np.ndarray, float)), (
            "Physical properties must be numpy arrays or floats."
        )
        return value

    def get_property(self):

        scope = self

        def fget(self):

            default = self._get(scope.name)
            if default is not None:
                return default
            if scope.reciprocal:
                default = self._get(scope.reciprocal.name)
                if default is not None:
                    # set by default reciprocal
                    return 1.0 / default
            if scope.mapping is None and scope.reciprocal is None:
                return None
            if scope.mapping is None:
                # look to the reciprocal
                if scope.reciprocal.mapping is None:
                    # there is no reciprocal mapping
                    reciprocal_val = self._get(scope.reciprocal.name)
                    if reciprocal_val is None:
                        raise AttributeError(
                            'A default for {}/{} has not been set'.format(
                                scope.name, scope.reciprocal.name
                            )
                        )
                # Set by mapped reciprocal
                return 1.0 / getattr(self, scope.reciprocal.name)

            mapping = getattr(self, scope.mapping.name)
            if mapping is None:
                raise AttributeError(
                    'A default `{}` or mapping `{}` has not been set.'.format(
                        scope.name,
                        scope.mapping.name
                    )
                )
            if self.model is None:
                raise AttributeError(
                    'A `model` is required for physical property {}'.format(
                        scope.name
                    )
                )
            return mapping * self.model

        def fset(self, value):
            if value is not properties.utils.undefined:
                value = scope.validate(self, value)
                if scope.reciprocal:
                    delattr(self, scope.reciprocal.name)
            self._set(scope.name, value)
            if value is not properties.utils.undefined:
                scope.clear_mappings(self)

        def fdel(self):
            self._set(scope.name, properties.utils.undefined)

        return property(fget=fget, fset=fset, fdel=fdel, doc=scope.doc)

    def as_pickle(self, instance):
        return instance._get(self.name)

    def summary(self, instance):
        default = instance._get(self.name)
        if default is not None:
            return '[*] {}: set by default value'.format(
                self.name
            )
        if self.reciprocal:
            default = instance._get(self.reciprocal.name)
            if default is not None:
                return '[*] {}: set by default reciprocal: 1.0 / {}'.format(
                    self.name,
                    self.reciprocal.name
                )
        if self.mapping is None and self.reciprocal is None:
            return '[ ] {}: property not set'.format(
                self.name,
                self.reciprocal.name
            )
        if self.mapping is None:
            if self.reciprocal.mapping is None:
                # there is no reciprocal mapping
                reciprocal_val = instance._get(self.reciprocal.name)
                if reciprocal_val is None:
                    return '[ ] {}: default for {}/{} not set'.format(
                        self.name, self.name, self.reciprocal.name
                    )
            return '[*] {}: set by mapped reciprocal 1.0 / ({} * {})'.format(
                self.name, self.reciprocal.mapping.name, self.reciprocal.name
            )

        mapping = getattr(instance, self.mapping.name)

        if mapping is None:
            return '[ ] {}: default `{}` or mapping `{}` not set'.format(
                self.name, self.name, self.mapping.name
            )
        if instance.model is None:
            return (
                '[ ] {}: model({}) required, from active `{}` mapping: {}'
            ).format(
                self.name,
                mapping.shape[1],
                self.mapping.name,
                str(mapping)
            )

        correct_shape = (
            mapping.shape[1] == '*' or
            mapping.shape[1] == len(instance.model)
        )

        if correct_shape:
            return '[*] {}: set by the `{}` mapping: {} * model({})'.format(
                self.name, self.mapping.name, str(mapping), len(instance.model)
            )

        return '[ ] {}: incorrect mapping/model shape: {} * model({})'.format(
            self.name, str(mapping), len(instance.model)
        )

class Derivative(properties.GettableProperty):

    physical_property = None

    @property
    def mapping(self):
        """The mapping looks through to the physical property map."""
        if self.physical_property is None:
            return None
        return self.physical_property.mapping

    def get_property(self):

        scope = self

        def fget(self):
            if scope.physical_property is None:
                return Utils.Zero()
            if scope.mapping is None:
                return Utils.Zero()
            mapping = getattr(self, scope.mapping.name)
            if mapping is None:
                return Utils.Zero()
            if self.model is None:
                return Utils.Zero()

            return mapping.deriv(self.model)

        return property(fget=fget, doc=scope.doc)

def Invertible(help, default=None):

    mapping = Mapping(
        "Mapping of {} to the inversion model.".format(help)
    )

    physical_property = PhysicalProperty(
        help,
        mapping=mapping
    )
    if default is not None:
        physical_property.default = default

    property_derivative = Derivative(
        "Derivative of {} wrt the model.".format(help),
        physical_property=physical_property
    )

    return physical_property, mapping, property_derivative

def Reciprocal(prop1, prop2):
    prop1.reciprocal = prop2
    prop2.reciprocal = prop1

class BaseSimPEG(properties.HasProperties):
    """"""

class HasModel(BaseSimPEG):

    model = Model("Inversion model.")

    @property
    def _all_map_names(self):
        """Returns all Mapping properties"""
        return sorted([
            k for k in self._props
            if isinstance(self._props[k], Mapping)
        ])

    @property
    def _act_map_names(self):
        """Returns all active Mapping properties"""
        return sorted([
            k for k in self._all_map_names
            if getattr(self, k) is not None
        ])

    @property
    def needs_model(self):
        """True if a model is necessary"""
        return len(self._act_map_names) > 0

    @property
    def _has_nested_models(self):
        for k in self._props:
            if (
                    isinstance(self._props[k], properties.Instance) and
                    issubclass(self._props[k].instance_class, HasModel)
               ):
                return True
        return False

    @properties.validator('model')
    def _check_model_valid(self, change):
        """Checks the model length and necessity"""
        if change['value'] is properties.utils.undefined:
            return True

        if not self.needs_model and not self._has_nested_models:
            warnings.warn(
                "Cannot add model as there are no active mappings"
                ", choose from: ['{}']".format(
                    "', '".join(self._all_map_names)
                )
            )
            return

        errors = []

        for name in self._act_map_names:
            mapping = getattr(self, name)
            correct_shape = (
                mapping.shape[1] == '*' or
                mapping.shape[1] == len(change['value'])
            )
            if not correct_shape:
                errors += [
                    '{}: expected model of len({}) for {}'.format(
                        name,
                        mapping.shape[1],
                        str(mapping)
                    )
                ]
        if len(errors) == 0:
            return True

        warnings.warn(
            'Model of len({}) incorrect shape for mappings: \n    {}'.format(
                len(change['value']),
                '\n    '.join(errors)
            )
        )

    @properties.validator
    def _check_valid(self):
        errors = []

        # Check if the model is necessary
        if self.needs_model and self.model is None:
            errors += ['model must not be None']
        if not self.needs_model and self.model is not None:
            errors += ['there are no active maps, but a model is provided']

        # Check each map is the same size
        shapes = []
        for name in self._act_map_names:
            shape = getattr(self, name).shape[1]
            if shape == '*':
                continue
            shapes += [shape]
        if not all(x == shapes[0] for x in shapes):
            errors += ['the mappings are not the same shape']

        # Check that the model is the same size as the mappings
        if len(shapes) > 0 and self.model is not None:
            if not len(self.model) == shapes[0]:
                errors += ['the model must be len({})'.format(shapes[0])]

        # Check each physical property
        check_boxes = sorted([
            self._props[k].summary(self) for k in self._props
            if isinstance(self._props[k], PhysicalProperty)
        ])
        for line in check_boxes:
            if line[:3] == '[ ]':
                errors += [line[4:]]

        if len(errors) == 0:
            return True

        raise ValueError(
            'The {} instance has the following errors: \n - {}'.format(
                self.__class__.__name__,
                '\n - '.join(errors)
            )
        )

    def summary(self):
        prop_names = sorted([
            k for k in self._props
            if isinstance(self._props[k], PhysicalProperty)
        ])

        out = ['Physical Properties:']

        # Grab the physical property summaries
        for prop in prop_names:
            out += [' ' + self._props[prop].summary(self)]

        # Grab the validation errors
        try:
            self.validate()
            out += ['', 'All checks pass!']
        except ValueError as e:
            out += ['', str(e)]

        return '\n'.join(out)
<commit_msg>add a custom method for building docs as per https://github.com/3ptscience/properties/issues/153<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import properties
import numpy as np
import warnings

from . import Maps
from . import Utils

class SphinxProp(object):
    """
    Update the auto-documenter from properties
    https://github.com/3ptscience/properties/issues/153
    """
    def sphinx_class(self):
        return ':class:`{cls} <{ref}>`'.format(
            cls='Model', ref='SimPEG.Props.Model'
        )

class Array(properties.Array, SphinxProp):

    class_info = 'a numpy, Zero or Identity array'

    def validate(self, instance, value):
        if isinstance(value, (Utils.Zero, Utils.Identity)):
            return value
        return super(Array, self).validate(instance, value)

class Float(properties.Float, SphinxProp):

    class_info = 'a float, Zero or Identity'

    def validate(self, instance, value):
        if isinstance(value, (Utils.Zero, Utils.Identity)):
            return value
        return super(Float, self).validate(instance, value)

class Integer(properties.Integer, SphinxProp):

    class_info = 'an Integer or *'

    def validate(self, instance, value):
        if isinstance(value, str):
            assert value == '*', 'value must be an integer or *, not {}'.format(
                value
            )
            return value
        return super(Integer, self).validate(instance, value)

class Model(properties.Array, SphinxProp):

    class_info = 'a numpy array'
    _required = False

class Mapping(properties.Property, SphinxProp):

    class_info = 'a SimPEG Map'
    _required = False

    @property
    def prop(self):
        return getattr(self, '_prop', None)

    @prop.setter
    def prop(self, value):
        assert isinstance(value, PhysicalProperty)
        value._mapping = self  # Skip the setter
        self._prop = value

    @property
    def reciprocal(self):
        if self.prop and self.prop.reciprocal:
            return self.prop.reciprocal.mapping

    @property
    def reciprocal_prop(self):
        if self.prop and self.prop.reciprocal:
            return self.prop.reciprocal

    def clear_props(self, instance):
        for prop in (self.prop, self.reciprocal_prop, self.reciprocal):
            if prop is not None:
                if prop.name in instance._props:
                    delattr(instance, prop.name)
                else:
                    setattr(instance, prop.name, None)

    def validate(self, instance, value):
        if not isinstance(value, Maps.IdentityMap):
            self.error(instance, value)
        return value

    def get_property(self):

        scope = self

        def fget(self):
            value = self._get(scope.name)
            if value is not None:
                return value
            if scope.reciprocal is None:
                return None
            reciprocal = self._get(scope.reciprocal.name)
            if reciprocal is None:
                return None
            return Maps.ReciprocalMap() * reciprocal

        def fset(self, value):
            if value is not properties.utils.undefined:
                value = scope.validate(self, value)
            self._set(scope.name, value)
            if value is not properties.utils.undefined:
                scope.clear_props(self)

        def fdel(self):
            self._set(scope.name, properties.utils.undefined)

        return property(fget=fget, fset=fset, fdel=fdel, doc=scope.doc)

    def as_pickle(self, instance):
        return instance._get(self.name)

class PhysicalProperty(properties.Property, SphinxProp):

    class_info = 'a physical property'
    reciprocal = None
    _required = False

    @property
    def mapping(self):
        return getattr(self, '_mapping', None)

    @mapping.setter
    def mapping(self, value):
        assert isinstance(value, Mapping)
        value._prop = self  # Skip the setter
        self._mapping = value

    def clear_mappings(self, instance):
        if self.mapping is not None:
            if self.mapping.name in instance._props:
                delattr(instance, self.mapping.name)
            else:
                setattr(instance, self.mapping.name, None)
        if self.reciprocal is not None:
            if self.reciprocal.mapping is not None:
                if self.reciprocal.mapping.name in instance._props:
                    delattr(instance, self.reciprocal.mapping.name)
                else:
                    setattr(instance, self.reciprocal.mapping.name, None)

    def validate(self, instance, value):
        assert isinstance(value, (np.ndarray, float)), (
            "Physical properties must be numpy arrays or floats."
        )
        return value

    def get_property(self):

        scope = self

        def fget(self):

            default = self._get(scope.name)
            if default is not None:
                return default
            if scope.reciprocal:
                default = self._get(scope.reciprocal.name)
                if default is not None:
                    # set by default reciprocal
                    return 1.0 / default
            if scope.mapping is None and scope.reciprocal is None:
                return None
            if scope.mapping is None:
                # look to the reciprocal
                if scope.reciprocal.mapping is None:
                    # there is no reciprocal mapping
                    reciprocal_val = self._get(scope.reciprocal.name)
                    if reciprocal_val is None:
                        raise AttributeError(
                            'A default for {}/{} has not been set'.format(
                                scope.name, scope.reciprocal.name
                            )
                        )
                # Set by mapped reciprocal
                return 1.0 / getattr(self, scope.reciprocal.name)

            mapping = getattr(self, scope.mapping.name)
            if mapping is None:
                raise AttributeError(
                    'A default `{}` or mapping `{}` has not been set.'.format(
                        scope.name,
                        scope.mapping.name
                    )
                )
            if self.model is None:
                raise AttributeError(
                    'A `model` is required for physical property {}'.format(
                        scope.name
                    )
                )
            return mapping * self.model

        def fset(self, value):
            if value is not properties.utils.undefined:
                value = scope.validate(self, value)
                if scope.reciprocal:
                    delattr(self, scope.reciprocal.name)
            self._set(scope.name, value)
            if value is not properties.utils.undefined:
                scope.clear_mappings(self)

        def fdel(self):
            self._set(scope.name, properties.utils.undefined)

        return property(fget=fget, fset=fset, fdel=fdel, doc=scope.doc)

    def as_pickle(self, instance):
        return instance._get(self.name)

    def summary(self, instance):
        default = instance._get(self.name)
        if default is not None:
            return '[*] {}: set by default value'.format(
                self.name
            )
        if self.reciprocal:
            default = instance._get(self.reciprocal.name)
            if default is not None:
                return '[*] {}: set by default reciprocal: 1.0 / {}'.format(
                    self.name,
                    self.reciprocal.name
                )
        if self.mapping is None and self.reciprocal is None:
            return '[ ] {}: property not set'.format(
                self.name,
                self.reciprocal.name
            )
        if self.mapping is None:
            if self.reciprocal.mapping is None:
                # there is no reciprocal mapping
                reciprocal_val = instance._get(self.reciprocal.name)
                if reciprocal_val is None:
                    return '[ ] {}: default for {}/{} not set'.format(
                        self.name, self.name, self.reciprocal.name
                    )
            return '[*] {}: set by mapped reciprocal 1.0 / ({} * {})'.format(
                self.name, self.reciprocal.mapping.name, self.reciprocal.name
            )

        mapping = getattr(instance, self.mapping.name)

        if mapping is None:
            return '[ ] {}: default `{}` or mapping `{}` not set'.format(
                self.name, self.name, self.mapping.name
            )
        if instance.model is None:
            return (
                '[ ] {}: model({}) required, from active `{}` mapping: {}'
            ).format(
                self.name,
                mapping.shape[1],
                self.mapping.name,
                str(mapping)
            )

        correct_shape = (
            mapping.shape[1] == '*' or
            mapping.shape[1] == len(instance.model)
        )

        if correct_shape:
            return '[*] {}: set by the `{}` mapping: {} * model({})'.format(
                self.name, self.mapping.name, str(mapping), len(instance.model)
            )

        return '[ ] {}: incorrect mapping/model shape: {} * model({})'.format(
            self.name, str(mapping), len(instance.model)
        )

class Derivative(properties.GettableProperty, SphinxProp):

    physical_property = None

    @property
    def mapping(self):
        """The mapping looks through to the physical property map."""
        if self.physical_property is None:
            return None
        return self.physical_property.mapping

    def get_property(self):

        scope = self

        def fget(self):
            if scope.physical_property is None:
                return Utils.Zero()
            if scope.mapping is None:
                return Utils.Zero()
            mapping = getattr(self, scope.mapping.name)
            if mapping is None:
                return Utils.Zero()
            if self.model is None:
                return Utils.Zero()

            return mapping.deriv(self.model)

        return property(fget=fget, doc=scope.doc)

def Invertible(help, default=None):

    mapping = Mapping(
        "Mapping of {} to the inversion model.".format(help)
    )

    physical_property = PhysicalProperty(
        help,
        mapping=mapping
    )
    if default is not None:
        physical_property.default = default

    property_derivative = Derivative(
        "Derivative of {} wrt the model.".format(help),
        physical_property=physical_property
    )

    return physical_property, mapping, property_derivative

def Reciprocal(prop1, prop2):
    prop1.reciprocal = prop2
    prop2.reciprocal = prop1

class BaseSimPEG(properties.HasProperties):
    """"""

class HasModel(BaseSimPEG):

    model = Model("Inversion model.")

    @property
    def _all_map_names(self):
        """Returns all Mapping properties"""
        return sorted([
            k for k in self._props
            if isinstance(self._props[k], Mapping)
        ])

    @property
    def _act_map_names(self):
        """Returns all active Mapping properties"""
        return sorted([
            k for k in self._all_map_names
            if getattr(self, k) is not None
        ])

    @property
    def needs_model(self):
        """True if a model is necessary"""
        return len(self._act_map_names) > 0

    @property
    def _has_nested_models(self):
        for k in self._props:
            if (
                    isinstance(self._props[k], properties.Instance) and
                    issubclass(self._props[k].instance_class, HasModel)
               ):
                return True
        return False

    @properties.validator('model')
    def _check_model_valid(self, change):
        """Checks the model length and necessity"""
        if change['value'] is properties.utils.undefined:
            return True

        if not self.needs_model and not self._has_nested_models:
            warnings.warn(
                "Cannot add model as there are no active mappings"
                ", choose from: ['{}']".format(
                    "', '".join(self._all_map_names)
                )
            )
            return

        errors = []

        for name in self._act_map_names:
            mapping = getattr(self, name)
            correct_shape = (
                mapping.shape[1] == '*' or
                mapping.shape[1] == len(change['value'])
            )
            if not correct_shape:
                errors += [
                    '{}: expected model of len({}) for {}'.format(
                        name,
                        mapping.shape[1],
                        str(mapping)
                    )
                ]
        if len(errors) == 0:
            return True

        warnings.warn(
            'Model of len({}) incorrect shape for mappings: \n    {}'.format(
                len(change['value']),
                '\n    '.join(errors)
            )
        )

    @properties.validator
    def _check_valid(self):
        errors = []

        # Check if the model is necessary
        if self.needs_model and self.model is None:
            errors += ['model must not be None']
        if not self.needs_model and self.model is not None:
            errors += ['there are no active maps, but a model is provided']

        # Check each map is the same size
        shapes = []
        for name in self._act_map_names:
            shape = getattr(self, name).shape[1]
            if shape == '*':
                continue
            shapes += [shape]
        if not all(x == shapes[0] for x in shapes):
            errors += ['the mappings are not the same shape']

        # Check that the model is the same size as the mappings
        if len(shapes) > 0 and self.model is not None:
            if not len(self.model) == shapes[0]:
                errors += ['the model must be len({})'.format(shapes[0])]

        # Check each physical property
        check_boxes = sorted([
            self._props[k].summary(self) for k in self._props
            if isinstance(self._props[k], PhysicalProperty)
        ])
        for line in check_boxes:
            if line[:3] == '[ ]':
                errors += [line[4:]]

        if len(errors) == 0:
            return True

        raise ValueError(
            'The {} instance has the following errors: \n - {}'.format(
                self.__class__.__name__,
                '\n - '.join(errors)
            )
        )

    def summary(self):
        prop_names = sorted([
            k for k in self._props
            if isinstance(self._props[k], PhysicalProperty)
        ])

        out = ['Physical Properties:']

        # Grab the physical property summaries
        for prop in prop_names:
            out += [' ' + self._props[prop].summary(self)]

        # Grab the validation errors
        try:
            self.validate()
            out += ['', 'All checks pass!']
        except ValueError as e:
            out += ['', str(e)]

        return '\n'.join(out)
<|endoftext|>


<commit_before>class StateSystem:
	def __init__(self, initial_state):
		self.state = initial_state()

	def update(self):
		next_state = self.state.update()
		if next_state:
			if hasattr(self.state, "cleanup"):
				self.state.cleanup()
			self.state = next_state()

# Try to keep Ullur specific stuff below this line to make it easier to separate later
import math
from bge import logic, events
from mathutils import Vector, Euler
from .character import UllurCharacter, Meatsack
from .ai.manager import Manager
from .ai.agent_bge import AgentBGE
from .collectable import mutate_collectables

class DefaultState:
	CAM_MAX_DIST = 9
	CAM_MIN_DIST = 7
	CAM_DOWN_LIMIT = 0.5
	CAM_UP_LIMIT = -1.1

	def __init__(self):
		self.character = UllurCharacter.spawn()

		self.meatsacks = []
		for i in [i for i in logic.getCurrentScene().objects if i.name.startswith('MeatsackSpawn')]:
			self.meatsacks.append(Meatsack.spawn(i.worldPosition, i.worldOrientation))

		self.ai_system = Manager()
		target = AgentBGE(self.character)
		for meatsack in self.meatsacks:
			agent = AgentBGE(meatsack)
			agent.target = target
			agent.load_definition("../scripts/ai/definitions/state_test.json")
			self.ai_system._agents.append(agent)

		self.collectables = []
		mutate_collectables(logic.getCurrentScene().objects, self.collectables)

		logic.mouse.position = (0.5, 0.5)

	def update(self):
		self.character.update()

		cam = logic.getCurrentScene().active_camera

		movevec = Vector((0, 0, 0))
		self.character.running = False

		for key, status in logic.keyboard.active_events.items():
			if key == events.WKEY:
				movevec += Vector((0, 1, 0))
			elif key == events.AKEY:
				movevec += Vector((-1, 0, 0))
			elif key == events.SKEY:
				movevec += Vector((0, -1, 0))
			elif key == events.DKEY:
				movevec += Vector((1, 0, 0))
			elif key == events.SPACEKEY and status == logic.KX_INPUT_JUST_ACTIVATED:
				self.character.jump()
			elif key == events.LEFTSHIFTKEY:
				self.character.running = True

		for event, status in logic.mouse.active_events.items():
			if event == events.LEFTMOUSE and status == logic.KX_INPUT_JUST_ACTIVATED:
				self.character.attack("LEFT")
			elif event == events.RIGHTMOUSE and status == logic.KX_INPUT_JUST_ACTIVATED:
				self.character.attack("RIGHT")

		dx = 0.5 - logic.mouse.position[0]
		dy = 0.5 - logic.mouse.position[1]

		if cam.parent:
			# X Movement
			if math.fabs(dx) > 0.01:
				cam.parent.applyRotation((0, 0, dx))

			# Y Movement
			cam_angle = cam.parent.localOrientation.to_euler('XYZ')
			move_down_limit = dy > 0 and cam_angle.x < self.CAM_DOWN_LIMIT
			move_up_limit = dy < 0 and cam_angle.x > self.CAM_UP_LIMIT
			if math.fabs(dy) > 0.01 and (move_down_limit or move_up_limit):
				cam.parent.applyRotation((dy/2, 0, 0), True)

			# Zoom in camera based on y movement
			if cam_angle.x > 0:
				fac = cam_angle.x / self.CAM_DOWN_LIMIT
				cam.localPosition.y = -((self.CAM_MAX_DIST - self.CAM_MIN_DIST) * (1 - fac) + self.CAM_MIN_DIST)
			else:
				cam.localPosition.y = -self.CAM_MAX_DIST

		logic.mouse.position = (0.5, 0.5)

		cam_vec = cam.getAxisVect((0, 0, -1))
		cam_vec.z = 0

		if cam_vec.length_squared != 0:
			offset = cam_vec.angle(Vector((0, 1, 0)))
			if cam_vec.x > 0:
				offset *= -1
			offset = Euler((0, 0, offset))
			movevec.rotate(offset)

		self.character.move(movevec.xy)

		if logic.getAverageFrameRate():
			dt = 1 / logic.getAverageFrameRate()
		else:
			dt = 0
		if self.ai_system:
			self.ai_system.update(dt)

		# Update meatsacks
		for i in self.meatsacks[:]:
			i.update()
			if i.is_dead:
				self.meatsacks.remove(i)
				i.endObject()

		if self.collectables is not None and len(self.collectables) == 0:
			self.collectables = None
			print("All collectables gathered.")

<commit_msg>Docs: Adding doctstrings to the state module.<commit_after>class StateSystem:
	"""A system for handling game states"""

	def __init__(self, initial_state):
		"""
		:param initial_state: The class of the first state to load
		"""
		self.state = initial_state()

	def update(self):
		"""Update method which should be called every frame to update this system and run its states"""

		next_state = self.state.update()
		if next_state:
			if hasattr(self.state, "cleanup"):
				self.state.cleanup()
			self.state = next_state()

# Try to keep Ullur specific stuff below this line to make it easier to separate later
import math
from bge import logic, events
from mathutils import Vector, Euler
from .character import UllurCharacter, Meatsack
from .ai.manager import Manager
from .ai.agent_bge import AgentBGE
from .collectable import mutate_collectables

class DefaultState:
	"""Ullur's main state"""

	CAM_MAX_DIST = 9  #: The maximum follow distance for the camera
	CAM_MIN_DIST = 7  #: The minimum follow distance for the camera
	CAM_DOWN_LIMIT = 0.5  #: The maximum angle of the camera relative to the horizontal (faces into the ground)
	CAM_UP_LIMIT = -1.1  #: The minimum angle of the camera relative to the horizontal (faces into the sky)

	def __init__(self):
		self.character = UllurCharacter.spawn()

		self.meatsacks = []
		for i in [i for i in logic.getCurrentScene().objects if i.name.startswith('MeatsackSpawn')]:
			self.meatsacks.append(Meatsack.spawn(i.worldPosition, i.worldOrientation))

		self.ai_system = Manager()
		target = AgentBGE(self.character)
		for meatsack in self.meatsacks:
			agent = AgentBGE(meatsack)
			agent.target = target
			agent.load_definition("../scripts/ai/definitions/state_test.json")
			self.ai_system._agents.append(agent)

		self.collectables = []
		mutate_collectables(logic.getCurrentScene().objects, self.collectables)

		logic.mouse.position = (0.5, 0.5)

	def update(self):
		"""Called by the :class:`.StateSystem` to run this state"""
		self.character.update()

		cam = logic.getCurrentScene().active_camera

		movevec = Vector((0, 0, 0))
		self.character.running = False

		for key, status in logic.keyboard.active_events.items():
			if key == events.WKEY:
				movevec += Vector((0, 1, 0))
			elif key == events.AKEY:
				movevec += Vector((-1, 0, 0))
			elif key == events.SKEY:
				movevec += Vector((0, -1, 0))
			elif key == events.DKEY:
				movevec += Vector((1, 0, 0))
			elif key == events.SPACEKEY and status == logic.KX_INPUT_JUST_ACTIVATED:
				self.character.jump()
			elif key == events.LEFTSHIFTKEY:
				self.character.running = True

		for event, status in logic.mouse.active_events.items():
			if event == events.LEFTMOUSE and status == logic.KX_INPUT_JUST_ACTIVATED:
				self.character.attack("LEFT")
			elif event == events.RIGHTMOUSE and status == logic.KX_INPUT_JUST_ACTIVATED:
				self.character.attack("RIGHT")

		dx = 0.5 - logic.mouse.position[0]
		dy = 0.5 - logic.mouse.position[1]

		if cam.parent:
			# X Movement
			if math.fabs(dx) > 0.01:
				cam.parent.applyRotation((0, 0, dx))

			# Y Movement
			cam_angle = cam.parent.localOrientation.to_euler('XYZ')
			move_down_limit = dy > 0 and cam_angle.x < self.CAM_DOWN_LIMIT
			move_up_limit = dy < 0 and cam_angle.x > self.CAM_UP_LIMIT
			if math.fabs(dy) > 0.01 and (move_down_limit or move_up_limit):
				cam.parent.applyRotation((dy/2, 0, 0), True)

			# Zoom in camera based on y movement
			if cam_angle.x > 0:
				fac = cam_angle.x / self.CAM_DOWN_LIMIT
				cam.localPosition.y = -((self.CAM_MAX_DIST - self.CAM_MIN_DIST) * (1 - fac) + self.CAM_MIN_DIST)
			else:
				cam.localPosition.y = -self.CAM_MAX_DIST

		logic.mouse.position = (0.5, 0.5)

		cam_vec = cam.getAxisVect((0, 0, -1))
		cam_vec.z = 0

		if cam_vec.length_squared != 0:
			offset = cam_vec.angle(Vector((0, 1, 0)))
			if cam_vec.x > 0:
				offset *= -1
			offset = Euler((0, 0, offset))
			movevec.rotate(offset)

		self.character.move(movevec.xy)

		if logic.getAverageFrameRate():
			dt = 1 / logic.getAverageFrameRate()
		else:
			dt = 0
		if self.ai_system:
			self.ai_system.update(dt)

		# Update meatsacks
		for i in self.meatsacks[:]:
			i.update()
			if i.is_dead:
				self.meatsacks.remove(i)
				i.endObject()

		if self.collectables is not None and len(self.collectables) == 0:
			self.collectables = None
			print("All collectables gathered.")

<|endoftext|>


<commit_before>#!/usr/bin/env python
# TODO
#   Additional SpaceAPI JSON stuff we can muck with, someday...
#     spacefed stream state.(open,lastchange,trigger_person,message)
#     state.icon.(open,closed) events[(name,type,timestamp,extra)]
#     contact.(phone,sip,keymasters(email alias?),irc,twitter,facebook)
#     contact.(google,identica,foursquare,email,ml,jabber)
#     contact.(issue_mail(email alias?))
#     sensors.(temperature[],door_locked[],barometer[],radiation.())
#     sensors.(humidity[],beverage_supply[],power_consumption[],wind[])
#     sensors.(network_connections[],account_balance[])
#     sensors.(total_member_count[],people_now_present[])
#     feeds.(blog,wiki,calendar,flickr).(type=rss|atom|ical,url)
#     cache.schedule=[mhd]\.[0-9]{2} projects[<string/URL>]
#     radio_show[(name,url,type=mp3|ogg,start=ISO8601,end)]
#        "ml": "melbourne-makerspace@googlegroups.com",

class SpaceAPIOpenClose: # publish open/closed status via the SpaceAPI
	# SpaceAPI testing tools
	#   sensor (open/closed) setting                      true|false|null
	#     curl --data-urlencode sensors='{"state":{"open":true}}' --data key=<key> https://spaceapi.net/new/space/melbourne_makerspace/sensor/set
	#   status reading
	#     curl https://spaceapi.net/new/space/melbourne_makerspace/status/json
	import requests, json, logging

	# configuration
	base_uri = "https://spaceapi.net/new/space/melbourne_makerspace"
	token_file = "/home/pi/spaceapi-token" #"/home/pi/spaceapi-net.pem"

	try:
		import http.client as http_client
	except ImportError:
		import httplib as http_client # python 2

	def __init__(self):
		import warnings # spaceapi.net's SSL certificate is hosed - ignore it
		import requests.packages.urllib3.exceptions as exceptions
		warnings.simplefilter("ignore", exceptions.InsecureRequestWarning)
		#self.http_client.HTTPConnection.debuglevel = 1
		requests_log = self.logging.getLogger("requests.packages.urllib3")
		requests_log.setLevel(self.logging.INFO) #.DEBUG
		requests_log.propagate = True

	def sendStatus(self, status):
		r = ""
		f = open(token_file, "r")
		try:
			s = self.json.dumps({"state" : {"open" : status}}, separators=(',', ':'))
			r = self.requests.get(self.base_uri + "/sensor/set/", verify=False,
			                      params={"sensors": s, "key": f.readline().strip()})
			if self.logging.getLogger().isEnabledFor(self.logging.DEBUG):
				text = r.text
				if r.headers["content-type"] == "application/json":
					text = self.json.dumps(r.json(), sort_keys=True, indent=4,
					                       separators=(',', ': '))
				self.logging.debug('{} {}'.format(text, r))
		finally:
			f.close()
		return r

	def closeUp(self):
		self.logging.info("Closing up")
		return self.sendStatus(False)

	def openUp(self):
		self.logging.info("Opening up")
		return self.sendStatus(True)

	def test(self, arg): # utility method for setting SpaceAPI status
		if arg == "close":
			return self.closeUp().content
		elif arg == "open":
			return self.openUp().content
		elif arg == "null" or arg == "none" or arg == "na":
			self.logging.info("Resetting status to N/A")
			return self.sendStatus(None).content

class GPIODoorSensor: # read open/closed status from door sensor via GPIO
	import logging, RPi.GPIO as GPIO

	# configuration
	DOOR_SENSOR = 26 # GPIO physical pin connected to door sensor

	def __init__(self, verbose=False):
		self.verbose = verbose
		self.logging.info("Initializing GPIO Door Sensor")
		self.GPIO.setmode(self.GPIO.BOARD)
		self.GPIO.setwarnings(False)
		# setup the GPIO pin connected to the door Sensor to read as input
		self.GPIO.setup(self.DOOR_SENSOR, self.GPIO.IN, pull_up_down=self.GPIO.PUD_DOWN)
		#self.GPIO.setup(self.DOOR_SENSOR, self.GPIO.IN)

	def read(self):
		sensor = self.GPIO.input(self.DOOR_SENSOR)
		if self.verbose:
			self.logging.debug("door Active = {}".format(str(sensor)))
		return sensor

	def reset(self):
		# clean up on normal exit
		self.logging.info("Resetting GPIO Door Sensor")
		self.GPIO.cleanup()

def monitor(sensor, openClose): # loop, reading sensor and publishing status
	from time import sleep

	doorClosed = True # set the initial door State to closed
	doorCount = 0     # for how many cycles has the sensor differed from saved state?

	# main program loop
	try:
		while True:
			doorCount = doorCount + 1 if sensor.read() != doorClosed else 0
			if doorCount > 3:     # trigger after 1.5 seconds (3 * 0.5)
				if doorClosed:    # magnet is not present, door is open
					openClose.openUp()
				else:             # magnet is present, door is closed
					openClose.closeUp()
				doorClosed = not doorClosed  # toggle saved state
				doorCount = 0

			sleep(0.5)
	except KeyboardInterrupt:
		pass
	finally:
		sensor.reset() # reset sensor hardware on exit

logFormat = "%(asctime)s %(levelname)s: %(message)s"
#logDateFormat = "%m/%d/%Y %H:%M:%S"

if __name__ == "__main__":
	import logging, sys
	loglevel = logging.INFO # initialize logging
	if len(sys.argv) > 1 and sys.argv[1] == "-d":
		loglevel = logging.DEBUG
	elif len(sys.argv) > 1 and sys.argv[1] == "-q":
		loglevel = logging.WARNING
	# initialize logging
	logging.basicConfig(filename="/var/log/spacemon.log", format=logFormat,
	                    level=loglevel) #datefmt=logDateFormat,

	# start SpaceMonitor with GPIO Sensor and SpaceAPI
	monitor(GPIODoorSensor(), SpaceAPIOpenClose())
<commit_msg>Fixed bug with token_file<commit_after>#!/usr/bin/env python
# TODO
#   Additional SpaceAPI JSON stuff we can muck with, someday...
#     spacefed stream state.(open,lastchange,trigger_person,message)
#     state.icon.(open,closed) events[(name,type,timestamp,extra)]
#     contact.(phone,sip,keymasters(email alias?),irc,twitter,facebook)
#     contact.(google,identica,foursquare,email,ml,jabber)
#     contact.(issue_mail(email alias?))
#     sensors.(temperature[],door_locked[],barometer[],radiation.())
#     sensors.(humidity[],beverage_supply[],power_consumption[],wind[])
#     sensors.(network_connections[],account_balance[])
#     sensors.(total_member_count[],people_now_present[])
#     feeds.(blog,wiki,calendar,flickr).(type=rss|atom|ical,url)
#     cache.schedule=[mhd]\.[0-9]{2} projects[<string/URL>]
#     radio_show[(name,url,type=mp3|ogg,start=ISO8601,end)]
#        "ml": "melbourne-makerspace@googlegroups.com",

class SpaceAPIOpenClose: # publish open/closed status via the SpaceAPI
	# SpaceAPI testing tools
	#   sensor (open/closed) setting                      true|false|null
	#     curl --data-urlencode sensors='{"state":{"open":true}}' --data key=<key> https://spaceapi.net/new/space/melbourne_makerspace/sensor/set
	#   status reading
	#     curl https://spaceapi.net/new/space/melbourne_makerspace/status/json
	import requests, json, logging

	# configuration
	base_uri = "https://spaceapi.net/new/space/melbourne_makerspace"
	token_file = "/home/pi/spaceapi-token" #"/home/pi/spaceapi-net.pem"

	try:
		import http.client as http_client
	except ImportError:
		import httplib as http_client # python 2

	def __init__(self):
		import warnings # spaceapi.net's SSL certificate is hosed - ignore it
		import requests.packages.urllib3.exceptions as exceptions
		warnings.simplefilter("ignore", exceptions.InsecureRequestWarning)
		#self.http_client.HTTPConnection.debuglevel = 1
		requests_log = self.logging.getLogger("requests.packages.urllib3")
		requests_log.setLevel(self.logging.INFO) #.DEBUG
		requests_log.propagate = True

	def sendStatus(self, status):
		r = ""
		f = open(self.token_file, "r")
		try:
			s = self.json.dumps({"state" : {"open" : status}}, separators=(',', ':'))
			r = self.requests.get(self.base_uri + "/sensor/set/", verify=False,
			                      params={"sensors": s, "key": f.readline().strip()})
			if self.logging.getLogger().isEnabledFor(self.logging.DEBUG):
				text = r.text
				if r.headers["content-type"] == "application/json":
					text = self.json.dumps(r.json(), sort_keys=True, indent=4,
					                       separators=(',', ': '))
				self.logging.debug('{} {}'.format(text, r))
		finally:
			f.close()
		return r

	def closeUp(self):
		self.logging.info("Closing up")
		return self.sendStatus(False)

	def openUp(self):
		self.logging.info("Opening up")
		return self.sendStatus(True)

	def test(self, arg): # utility method for setting SpaceAPI status
		if arg == "close":
			return self.closeUp().content
		elif arg == "open":
			return self.openUp().content
		elif arg == "null" or arg == "none" or arg == "na":
			self.logging.info("Resetting status to N/A")
			return self.sendStatus(None).content

class GPIODoorSensor: # read open/closed status from door sensor via GPIO
	import logging, RPi.GPIO as GPIO

	# configuration
	DOOR_SENSOR = 26 # GPIO physical pin connected to door sensor

	def __init__(self, verbose=False):
		self.verbose = verbose
		self.logging.info("Initializing GPIO Door Sensor")
		self.GPIO.setmode(self.GPIO.BOARD)
		self.GPIO.setwarnings(False)
		# setup the GPIO pin connected to the door Sensor to read as input
		self.GPIO.setup(self.DOOR_SENSOR, self.GPIO.IN, pull_up_down=self.GPIO.PUD_DOWN)
		#self.GPIO.setup(self.DOOR_SENSOR, self.GPIO.IN)

	def read(self):
		sensor = self.GPIO.input(self.DOOR_SENSOR)
		if self.verbose:
			self.logging.debug("door Active = {}".format(str(sensor)))
		return sensor

	def reset(self):
		# clean up on normal exit
		self.logging.info("Resetting GPIO Door Sensor")
		self.GPIO.cleanup()

def monitor(sensor, openClose): # loop, reading sensor and publishing status
	from time import sleep

	doorClosed = True # set the initial door State to closed
	doorCount = 0     # for how many cycles has the sensor differed from saved state?

	# main program loop
	try:
		while True:
			doorCount = doorCount + 1 if sensor.read() != doorClosed else 0
			if doorCount > 3:     # trigger after 1.5 seconds (3 * 0.5)
				if doorClosed:    # magnet is not present, door is open
					openClose.openUp()
				else:             # magnet is present, door is closed
					openClose.closeUp()
				doorClosed = not doorClosed  # toggle saved state
				doorCount = 0

			sleep(0.5)
	except KeyboardInterrupt:
		pass
	finally:
		sensor.reset() # reset sensor hardware on exit

logFormat = "%(asctime)s %(levelname)s: %(message)s"
#logDateFormat = "%m/%d/%Y %H:%M:%S"

if __name__ == "__main__":
	import logging, sys
	loglevel = logging.INFO # initialize logging
	if len(sys.argv) > 1 and sys.argv[1] == "-d":
		loglevel = logging.DEBUG
	elif len(sys.argv) > 1 and sys.argv[1] == "-q":
		loglevel = logging.WARNING
	# initialize logging
	logging.basicConfig(filename="/var/log/spacemon.log", format=logFormat,
	                    level=loglevel) #datefmt=logDateFormat,

	# start SpaceMonitor with GPIO Sensor and SpaceAPI
	monitor(GPIODoorSensor(), SpaceAPIOpenClose())
<|endoftext|>